CombinedText
stringlengths 4
3.42M
|
---|
#include "app.h"
#include "version.h"
#include "timer.h"
#include "file/config.h"
#include "image/header.h"
#include "image/voxel.h"
#include "image/copy.h"
#include "gui/opengl/gl.h"
#include "gui/opengl/lighting.h"
#include "gui/dialog/file.h"
#include "gui/dialog/opengl.h"
#include "gui/dialog/image_properties.h"
#include "gui/mrview/mode/base.h"
#include "gui/mrview/mode/list.h"
#include "gui/mrview/tool/base.h"
#include "gui/mrview/tool/list.h"
namespace MR
{
namespace GUI
{
namespace MRView
{
using namespace App;
/*
#define MODE(classname, specifier, name, description) #specifier ", "
#define MODE_OPTION(classname, specifier, name, description) MODE(classname, specifier, name, description)
const OptionGroup Window::options = OptionGroup ("General options")
+ Option ("mode", "select initial display mode by its short ID. Valid mode IDs are: "
#include "gui/mrview/mode/list.h"
)
+ Argument ("name");
#undef MODE
#undef MODE_OPTION
*/
namespace {
Qt::KeyboardModifiers get_modifier (const char* key, Qt::KeyboardModifiers default_key) {
std::string value = lowercase (MR::File::Config::get (key));
if (value.empty())
return default_key;
if (value == "shift") return Qt::ShiftModifier;
if (value == "alt") return Qt::AltModifier;
#ifdef MRTRIX_MACOSX
if (value == "ctrl") return Qt::MetaModifier;
if (value == "cmd") return Qt::ControlModifier;
#else
if (value == "ctrl") return Qt::ControlModifier;
if (value == "meta" || value == "win") return Qt::MetaModifier;
#endif
throw Exception ("no such modifier \"" + value + "\" (parsed from config file)");
return Qt::NoModifier;
}
}
std::string get_modifier (Qt::KeyboardModifiers key) {
switch (key) {
case Qt::ShiftModifier: return "Shift";
case Qt::AltModifier: return "Alt";
#ifdef MRTRIX_MACOSX
case Qt::ControlModifier: return "Cmd";
case Qt::MetaModifier: return "Ctrl";
#else
case Qt::ControlModifier: return "Ctrl";
case Qt::MetaModifier: return "Win";
#endif
default: assert (0);
}
return "Invalid";
}
// GLArea definitions:
inline Window::GLArea::GLArea (Window& parent) :
QGLWidget (GL::core_format(), &parent),
main (parent) {
setCursor (Cursor::crosshair);
setMouseTracking (true);
setAcceptDrops (true);
setFocusPolicy (Qt::StrongFocus);
QFont font_ = font();
font_.setPointSize (MR::File::Config::get_int ("FontSize", 10));
setFont (font_);
}
QSize Window::GLArea::minimumSizeHint () const {
return QSize (256, 256);
}
QSize Window::GLArea::sizeHint () const {
std::string init_size_string = lowercase (MR::File::Config::get ("MRViewInitWindowSize"));
std::vector<int> init_window_size;
if (init_size_string.length())
init_window_size = parse_ints(init_size_string);
if (init_window_size.size() == 2)
return QSize (init_window_size[0], init_window_size[1]);
else
return QSize (512, 512);
}
void Window::GLArea::dragEnterEvent (QDragEnterEvent* event) {
event->acceptProposedAction();
}
void Window::GLArea::dragMoveEvent (QDragMoveEvent* event) {
event->acceptProposedAction();
}
void Window::GLArea::dragLeaveEvent (QDragLeaveEvent* event) {
event->accept();
}
void Window::GLArea::dropEvent (QDropEvent* event) {
const QMimeData* mimeData = event->mimeData();
if (mimeData->hasUrls()) {
VecPtr<MR::Image::Header> list;
QList<QUrl> urlList = mimeData->urls();
for (int i = 0; i < urlList.size() && i < 32; ++i) {
try {
list.push_back (new MR::Image::Header (urlList.at (i).path().toUtf8().constData()));
}
catch (Exception& e) {
e.display();
}
}
if (list.size())
main.add_images (list);
}
}
void Window::GLArea::initializeGL () {
main.initGL();
}
void Window::GLArea::paintGL () {
main.paintGL();
}
void Window::GLArea::mousePressEvent (QMouseEvent* event) {
main.mousePressEventGL (event);
}
void Window::GLArea::mouseMoveEvent (QMouseEvent* event) {
main.mouseMoveEventGL (event);
}
void Window::GLArea::mouseReleaseEvent (QMouseEvent* event) {
main.mouseReleaseEventGL (event);
}
void Window::GLArea::wheelEvent (QWheelEvent* event) {
main.wheelEventGL (event);
}
// Main Window class:
Window::Window() :
glarea (new GLArea (*this)),
mode (NULL),
font (glarea->font()),
#ifdef MRTRIX_MACOSX
FocusModifier (get_modifier ("MRViewFocusModifierKey", Qt::AltModifier)),
#else
FocusModifier (get_modifier ("MRViewFocusModifierKey", Qt::MetaModifier)),
#endif
MoveModifier (get_modifier ("MRViewMoveModifierKey", Qt::ShiftModifier)),
RotateModifier (get_modifier ("MRViewRotateModifierKey", Qt::ControlModifier)),
mouse_action (NoAction),
orient (NAN, NAN, NAN, NAN),
field_of_view (100.0),
anatomical_plane (2),
colourbar_position_index (2),
snap_to_image_axes_and_voxel (true)
{
setDockOptions (AllowTabbedDocks);
setDocumentMode (true);
Options opt = get_options ("batch");
for (size_t n = 0; n < opt.size(); ++n) {
std::ifstream batch_file (opt[n][0].c_str());
if (!batch_file)
throw Exception ("error opening batch file \"" + opt[n][0] + "\": " + strerror (errno));
std::string command;
while (getline (batch_file, command))
batch_commands.push_back (command);
}
opt = get_options ("run");
for (size_t n = 0; n < opt.size(); ++n)
batch_commands.push_back (opt[n][0]);
setWindowTitle (tr ("MRView"));
setWindowIcon (QPixmap (":/mrtrix.png"));
{
int iconsize = MR::File::Config::get_int ("IconSize", 24);
setIconSize (QSize (iconsize, iconsize));
}
setCentralWidget (glarea);
QToolBar* toolbar;
QAction* action;
QMenu* menu;
QToolButton* button;
setTabPosition (Qt::AllDockWidgetAreas, QTabWidget::North);
// Main toolbar:
Qt::ToolBarArea toolbar_position = Qt::TopToolBarArea;
{
std::string toolbar_pos_spec = lowercase (MR::File::Config::get ("InitialToolBarPosition"));
if (toolbar_pos_spec.size()) {
if (toolbar_pos_spec == "bottom") toolbar_position = Qt::BottomToolBarArea;
else if (toolbar_pos_spec == "left") toolbar_position = Qt::LeftToolBarArea;
else if (toolbar_pos_spec == "right") toolbar_position = Qt::RightToolBarArea;
else if (toolbar_pos_spec != "top")
WARN ("invalid value for configuration entry \"InitialToolBarPosition\"");
}
}
Qt::ToolButtonStyle button_style = static_cast<Qt::ToolButtonStyle> (MR::File::Config::get_int ("ToolbarStyle", 2));
toolbar = new QToolBar ("Main toolbar", this);
addToolBar (toolbar_position, toolbar);
action = toolbar->toggleViewAction ();
action->setShortcut (tr ("Ctrl+M"));
addAction (action);
// File menu:
menu = new QMenu (tr ("File menu"), this);
action = menu->addAction (tr ("Open..."), this, SLOT (image_open_slot()));
action->setShortcut (tr ("Ctrl+O"));
addAction (action);
save_action = menu->addAction (tr ("Save..."), this, SLOT (image_save_slot()));
save_action->setShortcut (tr ("Ctrl+S"));
addAction (save_action);
close_action = menu->addAction (tr ("Close"), this, SLOT (image_close_slot()));
close_action->setShortcut (tr ("Ctrl+W"));
addAction (close_action);
menu->addSeparator();
action = menu->addAction (tr ("DICOM import..."), this, SLOT (image_import_DICOM_slot()));
action->setShortcut (tr ("Ctrl+D"));
addAction (action);
menu->addSeparator();
action = menu->addAction (tr ("Quit"), this, SLOT (close()));
action->setShortcut (tr ("Ctrl+Q"));
addAction (action);
button = new QToolButton (this);
button->setText ("File");
button->setToolButtonStyle (button_style);
button->setToolTip (tr ("File menu"));
button->setIcon (QIcon (":/start.svg"));
button->setPopupMode (QToolButton::InstantPopup);
button->setMenu (menu);
toolbar->addWidget (button);
// Image menu:
image_menu = new QMenu (tr ("Image menu"), this);
image_group = new QActionGroup (this);
image_group->setExclusive (true);
connect (image_group, SIGNAL (triggered (QAction*)), this, SLOT (image_select_slot (QAction*)));
properties_action = image_menu->addAction (tr ("Properties..."), this, SLOT (image_properties_slot()));
properties_action->setToolTip (tr ("Display the properties of the current image\n\nShortcut: Ctrl+P"));
addAction (properties_action);
image_menu->addSeparator();
next_slice_action = image_menu->addAction (tr ("Next slice"), this, SLOT (slice_next_slot()));
next_slice_action->setShortcut (tr ("Up"));
addAction (next_slice_action);
prev_slice_action = image_menu->addAction (tr ("Previous slice"), this, SLOT (slice_previous_slot()));
prev_slice_action->setShortcut (tr ("Down"));
addAction (prev_slice_action);
next_image_volume_action = image_menu->addAction (tr ("Next volume"), this, SLOT (image_next_volume_slot()));
next_image_volume_action->setShortcut (tr ("Right"));
addAction (next_image_volume_action);
prev_image_volume_action = image_menu->addAction (tr ("Previous volume"), this, SLOT (image_previous_volume_slot()));
prev_image_volume_action->setShortcut (tr ("Left"));
addAction (prev_image_volume_action);
next_image_volume_group_action = image_menu->addAction (tr ("Next volume group"), this, SLOT (image_next_volume_group_slot()));
next_image_volume_group_action->setShortcut (tr ("Shift+Right"));
addAction (next_image_volume_group_action);
prev_image_volume_group_action = image_menu->addAction (tr("Previous volume group"), this, SLOT (image_previous_volume_group_slot()));
prev_image_volume_group_action->setShortcut (tr ("Shift+Left"));
addAction (prev_image_volume_group_action);
image_menu->addSeparator();
next_image_action = image_menu->addAction (tr ("Next image"), this, SLOT (image_next_slot()));
next_image_action->setShortcut (tr ("PgDown"));
addAction (next_image_action);
prev_image_action = image_menu->addAction (tr ("Previous image"), this, SLOT (image_previous_slot()));
prev_image_action->setShortcut (tr ("PgUp"));
addAction (prev_image_action);
image_list_area = image_menu->addSeparator();
button = new QToolButton (this);
button->setText ("Image");
button->setToolButtonStyle (button_style);
button->setToolTip (tr ("Image menu"));
button->setIcon (QIcon (":/image.svg"));
button->setPopupMode (QToolButton::InstantPopup);
button->setMenu (image_menu);
toolbar->addWidget (button);
// Colourmap menu:
colourmap_menu = new QMenu (tr ("Colourmap menu"), this);
ColourMap::create_menu (this, colourmap_group, colourmap_menu, colourmap_actions, true);
connect (colourmap_group, SIGNAL (triggered (QAction*)), this, SLOT (select_colourmap_slot()));
colourmap_menu->addSeparator();
invert_scale_action = colourmap_menu->addAction (tr ("Invert"), this, SLOT (invert_scaling_slot()));
invert_scale_action->setCheckable (true);
invert_scale_action->setShortcut (tr("U"));
addAction (invert_scale_action);
colourmap_menu->addSeparator();
reset_windowing_action = colourmap_menu->addAction (tr ("Reset brightness/contrast"), this, SLOT (image_reset_slot()));
reset_windowing_action->setShortcut (tr ("Esc"));
addAction (reset_windowing_action);
image_interpolate_action = colourmap_menu->addAction (tr ("Interpolate"), this, SLOT (image_interpolate_slot()));
image_interpolate_action->setShortcut (tr ("I"));
image_interpolate_action->setCheckable (true);
image_interpolate_action->setChecked (true);
addAction (image_interpolate_action);
button = new QToolButton (this);
button->setText ("Colourmap");
button->setToolButtonStyle (button_style);
button->setToolTip (tr ("Colourmap menu"));
button->setIcon (QIcon (":/colourmap.svg"));
button->setPopupMode (QToolButton::InstantPopup);
button->setMenu (colourmap_menu);
toolbar->addWidget (button);
// Mode menu:
mode_group = new QActionGroup (this);
mode_group->setExclusive (true);
connect (mode_group, SIGNAL (triggered (QAction*)), this, SLOT (select_mode_slot (QAction*)));
menu = new QMenu ("Display mode", this);
#define MODE(classname, specifier, name, description) \
menu->addAction (new Action<classname> (mode_group, #name, #description, n++));
#define MODE_OPTION(classname, specifier, name, description) MODE(classname, specifier, name, description)
{
using namespace Mode;
size_t n = 1;
#include "gui/mrview/mode/list.h"
}
#undef MODE
#undef MODE_OPTION
mode_group->actions()[0]->setChecked (true);
for (int n = 0; n < mode_group->actions().size(); ++n)
addAction (mode_group->actions()[n]);
menu->addSeparator();
plane_group = new QActionGroup (this);
plane_group->setExclusive (true);
connect (plane_group, SIGNAL (triggered (QAction*)), this, SLOT (select_plane_slot (QAction*)));
axial_action = menu->addAction (tr ("Axial"));
axial_action->setShortcut (tr ("A"));
axial_action->setCheckable (true);
plane_group->addAction (axial_action);
addAction (axial_action);
sagittal_action = menu->addAction (tr ("Sagittal"));
sagittal_action->setShortcut (tr ("S"));
sagittal_action->setCheckable (true);
plane_group->addAction (sagittal_action);
addAction (sagittal_action);
coronal_action = menu->addAction (tr ("Coronal"));
coronal_action->setShortcut (tr ("C"));
coronal_action->setCheckable (true);
plane_group->addAction (coronal_action);
addAction (coronal_action);
menu->addSeparator();
action = menu->addAction (tr ("Toggle all annotations"), this, SLOT (toggle_annotations_slot()));
action->setShortcut (tr("Space"));
addAction (action);
show_crosshairs_action = menu->addAction (tr ("Show focus"), glarea, SLOT (updateGL()));
show_crosshairs_action->setShortcut (tr("F"));
show_crosshairs_action->setCheckable (true);
show_crosshairs_action->setChecked (true);
addAction (show_crosshairs_action);
show_comments_action = menu->addAction (tr ("Show comments"), glarea, SLOT (updateGL()));
show_comments_action->setToolTip (tr ("Show/hide image comments\n\nShortcut: H"));
show_comments_action->setShortcut (tr("H"));
show_comments_action->setCheckable (true);
show_comments_action->setChecked (true);
addAction (show_comments_action);
show_voxel_info_action = menu->addAction (tr ("Show voxel information"), glarea, SLOT (updateGL()));
show_voxel_info_action->setShortcut (tr("V"));
show_voxel_info_action->setCheckable (true);
show_voxel_info_action->setChecked (true);
addAction (show_voxel_info_action);
show_orientation_labels_action = menu->addAction (tr ("Show orientation labels"), glarea, SLOT (updateGL()));
show_orientation_labels_action->setShortcut (tr("O"));
show_orientation_labels_action->setCheckable (true);
show_orientation_labels_action->setChecked (true);
addAction (show_orientation_labels_action);
show_colourbar_action = menu->addAction (tr ("Show colour bar"), glarea, SLOT (updateGL()));
show_colourbar_action->setShortcut (tr("B"));
show_colourbar_action->setCheckable (true);
show_colourbar_action->setChecked (true);
addAction (show_colourbar_action);
menu->addSeparator();
full_screen_action = menu->addAction (tr ("Full screen"), this, SLOT (full_screen_slot()));
full_screen_action->setShortcut (tr ("F11"));
full_screen_action->setCheckable (true);
full_screen_action->setChecked (false);
addAction (full_screen_action);
action = menu->addAction (tr ("Reset view"), this, SLOT(reset_view_slot()));
action->setShortcut (tr ("R"));
addAction (action);
button = new QToolButton (this);
button->setText ("View");
button->setToolButtonStyle (button_style);
button->setToolTip (tr ("Display"));
button->setIcon (QIcon (":/mode.svg"));
button->setMenu (menu);
button->setPopupMode (QToolButton::InstantPopup);
toolbar->addWidget (button);
// Tool menu:
tool_group = new QActionGroup (this);
tool_group->setExclusive (false);
connect (tool_group, SIGNAL (triggered (QAction*)), this, SLOT (select_tool_slot (QAction*)));
menu = new QMenu (tr ("Tools"), this);
#undef TOOL
#define TOOL(classname, name, description) \
menu->addAction (new Action<Tool::classname> (tool_group, #name, #description, n++));
#define TOOL_OPTION(classname, name, description) TOOL(classname, name, description)
{
using namespace Tool;
size_t n = 1;
#include "gui/mrview/tool/list.h"
}
for (int n = 0; n < tool_group->actions().size(); ++n)
addAction (tool_group->actions()[n]);
button = new QToolButton (this);
button->setText ("Tool");
button->setToolButtonStyle (button_style);
button->setToolTip (tr ("Select additional tools..."));
button->setIcon (QIcon (":/tools.svg"));
button->setMenu (menu);
button->setPopupMode (QToolButton::InstantPopup);
toolbar->addWidget (button);
toolbar->addSeparator();
// Mouse mode actions:
mode_action_group = new QActionGroup (this);
mode_action_group->setExclusive (true);
connect (mode_action_group, SIGNAL (triggered (QAction*)), this, SLOT (select_mouse_mode_slot (QAction*)));
std::string modifier;
action = toolbar->addAction (QIcon (":/select_contrast.svg"), tr ("Change focus / contrast"));
action->setToolTip (tr ((
"Left-click: set focus\n"
"Right-click: change brightness/constrast\n\n"
"Shortcut: 1\n\n"
"Hold down " + get_modifier (FocusModifier) + " key to use this mode\n"
"regardless of currently selected mode").c_str()));
action->setShortcut (tr("1"));
action->setCheckable (true);
action->setChecked (true);
mode_action_group->addAction (action);
action = toolbar->addAction (QIcon (":/move.svg"), tr ("Move viewport"));
action->setToolTip (tr ((
"Left-click: move in-plane\n"
"Right-click: move through-plane\n\n"
"Shortcut: 2\n\n"
"Hold down " + get_modifier (MoveModifier) + " key to use this mode\n"
"regardless of currently selected mode").c_str()));
action->setShortcut (tr("2"));
action->setCheckable (true);
mode_action_group->addAction (action);
action = toolbar->addAction (QIcon (":/rotate.svg"), tr ("Move camera"));
action->setToolTip (tr ((
"Left-click: move camera in-plane\n"
"Right-click: rotate camera about view axis\n\n"
"Shortcut: 3\n\n"
"Hold down " + get_modifier (RotateModifier) + " key to use this mode\n"
"regardless of currently selected mode").c_str()));
action->setShortcut (tr("3"));
action->setCheckable (true);
mode_action_group->addAction (action);
for (int n = 0; n < mode_action_group->actions().size(); ++n)
addAction (mode_action_group->actions()[n]);
toolbar->addSeparator();
snap_to_image_action = toolbar->addAction (QIcon (":/lock.svg"),
tr ("Snap to image"), this, SLOT (snap_to_image_slot()));
snap_to_image_action->setToolTip (tr (
"Snap focus and view orientation to\n"
"image voxel grid and axes respectively\n\n"
"Shortcut: L"));
snap_to_image_action->setShortcut (tr("L"));
snap_to_image_action->setCheckable (true);
snap_to_image_action->setChecked (snap_to_image_axes_and_voxel);
addAction (snap_to_image_action);
toolbar->addSeparator();
// Help menu:
menu = new QMenu (tr ("Help"), this);
menu->addAction (tr("OpenGL"), this, SLOT (OpenGL_slot()));
menu->addAction (tr ("About"), this, SLOT (about_slot()));
menu->addAction (tr ("about Qt"), this, SLOT (aboutQt_slot()));
button = new QToolButton (this);
button->setText ("Help");
button->setToolButtonStyle (button_style);
button->setToolTip (tr ("Help"));
button->setIcon (QIcon (":/help.svg"));
button->setPopupMode (QToolButton::InstantPopup);
button->setMenu (menu);
toolbar->addWidget (button);
lighting_ = new GL::Lighting (this);
connect (lighting_, SIGNAL (changed()), glarea, SLOT (updateGL()));
set_image_menu ();
std::string cbar_pos = lowercase (MR::File::Config::get ("MRViewColourBarPosition"));
if (cbar_pos.size()) {
if (cbar_pos == "bottomleft") colourbar_position_index = 1;
else if (cbar_pos == "bottomright") colourbar_position_index = 2;
else if (cbar_pos == "topleft") colourbar_position_index = 3;
else if (cbar_pos == "topright") colourbar_position_index = 4;
else
WARN ("invalid specifier \"" + cbar_pos + "\" for config file entry \"MRViewColourBarPosition\"");
}
}
Window::~Window ()
{
mode = NULL;
delete glarea;
delete [] colourmap_actions;
}
void Window::image_open_slot ()
{
std::vector<std::string> image_list = Dialog::File::get_images (this, "Select images to open");
if (image_list.empty())
return;
VecPtr<MR::Image::Header> list;
for (size_t n = 0; n < image_list.size(); ++n)
list.push_back (new MR::Image::Header (image_list[n]));
add_images (list);
}
void Window::image_import_DICOM_slot ()
{
std::string folder = Dialog::File::get_folder (this, "Select DICOM folder to import");
if (folder.empty())
return;
try {
VecPtr<MR::Image::Header> list;
list.push_back (new MR::Image::Header (folder));
add_images (list);
}
catch (Exception& E) {
E.display();
}
}
void Window::add_images (VecPtr<MR::Image::Header>& list)
{
for (size_t i = 0; i < list.size(); ++i) {
QAction* action = new Image (*this, *list[i]);
image_group->addAction (action);
if (!i) image_select_slot (action);
}
set_image_menu();
}
void Window::image_save_slot ()
{
std::string image_name = Dialog::File::get_save_image_name (this, "Select image destination");
if (image_name.empty())
return;
try {
MR::Image::Buffer<cfloat> dest (image_name, image()->header());
MR::Image::Buffer<cfloat>::voxel_type vox (dest);
MR::Image::copy_with_progress (image()->voxel(), vox);
}
catch (Exception& E) {
E.display();
}
}
void Window::image_close_slot ()
{
Image* imagep = image();
assert (imagep);
QList<QAction*> list = image_group->actions();
if (list.size() > 1) {
for (int n = 0; n < list.size(); ++n) {
if (imagep == list[n]) {
image_select_slot (list[ (n+1) %list.size()]);
break;
}
}
}
image_group->removeAction (imagep);
delete imagep;
set_image_menu();
}
void Window::image_properties_slot ()
{
assert (image());
Dialog::ImageProperties props (this, image()->header());
props.exec();
}
void Window::select_mode_slot (QAction* action)
{
mode = dynamic_cast<GUI::MRView::Mode::__Action__*> (action)->create (*this);
set_mode_features();
emit modeChanged();
glarea->updateGL();
}
void Window::select_mouse_mode_slot (QAction* action)
{
set_cursor();
}
void Window::select_tool_slot (QAction* action)
{
Tool::Dock* tool = dynamic_cast<Tool::__Action__*>(action)->dock;
if (!tool) {
tool = dynamic_cast<Tool::__Action__*>(action)->create (*this);
connect (tool, SIGNAL (visibilityChanged (bool)), action, SLOT (setChecked (bool)));
for (int i = 0; i < tool_group->actions().size(); ++i) {
Tool::Dock* other_tool = dynamic_cast<Tool::__Action__*>(tool_group->actions()[i])->dock;
if (other_tool && other_tool != tool) {
QList<QDockWidget* > list = QMainWindow::tabifiedDockWidgets (other_tool);
if (list.size())
QMainWindow::tabifyDockWidget (list.last(), tool);
else
QMainWindow::tabifyDockWidget (other_tool, tool);
tool->show();
tool->raise();
return;
}
}
}
if (action->isChecked()) {
if (!tool->isVisible())
tool->show();
tool->raise();
} else {
tool->close();
}
glarea->updateGL();
}
void Window::select_colourmap_slot ()
{
Image* imagep = image();
if (imagep) {
QAction* action = colourmap_group->checkedAction();
size_t n = 0;
while (action != colourmap_actions[n])
++n;
imagep->set_colourmap (n);
glarea->updateGL();
}
}
void Window::invert_scaling_slot ()
{
if (image()) {
image()->set_invert_scale (invert_scale_action->isChecked());
glarea->updateGL();
}
}
void Window::snap_to_image_slot ()
{
if (image()) {
snap_to_image_axes_and_voxel = snap_to_image_action->isChecked();
glarea->updateGL();
}
}
void Window::on_scaling_changed ()
{
emit scalingChanged();
}
void Window::image_reset_slot ()
{
Image* imagep = image();
if (imagep) {
imagep->reset_windowing();
on_scaling_changed();
glarea->updateGL();
}
}
void Window::image_interpolate_slot ()
{
Image* imagep = image();
if (imagep) {
imagep->set_interpolate (image_interpolate_action->isChecked());
glarea->updateGL();
}
}
void Window::full_screen_slot ()
{
if (full_screen_action->isChecked())
showFullScreen();
else
showNormal();
}
void Window::select_plane_slot (QAction* action)
{
if (action == axial_action) set_plane (2);
else if (action == sagittal_action) set_plane (0);
else if (action == coronal_action) set_plane (1);
else assert (0);
glarea->updateGL();
}
void Window::reset_view_slot ()
{
if (image())
mode->reset_event();
}
void Window::slice_next_slot ()
{
mode->slice_move_event (1);
}
void Window::slice_previous_slot ()
{
mode->slice_move_event (-1);
}
void Window::image_next_slot ()
{
QAction* action = image_group->checkedAction();
int N = image_group->actions().size();
int n = image_group->actions().indexOf (action);
image_select_slot (image_group->actions()[(n+1)%N]);
}
void Window::image_previous_slot ()
{
QAction* action = image_group->checkedAction();
int N = image_group->actions().size();
int n = image_group->actions().indexOf (action);
image_select_slot (image_group->actions()[(n+N-1)%N]);
}
void Window::image_next_volume_slot ()
{
assert (image());
++image()->interp[3];
set_image_navigation_menu();
glarea->updateGL();
}
void Window::image_previous_volume_slot ()
{
assert (image());
--image()->interp[3];
set_image_navigation_menu();
glarea->updateGL();
}
void Window::image_next_volume_group_slot ()
{
assert (image());
++image()->interp[4];
set_image_navigation_menu();
glarea->updateGL();
}
void Window::image_previous_volume_group_slot ()
{
assert (image());
--image()->interp[4];
set_image_navigation_menu();
glarea->updateGL();
}
void Window::image_select_slot (QAction* action)
{
action->setChecked (true);
image_interpolate_action->setChecked (image()->interpolate());
size_t cmap_index = image()->colourmap;
colourmap_group->actions()[cmap_index]->setChecked (true);
invert_scale_action->setChecked (image()->scale_inverted());
setWindowTitle (image()->interp.name().c_str());
set_image_navigation_menu();
image()->set_allowed_features (
mode->features & Mode::ShaderThreshold,
mode->features & Mode::ShaderTransparency,
mode->features & Mode::ShaderLighting);
emit imageChanged();
glarea->updateGL();
}
void Window::toggle_annotations_slot ()
{
int current_annotations = 0x00000000;
if (show_crosshairs()) current_annotations |= 0x00000001;
if (show_comments()) current_annotations |= 0x00000002;
if (show_voxel_info()) current_annotations |= 0x00000004;
if (show_orientation_labels()) current_annotations |= 0x00000008;
if (show_colourbar()) current_annotations |= 0x00000010;
if (current_annotations) {
annotations = current_annotations;
show_crosshairs_action->setChecked (false);
show_comments_action->setChecked (false);
show_voxel_info_action->setChecked (false);
show_orientation_labels_action->setChecked (false);
show_colourbar_action->setChecked (false);
}
else {
if (!annotations)
annotations = 0xFFFFFFFF;
show_crosshairs_action->setChecked (annotations & 0x00000001);
show_comments_action->setChecked (annotations & 0x00000002);
show_voxel_info_action->setChecked (annotations & 0x00000004);
show_orientation_labels_action->setChecked (annotations & 0x00000008);
show_colourbar_action->setChecked (annotations & 0x00000010);
}
glarea->updateGL();
}
inline void Window::set_image_menu ()
{
int N = image_group->actions().size();
next_image_action->setEnabled (N>1);
prev_image_action->setEnabled (N>1);
reset_windowing_action->setEnabled (N>0);
colourmap_menu->setEnabled (N>0);
save_action->setEnabled (N>0);
close_action->setEnabled (N>0);
properties_action->setEnabled (N>0);
set_image_navigation_menu();
glarea->updateGL();
}
inline int Window::get_mouse_mode ()
{
if (mouse_action == NoAction && modifiers_ != Qt::NoModifier) {
if (modifiers_ == FocusModifier && ( mode->features & Mode::FocusContrast ))
return 1;
else if (modifiers_ == MoveModifier && ( mode->features & Mode::MoveTarget ))
return 2;
else if (modifiers_ == RotateModifier && ( mode->features & Mode::TiltRotate ))
return 3;
}
if (mouse_action == NoAction)
return mode_action_group->actions().indexOf (mode_action_group->checkedAction()) + 1;
return 0;
}
inline void Window::set_cursor ()
{
MouseAction cursor = mouse_action;
if (cursor == NoAction) {
switch (get_mouse_mode()) {
case 1: cursor = SetFocus; break;
case 2: cursor = Pan; break;
case 3: cursor = Tilt; break;
default: assert (0);
}
}
switch (cursor) {
case SetFocus: glarea->setCursor (Cursor::crosshair); break;
case Contrast: glarea->setCursor (Cursor::window); break;
case Pan: glarea->setCursor (Cursor::pan_crosshair); break;
case PanThrough: glarea->setCursor (Cursor::forward_backward); break;
case Tilt: glarea->setCursor (Cursor::throughplane_rotate); break;
case Rotate: glarea->setCursor (Cursor::inplane_rotate); break;
default: assert (0);
}
}
inline void Window::set_mode_features ()
{
mode_action_group->actions()[0]->setEnabled (mode->features & Mode::FocusContrast);
mode_action_group->actions()[1]->setEnabled (mode->features & Mode::MoveTarget);
mode_action_group->actions()[2]->setEnabled (mode->features & Mode::TiltRotate);
if (!mode_action_group->checkedAction()->isEnabled())
mode_action_group->actions()[0]->setChecked (true);
if (image())
image()->set_allowed_features (
mode->features & Mode::ShaderThreshold,
mode->features & Mode::ShaderTransparency,
mode->features & Mode::ShaderLighting);
}
inline void Window::set_image_navigation_menu ()
{
bool show_next_volume (false), show_prev_volume (false);
bool show_next_volume_group (false), show_prev_volume_group (false);
Image* imagep = image();
if (imagep) {
if (imagep->interp.ndim() > 3) {
if (imagep->interp[3] > 0)
show_prev_volume = true;
if (imagep->interp[3] < imagep->interp.dim(3)-1)
show_next_volume = true;
if (imagep->interp.ndim() > 4) {
if (imagep->interp[4] > 0)
show_prev_volume_group = true;
if (imagep->interp[4] < imagep->interp.dim(4)-1)
show_next_volume_group = true;
}
}
}
prev_image_volume_action->setEnabled (show_prev_volume);
next_image_volume_action->setEnabled (show_next_volume);
prev_image_volume_group_action->setEnabled (show_prev_volume_group);
next_image_volume_group_action->setEnabled (show_next_volume_group);
}
void Window::OpenGL_slot ()
{
Dialog::OpenGL gl (this, glarea->format());
gl.exec();
}
void Window::about_slot ()
{
std::string message =
"<h1>MRView</h1>The MRtrix viewer, version " MRTRIX_GIT_VERSION "<br>"
"<em>" + str (8*sizeof (size_t)) + " bit "
#ifdef NDEBUG
"release"
#else
"debug"
#endif
" version, built " + App::build_date + "</em><p>"
"<h4>Authors:</h4>" + MR::join (MR::split (App::AUTHOR, ",;&\n", true), "<br>") +
"<p><em>" + App::COPYRIGHT + "</em>";
QMessageBox::about (this, tr ("About MRView"), message.c_str());
}
void Window::aboutQt_slot ()
{
QMessageBox::aboutQt (this);
}
inline void Window::paintGL ()
{
gl::Enable (gl::MULTISAMPLE);
if (mode->in_paint())
return;
gl::DrawBuffer (gl::BACK);
mode->paintGL();
}
inline void Window::initGL ()
{
GL::init ();
font.initGL();
gl::ClearColor (0.0, 0.0, 0.0, 0.0);
gl::Enable (gl::DEPTH_TEST);
mode = dynamic_cast<Mode::__Action__*> (mode_group->actions()[0])->create (*this);
set_mode_features();
if (batch_commands.size())
QTimer::singleShot (0, this, SLOT (process_batch_command()));
}
template <class Event> inline void Window::grab_mouse_state (Event* event)
{
buttons_ = event->buttons();
modifiers_ = event->modifiers() & ( FocusModifier | MoveModifier | RotateModifier );
mouse_displacement_ = QPoint (0,0);
mouse_position_ = event->pos();
mouse_position_.setY (glarea->height() - mouse_position_.y());
}
template <class Event> inline void Window::update_mouse_state (Event* event)
{
mouse_displacement_ = mouse_position_;
mouse_position_ = event->pos();
mouse_position_.setY (glarea->height() - mouse_position_.y());
mouse_displacement_ = mouse_position_ - mouse_displacement_;
}
void Window::keyPressEvent (QKeyEvent* event)
{
modifiers_ = event->modifiers() & ( FocusModifier | MoveModifier | RotateModifier );
set_cursor();
}
void Window::keyReleaseEvent (QKeyEvent* event)
{
modifiers_ = event->modifiers() & ( FocusModifier | MoveModifier | RotateModifier );
set_cursor();
}
inline void Window::mousePressEventGL (QMouseEvent* event)
{
assert (mode);
grab_mouse_state (event);
if (image())
mode->mouse_press_event();
int group = get_mouse_mode();
if (buttons_ == Qt::MidButton)
mouse_action = Pan;
else if (group == 1) {
if (buttons_ == Qt::LeftButton) {
mouse_action = SetFocus;
if (image())
mode->set_focus_event();
}
else if (buttons_ == Qt::RightButton)
mouse_action = Contrast;
}
else if (group == 2) {
if (buttons_ == Qt::LeftButton)
mouse_action = Pan;
else if (buttons_ == Qt::RightButton)
mouse_action = PanThrough;
}
else if (group == 3) {
if (buttons_ == Qt::LeftButton)
mouse_action = Tilt;
else if (buttons_ == Qt::RightButton)
mouse_action = Rotate;
}
set_cursor();
event->accept();
}
inline void Window::mouseMoveEventGL (QMouseEvent* event)
{
assert (mode);
if (mouse_action == NoAction)
return;
if (!image())
return;
update_mouse_state (event);
switch (mouse_action) {
case SetFocus: mode->set_focus_event(); break;
case Contrast: mode->contrast_event(); break;
case Pan: mode->pan_event(); break;
case PanThrough: mode->panthrough_event(); break;
case Tilt: mode->tilt_event(); break;
case Rotate: mode->rotate_event(); break;
default: return;
}
event->accept();
}
inline void Window::mouseReleaseEventGL (QMouseEvent* event)
{
assert (mode);
mode->mouse_release_event();
mouse_action = NoAction;
set_cursor();
}
inline void Window::wheelEventGL (QWheelEvent* event)
{
assert (mode);
if (event->orientation() == Qt::Vertical) {
if (image()) {
grab_mouse_state (event);
mode->mouse_press_event();
if (buttons_ == Qt::NoButton) {
if (modifiers_ == Qt::ControlModifier) {
set_FOV (FOV() * Math::exp (-event->delta()/1200.0));
glarea->updateGL();
event->accept();
return;
}
int delta = event->delta() / 120.0;
if (modifiers_ == Qt::ShiftModifier) delta *= 10.0;
else if (modifiers_ != Qt::NoModifier)
return;
mode->slice_move_event (delta);
event->accept();
return;
}
}
if (buttons_ == Qt::LeftButton && modifiers_ == Qt::NoModifier) {
int current = 0, num = 0;
for (int i = 0; i < mode_action_group->actions().size(); ++i) {
if (mode_action_group->actions()[current] != mode_action_group->checkedAction())
current = num;
if (mode_action_group->actions()[i]->isEnabled())
++num;
}
current = (current + num - int(event->delta()/120.0)) % num;
num = 0;
for (int i = 0; i < mode_action_group->actions().size(); ++i) {
if (mode_action_group->actions()[i]->isEnabled()) {
if (current == num) {
mode_action_group->actions()[i]->setChecked (true);
break;
}
++num;
}
}
mouse_action = NoAction;
set_cursor();
return;
}
if (buttons_ == Qt::RightButton && modifiers_ == Qt::NoModifier) {
if (image_group->actions().size() > 1) {
QAction* action = image_group->checkedAction();
int N = image_group->actions().size();
int n = image_group->actions().indexOf (action);
image_select_slot (image_group->actions()[(n+N+int(event->delta()/120.0))%N]);
}
}
}
}
void Window::closeEvent (QCloseEvent* event)
{
qApp->quit();
event->accept();
}
void Window::process_batch_command ()
{
assert (batch_commands.size());
try {
std::string line;
do {
if (batch_commands.empty())
return;
line = batch_commands[0];
batch_commands.erase (batch_commands.begin(), batch_commands.begin()+1);
line = strip (line.substr (0, line.find_first_of ('#')));
} while (line.empty());
std::string cmd = line.substr (0, line.find_first_of (" :\t"));
std::string args;
if (line.size() > cmd.size()+1)
args = strip (line.substr (cmd.size()+1));
// starts of commands proper:
// BATCH_COMMAND view.mode index # Switch to view mode specified by the integer index. as per the view menu.
if (cmd == "view.mode") {
int n = to<int> (args) - 1;
if (n < 0 || n >= mode_group->actions().size())
throw Exception ("invalid mode index \"" + args + "\" in batch command");
select_mode_slot (mode_group->actions()[n]);
}
// BATCH_COMMAND view.size width,height # Set the size of the view area, in pixel units.
else if (cmd == "view.size") {
std::vector<int> glsize = parse_ints (args);
if (glsize.size() != 2)
throw Exception ("invalid argument \"" + args + "\" to view.size batch command");
QSize oldsize = glarea->size();
QSize winsize = size();
resize (winsize.width() - oldsize.width() + glsize[0], winsize.height() - oldsize.height() + glsize[1]);
}
// BATCH_COMMAND view.reset # Reset the view according to current image. This resets the FOV, projection, and focus.
else if (cmd == "view.reset")
reset_view_slot();
// BATCH_COMMAND view.fov num # Set the field of view, in mm.
else if (cmd == "view.fov") {
float fov = to<float> (args);
set_FOV (fov);
glarea->updateGL();
}
// BATCH_COMMAND view.focus x,y,z # Set the position of the crosshairs in scanner coordinates, with the new position supplied as a comma-separated list of floating-point values.
else if (cmd == "view.focus") {
std::vector<float> pos = parse_floats (args);
if (pos.size() != 3)
throw Exception ("batch command \"" + cmd + "\" expects a comma-separated list of 3 floating-point values");
set_focus (Point<> (pos[0], pos[1], pos[2]));
glarea->updateGL();
}
// BATCH_COMMAND view.voxel x,y,z # Set the position of the crosshairs in voxel coordinates, relative the image currently displayed. The new position should be supplied as a comma-separated list of floating-point values.
else if (cmd == "view.voxel") {
if (image()) {
std::vector<float> pos = parse_floats (args);
if (pos.size() != 3)
throw Exception ("batch command \"" + cmd + "\" expects a comma-separated list of 3 floating-point values");
set_focus (image()->interp.voxel2scanner (Point<> (pos[0], pos[1], pos[2])));
glarea->updateGL();
}
}
// BATCH_COMMAND view.fov num # Set the field of view, in mm.
else if (cmd == "view.fov") {
float fov = to<float> (args);
set_FOV (fov);
glarea->updateGL();
}
// BATCH_COMMAND view.plane num # Set the viewing plane, according to the mappping 0: sagittal; 1: coronal; 2: axial.
else if (cmd == "view.plane") {
int n = to<int> (args);
set_plane (n);
glarea->updateGL();
}
// BATCH_COMMAND view.lock # Set whether view is locked to image axes (0: no, 1: yes).
else if (cmd == "view.lock") {
bool n = to<bool> (args);
snap_to_image_action->setChecked (n);
snap_to_image_slot();
}
// BATCH_COMMAND image.select index # Switch to image number specified, with reference to the list of currently loaded images.
else if (cmd == "image.select") {
int n = to<int> (args) - 1;
if (n < 0 || n >= image_group->actions().size())
throw Exception ("invalid image index requested in batch command");
image_select_slot (image_group->actions()[n]);
}
// BATCH_COMMAND image.load path # Load image specified and make it current.
else if (cmd == "image.load") {
VecPtr<MR::Image::Header> list;
try { list.push_back (new MR::Image::Header (args)); }
catch (Exception& e) { e.display(); }
add_images (list);
}
// BATCH_COMMAND image.reset # Reset the image scaling.
else if (cmd == "image.reset")
image_reset_slot();
// BATCH_COMMAND image.colourmap index # Switch the image colourmap to that specified, as per the colourmap menu.
else if (cmd == "image.colourmap") {
int n = to<int> (args) - 1;
if (n < 0 || n >= colourmap_group->actions().size())
throw Exception ("invalid image colourmap index \"" + args + "\" requested in batch command");
colourmap_group->actions()[n]->setChecked (true);
select_colourmap_slot ();
}
// BATCH_COMMAND image.range min max # Set the image intensity range to that specified
else if (cmd == "image.range") {
if (image()) {
std::vector<std::string> param = split (args);
if (param.size() != 2)
throw Exception ("batch command image.range expects two arguments");
image()->set_windowing (to<float> (param[0]), to<float> (param[1]));
updateGL();
}
}
// BATCH_COMMAND tool.open index # Start the tool specified, indexed as per the tool menu
else if (cmd == "tool.open") {
int n = to<int> (args) - 1;
if (n < 0 || n >= tool_group->actions().size())
throw Exception ("invalid tool index \"" + args + "\" requested in batch command");
tool_group->actions()[n]->setChecked (true);
select_tool_slot (tool_group->actions()[n]);
}
// BATCH_COMMAND window.position x,y # Set the position of the main window, in pixel units.
else if (cmd == "window.position") {
std::vector<int> pos = parse_ints (args);
if (pos.size() != 2)
throw Exception ("invalid argument \"" + args + "\" to view.position batch command");
move (pos[0], pos[1]);
}
// BATCH_COMMAND window.fullscreen # Show fullscreen or windowed (0: windowed, 1: fullscreen).
else if (cmd == "window.fullscreen") {
bool n = to<bool> (args);
full_screen_action->setChecked (n);
full_screen_slot();
}
// BATCH_COMMAND exit # quit MRView.
else if (cmd == "exit")
qApp->quit();
else { // process by tool
int n = 0;
while (n < tools()->actions().size()) {
Tool::Dock* dock = dynamic_cast<Tool::__Action__*>(tools()->actions()[n])->dock;
if (dock)
if (dock->tool->process_batch_command (cmd, args))
break;
++n;
}
if (n >= tools()->actions().size())
WARN ("batch command \"" + cmd + "\" unclaimed by main window or any active tool - ignored");
}
// end of commands
}
catch (Exception& E) {
E.display();
qApp->quit();
}
if (batch_commands.size())
QTimer::singleShot (0, this, SLOT (process_batch_command()));
}
}
}
}
MRView: catch Exception on image open error
#include "app.h"
#include "version.h"
#include "timer.h"
#include "file/config.h"
#include "image/header.h"
#include "image/voxel.h"
#include "image/copy.h"
#include "gui/opengl/gl.h"
#include "gui/opengl/lighting.h"
#include "gui/dialog/file.h"
#include "gui/dialog/opengl.h"
#include "gui/dialog/image_properties.h"
#include "gui/mrview/mode/base.h"
#include "gui/mrview/mode/list.h"
#include "gui/mrview/tool/base.h"
#include "gui/mrview/tool/list.h"
namespace MR
{
namespace GUI
{
namespace MRView
{
using namespace App;
/*
#define MODE(classname, specifier, name, description) #specifier ", "
#define MODE_OPTION(classname, specifier, name, description) MODE(classname, specifier, name, description)
const OptionGroup Window::options = OptionGroup ("General options")
+ Option ("mode", "select initial display mode by its short ID. Valid mode IDs are: "
#include "gui/mrview/mode/list.h"
)
+ Argument ("name");
#undef MODE
#undef MODE_OPTION
*/
namespace {
Qt::KeyboardModifiers get_modifier (const char* key, Qt::KeyboardModifiers default_key) {
std::string value = lowercase (MR::File::Config::get (key));
if (value.empty())
return default_key;
if (value == "shift") return Qt::ShiftModifier;
if (value == "alt") return Qt::AltModifier;
#ifdef MRTRIX_MACOSX
if (value == "ctrl") return Qt::MetaModifier;
if (value == "cmd") return Qt::ControlModifier;
#else
if (value == "ctrl") return Qt::ControlModifier;
if (value == "meta" || value == "win") return Qt::MetaModifier;
#endif
throw Exception ("no such modifier \"" + value + "\" (parsed from config file)");
return Qt::NoModifier;
}
}
std::string get_modifier (Qt::KeyboardModifiers key) {
switch (key) {
case Qt::ShiftModifier: return "Shift";
case Qt::AltModifier: return "Alt";
#ifdef MRTRIX_MACOSX
case Qt::ControlModifier: return "Cmd";
case Qt::MetaModifier: return "Ctrl";
#else
case Qt::ControlModifier: return "Ctrl";
case Qt::MetaModifier: return "Win";
#endif
default: assert (0);
}
return "Invalid";
}
// GLArea definitions:
inline Window::GLArea::GLArea (Window& parent) :
QGLWidget (GL::core_format(), &parent),
main (parent) {
setCursor (Cursor::crosshair);
setMouseTracking (true);
setAcceptDrops (true);
setFocusPolicy (Qt::StrongFocus);
QFont font_ = font();
font_.setPointSize (MR::File::Config::get_int ("FontSize", 10));
setFont (font_);
}
QSize Window::GLArea::minimumSizeHint () const {
return QSize (256, 256);
}
QSize Window::GLArea::sizeHint () const {
std::string init_size_string = lowercase (MR::File::Config::get ("MRViewInitWindowSize"));
std::vector<int> init_window_size;
if (init_size_string.length())
init_window_size = parse_ints(init_size_string);
if (init_window_size.size() == 2)
return QSize (init_window_size[0], init_window_size[1]);
else
return QSize (512, 512);
}
void Window::GLArea::dragEnterEvent (QDragEnterEvent* event) {
event->acceptProposedAction();
}
void Window::GLArea::dragMoveEvent (QDragMoveEvent* event) {
event->acceptProposedAction();
}
void Window::GLArea::dragLeaveEvent (QDragLeaveEvent* event) {
event->accept();
}
void Window::GLArea::dropEvent (QDropEvent* event) {
const QMimeData* mimeData = event->mimeData();
if (mimeData->hasUrls()) {
VecPtr<MR::Image::Header> list;
QList<QUrl> urlList = mimeData->urls();
for (int i = 0; i < urlList.size() && i < 32; ++i) {
try {
list.push_back (new MR::Image::Header (urlList.at (i).path().toUtf8().constData()));
}
catch (Exception& e) {
e.display();
}
}
if (list.size())
main.add_images (list);
}
}
void Window::GLArea::initializeGL () {
main.initGL();
}
void Window::GLArea::paintGL () {
main.paintGL();
}
void Window::GLArea::mousePressEvent (QMouseEvent* event) {
main.mousePressEventGL (event);
}
void Window::GLArea::mouseMoveEvent (QMouseEvent* event) {
main.mouseMoveEventGL (event);
}
void Window::GLArea::mouseReleaseEvent (QMouseEvent* event) {
main.mouseReleaseEventGL (event);
}
void Window::GLArea::wheelEvent (QWheelEvent* event) {
main.wheelEventGL (event);
}
// Main Window class:
Window::Window() :
glarea (new GLArea (*this)),
mode (NULL),
font (glarea->font()),
#ifdef MRTRIX_MACOSX
FocusModifier (get_modifier ("MRViewFocusModifierKey", Qt::AltModifier)),
#else
FocusModifier (get_modifier ("MRViewFocusModifierKey", Qt::MetaModifier)),
#endif
MoveModifier (get_modifier ("MRViewMoveModifierKey", Qt::ShiftModifier)),
RotateModifier (get_modifier ("MRViewRotateModifierKey", Qt::ControlModifier)),
mouse_action (NoAction),
orient (NAN, NAN, NAN, NAN),
field_of_view (100.0),
anatomical_plane (2),
colourbar_position_index (2),
snap_to_image_axes_and_voxel (true)
{
setDockOptions (AllowTabbedDocks);
setDocumentMode (true);
Options opt = get_options ("batch");
for (size_t n = 0; n < opt.size(); ++n) {
std::ifstream batch_file (opt[n][0].c_str());
if (!batch_file)
throw Exception ("error opening batch file \"" + opt[n][0] + "\": " + strerror (errno));
std::string command;
while (getline (batch_file, command))
batch_commands.push_back (command);
}
opt = get_options ("run");
for (size_t n = 0; n < opt.size(); ++n)
batch_commands.push_back (opt[n][0]);
setWindowTitle (tr ("MRView"));
setWindowIcon (QPixmap (":/mrtrix.png"));
{
int iconsize = MR::File::Config::get_int ("IconSize", 24);
setIconSize (QSize (iconsize, iconsize));
}
setCentralWidget (glarea);
QToolBar* toolbar;
QAction* action;
QMenu* menu;
QToolButton* button;
setTabPosition (Qt::AllDockWidgetAreas, QTabWidget::North);
// Main toolbar:
Qt::ToolBarArea toolbar_position = Qt::TopToolBarArea;
{
std::string toolbar_pos_spec = lowercase (MR::File::Config::get ("InitialToolBarPosition"));
if (toolbar_pos_spec.size()) {
if (toolbar_pos_spec == "bottom") toolbar_position = Qt::BottomToolBarArea;
else if (toolbar_pos_spec == "left") toolbar_position = Qt::LeftToolBarArea;
else if (toolbar_pos_spec == "right") toolbar_position = Qt::RightToolBarArea;
else if (toolbar_pos_spec != "top")
WARN ("invalid value for configuration entry \"InitialToolBarPosition\"");
}
}
Qt::ToolButtonStyle button_style = static_cast<Qt::ToolButtonStyle> (MR::File::Config::get_int ("ToolbarStyle", 2));
toolbar = new QToolBar ("Main toolbar", this);
addToolBar (toolbar_position, toolbar);
action = toolbar->toggleViewAction ();
action->setShortcut (tr ("Ctrl+M"));
addAction (action);
// File menu:
menu = new QMenu (tr ("File menu"), this);
action = menu->addAction (tr ("Open..."), this, SLOT (image_open_slot()));
action->setShortcut (tr ("Ctrl+O"));
addAction (action);
save_action = menu->addAction (tr ("Save..."), this, SLOT (image_save_slot()));
save_action->setShortcut (tr ("Ctrl+S"));
addAction (save_action);
close_action = menu->addAction (tr ("Close"), this, SLOT (image_close_slot()));
close_action->setShortcut (tr ("Ctrl+W"));
addAction (close_action);
menu->addSeparator();
action = menu->addAction (tr ("DICOM import..."), this, SLOT (image_import_DICOM_slot()));
action->setShortcut (tr ("Ctrl+D"));
addAction (action);
menu->addSeparator();
action = menu->addAction (tr ("Quit"), this, SLOT (close()));
action->setShortcut (tr ("Ctrl+Q"));
addAction (action);
button = new QToolButton (this);
button->setText ("File");
button->setToolButtonStyle (button_style);
button->setToolTip (tr ("File menu"));
button->setIcon (QIcon (":/start.svg"));
button->setPopupMode (QToolButton::InstantPopup);
button->setMenu (menu);
toolbar->addWidget (button);
// Image menu:
image_menu = new QMenu (tr ("Image menu"), this);
image_group = new QActionGroup (this);
image_group->setExclusive (true);
connect (image_group, SIGNAL (triggered (QAction*)), this, SLOT (image_select_slot (QAction*)));
properties_action = image_menu->addAction (tr ("Properties..."), this, SLOT (image_properties_slot()));
properties_action->setToolTip (tr ("Display the properties of the current image\n\nShortcut: Ctrl+P"));
addAction (properties_action);
image_menu->addSeparator();
next_slice_action = image_menu->addAction (tr ("Next slice"), this, SLOT (slice_next_slot()));
next_slice_action->setShortcut (tr ("Up"));
addAction (next_slice_action);
prev_slice_action = image_menu->addAction (tr ("Previous slice"), this, SLOT (slice_previous_slot()));
prev_slice_action->setShortcut (tr ("Down"));
addAction (prev_slice_action);
next_image_volume_action = image_menu->addAction (tr ("Next volume"), this, SLOT (image_next_volume_slot()));
next_image_volume_action->setShortcut (tr ("Right"));
addAction (next_image_volume_action);
prev_image_volume_action = image_menu->addAction (tr ("Previous volume"), this, SLOT (image_previous_volume_slot()));
prev_image_volume_action->setShortcut (tr ("Left"));
addAction (prev_image_volume_action);
next_image_volume_group_action = image_menu->addAction (tr ("Next volume group"), this, SLOT (image_next_volume_group_slot()));
next_image_volume_group_action->setShortcut (tr ("Shift+Right"));
addAction (next_image_volume_group_action);
prev_image_volume_group_action = image_menu->addAction (tr("Previous volume group"), this, SLOT (image_previous_volume_group_slot()));
prev_image_volume_group_action->setShortcut (tr ("Shift+Left"));
addAction (prev_image_volume_group_action);
image_menu->addSeparator();
next_image_action = image_menu->addAction (tr ("Next image"), this, SLOT (image_next_slot()));
next_image_action->setShortcut (tr ("PgDown"));
addAction (next_image_action);
prev_image_action = image_menu->addAction (tr ("Previous image"), this, SLOT (image_previous_slot()));
prev_image_action->setShortcut (tr ("PgUp"));
addAction (prev_image_action);
image_list_area = image_menu->addSeparator();
button = new QToolButton (this);
button->setText ("Image");
button->setToolButtonStyle (button_style);
button->setToolTip (tr ("Image menu"));
button->setIcon (QIcon (":/image.svg"));
button->setPopupMode (QToolButton::InstantPopup);
button->setMenu (image_menu);
toolbar->addWidget (button);
// Colourmap menu:
colourmap_menu = new QMenu (tr ("Colourmap menu"), this);
ColourMap::create_menu (this, colourmap_group, colourmap_menu, colourmap_actions, true);
connect (colourmap_group, SIGNAL (triggered (QAction*)), this, SLOT (select_colourmap_slot()));
colourmap_menu->addSeparator();
invert_scale_action = colourmap_menu->addAction (tr ("Invert"), this, SLOT (invert_scaling_slot()));
invert_scale_action->setCheckable (true);
invert_scale_action->setShortcut (tr("U"));
addAction (invert_scale_action);
colourmap_menu->addSeparator();
reset_windowing_action = colourmap_menu->addAction (tr ("Reset brightness/contrast"), this, SLOT (image_reset_slot()));
reset_windowing_action->setShortcut (tr ("Esc"));
addAction (reset_windowing_action);
image_interpolate_action = colourmap_menu->addAction (tr ("Interpolate"), this, SLOT (image_interpolate_slot()));
image_interpolate_action->setShortcut (tr ("I"));
image_interpolate_action->setCheckable (true);
image_interpolate_action->setChecked (true);
addAction (image_interpolate_action);
button = new QToolButton (this);
button->setText ("Colourmap");
button->setToolButtonStyle (button_style);
button->setToolTip (tr ("Colourmap menu"));
button->setIcon (QIcon (":/colourmap.svg"));
button->setPopupMode (QToolButton::InstantPopup);
button->setMenu (colourmap_menu);
toolbar->addWidget (button);
// Mode menu:
mode_group = new QActionGroup (this);
mode_group->setExclusive (true);
connect (mode_group, SIGNAL (triggered (QAction*)), this, SLOT (select_mode_slot (QAction*)));
menu = new QMenu ("Display mode", this);
#define MODE(classname, specifier, name, description) \
menu->addAction (new Action<classname> (mode_group, #name, #description, n++));
#define MODE_OPTION(classname, specifier, name, description) MODE(classname, specifier, name, description)
{
using namespace Mode;
size_t n = 1;
#include "gui/mrview/mode/list.h"
}
#undef MODE
#undef MODE_OPTION
mode_group->actions()[0]->setChecked (true);
for (int n = 0; n < mode_group->actions().size(); ++n)
addAction (mode_group->actions()[n]);
menu->addSeparator();
plane_group = new QActionGroup (this);
plane_group->setExclusive (true);
connect (plane_group, SIGNAL (triggered (QAction*)), this, SLOT (select_plane_slot (QAction*)));
axial_action = menu->addAction (tr ("Axial"));
axial_action->setShortcut (tr ("A"));
axial_action->setCheckable (true);
plane_group->addAction (axial_action);
addAction (axial_action);
sagittal_action = menu->addAction (tr ("Sagittal"));
sagittal_action->setShortcut (tr ("S"));
sagittal_action->setCheckable (true);
plane_group->addAction (sagittal_action);
addAction (sagittal_action);
coronal_action = menu->addAction (tr ("Coronal"));
coronal_action->setShortcut (tr ("C"));
coronal_action->setCheckable (true);
plane_group->addAction (coronal_action);
addAction (coronal_action);
menu->addSeparator();
action = menu->addAction (tr ("Toggle all annotations"), this, SLOT (toggle_annotations_slot()));
action->setShortcut (tr("Space"));
addAction (action);
show_crosshairs_action = menu->addAction (tr ("Show focus"), glarea, SLOT (updateGL()));
show_crosshairs_action->setShortcut (tr("F"));
show_crosshairs_action->setCheckable (true);
show_crosshairs_action->setChecked (true);
addAction (show_crosshairs_action);
show_comments_action = menu->addAction (tr ("Show comments"), glarea, SLOT (updateGL()));
show_comments_action->setToolTip (tr ("Show/hide image comments\n\nShortcut: H"));
show_comments_action->setShortcut (tr("H"));
show_comments_action->setCheckable (true);
show_comments_action->setChecked (true);
addAction (show_comments_action);
show_voxel_info_action = menu->addAction (tr ("Show voxel information"), glarea, SLOT (updateGL()));
show_voxel_info_action->setShortcut (tr("V"));
show_voxel_info_action->setCheckable (true);
show_voxel_info_action->setChecked (true);
addAction (show_voxel_info_action);
show_orientation_labels_action = menu->addAction (tr ("Show orientation labels"), glarea, SLOT (updateGL()));
show_orientation_labels_action->setShortcut (tr("O"));
show_orientation_labels_action->setCheckable (true);
show_orientation_labels_action->setChecked (true);
addAction (show_orientation_labels_action);
show_colourbar_action = menu->addAction (tr ("Show colour bar"), glarea, SLOT (updateGL()));
show_colourbar_action->setShortcut (tr("B"));
show_colourbar_action->setCheckable (true);
show_colourbar_action->setChecked (true);
addAction (show_colourbar_action);
menu->addSeparator();
full_screen_action = menu->addAction (tr ("Full screen"), this, SLOT (full_screen_slot()));
full_screen_action->setShortcut (tr ("F11"));
full_screen_action->setCheckable (true);
full_screen_action->setChecked (false);
addAction (full_screen_action);
action = menu->addAction (tr ("Reset view"), this, SLOT(reset_view_slot()));
action->setShortcut (tr ("R"));
addAction (action);
button = new QToolButton (this);
button->setText ("View");
button->setToolButtonStyle (button_style);
button->setToolTip (tr ("Display"));
button->setIcon (QIcon (":/mode.svg"));
button->setMenu (menu);
button->setPopupMode (QToolButton::InstantPopup);
toolbar->addWidget (button);
// Tool menu:
tool_group = new QActionGroup (this);
tool_group->setExclusive (false);
connect (tool_group, SIGNAL (triggered (QAction*)), this, SLOT (select_tool_slot (QAction*)));
menu = new QMenu (tr ("Tools"), this);
#undef TOOL
#define TOOL(classname, name, description) \
menu->addAction (new Action<Tool::classname> (tool_group, #name, #description, n++));
#define TOOL_OPTION(classname, name, description) TOOL(classname, name, description)
{
using namespace Tool;
size_t n = 1;
#include "gui/mrview/tool/list.h"
}
for (int n = 0; n < tool_group->actions().size(); ++n)
addAction (tool_group->actions()[n]);
button = new QToolButton (this);
button->setText ("Tool");
button->setToolButtonStyle (button_style);
button->setToolTip (tr ("Select additional tools..."));
button->setIcon (QIcon (":/tools.svg"));
button->setMenu (menu);
button->setPopupMode (QToolButton::InstantPopup);
toolbar->addWidget (button);
toolbar->addSeparator();
// Mouse mode actions:
mode_action_group = new QActionGroup (this);
mode_action_group->setExclusive (true);
connect (mode_action_group, SIGNAL (triggered (QAction*)), this, SLOT (select_mouse_mode_slot (QAction*)));
std::string modifier;
action = toolbar->addAction (QIcon (":/select_contrast.svg"), tr ("Change focus / contrast"));
action->setToolTip (tr ((
"Left-click: set focus\n"
"Right-click: change brightness/constrast\n\n"
"Shortcut: 1\n\n"
"Hold down " + get_modifier (FocusModifier) + " key to use this mode\n"
"regardless of currently selected mode").c_str()));
action->setShortcut (tr("1"));
action->setCheckable (true);
action->setChecked (true);
mode_action_group->addAction (action);
action = toolbar->addAction (QIcon (":/move.svg"), tr ("Move viewport"));
action->setToolTip (tr ((
"Left-click: move in-plane\n"
"Right-click: move through-plane\n\n"
"Shortcut: 2\n\n"
"Hold down " + get_modifier (MoveModifier) + " key to use this mode\n"
"regardless of currently selected mode").c_str()));
action->setShortcut (tr("2"));
action->setCheckable (true);
mode_action_group->addAction (action);
action = toolbar->addAction (QIcon (":/rotate.svg"), tr ("Move camera"));
action->setToolTip (tr ((
"Left-click: move camera in-plane\n"
"Right-click: rotate camera about view axis\n\n"
"Shortcut: 3\n\n"
"Hold down " + get_modifier (RotateModifier) + " key to use this mode\n"
"regardless of currently selected mode").c_str()));
action->setShortcut (tr("3"));
action->setCheckable (true);
mode_action_group->addAction (action);
for (int n = 0; n < mode_action_group->actions().size(); ++n)
addAction (mode_action_group->actions()[n]);
toolbar->addSeparator();
snap_to_image_action = toolbar->addAction (QIcon (":/lock.svg"),
tr ("Snap to image"), this, SLOT (snap_to_image_slot()));
snap_to_image_action->setToolTip (tr (
"Snap focus and view orientation to\n"
"image voxel grid and axes respectively\n\n"
"Shortcut: L"));
snap_to_image_action->setShortcut (tr("L"));
snap_to_image_action->setCheckable (true);
snap_to_image_action->setChecked (snap_to_image_axes_and_voxel);
addAction (snap_to_image_action);
toolbar->addSeparator();
// Help menu:
menu = new QMenu (tr ("Help"), this);
menu->addAction (tr("OpenGL"), this, SLOT (OpenGL_slot()));
menu->addAction (tr ("About"), this, SLOT (about_slot()));
menu->addAction (tr ("about Qt"), this, SLOT (aboutQt_slot()));
button = new QToolButton (this);
button->setText ("Help");
button->setToolButtonStyle (button_style);
button->setToolTip (tr ("Help"));
button->setIcon (QIcon (":/help.svg"));
button->setPopupMode (QToolButton::InstantPopup);
button->setMenu (menu);
toolbar->addWidget (button);
lighting_ = new GL::Lighting (this);
connect (lighting_, SIGNAL (changed()), glarea, SLOT (updateGL()));
set_image_menu ();
std::string cbar_pos = lowercase (MR::File::Config::get ("MRViewColourBarPosition"));
if (cbar_pos.size()) {
if (cbar_pos == "bottomleft") colourbar_position_index = 1;
else if (cbar_pos == "bottomright") colourbar_position_index = 2;
else if (cbar_pos == "topleft") colourbar_position_index = 3;
else if (cbar_pos == "topright") colourbar_position_index = 4;
else
WARN ("invalid specifier \"" + cbar_pos + "\" for config file entry \"MRViewColourBarPosition\"");
}
}
Window::~Window ()
{
mode = NULL;
delete glarea;
delete [] colourmap_actions;
}
void Window::image_open_slot ()
{
std::vector<std::string> image_list = Dialog::File::get_images (this, "Select images to open");
if (image_list.empty())
return;
VecPtr<MR::Image::Header> list;
for (size_t n = 0; n < image_list.size(); ++n) {
try {
list.push_back (new MR::Image::Header (image_list[n]));
}
catch (Exception& E) {
E.display();
}
}
add_images (list);
}
void Window::image_import_DICOM_slot ()
{
std::string folder = Dialog::File::get_folder (this, "Select DICOM folder to import");
if (folder.empty())
return;
try {
VecPtr<MR::Image::Header> list;
list.push_back (new MR::Image::Header (folder));
add_images (list);
}
catch (Exception& E) {
E.display();
}
}
void Window::add_images (VecPtr<MR::Image::Header>& list)
{
for (size_t i = 0; i < list.size(); ++i) {
QAction* action = new Image (*this, *list[i]);
image_group->addAction (action);
if (!i) image_select_slot (action);
}
set_image_menu();
}
void Window::image_save_slot ()
{
std::string image_name = Dialog::File::get_save_image_name (this, "Select image destination");
if (image_name.empty())
return;
try {
MR::Image::Buffer<cfloat> dest (image_name, image()->header());
MR::Image::Buffer<cfloat>::voxel_type vox (dest);
MR::Image::copy_with_progress (image()->voxel(), vox);
}
catch (Exception& E) {
E.display();
}
}
void Window::image_close_slot ()
{
Image* imagep = image();
assert (imagep);
QList<QAction*> list = image_group->actions();
if (list.size() > 1) {
for (int n = 0; n < list.size(); ++n) {
if (imagep == list[n]) {
image_select_slot (list[ (n+1) %list.size()]);
break;
}
}
}
image_group->removeAction (imagep);
delete imagep;
set_image_menu();
}
void Window::image_properties_slot ()
{
assert (image());
Dialog::ImageProperties props (this, image()->header());
props.exec();
}
void Window::select_mode_slot (QAction* action)
{
mode = dynamic_cast<GUI::MRView::Mode::__Action__*> (action)->create (*this);
set_mode_features();
emit modeChanged();
glarea->updateGL();
}
void Window::select_mouse_mode_slot (QAction* action)
{
set_cursor();
}
void Window::select_tool_slot (QAction* action)
{
Tool::Dock* tool = dynamic_cast<Tool::__Action__*>(action)->dock;
if (!tool) {
tool = dynamic_cast<Tool::__Action__*>(action)->create (*this);
connect (tool, SIGNAL (visibilityChanged (bool)), action, SLOT (setChecked (bool)));
for (int i = 0; i < tool_group->actions().size(); ++i) {
Tool::Dock* other_tool = dynamic_cast<Tool::__Action__*>(tool_group->actions()[i])->dock;
if (other_tool && other_tool != tool) {
QList<QDockWidget* > list = QMainWindow::tabifiedDockWidgets (other_tool);
if (list.size())
QMainWindow::tabifyDockWidget (list.last(), tool);
else
QMainWindow::tabifyDockWidget (other_tool, tool);
tool->show();
tool->raise();
return;
}
}
}
if (action->isChecked()) {
if (!tool->isVisible())
tool->show();
tool->raise();
} else {
tool->close();
}
glarea->updateGL();
}
void Window::select_colourmap_slot ()
{
Image* imagep = image();
if (imagep) {
QAction* action = colourmap_group->checkedAction();
size_t n = 0;
while (action != colourmap_actions[n])
++n;
imagep->set_colourmap (n);
glarea->updateGL();
}
}
void Window::invert_scaling_slot ()
{
if (image()) {
image()->set_invert_scale (invert_scale_action->isChecked());
glarea->updateGL();
}
}
void Window::snap_to_image_slot ()
{
if (image()) {
snap_to_image_axes_and_voxel = snap_to_image_action->isChecked();
glarea->updateGL();
}
}
void Window::on_scaling_changed ()
{
emit scalingChanged();
}
void Window::image_reset_slot ()
{
Image* imagep = image();
if (imagep) {
imagep->reset_windowing();
on_scaling_changed();
glarea->updateGL();
}
}
void Window::image_interpolate_slot ()
{
Image* imagep = image();
if (imagep) {
imagep->set_interpolate (image_interpolate_action->isChecked());
glarea->updateGL();
}
}
void Window::full_screen_slot ()
{
if (full_screen_action->isChecked())
showFullScreen();
else
showNormal();
}
void Window::select_plane_slot (QAction* action)
{
if (action == axial_action) set_plane (2);
else if (action == sagittal_action) set_plane (0);
else if (action == coronal_action) set_plane (1);
else assert (0);
glarea->updateGL();
}
void Window::reset_view_slot ()
{
if (image())
mode->reset_event();
}
void Window::slice_next_slot ()
{
mode->slice_move_event (1);
}
void Window::slice_previous_slot ()
{
mode->slice_move_event (-1);
}
void Window::image_next_slot ()
{
QAction* action = image_group->checkedAction();
int N = image_group->actions().size();
int n = image_group->actions().indexOf (action);
image_select_slot (image_group->actions()[(n+1)%N]);
}
void Window::image_previous_slot ()
{
QAction* action = image_group->checkedAction();
int N = image_group->actions().size();
int n = image_group->actions().indexOf (action);
image_select_slot (image_group->actions()[(n+N-1)%N]);
}
void Window::image_next_volume_slot ()
{
assert (image());
++image()->interp[3];
set_image_navigation_menu();
glarea->updateGL();
}
void Window::image_previous_volume_slot ()
{
assert (image());
--image()->interp[3];
set_image_navigation_menu();
glarea->updateGL();
}
void Window::image_next_volume_group_slot ()
{
assert (image());
++image()->interp[4];
set_image_navigation_menu();
glarea->updateGL();
}
void Window::image_previous_volume_group_slot ()
{
assert (image());
--image()->interp[4];
set_image_navigation_menu();
glarea->updateGL();
}
void Window::image_select_slot (QAction* action)
{
action->setChecked (true);
image_interpolate_action->setChecked (image()->interpolate());
size_t cmap_index = image()->colourmap;
colourmap_group->actions()[cmap_index]->setChecked (true);
invert_scale_action->setChecked (image()->scale_inverted());
setWindowTitle (image()->interp.name().c_str());
set_image_navigation_menu();
image()->set_allowed_features (
mode->features & Mode::ShaderThreshold,
mode->features & Mode::ShaderTransparency,
mode->features & Mode::ShaderLighting);
emit imageChanged();
glarea->updateGL();
}
void Window::toggle_annotations_slot ()
{
int current_annotations = 0x00000000;
if (show_crosshairs()) current_annotations |= 0x00000001;
if (show_comments()) current_annotations |= 0x00000002;
if (show_voxel_info()) current_annotations |= 0x00000004;
if (show_orientation_labels()) current_annotations |= 0x00000008;
if (show_colourbar()) current_annotations |= 0x00000010;
if (current_annotations) {
annotations = current_annotations;
show_crosshairs_action->setChecked (false);
show_comments_action->setChecked (false);
show_voxel_info_action->setChecked (false);
show_orientation_labels_action->setChecked (false);
show_colourbar_action->setChecked (false);
}
else {
if (!annotations)
annotations = 0xFFFFFFFF;
show_crosshairs_action->setChecked (annotations & 0x00000001);
show_comments_action->setChecked (annotations & 0x00000002);
show_voxel_info_action->setChecked (annotations & 0x00000004);
show_orientation_labels_action->setChecked (annotations & 0x00000008);
show_colourbar_action->setChecked (annotations & 0x00000010);
}
glarea->updateGL();
}
inline void Window::set_image_menu ()
{
int N = image_group->actions().size();
next_image_action->setEnabled (N>1);
prev_image_action->setEnabled (N>1);
reset_windowing_action->setEnabled (N>0);
colourmap_menu->setEnabled (N>0);
save_action->setEnabled (N>0);
close_action->setEnabled (N>0);
properties_action->setEnabled (N>0);
set_image_navigation_menu();
glarea->updateGL();
}
inline int Window::get_mouse_mode ()
{
if (mouse_action == NoAction && modifiers_ != Qt::NoModifier) {
if (modifiers_ == FocusModifier && ( mode->features & Mode::FocusContrast ))
return 1;
else if (modifiers_ == MoveModifier && ( mode->features & Mode::MoveTarget ))
return 2;
else if (modifiers_ == RotateModifier && ( mode->features & Mode::TiltRotate ))
return 3;
}
if (mouse_action == NoAction)
return mode_action_group->actions().indexOf (mode_action_group->checkedAction()) + 1;
return 0;
}
inline void Window::set_cursor ()
{
MouseAction cursor = mouse_action;
if (cursor == NoAction) {
switch (get_mouse_mode()) {
case 1: cursor = SetFocus; break;
case 2: cursor = Pan; break;
case 3: cursor = Tilt; break;
default: assert (0);
}
}
switch (cursor) {
case SetFocus: glarea->setCursor (Cursor::crosshair); break;
case Contrast: glarea->setCursor (Cursor::window); break;
case Pan: glarea->setCursor (Cursor::pan_crosshair); break;
case PanThrough: glarea->setCursor (Cursor::forward_backward); break;
case Tilt: glarea->setCursor (Cursor::throughplane_rotate); break;
case Rotate: glarea->setCursor (Cursor::inplane_rotate); break;
default: assert (0);
}
}
inline void Window::set_mode_features ()
{
mode_action_group->actions()[0]->setEnabled (mode->features & Mode::FocusContrast);
mode_action_group->actions()[1]->setEnabled (mode->features & Mode::MoveTarget);
mode_action_group->actions()[2]->setEnabled (mode->features & Mode::TiltRotate);
if (!mode_action_group->checkedAction()->isEnabled())
mode_action_group->actions()[0]->setChecked (true);
if (image())
image()->set_allowed_features (
mode->features & Mode::ShaderThreshold,
mode->features & Mode::ShaderTransparency,
mode->features & Mode::ShaderLighting);
}
inline void Window::set_image_navigation_menu ()
{
bool show_next_volume (false), show_prev_volume (false);
bool show_next_volume_group (false), show_prev_volume_group (false);
Image* imagep = image();
if (imagep) {
if (imagep->interp.ndim() > 3) {
if (imagep->interp[3] > 0)
show_prev_volume = true;
if (imagep->interp[3] < imagep->interp.dim(3)-1)
show_next_volume = true;
if (imagep->interp.ndim() > 4) {
if (imagep->interp[4] > 0)
show_prev_volume_group = true;
if (imagep->interp[4] < imagep->interp.dim(4)-1)
show_next_volume_group = true;
}
}
}
prev_image_volume_action->setEnabled (show_prev_volume);
next_image_volume_action->setEnabled (show_next_volume);
prev_image_volume_group_action->setEnabled (show_prev_volume_group);
next_image_volume_group_action->setEnabled (show_next_volume_group);
}
void Window::OpenGL_slot ()
{
Dialog::OpenGL gl (this, glarea->format());
gl.exec();
}
void Window::about_slot ()
{
std::string message =
"<h1>MRView</h1>The MRtrix viewer, version " MRTRIX_GIT_VERSION "<br>"
"<em>" + str (8*sizeof (size_t)) + " bit "
#ifdef NDEBUG
"release"
#else
"debug"
#endif
" version, built " + App::build_date + "</em><p>"
"<h4>Authors:</h4>" + MR::join (MR::split (App::AUTHOR, ",;&\n", true), "<br>") +
"<p><em>" + App::COPYRIGHT + "</em>";
QMessageBox::about (this, tr ("About MRView"), message.c_str());
}
void Window::aboutQt_slot ()
{
QMessageBox::aboutQt (this);
}
inline void Window::paintGL ()
{
gl::Enable (gl::MULTISAMPLE);
if (mode->in_paint())
return;
gl::DrawBuffer (gl::BACK);
mode->paintGL();
}
inline void Window::initGL ()
{
GL::init ();
font.initGL();
gl::ClearColor (0.0, 0.0, 0.0, 0.0);
gl::Enable (gl::DEPTH_TEST);
mode = dynamic_cast<Mode::__Action__*> (mode_group->actions()[0])->create (*this);
set_mode_features();
if (batch_commands.size())
QTimer::singleShot (0, this, SLOT (process_batch_command()));
}
template <class Event> inline void Window::grab_mouse_state (Event* event)
{
buttons_ = event->buttons();
modifiers_ = event->modifiers() & ( FocusModifier | MoveModifier | RotateModifier );
mouse_displacement_ = QPoint (0,0);
mouse_position_ = event->pos();
mouse_position_.setY (glarea->height() - mouse_position_.y());
}
template <class Event> inline void Window::update_mouse_state (Event* event)
{
mouse_displacement_ = mouse_position_;
mouse_position_ = event->pos();
mouse_position_.setY (glarea->height() - mouse_position_.y());
mouse_displacement_ = mouse_position_ - mouse_displacement_;
}
void Window::keyPressEvent (QKeyEvent* event)
{
modifiers_ = event->modifiers() & ( FocusModifier | MoveModifier | RotateModifier );
set_cursor();
}
void Window::keyReleaseEvent (QKeyEvent* event)
{
modifiers_ = event->modifiers() & ( FocusModifier | MoveModifier | RotateModifier );
set_cursor();
}
inline void Window::mousePressEventGL (QMouseEvent* event)
{
assert (mode);
grab_mouse_state (event);
if (image())
mode->mouse_press_event();
int group = get_mouse_mode();
if (buttons_ == Qt::MidButton)
mouse_action = Pan;
else if (group == 1) {
if (buttons_ == Qt::LeftButton) {
mouse_action = SetFocus;
if (image())
mode->set_focus_event();
}
else if (buttons_ == Qt::RightButton)
mouse_action = Contrast;
}
else if (group == 2) {
if (buttons_ == Qt::LeftButton)
mouse_action = Pan;
else if (buttons_ == Qt::RightButton)
mouse_action = PanThrough;
}
else if (group == 3) {
if (buttons_ == Qt::LeftButton)
mouse_action = Tilt;
else if (buttons_ == Qt::RightButton)
mouse_action = Rotate;
}
set_cursor();
event->accept();
}
inline void Window::mouseMoveEventGL (QMouseEvent* event)
{
assert (mode);
if (mouse_action == NoAction)
return;
if (!image())
return;
update_mouse_state (event);
switch (mouse_action) {
case SetFocus: mode->set_focus_event(); break;
case Contrast: mode->contrast_event(); break;
case Pan: mode->pan_event(); break;
case PanThrough: mode->panthrough_event(); break;
case Tilt: mode->tilt_event(); break;
case Rotate: mode->rotate_event(); break;
default: return;
}
event->accept();
}
inline void Window::mouseReleaseEventGL (QMouseEvent* event)
{
assert (mode);
mode->mouse_release_event();
mouse_action = NoAction;
set_cursor();
}
inline void Window::wheelEventGL (QWheelEvent* event)
{
assert (mode);
if (event->orientation() == Qt::Vertical) {
if (image()) {
grab_mouse_state (event);
mode->mouse_press_event();
if (buttons_ == Qt::NoButton) {
if (modifiers_ == Qt::ControlModifier) {
set_FOV (FOV() * Math::exp (-event->delta()/1200.0));
glarea->updateGL();
event->accept();
return;
}
int delta = event->delta() / 120.0;
if (modifiers_ == Qt::ShiftModifier) delta *= 10.0;
else if (modifiers_ != Qt::NoModifier)
return;
mode->slice_move_event (delta);
event->accept();
return;
}
}
if (buttons_ == Qt::LeftButton && modifiers_ == Qt::NoModifier) {
int current = 0, num = 0;
for (int i = 0; i < mode_action_group->actions().size(); ++i) {
if (mode_action_group->actions()[current] != mode_action_group->checkedAction())
current = num;
if (mode_action_group->actions()[i]->isEnabled())
++num;
}
current = (current + num - int(event->delta()/120.0)) % num;
num = 0;
for (int i = 0; i < mode_action_group->actions().size(); ++i) {
if (mode_action_group->actions()[i]->isEnabled()) {
if (current == num) {
mode_action_group->actions()[i]->setChecked (true);
break;
}
++num;
}
}
mouse_action = NoAction;
set_cursor();
return;
}
if (buttons_ == Qt::RightButton && modifiers_ == Qt::NoModifier) {
if (image_group->actions().size() > 1) {
QAction* action = image_group->checkedAction();
int N = image_group->actions().size();
int n = image_group->actions().indexOf (action);
image_select_slot (image_group->actions()[(n+N+int(event->delta()/120.0))%N]);
}
}
}
}
void Window::closeEvent (QCloseEvent* event)
{
qApp->quit();
event->accept();
}
void Window::process_batch_command ()
{
assert (batch_commands.size());
try {
std::string line;
do {
if (batch_commands.empty())
return;
line = batch_commands[0];
batch_commands.erase (batch_commands.begin(), batch_commands.begin()+1);
line = strip (line.substr (0, line.find_first_of ('#')));
} while (line.empty());
std::string cmd = line.substr (0, line.find_first_of (" :\t"));
std::string args;
if (line.size() > cmd.size()+1)
args = strip (line.substr (cmd.size()+1));
// starts of commands proper:
// BATCH_COMMAND view.mode index # Switch to view mode specified by the integer index. as per the view menu.
if (cmd == "view.mode") {
int n = to<int> (args) - 1;
if (n < 0 || n >= mode_group->actions().size())
throw Exception ("invalid mode index \"" + args + "\" in batch command");
select_mode_slot (mode_group->actions()[n]);
}
// BATCH_COMMAND view.size width,height # Set the size of the view area, in pixel units.
else if (cmd == "view.size") {
std::vector<int> glsize = parse_ints (args);
if (glsize.size() != 2)
throw Exception ("invalid argument \"" + args + "\" to view.size batch command");
QSize oldsize = glarea->size();
QSize winsize = size();
resize (winsize.width() - oldsize.width() + glsize[0], winsize.height() - oldsize.height() + glsize[1]);
}
// BATCH_COMMAND view.reset # Reset the view according to current image. This resets the FOV, projection, and focus.
else if (cmd == "view.reset")
reset_view_slot();
// BATCH_COMMAND view.fov num # Set the field of view, in mm.
else if (cmd == "view.fov") {
float fov = to<float> (args);
set_FOV (fov);
glarea->updateGL();
}
// BATCH_COMMAND view.focus x,y,z # Set the position of the crosshairs in scanner coordinates, with the new position supplied as a comma-separated list of floating-point values.
else if (cmd == "view.focus") {
std::vector<float> pos = parse_floats (args);
if (pos.size() != 3)
throw Exception ("batch command \"" + cmd + "\" expects a comma-separated list of 3 floating-point values");
set_focus (Point<> (pos[0], pos[1], pos[2]));
glarea->updateGL();
}
// BATCH_COMMAND view.voxel x,y,z # Set the position of the crosshairs in voxel coordinates, relative the image currently displayed. The new position should be supplied as a comma-separated list of floating-point values.
else if (cmd == "view.voxel") {
if (image()) {
std::vector<float> pos = parse_floats (args);
if (pos.size() != 3)
throw Exception ("batch command \"" + cmd + "\" expects a comma-separated list of 3 floating-point values");
set_focus (image()->interp.voxel2scanner (Point<> (pos[0], pos[1], pos[2])));
glarea->updateGL();
}
}
// BATCH_COMMAND view.fov num # Set the field of view, in mm.
else if (cmd == "view.fov") {
float fov = to<float> (args);
set_FOV (fov);
glarea->updateGL();
}
// BATCH_COMMAND view.plane num # Set the viewing plane, according to the mappping 0: sagittal; 1: coronal; 2: axial.
else if (cmd == "view.plane") {
int n = to<int> (args);
set_plane (n);
glarea->updateGL();
}
// BATCH_COMMAND view.lock # Set whether view is locked to image axes (0: no, 1: yes).
else if (cmd == "view.lock") {
bool n = to<bool> (args);
snap_to_image_action->setChecked (n);
snap_to_image_slot();
}
// BATCH_COMMAND image.select index # Switch to image number specified, with reference to the list of currently loaded images.
else if (cmd == "image.select") {
int n = to<int> (args) - 1;
if (n < 0 || n >= image_group->actions().size())
throw Exception ("invalid image index requested in batch command");
image_select_slot (image_group->actions()[n]);
}
// BATCH_COMMAND image.load path # Load image specified and make it current.
else if (cmd == "image.load") {
VecPtr<MR::Image::Header> list;
try { list.push_back (new MR::Image::Header (args)); }
catch (Exception& e) { e.display(); }
add_images (list);
}
// BATCH_COMMAND image.reset # Reset the image scaling.
else if (cmd == "image.reset")
image_reset_slot();
// BATCH_COMMAND image.colourmap index # Switch the image colourmap to that specified, as per the colourmap menu.
else if (cmd == "image.colourmap") {
int n = to<int> (args) - 1;
if (n < 0 || n >= colourmap_group->actions().size())
throw Exception ("invalid image colourmap index \"" + args + "\" requested in batch command");
colourmap_group->actions()[n]->setChecked (true);
select_colourmap_slot ();
}
// BATCH_COMMAND image.range min max # Set the image intensity range to that specified
else if (cmd == "image.range") {
if (image()) {
std::vector<std::string> param = split (args);
if (param.size() != 2)
throw Exception ("batch command image.range expects two arguments");
image()->set_windowing (to<float> (param[0]), to<float> (param[1]));
updateGL();
}
}
// BATCH_COMMAND tool.open index # Start the tool specified, indexed as per the tool menu
else if (cmd == "tool.open") {
int n = to<int> (args) - 1;
if (n < 0 || n >= tool_group->actions().size())
throw Exception ("invalid tool index \"" + args + "\" requested in batch command");
tool_group->actions()[n]->setChecked (true);
select_tool_slot (tool_group->actions()[n]);
}
// BATCH_COMMAND window.position x,y # Set the position of the main window, in pixel units.
else if (cmd == "window.position") {
std::vector<int> pos = parse_ints (args);
if (pos.size() != 2)
throw Exception ("invalid argument \"" + args + "\" to view.position batch command");
move (pos[0], pos[1]);
}
// BATCH_COMMAND window.fullscreen # Show fullscreen or windowed (0: windowed, 1: fullscreen).
else if (cmd == "window.fullscreen") {
bool n = to<bool> (args);
full_screen_action->setChecked (n);
full_screen_slot();
}
// BATCH_COMMAND exit # quit MRView.
else if (cmd == "exit")
qApp->quit();
else { // process by tool
int n = 0;
while (n < tools()->actions().size()) {
Tool::Dock* dock = dynamic_cast<Tool::__Action__*>(tools()->actions()[n])->dock;
if (dock)
if (dock->tool->process_batch_command (cmd, args))
break;
++n;
}
if (n >= tools()->actions().size())
WARN ("batch command \"" + cmd + "\" unclaimed by main window or any active tool - ignored");
}
// end of commands
}
catch (Exception& E) {
E.display();
qApp->quit();
}
if (batch_commands.size())
QTimer::singleShot (0, this, SLOT (process_batch_command()));
}
}
}
}
|
/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "jstreamsconfig.h"
#include "streamindexer.h"
#include "fileinputstream.h"
#include "streamendanalyzer.h"
#include "streamthroughanalyzer.h"
#include "bz2endanalyzer.h"
#include "textendanalyzer.h"
#include "saxendanalyzer.h"
#include "tarendanalyzer.h"
#include "zipendanalyzer.h"
#include "pngendanalyzer.h"
#include "gzipendanalyzer.h"
#include "mailendanalyzer.h"
#include "digestthroughanalyzer.h"
#include "pluginthroughanalyzer.h"
#include "pluginendanalyzer.h"
#include "indexwriter.h"
#include <sys/stat.h>
using namespace std;
using namespace jstreams;
StreamIndexer::StreamIndexer(IndexWriter* w) :writer(w) {
moduleLoader.loadPlugins("/usr/local/lib/strigi");
moduleLoader.loadPlugins("/usr/lib/strigi");
moduleLoader.loadPlugins("/lib/strigi");
// todo: remove this
moduleLoader.loadPlugins("D:\\clients\\strigi_svn\\win\\out\\Debug");
if ( getenv("HOME") != NULL ){
string homedir = getenv("HOME");
homedir += "/testinstall/lib/strigi";
moduleLoader.loadPlugins(homedir.c_str());
}
}
StreamIndexer::~StreamIndexer() {
// delete the through analyzers and end analyzers
std::vector<std::vector<StreamThroughAnalyzer*> >::iterator tIter;
for (tIter = through.begin(); tIter != through.end(); ++tIter) {
std::vector<StreamThroughAnalyzer*>::iterator t;
for (t = tIter->begin(); t != tIter->end(); ++t) {
delete *t;
}
}
std::vector<std::vector<StreamEndAnalyzer*> >::iterator eIter;
for (eIter = end.begin(); eIter != end.end(); ++eIter) {
std::vector<StreamEndAnalyzer*>::iterator e;
for (e = eIter->begin(); e != eIter->end(); ++e) {
delete *e;
}
}
}
char
StreamIndexer::indexFile(const char *filepath) {
std::string path(filepath);
return indexFile(path);
}
char
StreamIndexer::indexFile(const std::string& filepath) {
struct stat s;
stat(filepath.c_str(), &s);
FileInputStream file(filepath.c_str());
// ensure a decent buffer size
//file.mark(65530);
return analyze(filepath, s.st_mtime, &file, 0);
}
void
StreamIndexer::addThroughAnalyzers() {
through.resize(through.size()+1);
std::vector<std::vector<StreamThroughAnalyzer*> >::reverse_iterator tIter;
tIter = through.rbegin();
StreamThroughAnalyzer* ana = new DigestThroughAnalyzer();
tIter->push_back(ana);
ana = new PluginThroughAnalyzer(&moduleLoader);
tIter->push_back(ana);
}
void
StreamIndexer::addEndAnalyzers() {
end.resize(end.size()+1);
std::vector<std::vector<StreamEndAnalyzer*> >::reverse_iterator eIter;
eIter = end.rbegin();
StreamEndAnalyzer* ana = new BZ2EndAnalyzer();
eIter->push_back(ana);
ana = new GZipEndAnalyzer();
eIter->push_back(ana);
ana = new TarEndAnalyzer();
eIter->push_back(ana);
ana = new MailEndAnalyzer();
eIter->push_back(ana);
ana = new ZipEndAnalyzer();
eIter->push_back(ana);
ana = new PngEndAnalyzer();
eIter->push_back(ana);
ana = new PluginEndAnalyzer(&moduleLoader);
eIter->push_back(ana);
/* ana = new PdfEndAnalyzer();
eIter->push_back(ana);*/
// add a sax analyzer before the text analyzer
//ana = new SaxEndAnalyzer();
//eIter->push_back(ana);
// add a text analyzer to the end of the queue
ana = new TextEndAnalyzer();
eIter->push_back(ana);
}
char
StreamIndexer::analyze(const std::string &path, time_t mtime,
InputStream *input, uint depth) {
static int count = 1;
if (++count % 1000 == 0) {
printf("file #%i: %s\n", count, path.c_str());
}
//printf("depth #%i: %s\n", depth, path.c_str());
Indexable idx(path, mtime, writer, depth);
// retrieve or construct the through analyzers and end analyzers
std::vector<std::vector<StreamThroughAnalyzer*> >::iterator tIter;
std::vector<std::vector<StreamEndAnalyzer*> >::iterator eIter;
while (through.size() < depth+1) {
addThroughAnalyzers();
addEndAnalyzers();
}
tIter = through.begin() + depth;
eIter = end.begin() + depth;
// insert the through analyzers
std::vector<StreamThroughAnalyzer*>::iterator ts;
for (ts = tIter->begin(); ts != tIter->end(); ++ts) {
(*ts)->setIndexable(&idx);
input = (*ts)->connectInputStream(input);
}
bool finished = false;
int32_t headersize = 1024;
const char* header;
headersize = input->read(header, headersize, 0);
if (input->reset(0) != 0) {
printf("resetting is impossible!! pos: %lli status: %i\n",
input->getPosition(), input->getStatus());
}
if (headersize < 0) finished = true;
int es = 0, size = eIter->size();
while (!finished && es != size) {
StreamEndAnalyzer* sea = (*eIter)[es];
if (sea->checkHeader(header, headersize)) {
char ar = sea->analyze(path, input, depth+1, this, &idx);
if (ar) {
int64_t pos = input->reset(0);
if (pos != 0) { // could not reset
printf("could not reset stream of %s from pos %lli to 0 "
"after reading with %s: %s\n", path.c_str(),
input->getPosition(), sea->getName(),
sea->getError().c_str());
removeIndexable(depth);
return -2;
}
} else {
finished = true;
}
eIter = end.begin() + depth;
}
es++;
}
// make sure the entire stream as read
int64_t nskipped;
do {
nskipped = input->skip(1000000);
} while (input->getStatus() == Ok);
if (input->getStatus() == Error) {
printf("Error: %s\n", input->getError());
removeIndexable(depth);
return -2;
}
// store the size of the stream
{
//tmp scope out tmp mem
char tmp[100];
sprintf(tmp, "%d", input->getSize());
idx.setField("size", tmp);
}
// remove references to the indexable before it goes out of scope
removeIndexable(depth);
return 0;
}
void
StreamIndexer::removeIndexable(uint depth) {
std::vector<std::vector<StreamThroughAnalyzer*> >::iterator tIter;
std::vector<StreamThroughAnalyzer*>::iterator ts;
tIter = through.begin() + depth;
for (ts = tIter->begin(); ts != tIter->end(); ++ts) {
// remove references to the indexable before it goes out of scope
(*ts)->setIndexable(0);
}
}
Add support for ar archives which means debian .deb packages can now also be indexed.
svn path=/trunk/playground/base/strigi/; revision=571428
/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "jstreamsconfig.h"
#include "streamindexer.h"
#include "fileinputstream.h"
#include "streamendanalyzer.h"
#include "streamthroughanalyzer.h"
#include "bz2endanalyzer.h"
#include "textendanalyzer.h"
#include "saxendanalyzer.h"
#include "tarendanalyzer.h"
#include "arendanalyzer.h"
#include "zipendanalyzer.h"
#include "pngendanalyzer.h"
#include "gzipendanalyzer.h"
#include "mailendanalyzer.h"
#include "digestthroughanalyzer.h"
#include "pluginthroughanalyzer.h"
#include "pluginendanalyzer.h"
#include "indexwriter.h"
#include <sys/stat.h>
using namespace std;
using namespace jstreams;
StreamIndexer::StreamIndexer(IndexWriter* w) :writer(w) {
moduleLoader.loadPlugins("/usr/local/lib/strigi");
moduleLoader.loadPlugins("/usr/lib/strigi");
moduleLoader.loadPlugins("/lib/strigi");
// todo: remove this
moduleLoader.loadPlugins("D:\\clients\\strigi_svn\\win\\out\\Debug");
if ( getenv("HOME") != NULL ){
string homedir = getenv("HOME");
homedir += "/testinstall/lib/strigi";
moduleLoader.loadPlugins(homedir.c_str());
}
}
StreamIndexer::~StreamIndexer() {
// delete the through analyzers and end analyzers
std::vector<std::vector<StreamThroughAnalyzer*> >::iterator tIter;
for (tIter = through.begin(); tIter != through.end(); ++tIter) {
std::vector<StreamThroughAnalyzer*>::iterator t;
for (t = tIter->begin(); t != tIter->end(); ++t) {
delete *t;
}
}
std::vector<std::vector<StreamEndAnalyzer*> >::iterator eIter;
for (eIter = end.begin(); eIter != end.end(); ++eIter) {
std::vector<StreamEndAnalyzer*>::iterator e;
for (e = eIter->begin(); e != eIter->end(); ++e) {
delete *e;
}
}
}
char
StreamIndexer::indexFile(const char *filepath) {
std::string path(filepath);
return indexFile(path);
}
char
StreamIndexer::indexFile(const std::string& filepath) {
struct stat s;
stat(filepath.c_str(), &s);
FileInputStream file(filepath.c_str());
// ensure a decent buffer size
//file.mark(65530);
return analyze(filepath, s.st_mtime, &file, 0);
}
void
StreamIndexer::addThroughAnalyzers() {
through.resize(through.size()+1);
std::vector<std::vector<StreamThroughAnalyzer*> >::reverse_iterator tIter;
tIter = through.rbegin();
StreamThroughAnalyzer* ana = new DigestThroughAnalyzer();
tIter->push_back(ana);
ana = new PluginThroughAnalyzer(&moduleLoader);
tIter->push_back(ana);
}
void
StreamIndexer::addEndAnalyzers() {
end.resize(end.size()+1);
std::vector<std::vector<StreamEndAnalyzer*> >::reverse_iterator eIter;
eIter = end.rbegin();
StreamEndAnalyzer* ana = new BZ2EndAnalyzer();
eIter->push_back(ana);
ana = new GZipEndAnalyzer();
eIter->push_back(ana);
ana = new TarEndAnalyzer();
eIter->push_back(ana);
ana = new ArEndAnalyzer();
eIter->push_back(ana);
ana = new MailEndAnalyzer();
eIter->push_back(ana);
ana = new ZipEndAnalyzer();
eIter->push_back(ana);
ana = new PngEndAnalyzer();
eIter->push_back(ana);
ana = new PluginEndAnalyzer(&moduleLoader);
eIter->push_back(ana);
/* ana = new PdfEndAnalyzer();
eIter->push_back(ana);*/
// add a sax analyzer before the text analyzer
//ana = new SaxEndAnalyzer();
//eIter->push_back(ana);
// add a text analyzer to the end of the queue
ana = new TextEndAnalyzer();
eIter->push_back(ana);
}
char
StreamIndexer::analyze(const std::string &path, time_t mtime,
InputStream *input, uint depth) {
static int count = 1;
if (++count % 1000 == 0) {
printf("file #%i: %s\n", count, path.c_str());
}
//printf("depth #%i: %s\n", depth, path.c_str());
Indexable idx(path, mtime, writer, depth);
// retrieve or construct the through analyzers and end analyzers
std::vector<std::vector<StreamThroughAnalyzer*> >::iterator tIter;
std::vector<std::vector<StreamEndAnalyzer*> >::iterator eIter;
while (through.size() < depth+1) {
addThroughAnalyzers();
addEndAnalyzers();
}
tIter = through.begin() + depth;
eIter = end.begin() + depth;
// insert the through analyzers
std::vector<StreamThroughAnalyzer*>::iterator ts;
for (ts = tIter->begin(); ts != tIter->end(); ++ts) {
(*ts)->setIndexable(&idx);
input = (*ts)->connectInputStream(input);
}
bool finished = false;
int32_t headersize = 1024;
const char* header;
headersize = input->read(header, headersize, 0);
if (input->reset(0) != 0) {
printf("resetting is impossible!! pos: %lli status: %i\n",
input->getPosition(), input->getStatus());
}
if (headersize < 0) finished = true;
int es = 0, size = eIter->size();
while (!finished && es != size) {
StreamEndAnalyzer* sea = (*eIter)[es];
if (sea->checkHeader(header, headersize)) {
char ar = sea->analyze(path, input, depth+1, this, &idx);
if (ar) {
int64_t pos = input->reset(0);
if (pos != 0) { // could not reset
printf("could not reset stream of %s from pos %lli to 0 "
"after reading with %s: %s\n", path.c_str(),
input->getPosition(), sea->getName(),
sea->getError().c_str());
removeIndexable(depth);
return -2;
}
} else {
finished = true;
}
eIter = end.begin() + depth;
}
es++;
}
// make sure the entire stream as read
int64_t nskipped;
do {
nskipped = input->skip(1000000);
} while (input->getStatus() == Ok);
if (input->getStatus() == Error) {
printf("Error: %s\n", input->getError());
removeIndexable(depth);
return -2;
}
// store the size of the stream
{
//tmp scope out tmp mem
char tmp[100];
sprintf(tmp, "%d", input->getSize());
idx.setField("size", tmp);
}
// remove references to the indexable before it goes out of scope
removeIndexable(depth);
return 0;
}
void
StreamIndexer::removeIndexable(uint depth) {
std::vector<std::vector<StreamThroughAnalyzer*> >::iterator tIter;
std::vector<StreamThroughAnalyzer*>::iterator ts;
tIter = through.begin() + depth;
for (ts = tIter->begin(); ts != tIter->end(); ++ts) {
// remove references to the indexable before it goes out of scope
(*ts)->setIndexable(0);
}
}
|
// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/util/util.hpp>
#include <nix/hdf5/SectionHDF5.hpp>
#include <nix/hdf5/PropertyHDF5.hpp>
using namespace std;
namespace nix {
namespace hdf5 {
SectionHDF5::SectionHDF5(const SectionHDF5 §ion)
: NamedEntityHDF5(section.file(), section.group(), section.id(), section.type(), section.name())
{
property_group = section.property_group;
section_group = section.section_group;
}
SectionHDF5::SectionHDF5(const File &file, const Group &group, const string &id,
const string &type, const string &name)
: SectionHDF5(file, nullptr, group, id, type, name)
{
}
SectionHDF5::SectionHDF5(const File &file, const Section &parent, const Group &group,
const string &id, const string &type, const string &name)
: SectionHDF5(file, parent, group, id, type, name, util::getTime())
{
}
SectionHDF5::SectionHDF5(const File &file, const Group &group, const string &id,
const string &type, const string &name, time_t time)
: SectionHDF5(file, nullptr, group, id, type, name, time)
{
}
SectionHDF5::SectionHDF5(const File &file, const Section &parent, const Group &group,
const string &id, const string &type, const string &name, time_t time)
: NamedEntityHDF5(file, group, id, type, name, time), parent_section(parent)
{
property_group = this->group().openGroup("properties");
section_group = this->group().openGroup("sections");
}
//--------------------------------------------------
// Attribute getter and setter
//--------------------------------------------------
void SectionHDF5::repository(const string &repository) {
if(repository.empty()) {
throw EmptyString("repository");
} else {
group().setAttr("repository", repository);
forceUpdatedAt();
}
}
boost::optional<string> SectionHDF5::repository() const {
boost::optional<string> ret;
string repository;
if(group().getAttr("repository", repository)) {
ret = repository;
}
return ret;
}
void SectionHDF5::repository(const none_t t) {
if(group().hasAttr("repository")) {
group().removeAttr("repository");
}
forceUpdatedAt();
}
void SectionHDF5::link(const std::string &id) {
if(id.empty()) {
throw EmptyString("mapping");
} else if (file().hasSection(id)) {
group().setAttr("link", id);
} else {
throw std::runtime_error("Section not found in file!");
}
}
Section SectionHDF5::link() const {
string id;
group().getAttr("link", id);
vector<Section> found;
if (id != "") {
auto filter = [&](const Section &s) {
return id == s.id();
};
found = file().findSections(filter);
}
if (found.size() > 0)
return found[0];
else
return Section();
}
void SectionHDF5::link(const none_t t) {
if(group().hasAttr("link")) {
group().removeAttr("link");
}
forceUpdatedAt();
}
void SectionHDF5::mapping(const string &mapping) {
if(mapping.empty()) {
throw EmptyString("mapping");
} else {
group().setAttr("mapping", mapping);
forceUpdatedAt();
}
}
boost::optional<string> SectionHDF5::mapping() const {
boost::optional<string> ret;
string mapping;
if(group().getAttr("mapping", mapping)) {
ret = mapping;
}
return ret;
}
void SectionHDF5::mapping(const none_t t) {
if(group().hasAttr("mapping")) {
group().removeAttr("mapping");
}
forceUpdatedAt();
}
//--------------------------------------------------
// Methods for parent access
//--------------------------------------------------
Section SectionHDF5::parent() const {
return parent_section;
}
//--------------------------------------------------
// Methods for child section access
//--------------------------------------------------
size_t SectionHDF5::sectionCount() const {
return section_group.objectCount();
}
bool SectionHDF5::hasSection(const string &id) const {
return section_group.hasGroup(id);
}
Section SectionHDF5::getSection(const string &id) const {
if (section_group.hasGroup(id)) {
Group group = section_group.openGroup(id, false);
std::string type;
std::string name;
group.getAttr("type", type);
group.getAttr("name", name);
Section parent(const_pointer_cast<SectionHDF5>(shared_from_this()));
auto tmp = make_shared<SectionHDF5>(file(), parent, group, id, type, name);
return Section(tmp);
} else {
return Section();
}
}
Section SectionHDF5::getSection(size_t index) const {
string id = section_group.objectName(index);
return getSection(id);
}
Section SectionHDF5::createSection(const string &name, const string &type) {
string new_id = util::createId("section");
while (section_group.hasObject(new_id)) {
new_id = util::createId("section");
}
Section parent(const_pointer_cast<SectionHDF5>(shared_from_this()));
Group grp = section_group.openGroup(new_id, true);
auto tmp = make_shared<SectionHDF5>(file(), parent, grp, new_id, type, name);
return Section(tmp);
}
bool SectionHDF5::deleteSection(const string &id) {
if (section_group.hasGroup(id)) {
section_group.removeGroup(id);
return true;
} else {
return false;
}
}
//--------------------------------------------------
// Methods for property access
//--------------------------------------------------
size_t SectionHDF5::propertyCount() const {
return property_group.objectCount();
}
bool SectionHDF5::hasProperty(const string &id) const {
return property_group.hasObject(id);
}
Property SectionHDF5::getProperty(const string &id) const {
if (property_group.hasData(id)) {
DataSet dset = property_group.openData(id);
string name;
dset.getAttr("name", name);
auto tmp = make_shared<PropertyHDF5>(file(), property_group, dset, id, name);
return Property(tmp);
} else {
return Property();
}
}
Property SectionHDF5::getProperty(size_t index) const {
string id = property_group.objectName(index);
return getProperty(id);
}
bool SectionHDF5::hasPropertyWithName(const string &name) const {
bool found = false;
for (size_t i = 0; i < propertyCount(); i++) {
string id = property_group.objectName(i);
DataSet dset = property_group.openData(id);
string other_name;
dset.getAttr("name", other_name);
if (other_name == name) {
found = true;
break;
}
}
return found;
}
Property SectionHDF5::getPropertyByName(const string &name) const {
Property prop;
for (size_t i = 0; i < propertyCount(); i++) {
string id = property_group.objectName(i);
DataSet dset = property_group.openData(id);
string other_name;
dset.getAttr("name", other_name);
if (other_name == name) {
string type;
dset.getAttr("type", type);
auto tmp = make_shared<PropertyHDF5>(file(), property_group, dset, id, name);
prop = Property(tmp);
break;
}
}
// return empty object if not found (since then "prop" is still empty Property)
return prop;
}
Property SectionHDF5::createProperty(const string &name, const Value & value) {
if (hasPropertyWithName(name))
throw runtime_error("Try to create a property with existing name: " + name);
string new_id = util::createId("property");
while (property_group.hasData(new_id))
new_id = util::createId("property");
NDSize size = {1};
DataType dtype = value.type();
H5::DataType fileType = DataSet::fileTypeForValue(dtype);
DataSet dataset = DataSet::create(property_group.h5Group(), new_id, fileType, size);
auto tmp = make_shared<PropertyHDF5>(file(), property_group, dataset, new_id, name);
return Property(tmp);
}
Property SectionHDF5::createProperty(const string &name, const vector<Value> &values) {
if (values.size() < 1) {
throw runtime_error("Trying to create a property without a value!");
}
Property p = createProperty(name, values[0]);
p.values(values);
return p;
}
bool SectionHDF5::deleteProperty(const string &id) {
if (property_group.hasData(id)) {
property_group.removeData(id);
return true;
} else {
return false;
}
}
SectionHDF5::~SectionHDF5() {}
} // namespace hdf5
} // namespace nix
fixed bug in SectionHDF::createProperty with single values
// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/util/util.hpp>
#include <nix/hdf5/SectionHDF5.hpp>
#include <nix/hdf5/PropertyHDF5.hpp>
using namespace std;
namespace nix {
namespace hdf5 {
SectionHDF5::SectionHDF5(const SectionHDF5 §ion)
: NamedEntityHDF5(section.file(), section.group(), section.id(), section.type(), section.name())
{
property_group = section.property_group;
section_group = section.section_group;
}
SectionHDF5::SectionHDF5(const File &file, const Group &group, const string &id,
const string &type, const string &name)
: SectionHDF5(file, nullptr, group, id, type, name)
{
}
SectionHDF5::SectionHDF5(const File &file, const Section &parent, const Group &group,
const string &id, const string &type, const string &name)
: SectionHDF5(file, parent, group, id, type, name, util::getTime())
{
}
SectionHDF5::SectionHDF5(const File &file, const Group &group, const string &id,
const string &type, const string &name, time_t time)
: SectionHDF5(file, nullptr, group, id, type, name, time)
{
}
SectionHDF5::SectionHDF5(const File &file, const Section &parent, const Group &group,
const string &id, const string &type, const string &name, time_t time)
: NamedEntityHDF5(file, group, id, type, name, time), parent_section(parent)
{
property_group = this->group().openGroup("properties");
section_group = this->group().openGroup("sections");
}
//--------------------------------------------------
// Attribute getter and setter
//--------------------------------------------------
void SectionHDF5::repository(const string &repository) {
if(repository.empty()) {
throw EmptyString("repository");
} else {
group().setAttr("repository", repository);
forceUpdatedAt();
}
}
boost::optional<string> SectionHDF5::repository() const {
boost::optional<string> ret;
string repository;
if(group().getAttr("repository", repository)) {
ret = repository;
}
return ret;
}
void SectionHDF5::repository(const none_t t) {
if(group().hasAttr("repository")) {
group().removeAttr("repository");
}
forceUpdatedAt();
}
void SectionHDF5::link(const std::string &id) {
if(id.empty()) {
throw EmptyString("mapping");
} else if (file().hasSection(id)) {
group().setAttr("link", id);
} else {
throw std::runtime_error("Section not found in file!");
}
}
Section SectionHDF5::link() const {
string id;
group().getAttr("link", id);
vector<Section> found;
if (id != "") {
auto filter = [&](const Section &s) {
return id == s.id();
};
found = file().findSections(filter);
}
if (found.size() > 0)
return found[0];
else
return Section();
}
void SectionHDF5::link(const none_t t) {
if(group().hasAttr("link")) {
group().removeAttr("link");
}
forceUpdatedAt();
}
void SectionHDF5::mapping(const string &mapping) {
if(mapping.empty()) {
throw EmptyString("mapping");
} else {
group().setAttr("mapping", mapping);
forceUpdatedAt();
}
}
boost::optional<string> SectionHDF5::mapping() const {
boost::optional<string> ret;
string mapping;
if(group().getAttr("mapping", mapping)) {
ret = mapping;
}
return ret;
}
void SectionHDF5::mapping(const none_t t) {
if(group().hasAttr("mapping")) {
group().removeAttr("mapping");
}
forceUpdatedAt();
}
//--------------------------------------------------
// Methods for parent access
//--------------------------------------------------
Section SectionHDF5::parent() const {
return parent_section;
}
//--------------------------------------------------
// Methods for child section access
//--------------------------------------------------
size_t SectionHDF5::sectionCount() const {
return section_group.objectCount();
}
bool SectionHDF5::hasSection(const string &id) const {
return section_group.hasGroup(id);
}
Section SectionHDF5::getSection(const string &id) const {
if (section_group.hasGroup(id)) {
Group group = section_group.openGroup(id, false);
std::string type;
std::string name;
group.getAttr("type", type);
group.getAttr("name", name);
Section parent(const_pointer_cast<SectionHDF5>(shared_from_this()));
auto tmp = make_shared<SectionHDF5>(file(), parent, group, id, type, name);
return Section(tmp);
} else {
return Section();
}
}
Section SectionHDF5::getSection(size_t index) const {
string id = section_group.objectName(index);
return getSection(id);
}
Section SectionHDF5::createSection(const string &name, const string &type) {
string new_id = util::createId("section");
while (section_group.hasObject(new_id)) {
new_id = util::createId("section");
}
Section parent(const_pointer_cast<SectionHDF5>(shared_from_this()));
Group grp = section_group.openGroup(new_id, true);
auto tmp = make_shared<SectionHDF5>(file(), parent, grp, new_id, type, name);
return Section(tmp);
}
bool SectionHDF5::deleteSection(const string &id) {
if (section_group.hasGroup(id)) {
section_group.removeGroup(id);
return true;
} else {
return false;
}
}
//--------------------------------------------------
// Methods for property access
//--------------------------------------------------
size_t SectionHDF5::propertyCount() const {
return property_group.objectCount();
}
bool SectionHDF5::hasProperty(const string &id) const {
return property_group.hasObject(id);
}
Property SectionHDF5::getProperty(const string &id) const {
if (property_group.hasData(id)) {
DataSet dset = property_group.openData(id);
string name;
dset.getAttr("name", name);
auto tmp = make_shared<PropertyHDF5>(file(), property_group, dset, id, name);
return Property(tmp);
} else {
return Property();
}
}
Property SectionHDF5::getProperty(size_t index) const {
string id = property_group.objectName(index);
return getProperty(id);
}
bool SectionHDF5::hasPropertyWithName(const string &name) const {
bool found = false;
for (size_t i = 0; i < propertyCount(); i++) {
string id = property_group.objectName(i);
DataSet dset = property_group.openData(id);
string other_name;
dset.getAttr("name", other_name);
if (other_name == name) {
found = true;
break;
}
}
return found;
}
Property SectionHDF5::getPropertyByName(const string &name) const {
Property prop;
for (size_t i = 0; i < propertyCount(); i++) {
string id = property_group.objectName(i);
DataSet dset = property_group.openData(id);
string other_name;
dset.getAttr("name", other_name);
if (other_name == name) {
string type;
dset.getAttr("type", type);
auto tmp = make_shared<PropertyHDF5>(file(), property_group, dset, id, name);
prop = Property(tmp);
break;
}
}
// return empty object if not found (since then "prop" is still empty Property)
return prop;
}
Property SectionHDF5::createProperty(const string &name, const Value &value) {
if (hasPropertyWithName(name))
throw runtime_error("Try to create a property with existing name: " + name);
string new_id = util::createId("property");
while (property_group.hasData(new_id))
new_id = util::createId("property");
NDSize size = {1};
DataType dtype = value.type();
H5::DataType fileType = DataSet::fileTypeForValue(dtype);
DataSet dataset = DataSet::create(property_group.h5Group(), new_id, fileType, size);
auto tmp = make_shared<PropertyHDF5>(file(), property_group, dataset, new_id, name);
Property p(tmp);
vector<Value> val{value};
p.values(val);
return p;
}
Property SectionHDF5::createProperty(const string &name, const vector<Value> &values) {
if (values.size() < 1) {
throw runtime_error("Trying to create a property without a value!");
}
Property p = createProperty(name, values[0]);
p.values(values);
return p;
}
bool SectionHDF5::deleteProperty(const string &id) {
if (property_group.hasData(id)) {
property_group.removeData(id);
return true;
} else {
return false;
}
}
SectionHDF5::~SectionHDF5() {}
} // namespace hdf5
} // namespace nix
|
/****************************************************************************
**
** Copyright (C) Qxt Foundation. Some rights reserved.
**
** This file is part of the QxtGui module of the Qxt library.
**
** This library is free software; you can redistribute it and/or modify it
** under the terms of the Common Public License, version 1.0, as published
** by IBM, and/or under the terms of the GNU Lesser General Public License,
** version 2.1, as published by the Free Software Foundation.
**
** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY
** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY
** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR
** FITNESS FOR A PARTICULAR PURPOSE.
**
** You should have received a copy of the CPL and the LGPL along with this
** file. See the LICENSE file and the cpl1.0.txt/lgpl-2.1.txt files
** included with the source distribution for more information.
** If you did not receive a copy of the licenses, contact the Qxt Foundation.
**
** <http://libqxt.org> <foundation@libqxt.org>
**
****************************************************************************/
#include "qxtheaderview.h"
class QxtHeaderViewPrivate : public QxtPrivate<QxtHeaderView>
{
public:
QXT_DECLARE_PUBLIC(QxtHeaderView);
QxtHeaderViewPrivate();
bool proportional;
QMap<int, int> factors;
};
QxtHeaderViewPrivate::QxtHeaderViewPrivate() : proportional(false)
{
}
/*!
\class QxtHeaderView QxtHeaderView
\inmodule QxtGui
\brief An extended QHeaderView with optionally proportional section sizes.
*/
/*!
Constructs a new QxtHeaderView with \a orientation and \a parent.
*/
QxtHeaderView::QxtHeaderView(Qt::Orientation orientation, QWidget* parent)
: QHeaderView(orientation, parent)
{
QXT_INIT_PRIVATE(QxtHeaderView);
}
/*!
\property QxtHeaderView::hasProportionalSectionSizes
\brief This property holds whether section sizes are proportional.
The default value is \bold true.
\bold {Note:} Enabling proportional sections sizes sets resize mode
\bold QHeaderView::Fixed, which means that the user cannot resize
sections.
*/
bool QxtHeaderView::hasProportionalSectionSizes() const
{
return qxt_d().proportional;
}
void QxtHeaderView::setProportionalSectionSizes(bool enabled)
{
if (qxt_d().proportional != enabled)
{
qxt_d().proportional = enabled;
if (enabled)
setResizeMode(QHeaderView::Fixed);
}
}
/*!
Returns the stretch factor of the section at \a logicalIndex.
\sa setSectionStretchFactor()
*/
int QxtHeaderView::sectionStretchFactor(int logicalIndex) const
{
return qxt_d().factors.value(logicalIndex);
}
/*!
Sets the stretch \a factor of the section at \a logicalIndex.
\sa sectionStretchFactor()
*/
void QxtHeaderView::setSectionStretchFactor(int logicalIndex, int factor)
{
qxt_d().factors.insert(logicalIndex, factor);
}
/*!
\reimp
*/
void QxtHeaderView::resizeEvent(QResizeEvent* event)
{
QHeaderView::resizeEvent(event);
if (qxt_d().proportional)
{
int total = 0;
for (int i = 0; i < count(); ++i)
total += qxt_d().factors.value(i, 1);
int totalSize = 0;
for (int i = 0; i < count() - 1; ++i)
{
qreal factor = qxt_d().factors.value(i, 1) / static_cast<qreal>(total);
int sectionSize = factor * (orientation() == Qt::Horizontal ? width() : height());
sectionSize = qMax(minimumSectionSize(), sectionSize);
resizeSection(i, sectionSize);
totalSize += sectionSize;
}
// avoid rounding errors, give rest to the last section
resizeSection(count() - 1, width() - totalSize);
}
}
Fixed QxtHeaderView docs.
/****************************************************************************
**
** Copyright (C) Qxt Foundation. Some rights reserved.
**
** This file is part of the QxtGui module of the Qxt library.
**
** This library is free software; you can redistribute it and/or modify it
** under the terms of the Common Public License, version 1.0, as published
** by IBM, and/or under the terms of the GNU Lesser General Public License,
** version 2.1, as published by the Free Software Foundation.
**
** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY
** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY
** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR
** FITNESS FOR A PARTICULAR PURPOSE.
**
** You should have received a copy of the CPL and the LGPL along with this
** file. See the LICENSE file and the cpl1.0.txt/lgpl-2.1.txt files
** included with the source distribution for more information.
** If you did not receive a copy of the licenses, contact the Qxt Foundation.
**
** <http://libqxt.org> <foundation@libqxt.org>
**
****************************************************************************/
#include "qxtheaderview.h"
class QxtHeaderViewPrivate : public QxtPrivate<QxtHeaderView>
{
public:
QXT_DECLARE_PUBLIC(QxtHeaderView);
QxtHeaderViewPrivate();
bool proportional;
QMap<int, int> factors;
};
QxtHeaderViewPrivate::QxtHeaderViewPrivate() : proportional(false)
{
}
/*!
\class QxtHeaderView QxtHeaderView
\inmodule QxtGui
\brief An extended QHeaderView with optionally proportional section sizes.
*/
/*!
Constructs a new QxtHeaderView with \a orientation and \a parent.
*/
QxtHeaderView::QxtHeaderView(Qt::Orientation orientation, QWidget* parent)
: QHeaderView(orientation, parent)
{
QXT_INIT_PRIVATE(QxtHeaderView);
}
/*!
\property QxtHeaderView::proportionalSectionSizes
\brief This property holds whether section sizes are proportional.
The default value is \bold true.
\bold {Note:} Enabling proportional sections sizes sets resize mode
\bold QHeaderView::Fixed, which means that the user cannot resize
sections.
*/
bool QxtHeaderView::hasProportionalSectionSizes() const
{
return qxt_d().proportional;
}
void QxtHeaderView::setProportionalSectionSizes(bool enabled)
{
if (qxt_d().proportional != enabled)
{
qxt_d().proportional = enabled;
if (enabled)
setResizeMode(QHeaderView::Fixed);
}
}
/*!
Returns the stretch factor of the section at \a logicalIndex.
\sa setSectionStretchFactor()
*/
int QxtHeaderView::sectionStretchFactor(int logicalIndex) const
{
return qxt_d().factors.value(logicalIndex);
}
/*!
Sets the stretch \a factor of the section at \a logicalIndex.
\sa sectionStretchFactor()
*/
void QxtHeaderView::setSectionStretchFactor(int logicalIndex, int factor)
{
qxt_d().factors.insert(logicalIndex, factor);
}
/*!
\reimp
*/
void QxtHeaderView::resizeEvent(QResizeEvent* event)
{
QHeaderView::resizeEvent(event);
if (qxt_d().proportional)
{
int total = 0;
for (int i = 0; i < count(); ++i)
total += qxt_d().factors.value(i, 1);
int totalSize = 0;
for (int i = 0; i < count() - 1; ++i)
{
qreal factor = qxt_d().factors.value(i, 1) / static_cast<qreal>(total);
int sectionSize = factor * (orientation() == Qt::Horizontal ? width() : height());
sectionSize = qMax(minimumSectionSize(), sectionSize);
resizeSection(i, sectionSize);
totalSize += sectionSize;
}
// avoid rounding errors, give rest to the last section
resizeSection(count() - 1, width() - totalSize);
}
}
|
/////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2020, The Regents of the University of California
// All rights reserved.
//
// BSD 3-Clause 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.
//
// * Neither the name of the copyright holder 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 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 "drcWidget.h"
#include <QApplication>
#include <QDebug>
#include <QFileDialog>
#include <QHeaderView>
#include <QVBoxLayout>
#include <boost/property_tree/json_parser.hpp>
#include <array>
#include <fstream>
#include <iomanip>
#include <map>
#include <regex>
#include <sstream>
#include "utl/Logger.h"
Q_DECLARE_METATYPE(gui::DRCViolation*);
namespace gui {
///////
DRCViolation::DRCViolation(const std::string& name,
const std::string& type,
const std::vector<std::any>& srcs,
const std::vector<DRCShape>& shapes,
odb::dbTechLayer* layer,
const std::string& comment,
int file_line)
: name_(name),
type_(type),
srcs_(srcs),
shapes_(shapes),
layer_(layer),
comment_(comment),
file_line_(file_line),
viewed_(false)
{
computeBBox();
}
DRCViolation::DRCViolation(const std::string& name,
const std::string& type,
const std::vector<DRCShape>& shapes,
const std::string& comment,
int file_line)
: DRCViolation(name, type, {}, shapes, nullptr, comment, file_line)
{
}
void DRCViolation::computeBBox()
{
QPolygon outline;
for (const auto& shape : shapes_) {
if (auto s = std::get_if<DRCLine>(&shape)) {
outline << QPoint((*s).first.x(), (*s).first.y());
outline << QPoint((*s).second.x(), (*s).second.y());
} else if (auto s = std::get_if<DRCRect>(&shape)) {
outline = outline.united(
QRect((*s).xMin(), (*s).yMin(), (*s).dx(), (*s).dy()));
} else if (auto s = std::get_if<DRCPoly>(&shape)) {
for (const auto& pt : *s) {
outline << QPoint(pt.x(), pt.y());
}
}
}
QRect bounds = outline.boundingRect();
bbox_
= odb::Rect(bounds.left(), bounds.bottom(), bounds.right(), bounds.top());
}
void DRCViolation::paint(Painter& painter)
{
for (const auto& shape : shapes_) {
if (auto s = std::get_if<DRCLine>(&shape)) {
const odb::Point& p1 = (*s).first;
const odb::Point& p2 = (*s).second;
painter.drawLine(p1.x(), p1.y(), p2.x(), p2.y());
} else if (auto s = std::get_if<DRCRect>(&shape)) {
painter.drawRect(*s);
} else if (auto s = std::get_if<DRCPoly>(&shape)) {
painter.drawPolygon(*s);
}
}
}
///////
DRCDescriptor::DRCDescriptor(const std::vector<std::unique_ptr<DRCViolation>>& violations) :
violations_(violations)
{
}
std::string DRCDescriptor::getName(std::any object) const
{
auto vio = std::any_cast<DRCViolation*>(object);
return vio->getType();
}
std::string DRCDescriptor::getTypeName() const
{
return "DRC";
}
bool DRCDescriptor::getBBox(std::any object, odb::Rect& bbox) const
{
auto vio = std::any_cast<DRCViolation*>(object);
bbox = vio->getBBox();
return true;
}
void DRCDescriptor::highlight(std::any object,
Painter& painter,
void* additional_data) const
{
auto vio = std::any_cast<DRCViolation*>(object);
vio->paint(painter);
}
Descriptor::Properties DRCDescriptor::getProperties(std::any object) const
{
auto vio = std::any_cast<DRCViolation*>(object);
Properties props;
auto gui = Gui::get();
auto layer = vio->getLayer();
if (layer != nullptr) {
props.push_back({"Layer", gui->makeSelected(layer)});
}
auto srcs = vio->getSources();
if (!srcs.empty()) {
SelectionSet sources;
for (auto src : srcs) {
auto select = gui->makeSelected(src);
if (select) {
sources.insert(select);
}
}
props.push_back({"Sources", sources});
}
auto& comment = vio->getComment();
if (!comment.empty()) {
props.push_back({"Comment", vio->getComment()});
}
int line_number = vio->getFileLine();
if (line_number != 0) {
props.push_back({"Line number:", line_number});
}
return props;
}
Selected DRCDescriptor::makeSelected(std::any object,
void* additional_data) const
{
if (auto vio = std::any_cast<DRCViolation*>(&object)) {
return Selected(*vio, this, additional_data);
}
return Selected();
}
bool DRCDescriptor::lessThan(std::any l, std::any r) const
{
auto l_drc = std::any_cast<DRCViolation*>(l);
auto r_drc = std::any_cast<DRCViolation*>(r);
return l_drc < r_drc;
}
bool DRCDescriptor::getAllObjects(SelectionSet& objects) const
{
for (auto& violation : violations_) {
objects.insert(makeSelected(violation.get(), nullptr));
}
return true;
}
///////
QVariant DRCItemModel::data(const QModelIndex& index, int role) const
{
if (role == Qt::FontRole) {
auto item_data = itemFromIndex(index)->data();
if (item_data.isValid()) {
DRCViolation* item = item_data.value<DRCViolation*>();
QFont font = QApplication::font();
font.setBold(!item->isViewed());
return font;
}
}
return QStandardItemModel::data(index, role);
}
///////
DRCWidget::DRCWidget(QWidget* parent)
: QDockWidget("DRC Viewer", parent),
logger_(nullptr),
view_(new QTreeView(this)),
model_(new DRCItemModel(this)),
block_(nullptr),
load_(new QPushButton("Load..."))
{
setObjectName("drc_viewer"); // for settings
model_->setHorizontalHeaderLabels({"Type", "Violation"});
view_->setModel(model_);
QHeaderView* header = view_->header();
header->setSectionResizeMode(0, QHeaderView::ResizeToContents);
header->setSectionResizeMode(1, QHeaderView::Stretch);
QWidget* container = new QWidget;
QVBoxLayout* layout = new QVBoxLayout;
layout->addWidget(view_);
layout->addWidget(load_);
container->setLayout(layout);
setWidget(container);
connect(view_,
SIGNAL(clicked(const QModelIndex&)),
this,
SLOT(clicked(const QModelIndex&)));
connect(view_->selectionModel(),
SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),
this,
SLOT(selectionChanged(const QItemSelection&, const QItemSelection&)));
connect(load_, SIGNAL(released()), this, SLOT(selectReport()));
Gui::get()->registerDescriptor<DRCViolation*>(new DRCDescriptor(violations_));
}
void DRCWidget::setLogger(utl::Logger* logger)
{
logger_ = logger;
}
void DRCWidget::selectReport()
{
// OpenLane uses .drc and OpenROAD-flow-scripts uses .rpt
QString filename = QFileDialog::getOpenFileName(
this,
tr("DRC Report"),
QString(),
tr("DRC Report (*.rpt *.drc *.json);;TritonRoute Report (*.rpt *.drc);;JSON (*.json);;All (*)"));
if (!filename.isEmpty()) {
loadReport(filename);
}
}
void DRCWidget::selectionChanged(const QItemSelection& selected, const QItemSelection& deselected)
{
auto indexes = selected.indexes();
if (indexes.isEmpty()) {
return;
}
emit clicked(indexes.first());
}
void DRCWidget::clicked(const QModelIndex& index)
{
QStandardItem* item = model_->itemFromIndex(index);
QVariant data = item->data();
if (data.isValid()) {
auto violation = data.value<DRCViolation*>();
if (qGuiApp->keyboardModifiers() & Qt::ControlModifier) {
violation->clearViewed();
} else {
Selected t = Gui::get()->makeSelected(violation);
emit selectDRC(t);
}
}
}
void DRCWidget::setBlock(odb::dbBlock* block)
{
block_ = block;
}
void DRCWidget::showEvent(QShowEvent* event)
{
toggleRenderer(true);
}
void DRCWidget::hideEvent(QHideEvent* event)
{
toggleRenderer(false);
}
void DRCWidget::toggleRenderer(bool visible)
{
if (!Gui::enabled()) {
return;
}
auto gui = Gui::get();
if (visible) {
gui->registerRenderer(this);
} else {
gui->unregisterRenderer(this);
}
}
void DRCWidget::updateModel()
{
auto makeItem = [](const QString& text) {
QStandardItem* item = new QStandardItem(text);
item->setEditable(false);
item->setSelectable(false);
return item;
};
model_->removeRows(0, model_->rowCount());
std::map<std::string, std::vector<DRCViolation*>> violation_by_type;
for (const auto& violation : violations_) {
violation_by_type[violation->getType()].push_back(violation.get());
}
for (const auto& [type, violation_list] : violation_by_type) {
QStandardItem* type_group = makeItem(QString::fromStdString(type));
int violation_idx = 1;
for (const auto& violation : violation_list) {
QStandardItem* violation_item
= makeItem(QString::fromStdString(violation->getName()));
violation_item->setSelectable(true);
violation_item->setData(QVariant::fromValue(violation));
QStandardItem* violation_index
= makeItem(QString::number(violation_idx++));
violation_index->setData(QVariant::fromValue(violation));
type_group->appendRow({violation_index, violation_item});
}
model_->appendRow(
{type_group,
makeItem(QString::number(violation_list.size()) + " violations")});
}
toggleRenderer(!this->isHidden());
redraw();
}
void DRCWidget::drawObjects(Painter& painter)
{
int min_box = 20.0 / painter.getPixelsPerDBU();
Painter::Color pen_color = Painter::white;
Painter::Color brush_color = pen_color;
brush_color.a = 50;
painter.setPen(pen_color, true, 0);
painter.setBrush(brush_color, Painter::Brush::DIAGONAL);
for (const auto& violation : violations_) {
const odb::Rect& box = violation->getBBox();
if (std::max(box.dx(), box.dy()) < min_box) {
// box is too small to be useful, so draw X instead
odb::Point center(box.xMin() + box.dx() / 2, box.yMin() + box.dy() / 2);
painter.drawLine({center.x() - min_box / 2, center.y() - min_box / 2},
{center.x() + min_box / 2, center.y() + min_box / 2});
painter.drawLine({center.x() - min_box / 2, center.y() + min_box / 2},
{center.x() + min_box / 2, center.y() - min_box / 2});
} else {
violation->paint(painter);
}
}
}
SelectionSet DRCWidget::select(odb::dbTechLayer* layer, const odb::Rect& region)
{
if (layer != nullptr) {
return SelectionSet();
}
auto gui = Gui::get();
SelectionSet selections;
for (const auto& violation : violations_) {
if (violation->getBBox().intersects(region)) {
selections.insert(gui->makeSelected(violation.get()));
}
}
return selections;
}
void DRCWidget::updateSelection(const Selected& selection)
{
const std::any& object = selection.getObject();
if (auto s = std::any_cast<DRCViolation*>(&object)) {
(*s)->setViewed();
emit update();
}
}
void DRCWidget::loadReport(const QString& filename)
{
violations_.clear();
try {
// OpenLane uses .drc and OpenROAD-flow-scripts uses .rpt
if (filename.endsWith(".rpt") || filename.endsWith(".drc")) {
loadTRReport(filename);
} else if (filename.endsWith(".json")) {
loadJSONReport(filename);
} else {
logger_->error(utl::GUI,
32,
"Unable to determine type of {}",
filename.toStdString());
}
} catch (std::runtime_error&) {
} // catch errors
updateModel();
raise();
}
void DRCWidget::loadTRReport(const QString& filename)
{
std::ifstream report(filename.toStdString());
if (!report.is_open()) {
logger_->error(utl::GUI,
30,
"Unable to open TritonRoute DRC report: {}",
filename.toStdString());
}
std::regex violation_type("\\s*violation type: (.*)");
std::regex srcs("\\s*srcs: (.*)");
std::regex bbox_layer("\\s*bbox = (.*) on Layer (.*)");
std::regex bbox_corners(
"\\s*\\(\\s*(.*),\\s*(.*)\\s*\\)\\s*-\\s*\\(\\s*(.*),\\s*(.*)\\s*\\)");
int line_number = 0;
auto tech = block_->getDataBase()->getTech();
while (!report.eof()) {
std::string line;
std::smatch base_match;
// type of violation
line_number++;
std::getline(report, line);
if (line.empty()) {
continue;
}
int violation_line_number = line_number;
std::string type;
if (std::regex_match(line, base_match, violation_type)) {
type = base_match[1].str();
} else {
logger_->error(
utl::GUI, 45, "Unable to parse line as violation type (line: {}): {}", line_number, line);
}
// sources of violation
line_number++;
int source_line_number = line_number;
std::getline(report, line);
std::string sources;
if (std::regex_match(line, base_match, srcs)) {
sources = base_match[1].str();
} else {
logger_->error(
utl::GUI, 46, "Unable to parse line as violation source (line: {}): {}", line_number, line);
}
line_number++;
std::getline(report, line);
// bounding box and layer
if (!std::regex_match(line, base_match, bbox_layer)) {
logger_->error(
utl::GUI, 47, "Unable to parse line as violation location (line: {}): {}", line_number, line);
}
std::string bbox = base_match[1].str();
odb::dbTechLayer* layer = tech->findLayer(base_match[2].str().c_str());
if (layer == nullptr) {
logger_->warn(
utl::GUI, 40, "Unable to find tech layer (line: {}): {}", line_number, base_match[2].str());
}
odb::Rect rect;
if (std::regex_match(bbox, base_match, bbox_corners)) {
try {
rect.set_xlo(std::stod(base_match[1].str())
* block_->getDbUnitsPerMicron());
rect.set_ylo(std::stod(base_match[2].str())
* block_->getDbUnitsPerMicron());
rect.set_xhi(std::stod(base_match[3].str())
* block_->getDbUnitsPerMicron());
rect.set_yhi(std::stod(base_match[4].str())
* block_->getDbUnitsPerMicron());
} catch (std::invalid_argument&) {
logger_->error(utl::GUI, 48, "Unable to parse bounding box (line: {}): {}", line_number, bbox);
} catch (std::out_of_range&) {
logger_->error(utl::GUI, 49, "Unable to parse bounding box (line: {}): {}", line_number, bbox);
}
} else {
logger_->error(utl::GUI, 50, "Unable to parse bounding box (line: {}): {}", line_number, bbox);
}
std::vector<std::any> srcs_list;
std::stringstream srcs_stream(sources);
std::string single_source;
std::string comment = "";
// split sources list
while (getline(srcs_stream, single_source, ' ')) {
if (single_source.empty()) {
continue;
}
auto ident = single_source.find(":");
std::string item_type = single_source.substr(0, ident);
std::string item_name = single_source.substr(ident + 1);
std::any item;
if (item_type == "net") {
odb::dbNet* net = block_->findNet(item_name.c_str());
if (net != nullptr) {
item = net;
} else {
logger_->warn(utl::GUI, 44, "Unable to find net (line: {}): {}", source_line_number, item_name);
}
} else if (item_type == "inst") {
odb::dbInst* inst = block_->findInst(item_name.c_str());
if (inst != nullptr) {
item = inst;
} else {
logger_->warn(utl::GUI, 43, "Unable to find instance (line: {}): {}", source_line_number, item_name);
}
} else if (item_type == "iterm") {
odb::dbITerm* iterm = block_->findITerm(item_name.c_str());
if (iterm != nullptr) {
item = iterm;
} else {
logger_->warn(utl::GUI, 42, "Unable to find iterm (line: {}): {}", source_line_number, item_name);
}
} else if (item_type == "bterm") {
odb::dbBTerm* bterm = block_->findBTerm(item_name.c_str());
if (bterm != nullptr) {
item = bterm;
} else {
logger_->warn(utl::GUI, 41, "Unable to find bterm (line: {}): {}", source_line_number, item_name);
}
} else if (item_type == "obstruction") {
bool found = false;
if (layer != nullptr) {
for (const auto& obs : block_->getObstructions()) {
auto obs_bbox = obs->getBBox();
if (obs_bbox->getTechLayer() == layer) {
odb::Rect obs_rect;
obs_bbox->getBox(obs_rect);
if (obs_rect.intersects(rect)) {
srcs_list.push_back(obs);
found = true;
}
}
}
}
if (!found) {
logger_->warn(utl::GUI, 52, "Unable to find obstruction (line: {})", source_line_number);
}
} else {
logger_->warn(utl::GUI, 51, "Unknown source type (line: {}): {}", source_line_number, item_type);
}
if (item.has_value()) {
srcs_list.push_back(item);
} else {
if (!item_name.empty()) {
comment += single_source + " ";
}
}
}
std::string name = "Layer: ";
if (layer != nullptr) {
name += layer->getName();
} else {
name += "<unknown>";
}
name += ", Sources: " + sources;
std::vector<DRCViolation::DRCShape> shapes({rect});
violations_.push_back(std::make_unique<DRCViolation>(
name, type, srcs_list, shapes, layer, comment, violation_line_number));
}
report.close();
}
void DRCWidget::loadJSONReport(const QString& filename)
{
boost::property_tree::ptree tree;
try {
boost::property_tree::json_parser::read_json(filename.toStdString(), tree);
}
catch (const boost::property_tree::json_parser_error& e1) {
logger_->error(utl::GUI, 55, "Unable to parse JSON file {}: {}", filename.toStdString(), e1.what());
}
for (const auto& rule : tree.get_child("DRC")) {
auto& drc_rule = rule.second;
const std::string violation_type = drc_rule.get<std::string>("name");
const std::string violation_text = drc_rule.get<std::string>("description");
int i = 0;
for (const auto& violation_shape : drc_rule.get_child("violations")) {
auto& shape = violation_shape.second;
std::vector<odb::Point> shape_points;
for (const auto& shape_pt : shape.get_child("shape")) {
auto& pt = shape_pt.second;
shape_points.push_back(odb::Point(
pt.get<double>("x") * block_->getDbUnitsPerMicron(),
pt.get<double>("y") * block_->getDbUnitsPerMicron()));
}
std::vector<DRCViolation::DRCShape> shapes;
const std::string shape_type = shape.get<std::string>("type");
if (shape_type == "box") {
shapes.push_back(DRCViolation::DRCRect(shape_points[0], shape_points[1]));
} else if (shape_type == "edge") {
shapes.push_back(DRCViolation::DRCLine(shape_points[0], shape_points[1]));
} else if (shape_type == "polygon") {
shapes.push_back(DRCViolation::DRCPoly(shape_points));
} else {
logger_->error(utl::GUI, 56, "Unable to parse violation shape: {}", shape_type);
}
std::string name = violation_type + " - " + std::to_string(++i);
violations_.push_back(std::make_unique<DRCViolation>(
name,
violation_type,
shapes,
violation_text,
0));
}
}
}
} // namespace gui
gui: ensure all DRCs are unselected when loading a new report
Signed-off-by: Peter Gadfort <7a938094a14a6d7745b59a60224c4a3a5eb6a3d8@army.mil>
/////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2020, The Regents of the University of California
// All rights reserved.
//
// BSD 3-Clause 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.
//
// * Neither the name of the copyright holder 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 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 "drcWidget.h"
#include <QApplication>
#include <QDebug>
#include <QFileDialog>
#include <QHeaderView>
#include <QVBoxLayout>
#include <boost/property_tree/json_parser.hpp>
#include <array>
#include <fstream>
#include <iomanip>
#include <map>
#include <regex>
#include <sstream>
#include "utl/Logger.h"
Q_DECLARE_METATYPE(gui::DRCViolation*);
namespace gui {
///////
DRCViolation::DRCViolation(const std::string& name,
const std::string& type,
const std::vector<std::any>& srcs,
const std::vector<DRCShape>& shapes,
odb::dbTechLayer* layer,
const std::string& comment,
int file_line)
: name_(name),
type_(type),
srcs_(srcs),
shapes_(shapes),
layer_(layer),
comment_(comment),
file_line_(file_line),
viewed_(false)
{
computeBBox();
}
DRCViolation::DRCViolation(const std::string& name,
const std::string& type,
const std::vector<DRCShape>& shapes,
const std::string& comment,
int file_line)
: DRCViolation(name, type, {}, shapes, nullptr, comment, file_line)
{
}
void DRCViolation::computeBBox()
{
QPolygon outline;
for (const auto& shape : shapes_) {
if (auto s = std::get_if<DRCLine>(&shape)) {
outline << QPoint((*s).first.x(), (*s).first.y());
outline << QPoint((*s).second.x(), (*s).second.y());
} else if (auto s = std::get_if<DRCRect>(&shape)) {
outline = outline.united(
QRect((*s).xMin(), (*s).yMin(), (*s).dx(), (*s).dy()));
} else if (auto s = std::get_if<DRCPoly>(&shape)) {
for (const auto& pt : *s) {
outline << QPoint(pt.x(), pt.y());
}
}
}
QRect bounds = outline.boundingRect();
bbox_
= odb::Rect(bounds.left(), bounds.bottom(), bounds.right(), bounds.top());
}
void DRCViolation::paint(Painter& painter)
{
for (const auto& shape : shapes_) {
if (auto s = std::get_if<DRCLine>(&shape)) {
const odb::Point& p1 = (*s).first;
const odb::Point& p2 = (*s).second;
painter.drawLine(p1.x(), p1.y(), p2.x(), p2.y());
} else if (auto s = std::get_if<DRCRect>(&shape)) {
painter.drawRect(*s);
} else if (auto s = std::get_if<DRCPoly>(&shape)) {
painter.drawPolygon(*s);
}
}
}
///////
DRCDescriptor::DRCDescriptor(const std::vector<std::unique_ptr<DRCViolation>>& violations) :
violations_(violations)
{
}
std::string DRCDescriptor::getName(std::any object) const
{
auto vio = std::any_cast<DRCViolation*>(object);
return vio->getType();
}
std::string DRCDescriptor::getTypeName() const
{
return "DRC";
}
bool DRCDescriptor::getBBox(std::any object, odb::Rect& bbox) const
{
auto vio = std::any_cast<DRCViolation*>(object);
bbox = vio->getBBox();
return true;
}
void DRCDescriptor::highlight(std::any object,
Painter& painter,
void* additional_data) const
{
auto vio = std::any_cast<DRCViolation*>(object);
vio->paint(painter);
}
Descriptor::Properties DRCDescriptor::getProperties(std::any object) const
{
auto vio = std::any_cast<DRCViolation*>(object);
Properties props;
auto gui = Gui::get();
auto layer = vio->getLayer();
if (layer != nullptr) {
props.push_back({"Layer", gui->makeSelected(layer)});
}
auto srcs = vio->getSources();
if (!srcs.empty()) {
SelectionSet sources;
for (auto src : srcs) {
auto select = gui->makeSelected(src);
if (select) {
sources.insert(select);
}
}
props.push_back({"Sources", sources});
}
auto& comment = vio->getComment();
if (!comment.empty()) {
props.push_back({"Comment", vio->getComment()});
}
int line_number = vio->getFileLine();
if (line_number != 0) {
props.push_back({"Line number:", line_number});
}
return props;
}
Selected DRCDescriptor::makeSelected(std::any object,
void* additional_data) const
{
if (auto vio = std::any_cast<DRCViolation*>(&object)) {
return Selected(*vio, this, additional_data);
}
return Selected();
}
bool DRCDescriptor::lessThan(std::any l, std::any r) const
{
auto l_drc = std::any_cast<DRCViolation*>(l);
auto r_drc = std::any_cast<DRCViolation*>(r);
return l_drc < r_drc;
}
bool DRCDescriptor::getAllObjects(SelectionSet& objects) const
{
for (auto& violation : violations_) {
objects.insert(makeSelected(violation.get(), nullptr));
}
return true;
}
///////
QVariant DRCItemModel::data(const QModelIndex& index, int role) const
{
if (role == Qt::FontRole) {
auto item_data = itemFromIndex(index)->data();
if (item_data.isValid()) {
DRCViolation* item = item_data.value<DRCViolation*>();
QFont font = QApplication::font();
font.setBold(!item->isViewed());
return font;
}
}
return QStandardItemModel::data(index, role);
}
///////
DRCWidget::DRCWidget(QWidget* parent)
: QDockWidget("DRC Viewer", parent),
logger_(nullptr),
view_(new QTreeView(this)),
model_(new DRCItemModel(this)),
block_(nullptr),
load_(new QPushButton("Load..."))
{
setObjectName("drc_viewer"); // for settings
model_->setHorizontalHeaderLabels({"Type", "Violation"});
view_->setModel(model_);
QHeaderView* header = view_->header();
header->setSectionResizeMode(0, QHeaderView::ResizeToContents);
header->setSectionResizeMode(1, QHeaderView::Stretch);
QWidget* container = new QWidget;
QVBoxLayout* layout = new QVBoxLayout;
layout->addWidget(view_);
layout->addWidget(load_);
container->setLayout(layout);
setWidget(container);
connect(view_,
SIGNAL(clicked(const QModelIndex&)),
this,
SLOT(clicked(const QModelIndex&)));
connect(view_->selectionModel(),
SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),
this,
SLOT(selectionChanged(const QItemSelection&, const QItemSelection&)));
connect(load_, SIGNAL(released()), this, SLOT(selectReport()));
Gui::get()->registerDescriptor<DRCViolation*>(new DRCDescriptor(violations_));
}
void DRCWidget::setLogger(utl::Logger* logger)
{
logger_ = logger;
}
void DRCWidget::selectReport()
{
// OpenLane uses .drc and OpenROAD-flow-scripts uses .rpt
QString filename = QFileDialog::getOpenFileName(
this,
tr("DRC Report"),
QString(),
tr("DRC Report (*.rpt *.drc *.json);;TritonRoute Report (*.rpt *.drc);;JSON (*.json);;All (*)"));
if (!filename.isEmpty()) {
loadReport(filename);
}
}
void DRCWidget::selectionChanged(const QItemSelection& selected, const QItemSelection& deselected)
{
auto indexes = selected.indexes();
if (indexes.isEmpty()) {
return;
}
emit clicked(indexes.first());
}
void DRCWidget::clicked(const QModelIndex& index)
{
QStandardItem* item = model_->itemFromIndex(index);
QVariant data = item->data();
if (data.isValid()) {
auto violation = data.value<DRCViolation*>();
if (qGuiApp->keyboardModifiers() & Qt::ControlModifier) {
violation->clearViewed();
} else {
Selected t = Gui::get()->makeSelected(violation);
emit selectDRC(t);
}
}
}
void DRCWidget::setBlock(odb::dbBlock* block)
{
block_ = block;
}
void DRCWidget::showEvent(QShowEvent* event)
{
toggleRenderer(true);
}
void DRCWidget::hideEvent(QHideEvent* event)
{
toggleRenderer(false);
}
void DRCWidget::toggleRenderer(bool visible)
{
if (!Gui::enabled()) {
return;
}
auto gui = Gui::get();
if (visible) {
gui->registerRenderer(this);
} else {
gui->unregisterRenderer(this);
}
}
void DRCWidget::updateModel()
{
auto makeItem = [](const QString& text) {
QStandardItem* item = new QStandardItem(text);
item->setEditable(false);
item->setSelectable(false);
return item;
};
model_->removeRows(0, model_->rowCount());
std::map<std::string, std::vector<DRCViolation*>> violation_by_type;
for (const auto& violation : violations_) {
violation_by_type[violation->getType()].push_back(violation.get());
}
for (const auto& [type, violation_list] : violation_by_type) {
QStandardItem* type_group = makeItem(QString::fromStdString(type));
int violation_idx = 1;
for (const auto& violation : violation_list) {
QStandardItem* violation_item
= makeItem(QString::fromStdString(violation->getName()));
violation_item->setSelectable(true);
violation_item->setData(QVariant::fromValue(violation));
QStandardItem* violation_index
= makeItem(QString::number(violation_idx++));
violation_index->setData(QVariant::fromValue(violation));
type_group->appendRow({violation_index, violation_item});
}
model_->appendRow(
{type_group,
makeItem(QString::number(violation_list.size()) + " violations")});
}
toggleRenderer(!this->isHidden());
redraw();
}
void DRCWidget::drawObjects(Painter& painter)
{
int min_box = 20.0 / painter.getPixelsPerDBU();
Painter::Color pen_color = Painter::white;
Painter::Color brush_color = pen_color;
brush_color.a = 50;
painter.setPen(pen_color, true, 0);
painter.setBrush(brush_color, Painter::Brush::DIAGONAL);
for (const auto& violation : violations_) {
const odb::Rect& box = violation->getBBox();
if (std::max(box.dx(), box.dy()) < min_box) {
// box is too small to be useful, so draw X instead
odb::Point center(box.xMin() + box.dx() / 2, box.yMin() + box.dy() / 2);
painter.drawLine({center.x() - min_box / 2, center.y() - min_box / 2},
{center.x() + min_box / 2, center.y() + min_box / 2});
painter.drawLine({center.x() - min_box / 2, center.y() + min_box / 2},
{center.x() + min_box / 2, center.y() - min_box / 2});
} else {
violation->paint(painter);
}
}
}
SelectionSet DRCWidget::select(odb::dbTechLayer* layer, const odb::Rect& region)
{
if (layer != nullptr) {
return SelectionSet();
}
auto gui = Gui::get();
SelectionSet selections;
for (const auto& violation : violations_) {
if (violation->getBBox().intersects(region)) {
selections.insert(gui->makeSelected(violation.get()));
}
}
return selections;
}
void DRCWidget::updateSelection(const Selected& selection)
{
const std::any& object = selection.getObject();
if (auto s = std::any_cast<DRCViolation*>(&object)) {
(*s)->setViewed();
emit update();
}
}
void DRCWidget::loadReport(const QString& filename)
{
Gui::get()->removeSelected<DRCViolation*>();
violations_.clear();
try {
// OpenLane uses .drc and OpenROAD-flow-scripts uses .rpt
if (filename.endsWith(".rpt") || filename.endsWith(".drc")) {
loadTRReport(filename);
} else if (filename.endsWith(".json")) {
loadJSONReport(filename);
} else {
logger_->error(utl::GUI,
32,
"Unable to determine type of {}",
filename.toStdString());
}
} catch (std::runtime_error&) {
} // catch errors
updateModel();
raise();
}
void DRCWidget::loadTRReport(const QString& filename)
{
std::ifstream report(filename.toStdString());
if (!report.is_open()) {
logger_->error(utl::GUI,
30,
"Unable to open TritonRoute DRC report: {}",
filename.toStdString());
}
std::regex violation_type("\\s*violation type: (.*)");
std::regex srcs("\\s*srcs: (.*)");
std::regex bbox_layer("\\s*bbox = (.*) on Layer (.*)");
std::regex bbox_corners(
"\\s*\\(\\s*(.*),\\s*(.*)\\s*\\)\\s*-\\s*\\(\\s*(.*),\\s*(.*)\\s*\\)");
int line_number = 0;
auto tech = block_->getDataBase()->getTech();
while (!report.eof()) {
std::string line;
std::smatch base_match;
// type of violation
line_number++;
std::getline(report, line);
if (line.empty()) {
continue;
}
int violation_line_number = line_number;
std::string type;
if (std::regex_match(line, base_match, violation_type)) {
type = base_match[1].str();
} else {
logger_->error(
utl::GUI, 45, "Unable to parse line as violation type (line: {}): {}", line_number, line);
}
// sources of violation
line_number++;
int source_line_number = line_number;
std::getline(report, line);
std::string sources;
if (std::regex_match(line, base_match, srcs)) {
sources = base_match[1].str();
} else {
logger_->error(
utl::GUI, 46, "Unable to parse line as violation source (line: {}): {}", line_number, line);
}
line_number++;
std::getline(report, line);
// bounding box and layer
if (!std::regex_match(line, base_match, bbox_layer)) {
logger_->error(
utl::GUI, 47, "Unable to parse line as violation location (line: {}): {}", line_number, line);
}
std::string bbox = base_match[1].str();
odb::dbTechLayer* layer = tech->findLayer(base_match[2].str().c_str());
if (layer == nullptr) {
logger_->warn(
utl::GUI, 40, "Unable to find tech layer (line: {}): {}", line_number, base_match[2].str());
}
odb::Rect rect;
if (std::regex_match(bbox, base_match, bbox_corners)) {
try {
rect.set_xlo(std::stod(base_match[1].str())
* block_->getDbUnitsPerMicron());
rect.set_ylo(std::stod(base_match[2].str())
* block_->getDbUnitsPerMicron());
rect.set_xhi(std::stod(base_match[3].str())
* block_->getDbUnitsPerMicron());
rect.set_yhi(std::stod(base_match[4].str())
* block_->getDbUnitsPerMicron());
} catch (std::invalid_argument&) {
logger_->error(utl::GUI, 48, "Unable to parse bounding box (line: {}): {}", line_number, bbox);
} catch (std::out_of_range&) {
logger_->error(utl::GUI, 49, "Unable to parse bounding box (line: {}): {}", line_number, bbox);
}
} else {
logger_->error(utl::GUI, 50, "Unable to parse bounding box (line: {}): {}", line_number, bbox);
}
std::vector<std::any> srcs_list;
std::stringstream srcs_stream(sources);
std::string single_source;
std::string comment = "";
// split sources list
while (getline(srcs_stream, single_source, ' ')) {
if (single_source.empty()) {
continue;
}
auto ident = single_source.find(":");
std::string item_type = single_source.substr(0, ident);
std::string item_name = single_source.substr(ident + 1);
std::any item;
if (item_type == "net") {
odb::dbNet* net = block_->findNet(item_name.c_str());
if (net != nullptr) {
item = net;
} else {
logger_->warn(utl::GUI, 44, "Unable to find net (line: {}): {}", source_line_number, item_name);
}
} else if (item_type == "inst") {
odb::dbInst* inst = block_->findInst(item_name.c_str());
if (inst != nullptr) {
item = inst;
} else {
logger_->warn(utl::GUI, 43, "Unable to find instance (line: {}): {}", source_line_number, item_name);
}
} else if (item_type == "iterm") {
odb::dbITerm* iterm = block_->findITerm(item_name.c_str());
if (iterm != nullptr) {
item = iterm;
} else {
logger_->warn(utl::GUI, 42, "Unable to find iterm (line: {}): {}", source_line_number, item_name);
}
} else if (item_type == "bterm") {
odb::dbBTerm* bterm = block_->findBTerm(item_name.c_str());
if (bterm != nullptr) {
item = bterm;
} else {
logger_->warn(utl::GUI, 41, "Unable to find bterm (line: {}): {}", source_line_number, item_name);
}
} else if (item_type == "obstruction") {
bool found = false;
if (layer != nullptr) {
for (const auto& obs : block_->getObstructions()) {
auto obs_bbox = obs->getBBox();
if (obs_bbox->getTechLayer() == layer) {
odb::Rect obs_rect;
obs_bbox->getBox(obs_rect);
if (obs_rect.intersects(rect)) {
srcs_list.push_back(obs);
found = true;
}
}
}
}
if (!found) {
logger_->warn(utl::GUI, 52, "Unable to find obstruction (line: {})", source_line_number);
}
} else {
logger_->warn(utl::GUI, 51, "Unknown source type (line: {}): {}", source_line_number, item_type);
}
if (item.has_value()) {
srcs_list.push_back(item);
} else {
if (!item_name.empty()) {
comment += single_source + " ";
}
}
}
std::string name = "Layer: ";
if (layer != nullptr) {
name += layer->getName();
} else {
name += "<unknown>";
}
name += ", Sources: " + sources;
std::vector<DRCViolation::DRCShape> shapes({rect});
violations_.push_back(std::make_unique<DRCViolation>(
name, type, srcs_list, shapes, layer, comment, violation_line_number));
}
report.close();
}
void DRCWidget::loadJSONReport(const QString& filename)
{
boost::property_tree::ptree tree;
try {
boost::property_tree::json_parser::read_json(filename.toStdString(), tree);
}
catch (const boost::property_tree::json_parser_error& e1) {
logger_->error(utl::GUI, 55, "Unable to parse JSON file {}: {}", filename.toStdString(), e1.what());
}
for (const auto& rule : tree.get_child("DRC")) {
auto& drc_rule = rule.second;
const std::string violation_type = drc_rule.get<std::string>("name");
const std::string violation_text = drc_rule.get<std::string>("description");
int i = 0;
for (const auto& violation_shape : drc_rule.get_child("violations")) {
auto& shape = violation_shape.second;
std::vector<odb::Point> shape_points;
for (const auto& shape_pt : shape.get_child("shape")) {
auto& pt = shape_pt.second;
shape_points.push_back(odb::Point(
pt.get<double>("x") * block_->getDbUnitsPerMicron(),
pt.get<double>("y") * block_->getDbUnitsPerMicron()));
}
std::vector<DRCViolation::DRCShape> shapes;
const std::string shape_type = shape.get<std::string>("type");
if (shape_type == "box") {
shapes.push_back(DRCViolation::DRCRect(shape_points[0], shape_points[1]));
} else if (shape_type == "edge") {
shapes.push_back(DRCViolation::DRCLine(shape_points[0], shape_points[1]));
} else if (shape_type == "polygon") {
shapes.push_back(DRCViolation::DRCPoly(shape_points));
} else {
logger_->error(utl::GUI, 56, "Unable to parse violation shape: {}", shape_type);
}
std::string name = violation_type + " - " + std::to_string(++i);
violations_.push_back(std::make_unique<DRCViolation>(
name,
violation_type,
shapes,
violation_text,
0));
}
}
}
} // namespace gui
|
/**************************************************************************
Copyright (c) 2021 sewenew
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 "async_connection.h"
#include <hiredis/async.h>
#include "errors.h"
namespace {
using namespace sw::redis;
void prepare_callback(redisAsyncContext *ctx, void *r, void *) {
assert(ctx != nullptr);
auto &connection = *(static_cast<AsyncConnectionSPtr *>(ctx->data));
redisReply *reply = static_cast<redisReply *>(r);
if (reply == nullptr) {
// Connection has bee closed.
//connection->reset();
// TODO: not sure if we should set this to be DISCONNECTING
return;
}
try {
if (reply::is_error(*reply)) {
throw_error(*reply);
}
reply::parse<void>(*reply);
connection->prepare();
} catch (const Error &e) {
connection->disconnect(std::make_exception_ptr(e));
}
}
}
namespace sw {
namespace redis {
FormattedCommand::FormattedCommand(char *data, int len) : _data(data), _size(len) {
if (data == nullptr || len < 0) {
throw Error("failed to format command");
}
}
FormattedCommand::~FormattedCommand() noexcept {
if (_data != nullptr) {
redisFreeCommand(_data);
}
}
void FormattedCommand::_move(FormattedCommand &&that) noexcept {
_data = that._data;
_size = that._size;
that._data = nullptr;
that._size = 0;
}
AsyncConnection::AsyncConnection(const ConnectionOptions &opts,
EventLoop *loop) : _opts(opts), _loop(loop) {}
void AsyncConnection::prepare() {
try {
switch (_status) {
case AsyncConnectionStatus::CONNECTED:
if (_need_auth()) {
_auth();
} else if (_need_select_db()) {
_select_db();
} else {
_status = AsyncConnectionStatus::READY;
}
break;
case AsyncConnectionStatus::AUTH:
if (_need_select_db()) {
_select_db();
} else {
_status = AsyncConnectionStatus::READY;
}
break;
case AsyncConnectionStatus::SELECT_DB:
_status = AsyncConnectionStatus::READY;
break;
default:
assert(false);
break;
}
if (_status == AsyncConnectionStatus::READY) {
// In case, there're pending commands.
_loop->notify();
}
} catch (const Error &e) {
disconnect(std::make_exception_ptr(e));
}
}
std::exception_ptr AsyncConnection::error() {
switch (_status) {
case AsyncConnectionStatus::DISCONNECTED:
return std::make_exception_ptr(Error("connection has been closed"));
case AsyncConnectionStatus::UNINITIALIZED:
return std::make_exception_ptr(Error("connection is uninitialized"));
default:
break;
}
return _err;
}
void AsyncConnection::reconnect() {
auto ctx = _connect(_opts);
assert(ctx && ctx->err == REDIS_OK);
_loop->attach(*ctx);
_ctx = ctx.release();
_status = AsyncConnectionStatus::CONNECTING;
}
void AsyncConnection::disconnect(std::exception_ptr err) {
// TODO: what if this method throw?
_loop->unwatch(shared_from_this());
_err = err;
_status = AsyncConnectionStatus::DISCONNECTING;
}
bool AsyncConnection::_need_auth() const {
return !_opts.password.empty() || _opts.user != "default";
}
void AsyncConnection::_auth() {
assert(!broken());
if (_opts.user == "default") {
if (redisAsyncCommand(_ctx, prepare_callback, nullptr, "AUTH %b",
_opts.password.data(), _opts.password.size()) != REDIS_OK) {
throw Error("failed to send auth command");
}
} else {
// Redis 6.0 or latter
if (redisAsyncCommand(_ctx, prepare_callback, nullptr, "AUTH %b %b",
_opts.user.data(), _opts.user.size(),
_opts.password.data(), _opts.password.size()) != REDIS_OK) {
throw Error("failed to send auth command");
}
}
_status = AsyncConnectionStatus::AUTH;
}
bool AsyncConnection::_need_select_db() const {
return _opts.db != 0;
}
void AsyncConnection::_select_db() {
assert(!broken());
if (redisAsyncCommand(_ctx, prepare_callback, nullptr, "SELECT %lld",
_opts.db) != REDIS_OK) {
throw Error("failed to send select command");
}
_status = AsyncConnectionStatus::SELECT_DB;
}
void AsyncConnection::_clean_async_context(void *data) {
auto *connection = static_cast<AsyncConnectionSPtr *>(data);
assert(connection != nullptr);
delete connection;
}
AsyncConnection::AsyncContextUPtr AsyncConnection::_connect(const ConnectionOptions &opts) {
redisAsyncContext *context = nullptr;
switch (opts.type) {
case ConnectionType::TCP:
context = redisAsyncConnect(opts.host.c_str(), _opts.port);
break;
case ConnectionType::UNIX:
context = redisAsyncConnectUnix(opts.path.c_str());
break;
default:
// Never goes here.
throw Error("Unknown connection type");
}
if (context == nullptr) {
throw Error("Failed to allocate memory for connection.");
}
auto ctx = AsyncContextUPtr(context);
if (ctx->err != REDIS_OK) {
throw_error(ctx->c, "failed to connect to server");
}
ctx->data = new AsyncConnectionSPtr(shared_from_this());
ctx->dataCleanup = _clean_async_context;
return ctx;
}
}
}
bug fix: type mismatch when calling redisAsyncCommand
/**************************************************************************
Copyright (c) 2021 sewenew
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 "async_connection.h"
#include <hiredis/async.h>
#include "errors.h"
namespace {
using namespace sw::redis;
void prepare_callback(redisAsyncContext *ctx, void *r, void *) {
assert(ctx != nullptr);
auto &connection = *(static_cast<AsyncConnectionSPtr *>(ctx->data));
redisReply *reply = static_cast<redisReply *>(r);
if (reply == nullptr) {
// Connection has bee closed.
//connection->reset();
// TODO: not sure if we should set this to be DISCONNECTING
return;
}
try {
if (reply::is_error(*reply)) {
throw_error(*reply);
}
reply::parse<void>(*reply);
connection->prepare();
} catch (const Error &e) {
connection->disconnect(std::make_exception_ptr(e));
}
}
}
namespace sw {
namespace redis {
FormattedCommand::FormattedCommand(char *data, int len) : _data(data), _size(len) {
if (data == nullptr || len < 0) {
throw Error("failed to format command");
}
}
FormattedCommand::~FormattedCommand() noexcept {
if (_data != nullptr) {
redisFreeCommand(_data);
}
}
void FormattedCommand::_move(FormattedCommand &&that) noexcept {
_data = that._data;
_size = that._size;
that._data = nullptr;
that._size = 0;
}
AsyncConnection::AsyncConnection(const ConnectionOptions &opts,
EventLoop *loop) : _opts(opts), _loop(loop) {}
void AsyncConnection::prepare() {
try {
switch (_status) {
case AsyncConnectionStatus::CONNECTED:
if (_need_auth()) {
_auth();
} else if (_need_select_db()) {
_select_db();
} else {
_status = AsyncConnectionStatus::READY;
}
break;
case AsyncConnectionStatus::AUTH:
if (_need_select_db()) {
_select_db();
} else {
_status = AsyncConnectionStatus::READY;
}
break;
case AsyncConnectionStatus::SELECT_DB:
_status = AsyncConnectionStatus::READY;
break;
default:
assert(false);
break;
}
if (_status == AsyncConnectionStatus::READY) {
// In case, there're pending commands.
_loop->notify();
}
} catch (const Error &e) {
disconnect(std::make_exception_ptr(e));
}
}
std::exception_ptr AsyncConnection::error() {
switch (_status) {
case AsyncConnectionStatus::DISCONNECTED:
return std::make_exception_ptr(Error("connection has been closed"));
case AsyncConnectionStatus::UNINITIALIZED:
return std::make_exception_ptr(Error("connection is uninitialized"));
default:
break;
}
return _err;
}
void AsyncConnection::reconnect() {
auto ctx = _connect(_opts);
assert(ctx && ctx->err == REDIS_OK);
_loop->attach(*ctx);
_ctx = ctx.release();
_status = AsyncConnectionStatus::CONNECTING;
}
void AsyncConnection::disconnect(std::exception_ptr err) {
// TODO: what if this method throw?
_loop->unwatch(shared_from_this());
_err = err;
_status = AsyncConnectionStatus::DISCONNECTING;
}
bool AsyncConnection::_need_auth() const {
return !_opts.password.empty() || _opts.user != "default";
}
void AsyncConnection::_auth() {
assert(!broken());
if (_opts.user == "default") {
if (redisAsyncCommand(_ctx, prepare_callback, nullptr, "AUTH %b",
_opts.password.data(), _opts.password.size()) != REDIS_OK) {
throw Error("failed to send auth command");
}
} else {
// Redis 6.0 or latter
if (redisAsyncCommand(_ctx, prepare_callback, nullptr, "AUTH %b %b",
_opts.user.data(), _opts.user.size(),
_opts.password.data(), _opts.password.size()) != REDIS_OK) {
throw Error("failed to send auth command");
}
}
_status = AsyncConnectionStatus::AUTH;
}
bool AsyncConnection::_need_select_db() const {
return _opts.db != 0;
}
void AsyncConnection::_select_db() {
assert(!broken());
if (redisAsyncCommand(_ctx, prepare_callback, nullptr, "SELECT %d",
_opts.db) != REDIS_OK) {
throw Error("failed to send select command");
}
_status = AsyncConnectionStatus::SELECT_DB;
}
void AsyncConnection::_clean_async_context(void *data) {
auto *connection = static_cast<AsyncConnectionSPtr *>(data);
assert(connection != nullptr);
delete connection;
}
AsyncConnection::AsyncContextUPtr AsyncConnection::_connect(const ConnectionOptions &opts) {
redisAsyncContext *context = nullptr;
switch (opts.type) {
case ConnectionType::TCP:
context = redisAsyncConnect(opts.host.c_str(), _opts.port);
break;
case ConnectionType::UNIX:
context = redisAsyncConnectUnix(opts.path.c_str());
break;
default:
// Never goes here.
throw Error("Unknown connection type");
}
if (context == nullptr) {
throw Error("Failed to allocate memory for connection.");
}
auto ctx = AsyncContextUPtr(context);
if (ctx->err != REDIS_OK) {
throw_error(ctx->c, "failed to connect to server");
}
ctx->data = new AsyncConnectionSPtr(shared_from_this());
ctx->dataCleanup = _clean_async_context;
return ctx;
}
}
}
|
#include "CWorm.h"
#include "util/vec.h"
#include "util/angle.h"
#include "util/log.h"
#include "gusgame.h"
#include "CGameObject.h"
#include "game/WormInputHandler.h"
#include "weapon_type.h"
#include "particle.h"
#include "player_options.h"
#include "CWormHuman.h"
#ifndef DEDICATED_ONLY
#include "base_animator.h"
#include "animators.h"
#include "sprite_set.h"
#include "sprite.h"
#include "gfx.h"
#include "CViewport.h"
#include "font.h"
#include "blitters/blitters.h"
#endif
#include "weapon.h"
#include "ninjarope.h"
#include "CMap.h"
#include "glua.h"
#include "lua51/luaapi/context.h"
#include "lua/bindings-objects.h"
#include <math.h>
#include <string>
#include <vector>
#include <boost/lexical_cast.hpp>
using boost::lexical_cast;
LuaReference CWorm::metaTable;
void CWorm::gusInit()
{
aimSpeed=(AngleDiff(0.0f)); aimAngle=(Angle(90.0f)); m_lastHurt=(0);
#ifndef DEDICATED_ONLY
m_animator=(0);
#endif
animate=(false); movable=(false); changing=(false);
m_dir=(1);
if(!gusGame.isLoaded()) {
skin = skinMask = NULL;
m_animator = m_fireconeAnimator = NULL;
m_currentFirecone = NULL;
m_ninjaRope = NULL;
return;
}
#ifndef DEDICATED_ONLY
skin = spriteList.load("skin");
skinMask = spriteList.load("skin-mask");
m_animator = new AnimLoopRight(skin,35);
m_fireconeTime = 0;
m_currentFirecone = NULL;
m_fireconeAnimator = NULL;
m_fireconeDistance = 0;
#endif
m_timeSinceDeath = 0;
aimRecoilSpeed = 0;
currentWeapon = 0;
m_weapons.assign(gusGame.options.maxWeapons, 0 );
m_weaponCount = 0;
for ( size_t i = 0; i < m_weapons.size(); ++i ) {
m_weapons[i] = new Weapon(gusGame.weaponList[rndInt(gusGame.weaponList.size())], this);
m_weaponCount++;
}
m_ninjaRope = new NinjaRope(gusGame.NRPartType, this);
movingLeft = false;
movingRight = false;
jumping = false;
}
void CWorm::gusShutdown()
{
#ifndef DEDICATED_ONLY
if(m_animator) {
delete m_animator;
m_animator = 0;
}
if(m_fireconeAnimator) {
delete m_fireconeAnimator;
m_fireconeAnimator = 0;
}
#endif
if(m_ninjaRope) {
m_ninjaRope->deleteMe = true;
m_ninjaRope = NULL;
}
//m_ninjaRope->deleteMe = true;
for ( size_t i = 0; i < m_weapons.size(); ++i) {
luaDelete(m_weapons[i]);
m_weapons[i] = 0;
}
}
void CWorm::deleteThis() {
finalize();
#ifndef NDEBUG
deleted = true;
#endif
if(luaReference)
{
lua.destroyReference(luaReference);
luaReference.reset();
}
// dont delete the object itself because we store it in CClient atm
}
void CWorm::assignOwner( CWormInputHandler* owner)
{
m_owner = owner;
}
NinjaRope* CWorm::getNinjaRopeObj()
{
return m_ninjaRope;
}
Weapon* CWorm::getCurrentWeaponRef()
{
return m_weapons[currentWeapon];
}
void CWorm::setWeapon( size_t index, WeaponType* type )
{
if(index >= m_weapons.size())
return;
luaDelete(m_weapons[index]);
m_weapons[index] = 0;
if ( type )
m_weapons[index] = new Weapon( type, this );
}
void CWorm::setWeapons( std::vector<WeaponType*> const& weaps )
{
if(weaps.size() > m_weapons.size())
return;
// Here is where the interception of the server can be done on the weapon selection
clearWeapons();
for ( size_t i = 0; i < weaps.size(); ++i ) {
setWeapon( i, weaps[i] );
}
}
void CWorm::clearWeapons()
{
for ( size_t i = 0; i < m_weapons.size(); ++i) {
luaDelete(m_weapons[i]);
m_weapons[i] = 0;
}
}
void CWorm::calculateReactionForce(BaseVec<long> origin, Direction d)
{
BaseVec<long> step;
long len = 0;
int bottom = gusGame.options.worm_weaponHeight;
int top = bottom - gusGame.options.worm_height + 1;
int left = (-gusGame.options.worm_width) / 2;
int right = (gusGame.options.worm_width) / 2;
switch(d) {
case Down: {
origin += BaseVec<long>(left, top);
step = BaseVec<long>(1, 0);
len = gusGame.options.worm_width;
}
break;
case Left: {
origin += BaseVec<long>(right, top + 1);
step = BaseVec<long>(0, 1);
len = gusGame.options.worm_height - 2;
}
break;
case Up: {
origin += BaseVec<long>(left, bottom);
step = BaseVec<long>(1, 0);
len = gusGame.options.worm_width;
}
break;
case Right: {
origin += BaseVec<long>(left, top + 1);
step = BaseVec<long>(0, 1);
len = gusGame.options.worm_height - 2;
}
break;
default:
return;
}
for(reacts[d] = 0; len > 0; --len) {
Material const& g = gusGame.level().getMaterial(origin.x, origin.y);
if(!g.worm_pass) {
++reacts[d];
}
origin += step;
}
}
void CWorm::calculateAllReactionForces(BaseVec<float>& nextPos, BaseVec<long>& inextPos)
{
//static const float correctionSpeed = 70.0f / 100.0f;
static const float correctionSpeed = 1.0f;
// Calculate all reaction forces
calculateReactionForce(inextPos, Down);
calculateReactionForce(inextPos, Left);
calculateReactionForce(inextPos, Up);
calculateReactionForce(inextPos, Right);
// Add more if the worm is outside the screen
if(inextPos.x < 5)
reacts[Right] += 5;
else if(inextPos.x > (long)gusGame.level().GetWidth() - 5)
reacts[Left] += 5;
if(inextPos.y < 5)
reacts[Down] += 5;
else if(inextPos.y > (long)gusGame.level().GetHeight() - 5)
reacts[Up] += 5;
if(reacts[Down] < 2 && reacts[Up] > 0
&& (reacts[Left] > 0 || reacts[Right] > 0)) {
pos().y -= correctionSpeed;
// Update next position as well
nextPos.y -= correctionSpeed;
inextPos.y = static_cast<long>(nextPos.y);
// Recalculate horizontal reaction forces.
// Liero does not recalculate vertical ones,
// so that is not a bug.
calculateReactionForce(inextPos, Left);
calculateReactionForce(inextPos, Right);
}
if(reacts[Up] < 2 && reacts[Down] > 0
&& (reacts[Left] > 0 || reacts[Right] > 0)) {
// Move one pixel per second
pos().y += correctionSpeed;
// Update next position as well
nextPos.y += correctionSpeed;
inextPos.y = static_cast<long>(nextPos.y);
// Recalculate horizontal reaction forces.
// Liero does not recalculate vertical ones,
// so that is not a bug.
calculateReactionForce(inextPos, Left);
calculateReactionForce(inextPos, Right);
}
if(gusGame.options.worm_disableWallHugging) {
if(reacts[Up] == 1 && reacts[Down] == 1
&& (reacts[Left] > 0 || reacts[Right] > 0)) {
reacts[Up] = 0;
reacts[Down] = 0;
}
}
}
void CWorm::processPhysics()
{
if(reacts[Up] > 0) {
// Friction
velocity().x *= gusGame.options.worm_friction;
}
velocity() *= gusGame.options.worm_airFriction;
if(velocity().x > 0.f) {
if(reacts[Left] > 0) {
if(velocity().x > gusGame.options.worm_bounceLimit) {
// TODO: Play bump sound
velocity().x *= -gusGame.options.worm_bounceQuotient;
} else
velocity().x = 0.f;
}
} else if(velocity().x < 0.f) {
if(reacts[Right] > 0) {
if(velocity().x < -gusGame.options.worm_bounceLimit) {
// TODO: Play bump sound
velocity().x *= -gusGame.options.worm_bounceQuotient;
} else
velocity().x = 0.f;
}
}
if(velocity().y > 0.f) {
if(reacts[Up] > 0) {
if(velocity().y > gusGame.options.worm_bounceLimit) {
// TODO: Play bump sound
velocity().y *= -gusGame.options.worm_bounceQuotient;
} else
velocity().y = 0.f;
}
} else if(velocity().y < 0.f) {
if(reacts[Down] > 0) {
if(velocity().y < -gusGame.options.worm_bounceLimit) {
// TODO: Play bump sound
velocity().y *= -gusGame.options.worm_bounceQuotient;
} else
velocity().y = 0.f;
}
}
if(reacts[Up] == 0) {
velocity().y += gusGame.options.worm_gravity;
}
if(velocity().x >= 0.f) {
if(reacts[Left] < 2)
pos().x += velocity().x;
} else {
if(reacts[Right] < 2)
pos().x += velocity().x;
}
if(velocity().y >= 0.f) {
if(reacts[Up] < 2)
pos().y += velocity().y;
} else {
if(reacts[Down] < 2)
pos().y += velocity().y;
}
}
void CWorm::processJumpingAndNinjaropeControls()
{
if(jumping && reacts[Up]) {
//Jump
velocity().y -= gusGame.options.worm_jumpForce;
jumping = false;
}
}
void CWorm::processMoveAndDig(void)
{
// ????????????? wtf is this for?
//if(!movable && !movingLeft && !movingRight)
// movable = true;
//if(movable)
if( true ) {
float acc = gusGame.options.worm_acceleration;
if(reacts[Up] <= 0)
acc *= gusGame.options.worm_airAccelerationFactor;
if(movingLeft && !movingRight) {
//TODO: Air acceleration
if(velocity().x > -gusGame.options.worm_maxSpeed) {
velocity().x -= acc;
}
if(m_dir > 0) {
aimSpeed = 0;
m_dir = -1;
}
animate = true;
} else if(movingRight && !movingLeft) {
//TODO: Air acceleration
if(velocity().x < gusGame.options.worm_maxSpeed) {
velocity().x += acc;
}
if(m_dir < 0) {
aimSpeed = 0;
m_dir = 1;
}
animate = true;
} else if(movingRight && movingLeft) {
// TODO: Digging
animate = false;
} else {
animate = false;
}
}
}
void CWorm::think()
{
if(getAlive()) {
if ( health <= 0 )
die();
BaseVec<float> next = pos() + velocity();
BaseVec<long> inext(static_cast<long>(next.x), static_cast<long>(next.y));
calculateAllReactionForces(next, inext);
processJumpingAndNinjaropeControls();
processPhysics();
processMoveAndDig();
aimAngle += aimSpeed;
if(aimAngle < Angle(0.0)) {
aimAngle = Angle(0.0);
aimSpeed = 0;
}
if(aimAngle > Angle::almost(180.0)) {
aimAngle = Angle::almost(180.0);
aimSpeed = 0;
}
for ( size_t i = 0; i < m_weapons.size(); ++i ) {
if ( m_weapons[i] )
m_weapons[i]->think( i == currentWeapon, i );
}
#ifndef DEDICATED_ONLY
if(animate)
m_animator->tick();
else
m_animator->reset();
if ( m_currentFirecone ) {
if ( m_fireconeTime == 0 )
m_currentFirecone = NULL;
--m_fireconeTime;
/*
if(m_fireconeAnimator)
m_fireconeAnimator->tick();*/
m_fireconeAnimator->tick();
}
#endif
} else {
if ( m_timeSinceDeath > gusGame.options.maxRespawnTime && gusGame.options.maxRespawnTime >= 0 ) {
respawn();
}
++m_timeSinceDeath;
}
}
Vec CWorm::getWeaponPos()
{
return pos();
}
#ifndef DEDICATED_ONLY
Vec CWorm::getRenderPos()
{
return renderPos;// - Vec(0,0.5);
}
#endif
Angle CWorm::getPointingAngle()
{
return m_dir > 0 ? aimAngle : Angle(360.0) - aimAngle ;
}
int CWorm::getWeaponIndexOffset( int offset )
{
if ( m_weaponCount > 0 ) {
if(offset < 0)
offset = -1;
else if(offset > 0)
offset = 1;
else
return currentWeapon;
unsigned int i = currentWeapon;
do
i = (i + offset + m_weaponCount) % m_weaponCount;
while(!m_weapons[i] && i != currentWeapon);
return i;
} else {
return currentWeapon;
}
}
void CWorm::setDir(int d)
{
m_dir = d;
}
bool CWorm::isCollidingWith( Vec const& point, float radius )
{
if ( !getAlive() )
return false;
float top = pos().y - gusGame.options.worm_boxTop;
if(point.y < top) {
float left = pos().x - gusGame.options.worm_boxRadius;
if(point.x < left)
return (point - Vec(left, top)).lengthSqr() < radius*radius;
float right = pos().x + gusGame.options.worm_boxRadius;
if(point.x > right)
return (point - Vec(right, top)).lengthSqr() < radius*radius;
return top - point.y < radius;
}
float bottom = pos().y + gusGame.options.worm_boxBottom;
if(point.y > bottom) {
float left = pos().x - gusGame.options.worm_boxRadius;
if(point.x < left)
return (point - Vec(left, bottom)).lengthSqr() < radius*radius;
float right = pos().x + gusGame.options.worm_boxRadius;
if(point.x > right)
return (point - Vec(right, bottom)).lengthSqr() < radius*radius;
return point.y - bottom < radius;
}
float left = pos().x - gusGame.options.worm_boxRadius;
if(point.x < left)
return left - point.x < radius;
float right = pos().x + gusGame.options.worm_boxRadius;
if(point.x > right)
return point.x - right < radius;
return true;
}
bool CWorm::isActive()
{
return getAlive();
}
void CWorm::removeRefsToPlayer(CWormInputHandler* player)
{
if ( m_lastHurt == player )
m_lastHurt = NULL;
CGameObject::removeRefsToPlayer(player);
}
//#define DEBUG_WORM_REACTS
#ifndef DEDICATED_ONLY
void CWorm::draw(CViewport* viewport)
{
if(!m_owner)
return;
if (getAlive()) {
/*
bool flipped = false;
if ( m_dir < 0 ) flipped = true;*/
BITMAP* where = viewport->dest;
IVec rPos = viewport->convertCoords( IVec(renderPos) );
{
int x = rPos.x;
int y = rPos.y;
int renderX = x;
int renderY = y;
if (m_ninjaRope->active) {
IVec nrPos = viewport->convertCoords( IVec(Vec(m_ninjaRope->pos())) );
line(where, x, y, nrPos.x, nrPos.y, m_ninjaRope->getColour());
}
if ( m_weapons[currentWeapon] )
m_weapons[currentWeapon]->drawBottom(where, renderX, renderY);
int colour = universalToLocalColor(m_owner->colour);
skin->getColoredSprite(m_animator->getFrame(), skinMask, colour, getPointingAngle())->draw(where, renderX, renderY);
if ( m_weapons[currentWeapon] )
m_weapons[currentWeapon]->drawTop(where, renderX, renderY);
if ( m_currentFirecone ) {
Vec distance = Vec(aimAngle, (double)m_fireconeDistance);
m_currentFirecone->getSprite(m_fireconeAnimator->getFrame(), getPointingAngle())->
draw(where, renderX+static_cast<int>(distance.x)*m_dir, renderY+static_cast<int>(distance.y));
}
}
#ifdef DEBUG_WORM_REACTS
{
int x = rPos.x;
int y = rPos.y;
gusGame.infoFont->draw(where, lexical_cast<std::string>(reacts[Up]), x, y + 15, 0);
gusGame.infoFont->draw(where, lexical_cast<std::string>(reacts[Down]), x, y - 15, 0);
gusGame.infoFont->draw(where, lexical_cast<std::string>(reacts[Left]), x + 15, y, 0);
gusGame.infoFont->draw(where, lexical_cast<std::string>(reacts[Right]), x - 15, y, 0);
}
#endif
}
}
#endif //DEDICATED_ONLY
void CWorm::respawn()
{
// Check if its already allowed to respawn
if ( m_timeSinceDeath > gusGame.options.minRespawnTime )
respawn( gusGame.level().getSpawnLocation( m_owner ) );
}
void CWorm::respawn( const Vec& newPos)
{
setAlive(true);
aimAngle = Angle(90.0);
velocity() = CVec ( 0, 0 );
pos() = newPos;
m_dir = 1;
#ifndef DEDICATED_ONLY
renderPos = pos();
#endif
m_lastHurt = NULL;
for ( size_t i = 0; i < m_weapons.size(); ++i ) {
if ( m_weapons[i] )
m_weapons[i]->reset();
}
}
void CWorm::dig()
{
if ( getAlive() )
dig( pos(), getPointingAngle() );
}
void CWorm::dig( const Vec& digPos, Angle angle )
{
if( gusGame.digObject )
gusGame.digObject->newParticle( gusGame.digObject, digPos, Vec(angle), m_dir, m_owner, angle );
}
void CWorm::die()
{
EACH_CALLBACK(i, wormDeath) {
(lua.call(*i), getLuaReference())();
}
bAlive = false;
if (m_owner) {
m_owner->stats->deaths++;
gusGame.displayKillMsg(m_owner, m_lastHurt); //TODO: Record what weapon it was?
}
if (m_lastHurt && m_lastHurt != m_owner)
m_lastHurt->stats->kills++;
m_ninjaRope->remove();
m_timeSinceDeath = 0;
if ( gusGame.deathObject ) {
gusGame.deathObject->newParticle( gusGame.deathObject, pos(), velocity(), m_dir, m_owner, Vec(velocity()).getAngle() );
}
}
void CWorm::changeWeaponTo( unsigned int weapIndex )
{
if ( m_weapons[currentWeapon] ) {
m_weapons[currentWeapon]->actionStop( Weapon::PRIMARY_TRIGGER );
m_weapons[currentWeapon]->actionStop( Weapon::SECONDARY_TRIGGER );
}
if ( weapIndex < m_weapons.size() && m_weapons[weapIndex] )
currentWeapon = weapIndex;
}
void CWorm::damage( float amount, CWormInputHandler* damager )
{
// TODO: maybe we could implement an armor system? ;O
m_lastHurt = damager;
health -= amount;
if ( health < 0 )
health = 0;
}
void CWorm::addAimSpeed( AngleDiff speed )
{
if ( m_owner )
aimSpeed += speed;
}
void CWorm::addRopeLength( float distance )
{
m_ninjaRope->addLength(distance);
}
#ifndef DEDICATED_ONLY
void CWorm::showFirecone( SpriteSet* sprite, int frames, float distance )
{
if(sprite) {
m_fireconeTime = frames;
m_currentFirecone = sprite;
delete m_fireconeAnimator;
m_fireconeAnimator = new AnimLoopRight( sprite, frames );
m_fireconeDistance = distance;
}
}
#endif
void CWorm::actionStart( Actions action )
{
switch ( action ) {
case MOVELEFT:
movingLeft = true;
break;
case MOVERIGHT:
movingRight = true;
break;
case FIRE:
if ( getAlive() && m_weapons[currentWeapon] )
m_weapons[currentWeapon]->actionStart( Weapon::PRIMARY_TRIGGER );
break;
case JUMP:
jumping = true;
break;
case NINJAROPE:
if ( getAlive() )
m_ninjaRope->shoot(getWeaponPos(), Vec(getPointingAngle(), (double)gusGame.options.ninja_rope_shootSpeed));
break;
case CHANGEWEAPON:
changing = true;
break;
case RESPAWN:
respawn();
break;
default:
break;
}
}
void CWorm::actionStop( Actions action )
{
switch ( action ) {
case MOVELEFT:
movingLeft = false;
break;
case MOVERIGHT:
movingRight = false;
break;
case FIRE:
if ( getAlive() && m_weapons[currentWeapon] )
m_weapons[currentWeapon]->actionStop( Weapon::PRIMARY_TRIGGER );
break;
case JUMP:
jumping = false;
break;
case NINJAROPE:
m_ninjaRope->remove();
break;
case CHANGEWEAPON:
changing = false;
break;
default:
break;
}
}
void CWorm::makeReference()
{
lua.pushFullReference(*this, metaTable);
}
void CWorm::finalize()
{
EACH_CALLBACK(i, wormRemoved) {
(lua.call(*i), getLuaReference())();
}
for ( size_t i = 0; i < m_weapons.size(); ++i) {
luaDelete(m_weapons[i]);
m_weapons[i] = 0;
}
}
fixing crash when gusanos is resetting
#include "CWorm.h"
#include "util/vec.h"
#include "util/angle.h"
#include "util/log.h"
#include "gusgame.h"
#include "CGameObject.h"
#include "game/WormInputHandler.h"
#include "weapon_type.h"
#include "particle.h"
#include "player_options.h"
#include "CWormHuman.h"
#ifndef DEDICATED_ONLY
#include "base_animator.h"
#include "animators.h"
#include "sprite_set.h"
#include "sprite.h"
#include "gfx.h"
#include "CViewport.h"
#include "font.h"
#include "blitters/blitters.h"
#endif
#include "weapon.h"
#include "ninjarope.h"
#include "CMap.h"
#include "glua.h"
#include "lua51/luaapi/context.h"
#include "lua/bindings-objects.h"
#include "game/Game.h"
#include <math.h>
#include <string>
#include <vector>
#include <boost/lexical_cast.hpp>
using boost::lexical_cast;
LuaReference CWorm::metaTable;
void CWorm::gusInit()
{
aimSpeed=(AngleDiff(0.0f)); aimAngle=(Angle(90.0f)); m_lastHurt=(0);
#ifndef DEDICATED_ONLY
m_animator=(0);
#endif
animate=(false); movable=(false); changing=(false);
m_dir=(1);
if(!gusGame.isLoaded()) {
skin = skinMask = NULL;
m_animator = m_fireconeAnimator = NULL;
m_currentFirecone = NULL;
m_ninjaRope = NULL;
return;
}
#ifndef DEDICATED_ONLY
skin = spriteList.load("skin");
skinMask = spriteList.load("skin-mask");
m_animator = new AnimLoopRight(skin,35);
m_fireconeTime = 0;
m_currentFirecone = NULL;
m_fireconeAnimator = NULL;
m_fireconeDistance = 0;
#endif
m_timeSinceDeath = 0;
aimRecoilSpeed = 0;
currentWeapon = 0;
m_weapons.assign(gusGame.options.maxWeapons, 0 );
m_weaponCount = 0;
for ( size_t i = 0; i < m_weapons.size(); ++i ) {
m_weapons[i] = new Weapon(gusGame.weaponList[rndInt(gusGame.weaponList.size())], this);
m_weaponCount++;
}
m_ninjaRope = new NinjaRope(gusGame.NRPartType, this);
movingLeft = false;
movingRight = false;
jumping = false;
}
void CWorm::gusShutdown()
{
#ifndef DEDICATED_ONLY
if(m_animator) {
delete m_animator;
m_animator = 0;
}
if(m_fireconeAnimator) {
delete m_fireconeAnimator;
m_fireconeAnimator = 0;
}
#endif
if(m_ninjaRope) {
m_ninjaRope->deleteMe = true;
m_ninjaRope = NULL;
}
//m_ninjaRope->deleteMe = true;
for ( size_t i = 0; i < m_weapons.size(); ++i) {
luaDelete(m_weapons[i]);
m_weapons[i] = 0;
}
// We must delete the object now out of the list because this destructor
// is not called from Gusanos but from CClient.
// NOTE: Not really the best way but I don't know a better way
// TODO: move this out here
#ifdef USE_GRID
for ( Grid::iterator iter = game.objects.beginAll(); iter;)
{
if( &*iter == this )
iter.erase();
else
++iter;
}
#else
for ( ObjectsList::Iterator iter = game.objects.begin(); iter; )
{
if ( &*iter == this )
{
ObjectsList::Iterator tmp = iter;
++iter;
tmp->deleteThis();
game.objects.erase(tmp);
}
else
++iter;
}
#endif
}
void CWorm::deleteThis() {
finalize();
#ifndef NDEBUG
deleted = true;
#endif
if(luaReference)
{
lua.destroyReference(luaReference);
luaReference.reset();
}
// dont delete the object itself because we store it in CClient atm
}
void CWorm::assignOwner( CWormInputHandler* owner)
{
m_owner = owner;
}
NinjaRope* CWorm::getNinjaRopeObj()
{
return m_ninjaRope;
}
Weapon* CWorm::getCurrentWeaponRef()
{
return m_weapons[currentWeapon];
}
void CWorm::setWeapon( size_t index, WeaponType* type )
{
if(index >= m_weapons.size())
return;
luaDelete(m_weapons[index]);
m_weapons[index] = 0;
if ( type )
m_weapons[index] = new Weapon( type, this );
}
void CWorm::setWeapons( std::vector<WeaponType*> const& weaps )
{
if(weaps.size() > m_weapons.size())
return;
// Here is where the interception of the server can be done on the weapon selection
clearWeapons();
for ( size_t i = 0; i < weaps.size(); ++i ) {
setWeapon( i, weaps[i] );
}
}
void CWorm::clearWeapons()
{
for ( size_t i = 0; i < m_weapons.size(); ++i) {
luaDelete(m_weapons[i]);
m_weapons[i] = 0;
}
}
void CWorm::calculateReactionForce(BaseVec<long> origin, Direction d)
{
BaseVec<long> step;
long len = 0;
int bottom = gusGame.options.worm_weaponHeight;
int top = bottom - gusGame.options.worm_height + 1;
int left = (-gusGame.options.worm_width) / 2;
int right = (gusGame.options.worm_width) / 2;
switch(d) {
case Down: {
origin += BaseVec<long>(left, top);
step = BaseVec<long>(1, 0);
len = gusGame.options.worm_width;
}
break;
case Left: {
origin += BaseVec<long>(right, top + 1);
step = BaseVec<long>(0, 1);
len = gusGame.options.worm_height - 2;
}
break;
case Up: {
origin += BaseVec<long>(left, bottom);
step = BaseVec<long>(1, 0);
len = gusGame.options.worm_width;
}
break;
case Right: {
origin += BaseVec<long>(left, top + 1);
step = BaseVec<long>(0, 1);
len = gusGame.options.worm_height - 2;
}
break;
default:
return;
}
for(reacts[d] = 0; len > 0; --len) {
Material const& g = gusGame.level().getMaterial(origin.x, origin.y);
if(!g.worm_pass) {
++reacts[d];
}
origin += step;
}
}
void CWorm::calculateAllReactionForces(BaseVec<float>& nextPos, BaseVec<long>& inextPos)
{
//static const float correctionSpeed = 70.0f / 100.0f;
static const float correctionSpeed = 1.0f;
// Calculate all reaction forces
calculateReactionForce(inextPos, Down);
calculateReactionForce(inextPos, Left);
calculateReactionForce(inextPos, Up);
calculateReactionForce(inextPos, Right);
// Add more if the worm is outside the screen
if(inextPos.x < 5)
reacts[Right] += 5;
else if(inextPos.x > (long)gusGame.level().GetWidth() - 5)
reacts[Left] += 5;
if(inextPos.y < 5)
reacts[Down] += 5;
else if(inextPos.y > (long)gusGame.level().GetHeight() - 5)
reacts[Up] += 5;
if(reacts[Down] < 2 && reacts[Up] > 0
&& (reacts[Left] > 0 || reacts[Right] > 0)) {
pos().y -= correctionSpeed;
// Update next position as well
nextPos.y -= correctionSpeed;
inextPos.y = static_cast<long>(nextPos.y);
// Recalculate horizontal reaction forces.
// Liero does not recalculate vertical ones,
// so that is not a bug.
calculateReactionForce(inextPos, Left);
calculateReactionForce(inextPos, Right);
}
if(reacts[Up] < 2 && reacts[Down] > 0
&& (reacts[Left] > 0 || reacts[Right] > 0)) {
// Move one pixel per second
pos().y += correctionSpeed;
// Update next position as well
nextPos.y += correctionSpeed;
inextPos.y = static_cast<long>(nextPos.y);
// Recalculate horizontal reaction forces.
// Liero does not recalculate vertical ones,
// so that is not a bug.
calculateReactionForce(inextPos, Left);
calculateReactionForce(inextPos, Right);
}
if(gusGame.options.worm_disableWallHugging) {
if(reacts[Up] == 1 && reacts[Down] == 1
&& (reacts[Left] > 0 || reacts[Right] > 0)) {
reacts[Up] = 0;
reacts[Down] = 0;
}
}
}
void CWorm::processPhysics()
{
if(reacts[Up] > 0) {
// Friction
velocity().x *= gusGame.options.worm_friction;
}
velocity() *= gusGame.options.worm_airFriction;
if(velocity().x > 0.f) {
if(reacts[Left] > 0) {
if(velocity().x > gusGame.options.worm_bounceLimit) {
// TODO: Play bump sound
velocity().x *= -gusGame.options.worm_bounceQuotient;
} else
velocity().x = 0.f;
}
} else if(velocity().x < 0.f) {
if(reacts[Right] > 0) {
if(velocity().x < -gusGame.options.worm_bounceLimit) {
// TODO: Play bump sound
velocity().x *= -gusGame.options.worm_bounceQuotient;
} else
velocity().x = 0.f;
}
}
if(velocity().y > 0.f) {
if(reacts[Up] > 0) {
if(velocity().y > gusGame.options.worm_bounceLimit) {
// TODO: Play bump sound
velocity().y *= -gusGame.options.worm_bounceQuotient;
} else
velocity().y = 0.f;
}
} else if(velocity().y < 0.f) {
if(reacts[Down] > 0) {
if(velocity().y < -gusGame.options.worm_bounceLimit) {
// TODO: Play bump sound
velocity().y *= -gusGame.options.worm_bounceQuotient;
} else
velocity().y = 0.f;
}
}
if(reacts[Up] == 0) {
velocity().y += gusGame.options.worm_gravity;
}
if(velocity().x >= 0.f) {
if(reacts[Left] < 2)
pos().x += velocity().x;
} else {
if(reacts[Right] < 2)
pos().x += velocity().x;
}
if(velocity().y >= 0.f) {
if(reacts[Up] < 2)
pos().y += velocity().y;
} else {
if(reacts[Down] < 2)
pos().y += velocity().y;
}
}
void CWorm::processJumpingAndNinjaropeControls()
{
if(jumping && reacts[Up]) {
//Jump
velocity().y -= gusGame.options.worm_jumpForce;
jumping = false;
}
}
void CWorm::processMoveAndDig(void)
{
// ????????????? wtf is this for?
//if(!movable && !movingLeft && !movingRight)
// movable = true;
//if(movable)
if( true ) {
float acc = gusGame.options.worm_acceleration;
if(reacts[Up] <= 0)
acc *= gusGame.options.worm_airAccelerationFactor;
if(movingLeft && !movingRight) {
//TODO: Air acceleration
if(velocity().x > -gusGame.options.worm_maxSpeed) {
velocity().x -= acc;
}
if(m_dir > 0) {
aimSpeed = 0;
m_dir = -1;
}
animate = true;
} else if(movingRight && !movingLeft) {
//TODO: Air acceleration
if(velocity().x < gusGame.options.worm_maxSpeed) {
velocity().x += acc;
}
if(m_dir < 0) {
aimSpeed = 0;
m_dir = 1;
}
animate = true;
} else if(movingRight && movingLeft) {
// TODO: Digging
animate = false;
} else {
animate = false;
}
}
}
void CWorm::think()
{
if(getAlive()) {
if ( health <= 0 )
die();
BaseVec<float> next = pos() + velocity();
BaseVec<long> inext(static_cast<long>(next.x), static_cast<long>(next.y));
calculateAllReactionForces(next, inext);
processJumpingAndNinjaropeControls();
processPhysics();
processMoveAndDig();
aimAngle += aimSpeed;
if(aimAngle < Angle(0.0)) {
aimAngle = Angle(0.0);
aimSpeed = 0;
}
if(aimAngle > Angle::almost(180.0)) {
aimAngle = Angle::almost(180.0);
aimSpeed = 0;
}
for ( size_t i = 0; i < m_weapons.size(); ++i ) {
if ( m_weapons[i] )
m_weapons[i]->think( i == currentWeapon, i );
}
#ifndef DEDICATED_ONLY
if(animate)
m_animator->tick();
else
m_animator->reset();
if ( m_currentFirecone ) {
if ( m_fireconeTime == 0 )
m_currentFirecone = NULL;
--m_fireconeTime;
/*
if(m_fireconeAnimator)
m_fireconeAnimator->tick();*/
m_fireconeAnimator->tick();
}
#endif
} else {
if ( m_timeSinceDeath > gusGame.options.maxRespawnTime && gusGame.options.maxRespawnTime >= 0 ) {
respawn();
}
++m_timeSinceDeath;
}
}
Vec CWorm::getWeaponPos()
{
return pos();
}
#ifndef DEDICATED_ONLY
Vec CWorm::getRenderPos()
{
return renderPos;// - Vec(0,0.5);
}
#endif
Angle CWorm::getPointingAngle()
{
return m_dir > 0 ? aimAngle : Angle(360.0) - aimAngle ;
}
int CWorm::getWeaponIndexOffset( int offset )
{
if ( m_weaponCount > 0 ) {
if(offset < 0)
offset = -1;
else if(offset > 0)
offset = 1;
else
return currentWeapon;
unsigned int i = currentWeapon;
do
i = (i + offset + m_weaponCount) % m_weaponCount;
while(!m_weapons[i] && i != currentWeapon);
return i;
} else {
return currentWeapon;
}
}
void CWorm::setDir(int d)
{
m_dir = d;
}
bool CWorm::isCollidingWith( Vec const& point, float radius )
{
if ( !getAlive() )
return false;
float top = pos().y - gusGame.options.worm_boxTop;
if(point.y < top) {
float left = pos().x - gusGame.options.worm_boxRadius;
if(point.x < left)
return (point - Vec(left, top)).lengthSqr() < radius*radius;
float right = pos().x + gusGame.options.worm_boxRadius;
if(point.x > right)
return (point - Vec(right, top)).lengthSqr() < radius*radius;
return top - point.y < radius;
}
float bottom = pos().y + gusGame.options.worm_boxBottom;
if(point.y > bottom) {
float left = pos().x - gusGame.options.worm_boxRadius;
if(point.x < left)
return (point - Vec(left, bottom)).lengthSqr() < radius*radius;
float right = pos().x + gusGame.options.worm_boxRadius;
if(point.x > right)
return (point - Vec(right, bottom)).lengthSqr() < radius*radius;
return point.y - bottom < radius;
}
float left = pos().x - gusGame.options.worm_boxRadius;
if(point.x < left)
return left - point.x < radius;
float right = pos().x + gusGame.options.worm_boxRadius;
if(point.x > right)
return point.x - right < radius;
return true;
}
bool CWorm::isActive()
{
return getAlive();
}
void CWorm::removeRefsToPlayer(CWormInputHandler* player)
{
if ( m_lastHurt == player )
m_lastHurt = NULL;
CGameObject::removeRefsToPlayer(player);
}
//#define DEBUG_WORM_REACTS
#ifndef DEDICATED_ONLY
void CWorm::draw(CViewport* viewport)
{
if(!m_owner)
return;
if (getAlive()) {
/*
bool flipped = false;
if ( m_dir < 0 ) flipped = true;*/
BITMAP* where = viewport->dest;
IVec rPos = viewport->convertCoords( IVec(renderPos) );
{
int x = rPos.x;
int y = rPos.y;
int renderX = x;
int renderY = y;
if (m_ninjaRope->active) {
IVec nrPos = viewport->convertCoords( IVec(Vec(m_ninjaRope->pos())) );
line(where, x, y, nrPos.x, nrPos.y, m_ninjaRope->getColour());
}
if ( m_weapons[currentWeapon] )
m_weapons[currentWeapon]->drawBottom(where, renderX, renderY);
int colour = universalToLocalColor(m_owner->colour);
skin->getColoredSprite(m_animator->getFrame(), skinMask, colour, getPointingAngle())->draw(where, renderX, renderY);
if ( m_weapons[currentWeapon] )
m_weapons[currentWeapon]->drawTop(where, renderX, renderY);
if ( m_currentFirecone ) {
Vec distance = Vec(aimAngle, (double)m_fireconeDistance);
m_currentFirecone->getSprite(m_fireconeAnimator->getFrame(), getPointingAngle())->
draw(where, renderX+static_cast<int>(distance.x)*m_dir, renderY+static_cast<int>(distance.y));
}
}
#ifdef DEBUG_WORM_REACTS
{
int x = rPos.x;
int y = rPos.y;
gusGame.infoFont->draw(where, lexical_cast<std::string>(reacts[Up]), x, y + 15, 0);
gusGame.infoFont->draw(where, lexical_cast<std::string>(reacts[Down]), x, y - 15, 0);
gusGame.infoFont->draw(where, lexical_cast<std::string>(reacts[Left]), x + 15, y, 0);
gusGame.infoFont->draw(where, lexical_cast<std::string>(reacts[Right]), x - 15, y, 0);
}
#endif
}
}
#endif //DEDICATED_ONLY
void CWorm::respawn()
{
// Check if its already allowed to respawn
if ( m_timeSinceDeath > gusGame.options.minRespawnTime )
respawn( gusGame.level().getSpawnLocation( m_owner ) );
}
void CWorm::respawn( const Vec& newPos)
{
setAlive(true);
aimAngle = Angle(90.0);
velocity() = CVec ( 0, 0 );
pos() = newPos;
m_dir = 1;
#ifndef DEDICATED_ONLY
renderPos = pos();
#endif
m_lastHurt = NULL;
for ( size_t i = 0; i < m_weapons.size(); ++i ) {
if ( m_weapons[i] )
m_weapons[i]->reset();
}
}
void CWorm::dig()
{
if ( getAlive() )
dig( pos(), getPointingAngle() );
}
void CWorm::dig( const Vec& digPos, Angle angle )
{
if( gusGame.digObject )
gusGame.digObject->newParticle( gusGame.digObject, digPos, Vec(angle), m_dir, m_owner, angle );
}
void CWorm::die()
{
EACH_CALLBACK(i, wormDeath) {
(lua.call(*i), getLuaReference())();
}
bAlive = false;
if (m_owner) {
m_owner->stats->deaths++;
gusGame.displayKillMsg(m_owner, m_lastHurt); //TODO: Record what weapon it was?
}
if (m_lastHurt && m_lastHurt != m_owner)
m_lastHurt->stats->kills++;
m_ninjaRope->remove();
m_timeSinceDeath = 0;
if ( gusGame.deathObject ) {
gusGame.deathObject->newParticle( gusGame.deathObject, pos(), velocity(), m_dir, m_owner, Vec(velocity()).getAngle() );
}
}
void CWorm::changeWeaponTo( unsigned int weapIndex )
{
if ( m_weapons[currentWeapon] ) {
m_weapons[currentWeapon]->actionStop( Weapon::PRIMARY_TRIGGER );
m_weapons[currentWeapon]->actionStop( Weapon::SECONDARY_TRIGGER );
}
if ( weapIndex < m_weapons.size() && m_weapons[weapIndex] )
currentWeapon = weapIndex;
}
void CWorm::damage( float amount, CWormInputHandler* damager )
{
// TODO: maybe we could implement an armor system? ;O
m_lastHurt = damager;
health -= amount;
if ( health < 0 )
health = 0;
}
void CWorm::addAimSpeed( AngleDiff speed )
{
if ( m_owner )
aimSpeed += speed;
}
void CWorm::addRopeLength( float distance )
{
m_ninjaRope->addLength(distance);
}
#ifndef DEDICATED_ONLY
void CWorm::showFirecone( SpriteSet* sprite, int frames, float distance )
{
if(sprite) {
m_fireconeTime = frames;
m_currentFirecone = sprite;
delete m_fireconeAnimator;
m_fireconeAnimator = new AnimLoopRight( sprite, frames );
m_fireconeDistance = distance;
}
}
#endif
void CWorm::actionStart( Actions action )
{
switch ( action ) {
case MOVELEFT:
movingLeft = true;
break;
case MOVERIGHT:
movingRight = true;
break;
case FIRE:
if ( getAlive() && m_weapons[currentWeapon] )
m_weapons[currentWeapon]->actionStart( Weapon::PRIMARY_TRIGGER );
break;
case JUMP:
jumping = true;
break;
case NINJAROPE:
if ( getAlive() )
m_ninjaRope->shoot(getWeaponPos(), Vec(getPointingAngle(), (double)gusGame.options.ninja_rope_shootSpeed));
break;
case CHANGEWEAPON:
changing = true;
break;
case RESPAWN:
respawn();
break;
default:
break;
}
}
void CWorm::actionStop( Actions action )
{
switch ( action ) {
case MOVELEFT:
movingLeft = false;
break;
case MOVERIGHT:
movingRight = false;
break;
case FIRE:
if ( getAlive() && m_weapons[currentWeapon] )
m_weapons[currentWeapon]->actionStop( Weapon::PRIMARY_TRIGGER );
break;
case JUMP:
jumping = false;
break;
case NINJAROPE:
m_ninjaRope->remove();
break;
case CHANGEWEAPON:
changing = false;
break;
default:
break;
}
}
void CWorm::makeReference()
{
lua.pushFullReference(*this, metaTable);
}
void CWorm::finalize()
{
EACH_CALLBACK(i, wormRemoved) {
(lua.call(*i), getLuaReference())();
}
for ( size_t i = 0; i < m_weapons.size(); ++i) {
luaDelete(m_weapons[i]);
m_weapons[i] = 0;
}
}
|
/*
* netstream.cpp
* Gusanos
*
* Created by Albert Zeyer on 30.11.09.
* code under LGPL
*
*/
#include "netstream.h"
#include "Networking.h"
#include "EndianSwap.h"
#include "gusanos/encoding.h"
#include "CBytestream.h"
#include "Protocol.h"
#include "CServer.h"
#include "CServerConnection.h"
#include "CClient.h"
#include "CServerNetEngine.h"
#include "CChannel.h"
Net_BitStream::Net_BitStream(const std::string& raw) {
m_readPos = 0;
m_data.reserve( raw.size() * 8 );
for(size_t i = 0; i < raw.size(); ++i)
addInt((unsigned char) raw[i], 8);
}
// Grows the bit stream if the number of bits that are going to be added exceeds the buffer size
void Net_BitStream::growIfNeeded(size_t addBits)
{
m_data.reserve(m_data.size() + addBits);
}
static const unsigned char bitMasks[] = { 1, 2, 4, 8, 16, 32, 64, 128 };
void Net_BitStream::writeBits(const std::vector<bool>& bits)
{
growIfNeeded(bits.size());
for(std::vector<bool>::const_iterator i = bits.begin(); i != bits.end(); ++i)
m_data.push_back(*i);
}
std::vector<bool> Net_BitStream::readBits(size_t bitCount)
{
std::vector<bool> ret;
ret.reserve(bitCount);
for(size_t i = 0; i < bitCount && m_readPos < m_data.size(); ++i, ++m_readPos)
ret.push_back(m_data[m_readPos]);
if(ret.size() < bitCount)
errors << "Net_BitStream::readBits: reading from behind end" << endl;
return ret;
}
void Net_BitStream::addBool(bool b) {
m_data.push_back(b);
}
void Net_BitStream::addInt(int n, int bits) {
growIfNeeded(bits);
for(int i = 0; i < bits; ++i)
m_data.push_back( (((unsigned long)n >> i) & 1) != 0 );
}
void Net_BitStream::addSignedInt(int n, int bits) {
growIfNeeded(bits);
addBool( n < 0 );
if( n >= 0)
addInt(n, bits - 1);
else
addInt((1 << (bits - 1)) - n, bits - 1);
}
void Net_BitStream::addFloat(float f, int bits) {
// TODO: check bits
union {
char bytes[4];
float f;
} data;
data.f = f;
BEndianSwap(data.f);
addBitStream( Net_BitStream( std::string(data.bytes, 4) ) );
}
void Net_BitStream::addBitStream(const Net_BitStream& str) {
writeBits(str.m_data);
}
void Net_BitStream::addString(const std::string& str) {
std::string::const_iterator end = str.end();
for(std::string::const_iterator i = str.begin(); i != end; ++i)
if(*i == 0) {
warnings << "Net_BitStream::addString: strings contains NULL-char: " << str << endl;
end = i;
}
std::string raw(str.begin(), end);
raw += '\0';
addBitStream(Net_BitStream(raw));
}
bool Net_BitStream::getBool() {
if(m_readPos < m_data.size()) {
bool ret = m_data[m_readPos];
m_readPos++;
return ret;
}
errors << "Net_BitStream::getBool: reading from behind end" << endl;
return false;
}
int Net_BitStream::getInt(int bits) {
unsigned long ret = 0;
for(int i = 0; i < bits; ++i)
if(getBool()) ret |= 1 << i;
return ret;
}
int Net_BitStream::getSignedInt(int bits) {
bool sign = getBool();
if( !sign /*n >= 0*/ )
return getInt(bits - 1);
else
return (1 << (bits - 1)) - getInt(bits - 1);
}
static char getCharFromBits(Net_BitStream& bs) {
return (char) (unsigned char) bs.getInt(8);
}
float Net_BitStream::getFloat(int bits) {
// TODO: see addFloat, check bits
union {
char bytes[4];
float f;
} data;
for(int i = 0; i < 4; ++i)
data.bytes[i] = getCharFromBits(*this);
BEndianSwap(data.f);
return data.f;
}
std::string Net_BitStream::getString() {
std::string ret;
while(char c = getCharFromBits(*this))
ret += c;
return ret;
}
Net_BitStream* Net_BitStream::Duplicate() {
return new Net_BitStream(*this);
}
void Net_BitStream::reset()
{
m_readPos = 0;
m_data.clear();
}
//
// Net_BitStream Tests
//
bool Net_BitStream::testBool()
{
reset();
addBool(true);
addBool(false);
bool r1 = getBool();
bool r2 = getBool();
return r1 && !r2;
}
bool Net_BitStream::testInt()
{
reset();
for (int i = 0; i < 32; i++)
addInt(1 << i, i + 1);
for (int i = 0; i < 32; i++)
if (getInt(i + 1) != (1 << i))
return false;
return true;
}
bool Net_BitStream::testFloat()
{
reset();
union T {
int n;
float f;
};
for (int i = 0; i < 32; i++) {
T t; t.n = 1 << i;
addFloat(t.f, i + 1);
}
for (int i = 0; i < 32; i++) {
T t; t.f = getFloat(i + 1);
if (t.n != (1 << i))
return false;
}
return true;
}
bool Net_BitStream::testStream()
{
reset();
Net_BitStream s2;
s2.addBool(true);
s2.addBool(false);
s2.addInt(50, 32);
s2.addInt(60, 16);
s2.addInt(30, 5);
addInt(14, 4);
addBool(true);
addBitStream(s2);
if (getInt(4) != 14)
return false;
if (getBool() != true)
return false;
if (getBool() != true)
return false;
if (getBool() != false)
return false;
if (getInt(32) != 50)
return false;
if (getInt(16) != 60)
return false;
if (getInt(5) != 30)
return false;
return true;
}
bool Net_BitStream::testSafety()
{
try {
reset();
getBool();
addInt(5, 5);
getInt(6);
addFloat(0.0f, 32);
getFloat(31);
getInt(5);
} catch (...) {
return false;
}
return true;
}
bool Net_BitStream::testString()
{
addBool(true);
addString("some short text to test bitstream");
if (getBool() != true)
return false;
if (std::string(getString()) != "some short text to test bitstream")
return false;
return true;
}
bool Net_BitStream::runTests()
{
bool res = true;
if (!testBool()) {
printf("Boolean test failed!\n");
res = false;
}
if (!testInt()) {
printf("Integer test failed\n");
res = false;
}
if (!testFloat()) {
printf("Float test failed\n");
res = false;
}
if (!testStream()) {
printf("Stream test failed\n");
res = false;
}
if (!testString()) {
printf("String test failed\n");
res = false;
}
if (!testSafety()) {
printf("Safety test failed\n");
res = false;
}
return res;
}
struct NetControlIntern {
NetControlIntern() {
isServer = false;
controlId = 0;
myConnIdOnServer = INVALID_CONN_ID;
cbNodeRequest_Dynamic = false;
cbNodeRequest_nodeId = INVALID_NODE_ID;
}
bool isServer;
int controlId;
std::string debugName;
Net_ConnID myConnIdOnServer;
bool cbNodeRequest_Dynamic;
Net_NodeID cbNodeRequest_nodeId;
struct DataPackage {
DataPackage() : type(Type(-1)), sendMode(eNet_ReliableOrdered), repRules(Net_REPRULE_NONE) {}
enum Type {
GPT_NodeUpdate, // very first because the most often -> less bits to sends
GPT_NodeInit,
GPT_NodeRemove,
GPT_NodeEvent, /* eNet_EventUser */
// here start all types where we dont send the nodeID
GPT_Direct,
GPT_ConnectRequest,
GPT_ConnectResult,
};
Type type;
Net_ConnID connID; // target or source
SmartPointer<NetNodeIntern> node; // node this is about; this is used for sending
Net_NodeID nodeId; // node this is about; this is used for receiving; NULL iff !nodeMustBeSet()
Net_BitStream data;
eNet_SendMode sendMode;
Net_RepRules repRules; // if node is set, while sending, these are checked
bool nodeMustBeSet() { return type < GPT_Direct; }
void send(CBytestream& bs);
void read(const SmartPointer<NetControlIntern>& con, CBytestream& bs);
};
typedef std::list<DataPackage> Packages;
Packages packetsToSend;
Packages packetsReceived;
struct Class {
std::string name;
Net_ClassID id;
Net_ClassFlags flags;
Class() : id(INVALID_CLASS_ID), flags(0) {}
Class(const std::string& n, Net_ClassID i, Net_ClassFlags f) : name(n), id(i), flags(f) {}
};
typedef std::map<Net_ClassID, Class> Classes;
Classes classes;
typedef std::map<Net_NodeID, Net_Node*> Nodes;
Nodes nodes;
typedef std::set<Net_Node*> LocalNodes;
LocalNodes localNodes;
DataPackage& pushPackageToSend() { packetsToSend.push_back(DataPackage()); return packetsToSend.back(); }
Net_NodeID getUnusedNodeId() {
if(nodes.size() == 0) return 2;
return nodes.rbegin()->first + 1;
}
Net_Node* getNode(Net_NodeID id) {
if(id == INVALID_NODE_ID) return NULL;
Nodes::iterator i = nodes.find(id);
if(i != nodes.end()) return i->second;
return NULL;
}
Class* getClass(Net_ClassID cid) {
Classes::iterator i = classes.find(cid);
if(i != classes.end()) return &i->second;
return NULL;
}
std::string debugClassName(Net_ClassID cid) {
Classes::iterator i = classes.find(cid);
if(i == classes.end()) return "INVALID-CLASS(" + itoa(cid) + ")";
return "Class(" + itoa(cid) + ":" + i->second.name + ")";
}
};
struct NetNodeIntern {
NetNodeIntern() :
control(NULL), classId(INVALID_CLASS_ID), nodeId(INVALID_NODE_ID), role(eNet_RoleUndefined),
eventForInit(false), eventForRemove(false),
ownerConn(NetConnID_server()),
forthcomingReplicatorInterceptID(0), interceptor(NULL) {}
~NetNodeIntern() { clearReplicationSetup(); }
SmartPointer<NetControlIntern> control;
Net_ClassID classId;
Net_NodeID nodeId;
eNet_NodeRole role;
bool eventForInit, eventForRemove;
std::auto_ptr<Net_BitStream> announceData;
Net_ConnID ownerConn;
typedef std::list< std::pair<Net_Replicator*,bool> > ReplicationSetup;
ReplicationSetup replicationSetup;
Net_InterceptID forthcomingReplicatorInterceptID;
Net_NodeReplicationInterceptor* interceptor;
void clearReplicationSetup() {
for(ReplicationSetup::iterator i = replicationSetup.begin(); i != replicationSetup.end(); ++i)
if(/* autodelete */ i->second)
delete i->first;
replicationSetup.clear();
}
struct Event {
eNet_Event ev;
eNet_NodeRole role;
Net_ConnID cid;
Net_BitStream stream;
Event() : ev(eNet_Event(-1)), role(eNet_RoleUndefined), cid(INVALID_CONN_ID) {}
Event(eNet_Event _ev, eNet_NodeRole _r, Net_ConnID _cid, const Net_BitStream& _s) : ev(_ev), role(_r), cid(_cid), stream(_s) {}
static Event NodeInit(Net_ConnID c) { return Event(eNet_EventInit, eNet_RoleAuthority /* TODO? */, c, Net_BitStream()); }
static Event NodeRemoved(Net_ConnID c) { return Event(eNet_EventRemoved, eNet_RoleAuthority /* TODO? */, c, Net_BitStream()); }
static Event User(const Net_BitStream& s, Net_ConnID c) { return Event(eNet_EventUser, eNet_RoleAuthority /* TODO? */, c, s); }
};
typedef std::list<Event> Events;
Events incomingEvents;
Event curIncomingEvent;
std::string debugStr() {
if(control.get() == NULL) return "Node-no-control";
if(nodeId == INVALID_NODE_ID) return "Node-invalid";
if(classId == INVALID_CLASS_ID) return "Node-no-ClassID";
return "Node(" + itoa(nodeId) + "," + control->debugClassName(classId) + ")";
}
};
template <> void SmartPointer_ObjectDeinit<NetControlIntern> ( NetControlIntern * obj )
{
delete obj;
}
Net_Control::Net_Control(bool isServer) : intern(NULL) {
intern = new NetControlIntern();
intern->isServer = isServer;
}
Net_Control::~Net_Control() {
intern = NULL;
}
void Net_Control::Shutdown() {}
void Net_Control::Net_disconnectAll(Net_BitStream*) {}
void Net_Control::Net_Disconnect(Net_ConnID id, Net_BitStream*) {}
static std::string rawFromBits(Net_BitStream& bits) {
size_t oldPos = bits.bitPos();
bits.resetPos();
std::string ret;
ret.reserve((bits.bitSize() + 7) / 8);
for(size_t i = 0; i < bits.bitSize() / 8; ++i)
ret += getCharFromBits(bits);
if(bits.bitSize() % 8 != 0)
ret += (char) (unsigned char) bits.getInt(bits.bitSize() % 8);
bits.setBitPos(oldPos);
return ret;
}
static void writeEliasGammaNr(CBytestream& bs, size_t n) {
Net_BitStream bits;
Encoding::encodeEliasGamma(bits, n + 1);
bs.writeData(rawFromBits(bits));
}
static size_t readEliasGammaNr(CBytestream& bs) {
Net_BitStream bits(bs.data().substr(bs.GetPos()));
size_t n = Encoding::decodeEliasGamma(bits) - 1;
if(n == size_t(-1)) {
errors << "readEliasGammaNr: stream reached end" << endl;
bs.SkipAll();
return 0;
}
bs.Skip( (bits.bitPos() + 7) / 8 );
return n;
}
void NetControlIntern::DataPackage::send(CBytestream& bs) {
bs.writeByte(type);
if(nodeMustBeSet()) {
if(node.get() == NULL) {
errors << "NetControlIntern::DataPackage::send: node was not set" << endl;
writeEliasGammaNr(bs, INVALID_NODE_ID);
}
else
writeEliasGammaNr(bs, node->nodeId);
}
writeEliasGammaNr(bs, (data.bitSize() + 7)/8);
bs.writeData(rawFromBits(data));
}
void NetControlIntern::DataPackage::read(const SmartPointer<NetControlIntern>& con, CBytestream& bs) {
type = (NetControlIntern::DataPackage::Type) bs.readByte();
nodeId = nodeMustBeSet() ? readEliasGammaNr(bs) : INVALID_NODE_ID;
node = NULL;
size_t len = readEliasGammaNr(bs);
data = Net_BitStream( bs.getRawData( bs.GetPos(), bs.GetPos() + len ) );
bs.Skip(len);
}
static bool composePackagesForConn(CBytestream& bs, const SmartPointer<NetControlIntern>& con, Net_ConnID connid) {
typedef std::list<NetControlIntern::DataPackage*> Packages;
Packages packages;
for(NetControlIntern::Packages::iterator i = con->packetsToSend.begin(); i != con->packetsToSend.end(); ++i)
if(i->connID == INVALID_CONN_ID || i->connID == connid) {
if(!isServerNetConnID(connid)) {
CServerConnection* cl = serverConnFromNetConnID(connid);
if(!cl->gusLoggedIn()) {
if(i->type == NetControlIntern::DataPackage::GPT_ConnectResult)
cl->gusLoggedIn() = true;
else
continue;
}
}
if(i->nodeMustBeSet()) {
if(i->node.get() == NULL) {
errors << "composePackagesForConn: node must be set but is unset" << endl;
continue;
}
if(!con->isServer) {
if(i->repRules & Net_REPRULE_OWNER_2_AUTH) {
if(i->node->ownerConn != con->myConnIdOnServer)
continue;
}
else
continue;
}
else { // server
bool trgtIsOwner = i->node->ownerConn == connid;
if(trgtIsOwner && !(i->repRules & Net_REPRULE_AUTH_2_OWNER))
continue;
if(!trgtIsOwner && !(i->repRules & Net_REPRULE_AUTH_2_PROXY))
continue;
}
}
else { // no node
if(i->repRules != Net_REPRULE_NONE)
warnings << "reprules should be none for gus package of type " << i->type << endl;
}
packages.push_back(&*i);
}
if(packages.size() == 0) return false;
bs.writeByte(con->isServer ? (uchar)S2C_GUSANOS : (uchar)C2S_GUSANOS);
writeEliasGammaNr(bs, packages.size());
for(Packages::iterator i = packages.begin(); i != packages.end(); ++i)
(*i)->send(bs);
//bs.Dump();
return true;
}
static std::vector<CServerConnection*> getConnsForId(Net_ConnID cid) {
std::vector<CServerConnection*> ret;
if(cid == INVALID_CONN_ID) {
ret.reserve(MAX_CLIENTS);
CServerConnection *cl = cServer->getClients();
for(int c = 0; c < MAX_CLIENTS; c++, cl++) {
if(cl->getStatus() == NET_DISCONNECTED || cl->getStatus() == NET_ZOMBIE) continue;
if(cl->getNetEngine() == NULL) continue;
if(cl->isLocalClient()) continue;
if(cl->getClientVersion() < OLXBetaVersion(0,59,1)) continue;
ret.push_back(cl);
}
}
else {
CServerConnection *cl = serverConnFromNetConnID(cid);
if(cl) ret.push_back(cl);
}
return ret;
}
void Net_Control::olxSend(bool /* sendPendingOnly */) {
if(intern->packetsToSend.size() == 0) return;
if(tLX->iGameType == GME_JOIN) {
if(cClient->getServerVersion() >= OLXBetaVersion(0,59,1)) {
CBytestream bs;
if(composePackagesForConn(bs, this->intern, NetConnID_server()))
cClient->getChannel()->AddReliablePacketToSend(bs);
}
} else {
// send to all except local client
std::vector<CServerConnection*> conns = getConnsForId(INVALID_CONN_ID);
for(size_t i = 0; i < conns.size(); ++i) {
CBytestream bs;
if(composePackagesForConn(bs, this->intern, NetConnID_conn(conns[i])))
conns[i]->getNetEngine()->SendPacket(&bs);
}
}
intern->packetsToSend.clear();
}
void Net_Control::olxParse(Net_ConnID src, CBytestream& bs) {
//size_t bsStart = bs.GetPos();
size_t len = readEliasGammaNr(bs);
for(size_t i = 0; i < len; ++i) {
intern->packetsReceived.push_back(NetControlIntern::DataPackage());
NetControlIntern::DataPackage& p = intern->packetsReceived.back();
p.read(this->intern, bs);
p.connID = src;
}
//bs.Dump(PrintOnLogger(notes), std::set<size_t>(), bsStart, bs.GetPos() - bsStart);
}
void Net_Control::olxHandleClientDisconnect(Net_ConnID cl) {
// push node remove events for those nodes where we requested it
for(NetControlIntern::Nodes::iterator i = intern->nodes.begin(); i != intern->nodes.end(); ++i) {
Net_Node* node = i->second;
if(node->intern->eventForRemove)
node->intern->incomingEvents.push_back( NetNodeIntern::Event::NodeRemoved(cl) );
}
}
static void pushNodeUpdate(Net_Control* con, Net_Node* node, const std::vector<Net_BitStream>& replData, Net_RepRules rule) {
NetControlIntern::DataPackage p;
p.connID = INVALID_CONN_ID;
p.sendMode = eNet_ReliableOrdered; // TODO ?
p.repRules = rule;
p.type = NetControlIntern::DataPackage::GPT_NodeUpdate;
p.node = node->intern;
size_t count = 0;
size_t k = 0;
for(NetNodeIntern::ReplicationSetup::iterator j = node->intern->replicationSetup.begin(); j != node->intern->replicationSetup.end(); ++j, ++k) {
if(replData[k].bitSize() > 0) {
Net_ReplicatorBasic* replicator = dynamic_cast<Net_ReplicatorBasic*>(j->first);
if(replicator->getSetup()->repRules & rule) {
p.data.addBitStream(replData[k]);
count++;
}
else
p.data.addBool(false);
}
else
p.data.addBool(false);
}
if(count > 0)
con->intern->pushPackageToSend() = p;
}
void Net_Control::Net_processOutput() {
// goes through the nodes and push Node-updates as needed
for(NetControlIntern::Nodes::iterator i = intern->nodes.begin(); i != intern->nodes.end(); ++i) {
Net_Node* node = i->second;
std::vector<Net_BitStream> replData;
replData.resize(node->intern->replicationSetup.size());
size_t count = 0;
size_t k = 0;
for(NetNodeIntern::ReplicationSetup::iterator j = node->intern->replicationSetup.begin(); j != node->intern->replicationSetup.end(); ++j, ++k) {
Net_ReplicatorBasic* replicator = dynamic_cast<Net_ReplicatorBasic*>(j->first);
if(replicator == NULL) {
errors << "Replicator is not a basic replicator" << endl;
continue;
}
if(!replicator->checkState())
continue;
//eNet_NodeRole remoterole = !con->intern->isServer ? eNet_RoleAuthority : (rule == Net_REPRULE_AUTH_2_OWNER) ? eNet_RoleOwner : eNet_RoleProxy;
if(node->intern->interceptor) {
if(!node->intern->interceptor->outPreUpdateItem(node, eNet_RoleProxy, replicator))
continue;
}
replData[k].addBool(true);
replicator->packData(&replData[k]);
count++;
}
if(count == 0) continue;
if(node->intern->role == eNet_RoleAuthority) {
pushNodeUpdate(this, node, replData, Net_REPRULE_AUTH_2_PROXY);
pushNodeUpdate(this, node, replData, Net_REPRULE_AUTH_2_OWNER);
}
else if(node->intern->role == eNet_RoleOwner) {
pushNodeUpdate(this, node, replData, Net_REPRULE_OWNER_2_AUTH);
}
}
}
static void doNodeUpdate(Net_Node* node, Net_BitStream& bs, Net_ConnID cid) {
size_t i = 0;
for(NetNodeIntern::ReplicationSetup::iterator j = node->intern->replicationSetup.begin(); j != node->intern->replicationSetup.end(); ++j, ++i) {
if( /* skip mark */ !bs.getBool()) continue;
Net_ReplicatorBasic* replicator = dynamic_cast<Net_ReplicatorBasic*>(j->first);
if(replicator == NULL) {
errors << "Replicator " << i << " in update of node " << node->intern->debugStr() << " is not a basic replicator" << endl;
break; // nothing else we can do
}
bool store = true;
if(node->intern->interceptor) {
Net_BitStream peekStream(bs);
replicator->peekStream = &peekStream;
store = node->intern->interceptor->inPreUpdateItem(node, cid, eNet_RoleAuthority, replicator);
replicator->clearPeekData();
replicator->ptr = NULL;
replicator->peekStream = NULL;
}
replicator->unpackData(&bs, store);
}
}
static void tellClientAboutNode(Net_Node* node, Net_ConnID connid) {
if(node->intern->interceptor)
node->intern->interceptor->outPreReplicateNode(node, (connid == node->intern->ownerConn) ? eNet_RoleOwner : eNet_RoleProxy);
NetControlIntern::DataPackage& p = node->intern->control->pushPackageToSend();
p.connID = connid;
p.sendMode = eNet_ReliableOrdered;
p.repRules = Net_REPRULE_AUTH_2_ALL;
p.type = NetControlIntern::DataPackage::GPT_NodeInit;
p.node = node->intern;
p.data.addInt(node->intern->classId, 32);
p.data.addInt(node->intern->ownerConn, 32);
bool announce = node->intern->control->classes[node->intern->classId].flags & Net_CLASSFLAG_ANNOUNCEDATA;
if(node->intern->announceData.get() && !announce)
warnings << "node " << node->intern->debugStr() << " has announce data but class doesnt have flag set" << endl;
else if(!node->intern->announceData.get() && announce)
warnings << "node " << node->intern->debugStr() << " has no announce data but class requests it" << endl;
else if(node->intern->announceData.get() && announce)
p.data.addBitStream(*node->intern->announceData.get());
if(node->intern->eventForInit) {
std::vector<CServerConnection*> conns = getConnsForId(p.connID);
for(size_t i = 0; i < conns.size(); ++i)
node->intern->incomingEvents.push_back( NetNodeIntern::Event::NodeInit(NetConnID_conn(conns[i])) );
}
}
static bool unregisterNode(Net_Node* node);
static void tellClientAboutAllNodes(const SmartPointer<NetControlIntern>& con, Net_ConnID connid) {
for(NetControlIntern::Nodes::iterator i = con->nodes.begin(); i != con->nodes.end(); ++i) {
tellClientAboutNode(i->second, connid);
}
}
void Net_Control::Net_processInput() {
for(NetControlIntern::Packages::iterator i = intern->packetsReceived.begin(); i != intern->packetsReceived.end(); ++i) {
switch(i->type) {
case NetControlIntern::DataPackage::GPT_Direct:
Net_cbDataReceived(i->connID, i->data);
break;
case NetControlIntern::DataPackage::GPT_ConnectRequest: {
if(!intern->isServer) {
warnings << "Net_processInput: got GPT_ConnectRequest as client" << endl;
break;
}
CServerConnection* cl = serverConnFromNetConnID(i->connID);
if(cl == NULL) {
errors << "Net_processInput GPT_ConnectRequest: didn't found connection for id " << i->connID << endl;
break;
}
if(cl->gusLoggedIn()) {
warnings << "Net_processInput GPT_ConnectRequest: client " << i->connID << " was already logged in" << endl;
break;
}
// in olxSend, when we handle this package, we set gusLoggedIn() = true
NetControlIntern::DataPackage& p = intern->pushPackageToSend();
p.connID = i->connID;
p.sendMode = eNet_ReliableOrdered;
p.repRules = Net_REPRULE_NONE;
p.type = NetControlIntern::DataPackage::GPT_ConnectResult;
p.data.addInt(i->connID, 32); // we tell client about its connection ID
tellClientAboutAllNodes(this->intern, i->connID);
Net_cbConnectionSpawned(i->connID);
break;
}
case NetControlIntern::DataPackage::GPT_ConnectResult: {
if(intern->isServer) {
warnings << "Net_processInput: got GPT_ConnectResult as server" << endl;
break;
}
intern->myConnIdOnServer = i->data.getInt(32);
Net_cbConnectResult(eNet_ConnAccepted);
break;
}
case NetControlIntern::DataPackage::GPT_NodeInit: {
if(intern->isServer) {
warnings << "Net_processInput: got GPT_NodeInit as server" << endl;
break;
}
Net_ClassID classId = i->data.getInt(32);
Net_ConnID ownerConnId = i->data.getInt(32);
NetControlIntern::Class* nodeClass = intern->getClass(classId);
if(nodeClass == NULL) {
warnings << "NodeInit for node " << i->nodeId << " with class " << classId << " failed because that class is unknown" << endl;
break;
}
intern->cbNodeRequest_Dynamic = true;
intern->cbNodeRequest_nodeId = i->nodeId;
bool announce = nodeClass->flags & Net_CLASSFLAG_ANNOUNCEDATA;
eNet_NodeRole role = (ownerConnId == intern->myConnIdOnServer) ? eNet_RoleOwner : eNet_RoleProxy;
Net_cbNodeRequest_Dynamic(i->connID, classId, announce ? &i->data : NULL, role, i->nodeId);
if(intern->cbNodeRequest_Dynamic) { // we didnt created the node - otherwise this would be false
errors << "Net_cbNodeRequest_Dynamic callback didnt created the node " << i->nodeId << " with class " << classId << endl;
intern->cbNodeRequest_Dynamic = false; // reset anyway
break;
}
Net_Node* node = intern->getNode(i->nodeId);
if(node == NULL) {
errors << "NodeInit: node " << i->nodeId << " not found after dynamic creation" << endl;
break;
}
node->intern->ownerConn = ownerConnId;
node->intern->role = role;
if(node->intern->classId != classId)
warnings << "NodeInit requested a node of class " << classId << " but a node of class " << node->intern->classId << " was created" << endl;
break;
}
case NetControlIntern::DataPackage::GPT_NodeRemove: {
if(intern->isServer) {
warnings << "Net_processInput: got GPT_NodeRemove as server" << endl;
break;
}
Net_Node* node = intern->getNode(i->nodeId);
if(node == NULL) {
warnings << "NodeRemove: node " << i->nodeId << " not found" << endl;
break;
}
// we are proxy or owner -> in any case, always push this event
node->intern->incomingEvents.push_back( NetNodeIntern::Event::NodeRemoved(i->connID) );
unregisterNode(node);
break;
}
case NetControlIntern::DataPackage::GPT_NodeUpdate: {
Net_Node* node = intern->getNode(i->nodeId);
if(node == NULL) {
warnings << "NodeUpdate: node " << i->nodeId << " not found" << endl;
break;
}
if(intern->isServer) {
if(node->intern->ownerConn != i->connID) {
warnings << "Net_processInput: got GPT_NodeUpdate as server from proxy" << endl;
break;
}
}
doNodeUpdate(node, i->data, i->connID);
break;
}
case NetControlIntern::DataPackage::GPT_NodeEvent: {
Net_Node* node = intern->getNode(i->nodeId);
if(node == NULL) {
warnings << "NodeEvent: node " << i->nodeId << " not found" << endl;
break;
}
if(intern->isServer) {
if(node->intern->ownerConn != i->connID) {
warnings << "NodeEvent: got event for node " << i->nodeId << " from non-owner " << i->connID << ", owner is " << node->intern->ownerConn << endl;
break;
}
}
node->intern->incomingEvents.push_back( NetNodeIntern::Event::User(i->data, i->connID) );
break;
}
default:
warnings << "invalid Gusanos data package type" << endl;
}
}
intern->packetsReceived.clear();
}
void Net_Control::Net_ConnectToServer() {
NetControlIntern::DataPackage& p = intern->pushPackageToSend();
p.connID = NetConnID_server();
p.type = NetControlIntern::DataPackage::GPT_ConnectRequest;
p.sendMode = eNet_ReliableOrdered;
p.repRules = Net_REPRULE_NONE; // this is anyway ignored here
}
void Net_Control::Net_sendData(Net_ConnID id, Net_BitStream* s, eNet_SendMode m) {
NetControlIntern::DataPackage& p = intern->pushPackageToSend();
p.connID = id;
p.sendMode = m;
p.repRules = Net_REPRULE_NONE; // anyway ignored
p.type = NetControlIntern::DataPackage::GPT_Direct;
p.data = *s;
delete s;
}
Net_ClassID Net_Control::Net_registerClass(const std::string& classname, Net_ClassFlags flags) {
Net_ClassID id = 1;
if(intern->classes.size() > 0)
id = intern->classes.rbegin()->first + 1;
intern->classes[id] = NetControlIntern::Class(classname, id, flags);
return id;
}
void Net_Control::Net_setControlID(int id) { intern->controlId = id; }
void Net_Control::Net_setDebugName(const std::string& n) { intern->debugName = n; }
void Net_Control::Net_requestNetMode(Net_ConnID, int) {
// we silently ignore that because we dont have different netstream levels
}
static bool __unregisterNode(Net_Node* node) {
if(node->intern->nodeId != INVALID_NODE_ID) {
if(node->intern->control.get() == NULL) {
errors << "Net_Node::unregisterNode: node was a valid id but no reference to Net_Control" << endl;
return false;
}
if(node->intern->nodeId != UNIQUE_NODE_ID) { // dynamic node
NetControlIntern::Nodes& nodes = node->intern->control->nodes;
NetControlIntern::Nodes::iterator i = nodes.find(node->intern->nodeId);
if(i == nodes.end()) {
errors << "Net_Node::unregisterNode: dynamic node not found in node-list" << endl;
return false;
}
nodes.erase(i);
if(node->intern->role == eNet_RoleAuthority) {
NetControlIntern::DataPackage& p = node->intern->control->pushPackageToSend();
p.connID = 0;
p.sendMode = eNet_ReliableOrdered;
p.repRules = Net_REPRULE_AUTH_2_ALL;
p.type = NetControlIntern::DataPackage::GPT_NodeRemove;
p.node = node->intern;
}
}
else { // unique node
NetControlIntern::LocalNodes& nodes = node->intern->control->localNodes;
NetControlIntern::LocalNodes::iterator i = nodes.find(node);
if(i == nodes.end()) {
errors << "Net_Node::unregisterNode: unique node not found in node-list" << endl;
return false;
}
nodes.erase(i);
}
notes << "Node " << node->intern->nodeId << " with class " << node->intern->control->classes[node->intern->classId].name << " unregisters" << endl;
return true;
}
return false;
}
static bool unregisterNode(Net_Node* node) {
bool ret = __unregisterNode(node);
return ret;
}
template <> void SmartPointer_ObjectDeinit<NetNodeIntern> ( NetNodeIntern * obj )
{
delete obj;
}
Net_Node::Net_Node() {
intern = new NetNodeIntern();
}
Net_Node::~Net_Node() {
unregisterNode(this);
intern = NULL;
}
eNet_NodeRole Net_Node::getRole() { return intern->role; }
void Net_Node::setOwner(Net_ConnID cid) { intern->ownerConn = cid; }
void Net_Node::setAnnounceData(Net_BitStream* s) { intern->announceData = std::auto_ptr<Net_BitStream>(s); }
Net_NodeID Net_Node::getNetworkID() { return intern->nodeId; }
static void tellAllClientsAboutNode(Net_Node* node) {
for(int i = 0; i < MAX_CLIENTS; ++i) {
if(cServer->getClients()[i].getStatus() != NET_CONNECTED) continue;
if(cServer->getClients()[i].getNetEngine() == NULL) continue;
tellClientAboutNode(node, NetConnID_conn(&cServer->getClients()[i]));
}
}
static bool registerNode(Net_ClassID classid, Net_Node* node, Net_NodeID nid, eNet_NodeRole role, const SmartPointer<NetControlIntern>& con) {
if(node->intern->nodeId != INVALID_NODE_ID) {
errors << "Net_Node::registerNode " << node->intern->debugStr() << " trying to register node twice" << endl;
return false;
}
if(con.get() == NULL) {
errors << "Net_Node::registerNode without Net_Control" << endl;
return false;
}
if(nid != UNIQUE_NODE_ID && con->getNode(nid)) {
errors << "Net_Node::registerNode " << node->intern->debugStr() << " node id " << nid << " was already taken by " << con->getNode(nid)->intern->debugStr() << endl;
return false;
}
node->intern->control = con;
node->intern->classId = classid;
node->intern->nodeId = nid;
node->intern->role = role;
if(nid == UNIQUE_NODE_ID)
con->localNodes.insert(node);
else {
con->nodes[nid] = node;
if(role == eNet_RoleAuthority)
tellAllClientsAboutNode(node);
}
notes << "Node " << nid << " registers with role " << role << " and class " << con->classes[classid].name << endl;
return true;
}
bool Net_Node::registerNodeUnique(Net_ClassID cid, eNet_NodeRole role, Net_Control* con) {
return registerNode(cid, this, UNIQUE_NODE_ID, role, con->intern);
}
bool Net_Node::registerNodeDynamic(Net_ClassID cid, Net_Control* con) {
eNet_NodeRole role = con->intern->cbNodeRequest_Dynamic ? eNet_RoleProxy : eNet_RoleAuthority;
if(con->intern->isServer && role != eNet_RoleAuthority) {
errors << "registerNodeDynamic: want to register proxy node on server" << endl;
return false; // stop because otherwise we probably would crash
}
if(!con->intern->isServer && role == eNet_RoleAuthority) {
errors << "registerNodeDynamic: want to register authority node on client" << endl;
return false; // stop because otherwise we probably would crash
}
Net_NodeID nid = con->intern->cbNodeRequest_Dynamic ? con->intern->cbNodeRequest_nodeId : con->intern->getUnusedNodeId();
con->intern->cbNodeRequest_Dynamic = false; // only for first node
return registerNode(cid, this, nid, role, con->intern);
}
bool Net_Node::registerRequestedNode(Net_ClassID cid, Net_Control* con) { return registerNodeDynamic(cid, con); }
void Net_Node::applyForNetLevel(int something) {}
void Net_Node::removeFromNetLevel(int something) {}
void Net_Node::setEventNotification(bool eventForInit /* eNet_EventInit */, bool eventForRemove /* eNet_EventRemoved */) {
intern->eventForInit = eventForInit;
intern->eventForRemove = eventForRemove;
}
void Net_Node::sendEvent(eNet_SendMode m, Net_RepRules rules, Net_BitStream* s) {
NetControlIntern::DataPackage& p = intern->control->pushPackageToSend();
p.connID = INVALID_CONN_ID;
p.sendMode = m;
p.repRules = rules;
p.type = NetControlIntern::DataPackage::GPT_NodeEvent;
p.node = intern;
p.data = *s;
delete s;
}
void Net_Node::sendEventDirect(eNet_SendMode m, Net_BitStream* s, Net_ConnID cid) {
if(!intern->control->isServer) {
errors << "Net_Node::sendEventDirect (node " << intern->nodeId << ") only works as server" << endl;
return;
}
NetControlIntern::DataPackage& p = intern->control->pushPackageToSend();
p.connID = cid;
p.sendMode = m;
p.repRules = Net_REPRULE_AUTH_2_ALL;
p.type = NetControlIntern::DataPackage::GPT_NodeEvent;
p.node = intern;
p.data = *s;
delete s;
}
bool Net_Node::checkEventWaiting() { return intern->incomingEvents.size() > 0; }
Net_BitStream* Net_Node::getNextEvent(eNet_Event* e, eNet_NodeRole* r, Net_ConnID* cid) {
if(intern->incomingEvents.size() == 0) return NULL;
NetNodeIntern::Event& ev = intern->curIncomingEvent = intern->incomingEvents.front();
intern->incomingEvents.pop_front();
if(e) *e = ev.ev;
if(r) *r = ev.role;
if(cid) *cid = ev.cid;
return &ev.stream;
}
void Net_Node::beginReplicationSetup() {
intern->clearReplicationSetup();
}
void Net_Node::addReplicator(Net_Replicator* rep, bool autodelete) {
intern->replicationSetup.push_back( std::make_pair(rep, autodelete) );
}
void Net_Node::addReplicationInt(Net_S32* n, int bits, bool, Net_RepFlags f, Net_RepRules r, Net_InterceptID id, int p2, int p3) {
if((f & Net_REPFLAG_INTERCEPT) && id == 0)
id = intern->forthcomingReplicatorInterceptID;
struct IntReplicator : Net_ReplicatorBasic {
Net_ReplicatorSetup setup;
typedef Net_S32 Num;
Num* n;
Num old;
int bits;
IntReplicator(const Net_ReplicatorSetup& s) : Net_ReplicatorBasic(&setup), setup(s) {}
Net_Replicator* Duplicate(Net_Replicator*) { return new IntReplicator(*this); }
void* peekData() { peekDataStore(new Num(peekStream->getInt(bits))); return peekDataRetrieve(); }
void clearPeekData() { Num* p = (Num*)peekDataRetrieve(); if(p) delete p; }
bool checkState() { return *n != old; }
void packData(Net_BitStream *_stream) { _stream->addInt(*n, bits); old = *n; }
void unpackData(Net_BitStream *_stream, bool _store) {
Num i = _stream->getInt(bits);
if(_store) *n = i;
}
};
IntReplicator* rep = new IntReplicator(Net_ReplicatorSetup(f, r, id, p2, p3));
rep->n = n;
rep->old = *n;
rep->bits = bits;
addReplicator(rep, true);
}
void Net_Node::addReplicationFloat(Net_Float* n, int bits, Net_RepFlags f, Net_RepRules r, Net_InterceptID id, int p2, int p3) {
if((f & Net_REPFLAG_INTERCEPT) && id == 0)
id = intern->forthcomingReplicatorInterceptID;
struct FloatReplicator : Net_ReplicatorBasic {
Net_ReplicatorSetup setup;
typedef Net_Float Num;
Num* n;
Num old;
int bits;
FloatReplicator(const Net_ReplicatorSetup& s) : Net_ReplicatorBasic(&setup), setup(s) {}
Net_Replicator* Duplicate(Net_Replicator*) { return new FloatReplicator(*this); }
void* peekData() { peekDataStore(new Num(peekStream->getFloat(bits))); return peekDataRetrieve(); }
void clearPeekData() { Num* p = (Num*)peekDataRetrieve(); if(p) delete p; }
bool checkState() { return *n != old; }
void packData(Net_BitStream *_stream) { _stream->addFloat(*n, bits); old = *n; }
void unpackData(Net_BitStream *_stream, bool _store) {
Num i = _stream->getFloat(bits);
if(_store) *n = i;
}
};
FloatReplicator* rep = new FloatReplicator(Net_ReplicatorSetup(f, r, id, p2, p3));
rep->n = n;
rep->old = *n;
rep->bits = bits;
addReplicator(rep, true);
}
void Net_Node::endReplicationSetup() {}
void Net_Node::setInterceptID(Net_InterceptID id) { intern->forthcomingReplicatorInterceptID = id; }
void Net_Node::setReplicationInterceptor(Net_NodeReplicationInterceptor* inter) { intern->interceptor = inter; }
Net_ReplicatorSetup::Net_ReplicatorSetup(Net_RepFlags flags, Net_RepRules rules, Net_InterceptID id, int p2, int p3) {
repFlags = flags;
repRules = rules;
interceptId = id;
}
Net_ConnID NetConnID_server() {
return Net_ConnID(-1);
}
Net_ConnID NetConnID_conn(CServerConnection* cl) {
for(int i = 0; i < MAX_CLIENTS; i++) {
if(&cServer->getClients()[i] == cl) return i + 1;
}
errors << "NetConnID_conn: connection invalid" << endl;
return INVALID_CONN_ID;
}
CServerConnection* serverConnFromNetConnID(Net_ConnID id) {
if(!cServer->getClients() || !cServer->isServerRunning()) {
errors << "serverConnFromNetConnID: server is not running" << endl;
return NULL;
}
if(id >= 1 && id <= MAX_CLIENTS) return &cServer->getClients()[id - 1];
errors << "serverConnFromNetConnID: id " << id << " is invalid" << endl;
return NULL;
}
bool isServerNetConnID(Net_ConnID id) {
return id == NetConnID_server();
}
do initial node update for new nodes
/*
* netstream.cpp
* Gusanos
*
* Created by Albert Zeyer on 30.11.09.
* code under LGPL
*
*/
#include "netstream.h"
#include "Networking.h"
#include "EndianSwap.h"
#include "gusanos/encoding.h"
#include "CBytestream.h"
#include "Protocol.h"
#include "CServer.h"
#include "CServerConnection.h"
#include "CClient.h"
#include "CServerNetEngine.h"
#include "CChannel.h"
Net_BitStream::Net_BitStream(const std::string& raw) {
m_readPos = 0;
m_data.reserve( raw.size() * 8 );
for(size_t i = 0; i < raw.size(); ++i)
addInt((unsigned char) raw[i], 8);
}
// Grows the bit stream if the number of bits that are going to be added exceeds the buffer size
void Net_BitStream::growIfNeeded(size_t addBits)
{
m_data.reserve(m_data.size() + addBits);
}
static const unsigned char bitMasks[] = { 1, 2, 4, 8, 16, 32, 64, 128 };
void Net_BitStream::writeBits(const std::vector<bool>& bits)
{
growIfNeeded(bits.size());
for(std::vector<bool>::const_iterator i = bits.begin(); i != bits.end(); ++i)
m_data.push_back(*i);
}
std::vector<bool> Net_BitStream::readBits(size_t bitCount)
{
std::vector<bool> ret;
ret.reserve(bitCount);
for(size_t i = 0; i < bitCount && m_readPos < m_data.size(); ++i, ++m_readPos)
ret.push_back(m_data[m_readPos]);
if(ret.size() < bitCount)
errors << "Net_BitStream::readBits: reading from behind end" << endl;
return ret;
}
void Net_BitStream::addBool(bool b) {
m_data.push_back(b);
}
void Net_BitStream::addInt(int n, int bits) {
growIfNeeded(bits);
for(int i = 0; i < bits; ++i)
m_data.push_back( (((unsigned long)n >> i) & 1) != 0 );
}
void Net_BitStream::addSignedInt(int n, int bits) {
growIfNeeded(bits);
addBool( n < 0 );
if( n >= 0)
addInt(n, bits - 1);
else
addInt((1 << (bits - 1)) - n, bits - 1);
}
void Net_BitStream::addFloat(float f, int bits) {
// TODO: check bits
union {
char bytes[4];
float f;
} data;
data.f = f;
BEndianSwap(data.f);
addBitStream( Net_BitStream( std::string(data.bytes, 4) ) );
}
void Net_BitStream::addBitStream(const Net_BitStream& str) {
writeBits(str.m_data);
}
void Net_BitStream::addString(const std::string& str) {
std::string::const_iterator end = str.end();
for(std::string::const_iterator i = str.begin(); i != end; ++i)
if(*i == 0) {
warnings << "Net_BitStream::addString: strings contains NULL-char: " << str << endl;
end = i;
}
std::string raw(str.begin(), end);
raw += '\0';
addBitStream(Net_BitStream(raw));
}
bool Net_BitStream::getBool() {
if(m_readPos < m_data.size()) {
bool ret = m_data[m_readPos];
m_readPos++;
return ret;
}
errors << "Net_BitStream::getBool: reading from behind end" << endl;
return false;
}
int Net_BitStream::getInt(int bits) {
unsigned long ret = 0;
for(int i = 0; i < bits; ++i)
if(getBool()) ret |= 1 << i;
return ret;
}
int Net_BitStream::getSignedInt(int bits) {
bool sign = getBool();
if( !sign /*n >= 0*/ )
return getInt(bits - 1);
else
return (1 << (bits - 1)) - getInt(bits - 1);
}
static char getCharFromBits(Net_BitStream& bs) {
return (char) (unsigned char) bs.getInt(8);
}
float Net_BitStream::getFloat(int bits) {
// TODO: see addFloat, check bits
union {
char bytes[4];
float f;
} data;
for(int i = 0; i < 4; ++i)
data.bytes[i] = getCharFromBits(*this);
BEndianSwap(data.f);
return data.f;
}
std::string Net_BitStream::getString() {
std::string ret;
while(char c = getCharFromBits(*this))
ret += c;
return ret;
}
Net_BitStream* Net_BitStream::Duplicate() {
return new Net_BitStream(*this);
}
void Net_BitStream::reset()
{
m_readPos = 0;
m_data.clear();
}
//
// Net_BitStream Tests
//
bool Net_BitStream::testBool()
{
reset();
addBool(true);
addBool(false);
bool r1 = getBool();
bool r2 = getBool();
return r1 && !r2;
}
bool Net_BitStream::testInt()
{
reset();
for (int i = 0; i < 32; i++)
addInt(1 << i, i + 1);
for (int i = 0; i < 32; i++)
if (getInt(i + 1) != (1 << i))
return false;
return true;
}
bool Net_BitStream::testFloat()
{
reset();
union T {
int n;
float f;
};
for (int i = 0; i < 32; i++) {
T t; t.n = 1 << i;
addFloat(t.f, i + 1);
}
for (int i = 0; i < 32; i++) {
T t; t.f = getFloat(i + 1);
if (t.n != (1 << i))
return false;
}
return true;
}
bool Net_BitStream::testStream()
{
reset();
Net_BitStream s2;
s2.addBool(true);
s2.addBool(false);
s2.addInt(50, 32);
s2.addInt(60, 16);
s2.addInt(30, 5);
addInt(14, 4);
addBool(true);
addBitStream(s2);
if (getInt(4) != 14)
return false;
if (getBool() != true)
return false;
if (getBool() != true)
return false;
if (getBool() != false)
return false;
if (getInt(32) != 50)
return false;
if (getInt(16) != 60)
return false;
if (getInt(5) != 30)
return false;
return true;
}
bool Net_BitStream::testSafety()
{
try {
reset();
getBool();
addInt(5, 5);
getInt(6);
addFloat(0.0f, 32);
getFloat(31);
getInt(5);
} catch (...) {
return false;
}
return true;
}
bool Net_BitStream::testString()
{
addBool(true);
addString("some short text to test bitstream");
if (getBool() != true)
return false;
if (std::string(getString()) != "some short text to test bitstream")
return false;
return true;
}
bool Net_BitStream::runTests()
{
bool res = true;
if (!testBool()) {
printf("Boolean test failed!\n");
res = false;
}
if (!testInt()) {
printf("Integer test failed\n");
res = false;
}
if (!testFloat()) {
printf("Float test failed\n");
res = false;
}
if (!testStream()) {
printf("Stream test failed\n");
res = false;
}
if (!testString()) {
printf("String test failed\n");
res = false;
}
if (!testSafety()) {
printf("Safety test failed\n");
res = false;
}
return res;
}
struct NetControlIntern {
NetControlIntern() {
isServer = false;
controlId = 0;
myConnIdOnServer = INVALID_CONN_ID;
cbNodeRequest_Dynamic = false;
cbNodeRequest_nodeId = INVALID_NODE_ID;
}
bool isServer;
int controlId;
std::string debugName;
Net_ConnID myConnIdOnServer;
bool cbNodeRequest_Dynamic;
Net_NodeID cbNodeRequest_nodeId;
struct DataPackage {
DataPackage() : type(Type(-1)), sendMode(eNet_ReliableOrdered), repRules(Net_REPRULE_NONE) {}
enum Type {
GPT_NodeUpdate, // very first because the most often -> less bits to sends
GPT_NodeInit,
GPT_NodeRemove,
GPT_NodeEvent, /* eNet_EventUser */
// here start all types where we dont send the nodeID
GPT_Direct,
GPT_ConnectRequest,
GPT_ConnectResult,
};
Type type;
Net_ConnID connID; // target or source
SmartPointer<NetNodeIntern> node; // node this is about; this is used for sending
Net_NodeID nodeId; // node this is about; this is used for receiving; NULL iff !nodeMustBeSet()
Net_BitStream data;
eNet_SendMode sendMode;
Net_RepRules repRules; // if node is set, while sending, these are checked
bool nodeMustBeSet() { return type < GPT_Direct; }
void send(CBytestream& bs);
void read(const SmartPointer<NetControlIntern>& con, CBytestream& bs);
};
typedef std::list<DataPackage> Packages;
Packages packetsToSend;
Packages packetsReceived;
struct Class {
std::string name;
Net_ClassID id;
Net_ClassFlags flags;
Class() : id(INVALID_CLASS_ID), flags(0) {}
Class(const std::string& n, Net_ClassID i, Net_ClassFlags f) : name(n), id(i), flags(f) {}
};
typedef std::map<Net_ClassID, Class> Classes;
Classes classes;
typedef std::map<Net_NodeID, Net_Node*> Nodes;
Nodes nodes;
typedef std::set<Net_Node*> LocalNodes;
LocalNodes localNodes;
DataPackage& pushPackageToSend() { packetsToSend.push_back(DataPackage()); return packetsToSend.back(); }
Net_NodeID getUnusedNodeId() {
if(nodes.size() == 0) return 2;
return nodes.rbegin()->first + 1;
}
Net_Node* getNode(Net_NodeID id) {
if(id == INVALID_NODE_ID) return NULL;
Nodes::iterator i = nodes.find(id);
if(i != nodes.end()) return i->second;
return NULL;
}
Class* getClass(Net_ClassID cid) {
Classes::iterator i = classes.find(cid);
if(i != classes.end()) return &i->second;
return NULL;
}
std::string debugClassName(Net_ClassID cid) {
Classes::iterator i = classes.find(cid);
if(i == classes.end()) return "INVALID-CLASS(" + itoa(cid) + ")";
return "Class(" + itoa(cid) + ":" + i->second.name + ")";
}
};
struct NetNodeIntern {
NetNodeIntern() :
control(NULL), classId(INVALID_CLASS_ID), nodeId(INVALID_NODE_ID), role(eNet_RoleUndefined),
eventForInit(false), eventForRemove(false),
ownerConn(NetConnID_server()),
forthcomingReplicatorInterceptID(0), interceptor(NULL) {}
~NetNodeIntern() { clearReplicationSetup(); }
SmartPointer<NetControlIntern> control;
Net_ClassID classId;
Net_NodeID nodeId;
eNet_NodeRole role;
bool eventForInit, eventForRemove;
std::auto_ptr<Net_BitStream> announceData;
Net_ConnID ownerConn;
typedef std::list< std::pair<Net_Replicator*,bool> > ReplicationSetup;
ReplicationSetup replicationSetup;
Net_InterceptID forthcomingReplicatorInterceptID;
Net_NodeReplicationInterceptor* interceptor;
void clearReplicationSetup() {
for(ReplicationSetup::iterator i = replicationSetup.begin(); i != replicationSetup.end(); ++i)
if(/* autodelete */ i->second)
delete i->first;
replicationSetup.clear();
}
struct Event {
eNet_Event ev;
eNet_NodeRole role;
Net_ConnID cid;
Net_BitStream stream;
Event() : ev(eNet_Event(-1)), role(eNet_RoleUndefined), cid(INVALID_CONN_ID) {}
Event(eNet_Event _ev, eNet_NodeRole _r, Net_ConnID _cid, const Net_BitStream& _s) : ev(_ev), role(_r), cid(_cid), stream(_s) {}
static Event NodeInit(Net_ConnID c) { return Event(eNet_EventInit, eNet_RoleAuthority /* TODO? */, c, Net_BitStream()); }
static Event NodeRemoved(Net_ConnID c) { return Event(eNet_EventRemoved, eNet_RoleAuthority /* TODO? */, c, Net_BitStream()); }
static Event User(const Net_BitStream& s, Net_ConnID c) { return Event(eNet_EventUser, eNet_RoleAuthority /* TODO? */, c, s); }
};
typedef std::list<Event> Events;
Events incomingEvents;
Event curIncomingEvent;
std::string debugStr() {
if(control.get() == NULL) return "Node-no-control";
if(nodeId == INVALID_NODE_ID) return "Node-invalid";
if(classId == INVALID_CLASS_ID) return "Node-no-ClassID";
return "Node(" + itoa(nodeId) + "," + control->debugClassName(classId) + ")";
}
};
template <> void SmartPointer_ObjectDeinit<NetControlIntern> ( NetControlIntern * obj )
{
delete obj;
}
Net_Control::Net_Control(bool isServer) : intern(NULL) {
intern = new NetControlIntern();
intern->isServer = isServer;
}
Net_Control::~Net_Control() {
intern = NULL;
}
void Net_Control::Shutdown() {}
void Net_Control::Net_disconnectAll(Net_BitStream*) {}
void Net_Control::Net_Disconnect(Net_ConnID id, Net_BitStream*) {}
static std::string rawFromBits(Net_BitStream& bits) {
size_t oldPos = bits.bitPos();
bits.resetPos();
std::string ret;
ret.reserve((bits.bitSize() + 7) / 8);
for(size_t i = 0; i < bits.bitSize() / 8; ++i)
ret += getCharFromBits(bits);
if(bits.bitSize() % 8 != 0)
ret += (char) (unsigned char) bits.getInt(bits.bitSize() % 8);
bits.setBitPos(oldPos);
return ret;
}
static void writeEliasGammaNr(CBytestream& bs, size_t n) {
Net_BitStream bits;
Encoding::encodeEliasGamma(bits, n + 1);
bs.writeData(rawFromBits(bits));
}
static size_t readEliasGammaNr(CBytestream& bs) {
Net_BitStream bits(bs.data().substr(bs.GetPos()));
size_t n = Encoding::decodeEliasGamma(bits) - 1;
if(n == size_t(-1)) {
errors << "readEliasGammaNr: stream reached end" << endl;
bs.SkipAll();
return 0;
}
bs.Skip( (bits.bitPos() + 7) / 8 );
return n;
}
void NetControlIntern::DataPackage::send(CBytestream& bs) {
bs.writeByte(type);
if(nodeMustBeSet()) {
if(node.get() == NULL) {
errors << "NetControlIntern::DataPackage::send: node was not set" << endl;
writeEliasGammaNr(bs, INVALID_NODE_ID);
}
else
writeEliasGammaNr(bs, node->nodeId);
}
writeEliasGammaNr(bs, (data.bitSize() + 7)/8);
bs.writeData(rawFromBits(data));
}
void NetControlIntern::DataPackage::read(const SmartPointer<NetControlIntern>& con, CBytestream& bs) {
type = (NetControlIntern::DataPackage::Type) bs.readByte();
nodeId = nodeMustBeSet() ? readEliasGammaNr(bs) : INVALID_NODE_ID;
node = NULL;
size_t len = readEliasGammaNr(bs);
data = Net_BitStream( bs.getRawData( bs.GetPos(), bs.GetPos() + len ) );
bs.Skip(len);
}
static bool composePackagesForConn(CBytestream& bs, const SmartPointer<NetControlIntern>& con, Net_ConnID connid) {
typedef std::list<NetControlIntern::DataPackage*> Packages;
Packages packages;
for(NetControlIntern::Packages::iterator i = con->packetsToSend.begin(); i != con->packetsToSend.end(); ++i)
if(i->connID == INVALID_CONN_ID || i->connID == connid) {
if(!isServerNetConnID(connid)) {
CServerConnection* cl = serverConnFromNetConnID(connid);
if(!cl->gusLoggedIn()) {
if(i->type == NetControlIntern::DataPackage::GPT_ConnectResult)
cl->gusLoggedIn() = true;
else
continue;
}
}
if(i->nodeMustBeSet()) {
if(i->node.get() == NULL) {
errors << "composePackagesForConn: node must be set but is unset" << endl;
continue;
}
if(!con->isServer) {
if(i->repRules & Net_REPRULE_OWNER_2_AUTH) {
if(i->node->ownerConn != con->myConnIdOnServer)
continue;
}
else
continue;
}
else { // server
bool trgtIsOwner = i->node->ownerConn == connid;
if(trgtIsOwner && !(i->repRules & Net_REPRULE_AUTH_2_OWNER))
continue;
if(!trgtIsOwner && !(i->repRules & Net_REPRULE_AUTH_2_PROXY))
continue;
}
}
else { // no node
if(i->repRules != Net_REPRULE_NONE)
warnings << "reprules should be none for gus package of type " << i->type << endl;
}
packages.push_back(&*i);
}
if(packages.size() == 0) return false;
bs.writeByte(con->isServer ? (uchar)S2C_GUSANOS : (uchar)C2S_GUSANOS);
writeEliasGammaNr(bs, packages.size());
for(Packages::iterator i = packages.begin(); i != packages.end(); ++i)
(*i)->send(bs);
//bs.Dump();
return true;
}
static std::vector<CServerConnection*> getConnsForId(Net_ConnID cid) {
std::vector<CServerConnection*> ret;
if(cid == INVALID_CONN_ID) {
ret.reserve(MAX_CLIENTS);
CServerConnection *cl = cServer->getClients();
for(int c = 0; c < MAX_CLIENTS; c++, cl++) {
if(cl->getStatus() == NET_DISCONNECTED || cl->getStatus() == NET_ZOMBIE) continue;
if(cl->getNetEngine() == NULL) continue;
if(cl->isLocalClient()) continue;
if(cl->getClientVersion() < OLXBetaVersion(0,59,1)) continue;
ret.push_back(cl);
}
}
else {
CServerConnection *cl = serverConnFromNetConnID(cid);
if(cl) ret.push_back(cl);
}
return ret;
}
void Net_Control::olxSend(bool /* sendPendingOnly */) {
if(intern->packetsToSend.size() == 0) return;
if(tLX->iGameType == GME_JOIN) {
if(cClient->getServerVersion() >= OLXBetaVersion(0,59,1)) {
CBytestream bs;
if(composePackagesForConn(bs, this->intern, NetConnID_server()))
cClient->getChannel()->AddReliablePacketToSend(bs);
}
} else {
// send to all except local client
std::vector<CServerConnection*> conns = getConnsForId(INVALID_CONN_ID);
for(size_t i = 0; i < conns.size(); ++i) {
CBytestream bs;
if(composePackagesForConn(bs, this->intern, NetConnID_conn(conns[i])))
conns[i]->getNetEngine()->SendPacket(&bs);
}
}
intern->packetsToSend.clear();
}
void Net_Control::olxParse(Net_ConnID src, CBytestream& bs) {
//size_t bsStart = bs.GetPos();
size_t len = readEliasGammaNr(bs);
for(size_t i = 0; i < len; ++i) {
intern->packetsReceived.push_back(NetControlIntern::DataPackage());
NetControlIntern::DataPackage& p = intern->packetsReceived.back();
p.read(this->intern, bs);
p.connID = src;
}
//bs.Dump(PrintOnLogger(notes), std::set<size_t>(), bsStart, bs.GetPos() - bsStart);
}
void Net_Control::olxHandleClientDisconnect(Net_ConnID cl) {
// push node remove events for those nodes where we requested it
for(NetControlIntern::Nodes::iterator i = intern->nodes.begin(); i != intern->nodes.end(); ++i) {
Net_Node* node = i->second;
if(node->intern->eventForRemove)
node->intern->incomingEvents.push_back( NetNodeIntern::Event::NodeRemoved(cl) );
}
}
static void pushNodeUpdate(Net_Node* node, const std::vector<Net_BitStream>& replData, Net_RepRules rule) {
NetControlIntern::DataPackage p;
p.connID = INVALID_CONN_ID;
p.sendMode = eNet_ReliableOrdered; // TODO ?
p.repRules = rule;
p.type = NetControlIntern::DataPackage::GPT_NodeUpdate;
p.node = node->intern;
size_t count = 0;
size_t k = 0;
for(NetNodeIntern::ReplicationSetup::iterator j = node->intern->replicationSetup.begin(); j != node->intern->replicationSetup.end(); ++j, ++k) {
if(replData[k].bitSize() > 0) {
Net_ReplicatorBasic* replicator = dynamic_cast<Net_ReplicatorBasic*>(j->first);
if(replicator->getSetup()->repRules & rule) {
p.data.addBitStream(replData[k]);
count++;
}
else
p.data.addBool(false);
}
else
p.data.addBool(false);
}
if(count > 0)
node->intern->control->pushPackageToSend() = p;
}
static void handleNodeForUpdate(Net_Node* node, bool forceUpdate) {
std::vector<Net_BitStream> replData;
replData.resize(node->intern->replicationSetup.size());
size_t count = 0;
size_t k = 0;
for(NetNodeIntern::ReplicationSetup::iterator j = node->intern->replicationSetup.begin(); j != node->intern->replicationSetup.end(); ++j, ++k) {
Net_ReplicatorBasic* replicator = dynamic_cast<Net_ReplicatorBasic*>(j->first);
if(replicator == NULL) {
errors << "Replicator is not a basic replicator" << endl;
continue;
}
if(!forceUpdate && !replicator->checkState())
continue;
//eNet_NodeRole remoterole = !con->intern->isServer ? eNet_RoleAuthority : (rule == Net_REPRULE_AUTH_2_OWNER) ? eNet_RoleOwner : eNet_RoleProxy;
if(node->intern->interceptor) {
if(!node->intern->interceptor->outPreUpdateItem(node, eNet_RoleProxy, replicator))
continue;
}
replData[k].addBool(true);
replicator->packData(&replData[k]);
count++;
}
if(count == 0) return;
if(node->intern->role == eNet_RoleAuthority) {
pushNodeUpdate(node, replData, Net_REPRULE_AUTH_2_PROXY);
pushNodeUpdate(node, replData, Net_REPRULE_AUTH_2_OWNER);
}
else if(node->intern->role == eNet_RoleOwner) {
pushNodeUpdate(node, replData, Net_REPRULE_OWNER_2_AUTH);
}
}
void Net_Control::Net_processOutput() {
// goes through the nodes and push Node-updates as needed
for(NetControlIntern::Nodes::iterator i = intern->nodes.begin(); i != intern->nodes.end(); ++i) {
Net_Node* node = i->second;
handleNodeForUpdate(node, false);
}
}
static void doNodeUpdate(Net_Node* node, Net_BitStream& bs, Net_ConnID cid) {
size_t i = 0;
for(NetNodeIntern::ReplicationSetup::iterator j = node->intern->replicationSetup.begin(); j != node->intern->replicationSetup.end(); ++j, ++i) {
if( /* skip mark */ !bs.getBool()) continue;
Net_ReplicatorBasic* replicator = dynamic_cast<Net_ReplicatorBasic*>(j->first);
if(replicator == NULL) {
errors << "Replicator " << i << " in update of node " << node->intern->debugStr() << " is not a basic replicator" << endl;
break; // nothing else we can do
}
bool store = true;
if(node->intern->interceptor) {
Net_BitStream peekStream(bs);
replicator->peekStream = &peekStream;
store = node->intern->interceptor->inPreUpdateItem(node, cid, eNet_RoleAuthority, replicator);
replicator->clearPeekData();
replicator->ptr = NULL;
replicator->peekStream = NULL;
}
replicator->unpackData(&bs, store);
}
}
static void tellClientAboutNode(Net_Node* node, Net_ConnID connid) {
if(node->intern->interceptor)
node->intern->interceptor->outPreReplicateNode(node, (connid == node->intern->ownerConn) ? eNet_RoleOwner : eNet_RoleProxy);
NetControlIntern::DataPackage& p = node->intern->control->pushPackageToSend();
p.connID = connid;
p.sendMode = eNet_ReliableOrdered;
p.repRules = Net_REPRULE_AUTH_2_ALL;
p.type = NetControlIntern::DataPackage::GPT_NodeInit;
p.node = node->intern;
p.data.addInt(node->intern->classId, 32);
p.data.addInt(node->intern->ownerConn, 32);
bool announce = node->intern->control->classes[node->intern->classId].flags & Net_CLASSFLAG_ANNOUNCEDATA;
if(node->intern->announceData.get() && !announce)
warnings << "node " << node->intern->debugStr() << " has announce data but class doesnt have flag set" << endl;
else if(!node->intern->announceData.get() && announce)
warnings << "node " << node->intern->debugStr() << " has no announce data but class requests it" << endl;
else if(node->intern->announceData.get() && announce)
p.data.addBitStream(*node->intern->announceData.get());
if(node->intern->eventForInit) {
std::vector<CServerConnection*> conns = getConnsForId(p.connID);
for(size_t i = 0; i < conns.size(); ++i)
node->intern->incomingEvents.push_back( NetNodeIntern::Event::NodeInit(NetConnID_conn(conns[i])) );
}
handleNodeForUpdate(node, true);
}
static bool unregisterNode(Net_Node* node);
static void tellClientAboutAllNodes(const SmartPointer<NetControlIntern>& con, Net_ConnID connid) {
for(NetControlIntern::Nodes::iterator i = con->nodes.begin(); i != con->nodes.end(); ++i) {
tellClientAboutNode(i->second, connid);
}
}
void Net_Control::Net_processInput() {
for(NetControlIntern::Packages::iterator i = intern->packetsReceived.begin(); i != intern->packetsReceived.end(); ++i) {
switch(i->type) {
case NetControlIntern::DataPackage::GPT_Direct:
Net_cbDataReceived(i->connID, i->data);
break;
case NetControlIntern::DataPackage::GPT_ConnectRequest: {
if(!intern->isServer) {
warnings << "Net_processInput: got GPT_ConnectRequest as client" << endl;
break;
}
CServerConnection* cl = serverConnFromNetConnID(i->connID);
if(cl == NULL) {
errors << "Net_processInput GPT_ConnectRequest: didn't found connection for id " << i->connID << endl;
break;
}
if(cl->gusLoggedIn()) {
warnings << "Net_processInput GPT_ConnectRequest: client " << i->connID << " was already logged in" << endl;
break;
}
// in olxSend, when we handle this package, we set gusLoggedIn() = true
NetControlIntern::DataPackage& p = intern->pushPackageToSend();
p.connID = i->connID;
p.sendMode = eNet_ReliableOrdered;
p.repRules = Net_REPRULE_NONE;
p.type = NetControlIntern::DataPackage::GPT_ConnectResult;
p.data.addInt(i->connID, 32); // we tell client about its connection ID
tellClientAboutAllNodes(this->intern, i->connID);
Net_cbConnectionSpawned(i->connID);
break;
}
case NetControlIntern::DataPackage::GPT_ConnectResult: {
if(intern->isServer) {
warnings << "Net_processInput: got GPT_ConnectResult as server" << endl;
break;
}
intern->myConnIdOnServer = i->data.getInt(32);
Net_cbConnectResult(eNet_ConnAccepted);
break;
}
case NetControlIntern::DataPackage::GPT_NodeInit: {
if(intern->isServer) {
warnings << "Net_processInput: got GPT_NodeInit as server" << endl;
break;
}
Net_ClassID classId = i->data.getInt(32);
Net_ConnID ownerConnId = i->data.getInt(32);
NetControlIntern::Class* nodeClass = intern->getClass(classId);
if(nodeClass == NULL) {
warnings << "NodeInit for node " << i->nodeId << " with class " << classId << " failed because that class is unknown" << endl;
break;
}
intern->cbNodeRequest_Dynamic = true;
intern->cbNodeRequest_nodeId = i->nodeId;
bool announce = nodeClass->flags & Net_CLASSFLAG_ANNOUNCEDATA;
eNet_NodeRole role = (ownerConnId == intern->myConnIdOnServer) ? eNet_RoleOwner : eNet_RoleProxy;
Net_cbNodeRequest_Dynamic(i->connID, classId, announce ? &i->data : NULL, role, i->nodeId);
if(intern->cbNodeRequest_Dynamic) { // we didnt created the node - otherwise this would be false
errors << "Net_cbNodeRequest_Dynamic callback didnt created the node " << i->nodeId << " with class " << classId << endl;
intern->cbNodeRequest_Dynamic = false; // reset anyway
break;
}
Net_Node* node = intern->getNode(i->nodeId);
if(node == NULL) {
errors << "NodeInit: node " << i->nodeId << " not found after dynamic creation" << endl;
break;
}
node->intern->ownerConn = ownerConnId;
node->intern->role = role;
if(node->intern->classId != classId)
warnings << "NodeInit requested a node of class " << classId << " but a node of class " << node->intern->classId << " was created" << endl;
break;
}
case NetControlIntern::DataPackage::GPT_NodeRemove: {
if(intern->isServer) {
warnings << "Net_processInput: got GPT_NodeRemove as server" << endl;
break;
}
Net_Node* node = intern->getNode(i->nodeId);
if(node == NULL) {
warnings << "NodeRemove: node " << i->nodeId << " not found" << endl;
break;
}
// we are proxy or owner -> in any case, always push this event
node->intern->incomingEvents.push_back( NetNodeIntern::Event::NodeRemoved(i->connID) );
unregisterNode(node);
break;
}
case NetControlIntern::DataPackage::GPT_NodeUpdate: {
Net_Node* node = intern->getNode(i->nodeId);
if(node == NULL) {
warnings << "NodeUpdate: node " << i->nodeId << " not found" << endl;
break;
}
if(intern->isServer) {
if(node->intern->ownerConn != i->connID) {
warnings << "Net_processInput: got GPT_NodeUpdate as server from proxy" << endl;
break;
}
}
doNodeUpdate(node, i->data, i->connID);
break;
}
case NetControlIntern::DataPackage::GPT_NodeEvent: {
Net_Node* node = intern->getNode(i->nodeId);
if(node == NULL) {
warnings << "NodeEvent: node " << i->nodeId << " not found" << endl;
break;
}
if(intern->isServer) {
if(node->intern->ownerConn != i->connID) {
warnings << "NodeEvent: got event for node " << i->nodeId << " from non-owner " << i->connID << ", owner is " << node->intern->ownerConn << endl;
break;
}
}
node->intern->incomingEvents.push_back( NetNodeIntern::Event::User(i->data, i->connID) );
break;
}
default:
warnings << "invalid Gusanos data package type" << endl;
}
}
intern->packetsReceived.clear();
}
void Net_Control::Net_ConnectToServer() {
NetControlIntern::DataPackage& p = intern->pushPackageToSend();
p.connID = NetConnID_server();
p.type = NetControlIntern::DataPackage::GPT_ConnectRequest;
p.sendMode = eNet_ReliableOrdered;
p.repRules = Net_REPRULE_NONE; // this is anyway ignored here
}
void Net_Control::Net_sendData(Net_ConnID id, Net_BitStream* s, eNet_SendMode m) {
NetControlIntern::DataPackage& p = intern->pushPackageToSend();
p.connID = id;
p.sendMode = m;
p.repRules = Net_REPRULE_NONE; // anyway ignored
p.type = NetControlIntern::DataPackage::GPT_Direct;
p.data = *s;
delete s;
}
Net_ClassID Net_Control::Net_registerClass(const std::string& classname, Net_ClassFlags flags) {
Net_ClassID id = 1;
if(intern->classes.size() > 0)
id = intern->classes.rbegin()->first + 1;
intern->classes[id] = NetControlIntern::Class(classname, id, flags);
return id;
}
void Net_Control::Net_setControlID(int id) { intern->controlId = id; }
void Net_Control::Net_setDebugName(const std::string& n) { intern->debugName = n; }
void Net_Control::Net_requestNetMode(Net_ConnID, int) {
// we silently ignore that because we dont have different netstream levels
}
static bool __unregisterNode(Net_Node* node) {
if(node->intern->nodeId != INVALID_NODE_ID) {
if(node->intern->control.get() == NULL) {
errors << "Net_Node::unregisterNode: node was a valid id but no reference to Net_Control" << endl;
return false;
}
if(node->intern->nodeId != UNIQUE_NODE_ID) { // dynamic node
NetControlIntern::Nodes& nodes = node->intern->control->nodes;
NetControlIntern::Nodes::iterator i = nodes.find(node->intern->nodeId);
if(i == nodes.end()) {
errors << "Net_Node::unregisterNode: dynamic node not found in node-list" << endl;
return false;
}
nodes.erase(i);
if(node->intern->role == eNet_RoleAuthority) {
NetControlIntern::DataPackage& p = node->intern->control->pushPackageToSend();
p.connID = 0;
p.sendMode = eNet_ReliableOrdered;
p.repRules = Net_REPRULE_AUTH_2_ALL;
p.type = NetControlIntern::DataPackage::GPT_NodeRemove;
p.node = node->intern;
}
}
else { // unique node
NetControlIntern::LocalNodes& nodes = node->intern->control->localNodes;
NetControlIntern::LocalNodes::iterator i = nodes.find(node);
if(i == nodes.end()) {
errors << "Net_Node::unregisterNode: unique node not found in node-list" << endl;
return false;
}
nodes.erase(i);
}
notes << "Node " << node->intern->nodeId << " with class " << node->intern->control->classes[node->intern->classId].name << " unregisters" << endl;
return true;
}
return false;
}
static bool unregisterNode(Net_Node* node) {
bool ret = __unregisterNode(node);
return ret;
}
template <> void SmartPointer_ObjectDeinit<NetNodeIntern> ( NetNodeIntern * obj )
{
delete obj;
}
Net_Node::Net_Node() {
intern = new NetNodeIntern();
}
Net_Node::~Net_Node() {
unregisterNode(this);
intern = NULL;
}
eNet_NodeRole Net_Node::getRole() { return intern->role; }
void Net_Node::setOwner(Net_ConnID cid) { intern->ownerConn = cid; }
void Net_Node::setAnnounceData(Net_BitStream* s) { intern->announceData = std::auto_ptr<Net_BitStream>(s); }
Net_NodeID Net_Node::getNetworkID() { return intern->nodeId; }
static void tellAllClientsAboutNode(Net_Node* node) {
for(int i = 0; i < MAX_CLIENTS; ++i) {
if(cServer->getClients()[i].getStatus() != NET_CONNECTED) continue;
if(cServer->getClients()[i].getNetEngine() == NULL) continue;
tellClientAboutNode(node, NetConnID_conn(&cServer->getClients()[i]));
}
}
static bool registerNode(Net_ClassID classid, Net_Node* node, Net_NodeID nid, eNet_NodeRole role, const SmartPointer<NetControlIntern>& con) {
if(node->intern->nodeId != INVALID_NODE_ID) {
errors << "Net_Node::registerNode " << node->intern->debugStr() << " trying to register node twice" << endl;
return false;
}
if(con.get() == NULL) {
errors << "Net_Node::registerNode without Net_Control" << endl;
return false;
}
if(nid != UNIQUE_NODE_ID && con->getNode(nid)) {
errors << "Net_Node::registerNode " << node->intern->debugStr() << " node id " << nid << " was already taken by " << con->getNode(nid)->intern->debugStr() << endl;
return false;
}
node->intern->control = con;
node->intern->classId = classid;
node->intern->nodeId = nid;
node->intern->role = role;
if(nid == UNIQUE_NODE_ID)
con->localNodes.insert(node);
else {
con->nodes[nid] = node;
if(role == eNet_RoleAuthority)
tellAllClientsAboutNode(node);
}
notes << "Node " << nid << " registers with role " << role << " and class " << con->classes[classid].name << endl;
return true;
}
bool Net_Node::registerNodeUnique(Net_ClassID cid, eNet_NodeRole role, Net_Control* con) {
return registerNode(cid, this, UNIQUE_NODE_ID, role, con->intern);
}
bool Net_Node::registerNodeDynamic(Net_ClassID cid, Net_Control* con) {
eNet_NodeRole role = con->intern->cbNodeRequest_Dynamic ? eNet_RoleProxy : eNet_RoleAuthority;
if(con->intern->isServer && role != eNet_RoleAuthority) {
errors << "registerNodeDynamic: want to register proxy node on server" << endl;
return false; // stop because otherwise we probably would crash
}
if(!con->intern->isServer && role == eNet_RoleAuthority) {
errors << "registerNodeDynamic: want to register authority node on client" << endl;
return false; // stop because otherwise we probably would crash
}
Net_NodeID nid = con->intern->cbNodeRequest_Dynamic ? con->intern->cbNodeRequest_nodeId : con->intern->getUnusedNodeId();
con->intern->cbNodeRequest_Dynamic = false; // only for first node
return registerNode(cid, this, nid, role, con->intern);
}
bool Net_Node::registerRequestedNode(Net_ClassID cid, Net_Control* con) { return registerNodeDynamic(cid, con); }
void Net_Node::applyForNetLevel(int something) {}
void Net_Node::removeFromNetLevel(int something) {}
void Net_Node::setEventNotification(bool eventForInit /* eNet_EventInit */, bool eventForRemove /* eNet_EventRemoved */) {
intern->eventForInit = eventForInit;
intern->eventForRemove = eventForRemove;
}
void Net_Node::sendEvent(eNet_SendMode m, Net_RepRules rules, Net_BitStream* s) {
NetControlIntern::DataPackage& p = intern->control->pushPackageToSend();
p.connID = INVALID_CONN_ID;
p.sendMode = m;
p.repRules = rules;
p.type = NetControlIntern::DataPackage::GPT_NodeEvent;
p.node = intern;
p.data = *s;
delete s;
}
void Net_Node::sendEventDirect(eNet_SendMode m, Net_BitStream* s, Net_ConnID cid) {
if(!intern->control->isServer) {
errors << "Net_Node::sendEventDirect (node " << intern->nodeId << ") only works as server" << endl;
return;
}
NetControlIntern::DataPackage& p = intern->control->pushPackageToSend();
p.connID = cid;
p.sendMode = m;
p.repRules = Net_REPRULE_AUTH_2_ALL;
p.type = NetControlIntern::DataPackage::GPT_NodeEvent;
p.node = intern;
p.data = *s;
delete s;
}
bool Net_Node::checkEventWaiting() { return intern->incomingEvents.size() > 0; }
Net_BitStream* Net_Node::getNextEvent(eNet_Event* e, eNet_NodeRole* r, Net_ConnID* cid) {
if(intern->incomingEvents.size() == 0) return NULL;
NetNodeIntern::Event& ev = intern->curIncomingEvent = intern->incomingEvents.front();
intern->incomingEvents.pop_front();
if(e) *e = ev.ev;
if(r) *r = ev.role;
if(cid) *cid = ev.cid;
return &ev.stream;
}
void Net_Node::beginReplicationSetup() {
intern->clearReplicationSetup();
}
void Net_Node::addReplicator(Net_Replicator* rep, bool autodelete) {
intern->replicationSetup.push_back( std::make_pair(rep, autodelete) );
}
void Net_Node::addReplicationInt(Net_S32* n, int bits, bool, Net_RepFlags f, Net_RepRules r, Net_InterceptID id, int p2, int p3) {
if((f & Net_REPFLAG_INTERCEPT) && id == 0)
id = intern->forthcomingReplicatorInterceptID;
struct IntReplicator : Net_ReplicatorBasic {
Net_ReplicatorSetup setup;
typedef Net_S32 Num;
Num* n;
Num old;
int bits;
IntReplicator(const Net_ReplicatorSetup& s) : Net_ReplicatorBasic(&setup), setup(s) {}
Net_Replicator* Duplicate(Net_Replicator*) { return new IntReplicator(*this); }
void* peekData() { peekDataStore(new Num(peekStream->getInt(bits))); return peekDataRetrieve(); }
void clearPeekData() { Num* p = (Num*)peekDataRetrieve(); if(p) delete p; }
bool checkState() { bool diff = *n != old; old = *n; return diff; }
void packData(Net_BitStream *_stream) { _stream->addInt(*n, bits); }
void unpackData(Net_BitStream *_stream, bool _store) {
Num i = _stream->getInt(bits);
if(_store) *n = i;
}
};
IntReplicator* rep = new IntReplicator(Net_ReplicatorSetup(f, r, id, p2, p3));
rep->n = n;
rep->old = *n;
rep->bits = bits;
addReplicator(rep, true);
}
void Net_Node::addReplicationFloat(Net_Float* n, int bits, Net_RepFlags f, Net_RepRules r, Net_InterceptID id, int p2, int p3) {
if((f & Net_REPFLAG_INTERCEPT) && id == 0)
id = intern->forthcomingReplicatorInterceptID;
struct FloatReplicator : Net_ReplicatorBasic {
Net_ReplicatorSetup setup;
typedef Net_Float Num;
Num* n;
Num old;
int bits;
FloatReplicator(const Net_ReplicatorSetup& s) : Net_ReplicatorBasic(&setup), setup(s) {}
Net_Replicator* Duplicate(Net_Replicator*) { return new FloatReplicator(*this); }
void* peekData() { peekDataStore(new Num(peekStream->getFloat(bits))); return peekDataRetrieve(); }
void clearPeekData() { Num* p = (Num*)peekDataRetrieve(); if(p) delete p; }
bool checkState() { bool diff = *n != old; old = *n; return diff; }
void packData(Net_BitStream *_stream) { _stream->addFloat(*n, bits); }
void unpackData(Net_BitStream *_stream, bool _store) {
Num i = _stream->getFloat(bits);
if(_store) *n = i;
}
};
FloatReplicator* rep = new FloatReplicator(Net_ReplicatorSetup(f, r, id, p2, p3));
rep->n = n;
rep->old = *n;
rep->bits = bits;
addReplicator(rep, true);
}
void Net_Node::endReplicationSetup() {}
void Net_Node::setInterceptID(Net_InterceptID id) { intern->forthcomingReplicatorInterceptID = id; }
void Net_Node::setReplicationInterceptor(Net_NodeReplicationInterceptor* inter) { intern->interceptor = inter; }
Net_ReplicatorSetup::Net_ReplicatorSetup(Net_RepFlags flags, Net_RepRules rules, Net_InterceptID id, int p2, int p3) {
repFlags = flags;
repRules = rules;
interceptId = id;
}
Net_ConnID NetConnID_server() {
return Net_ConnID(-1);
}
Net_ConnID NetConnID_conn(CServerConnection* cl) {
for(int i = 0; i < MAX_CLIENTS; i++) {
if(&cServer->getClients()[i] == cl) return i + 1;
}
errors << "NetConnID_conn: connection invalid" << endl;
return INVALID_CONN_ID;
}
CServerConnection* serverConnFromNetConnID(Net_ConnID id) {
if(!cServer->getClients() || !cServer->isServerRunning()) {
errors << "serverConnFromNetConnID: server is not running" << endl;
return NULL;
}
if(id >= 1 && id <= MAX_CLIENTS) return &cServer->getClients()[id - 1];
errors << "serverConnFromNetConnID: id " << id << " is invalid" << endl;
return NULL;
}
bool isServerNetConnID(Net_ConnID id) {
return id == NetConnID_server();
}
|
/*
* SHA-{224,256}
* (C) 1999-2008 Jack Lloyd
* 2007 FlexSecure GmbH
*
* Distributed under the terms of the Botan license
*/
#include <botan/sha2_32.h>
#include <botan/loadstor.h>
#include <botan/rotate.h>
namespace Botan {
namespace {
/*
* SHA-256 Rho Function
*/
inline u32bit rho(u32bit X, u32bit rot1, u32bit rot2, u32bit rot3)
{
return (rotate_right(X, rot1) ^ rotate_right(X, rot2) ^
rotate_right(X, rot3));
}
/*
* SHA-256 Sigma Function
*/
inline u32bit sigma(u32bit X, u32bit rot1, u32bit rot2, u32bit shift)
{
return (rotate_right(X, rot1) ^ rotate_right(X, rot2) ^ (X >> shift));
}
/*
* SHA-256 F1 Function
*/
inline void F1(u32bit A, u32bit B, u32bit C, u32bit& D,
u32bit E, u32bit F, u32bit G, u32bit& H,
u32bit msg, u32bit magic)
{
magic += rho(E, 6, 11, 25) + ((E & F) ^ (~E & G)) + msg;
D += magic + H;
H += magic + rho(A, 2, 13, 22) + ((A & B) ^ (A & C) ^ (B & C));
}
}
/*
* SHA-256 Compression Function
*/
void SHA_224_256_BASE::compress_n(const byte input[], u32bit blocks)
{
u32bit A = digest[0], B = digest[1], C = digest[2],
D = digest[3], E = digest[4], F = digest[5],
G = digest[6], H = digest[7];
for(u32bit i = 0; i != blocks; ++i)
{
load_be(W.begin(), input, 16);
for(u32bit j = 16; j != 64; j += 8)
{
W[j ] = sigma(W[j- 2], 17, 19, 10) + W[j-7] +
sigma(W[j-15], 7, 18, 3) + W[j-16];
W[j+1] = sigma(W[j- 1], 17, 19, 10) + W[j-6] +
sigma(W[j-14], 7, 18, 3) + W[j-15];
W[j+2] = sigma(W[j ], 17, 19, 10) + W[j-5] +
sigma(W[j-13], 7, 18, 3) + W[j-14];
W[j+3] = sigma(W[j+ 1], 17, 19, 10) + W[j-4] +
sigma(W[j-12], 7, 18, 3) + W[j-13];
W[j+4] = sigma(W[j+ 2], 17, 19, 10) + W[j-3] +
sigma(W[j-11], 7, 18, 3) + W[j-12];
W[j+5] = sigma(W[j+ 3], 17, 19, 10) + W[j-2] +
sigma(W[j-10], 7, 18, 3) + W[j-11];
W[j+6] = sigma(W[j+ 4], 17, 19, 10) + W[j-1] +
sigma(W[j- 9], 7, 18, 3) + W[j-10];
W[j+7] = sigma(W[j+ 5], 17, 19, 10) + W[j ] +
sigma(W[j- 8], 7, 18, 3) + W[j- 9];
}
F1(A, B, C, D, E, F, G, H, W[ 0], 0x428A2F98);
F1(H, A, B, C, D, E, F, G, W[ 1], 0x71374491);
F1(G, H, A, B, C, D, E, F, W[ 2], 0xB5C0FBCF);
F1(F, G, H, A, B, C, D, E, W[ 3], 0xE9B5DBA5);
F1(E, F, G, H, A, B, C, D, W[ 4], 0x3956C25B);
F1(D, E, F, G, H, A, B, C, W[ 5], 0x59F111F1);
F1(C, D, E, F, G, H, A, B, W[ 6], 0x923F82A4);
F1(B, C, D, E, F, G, H, A, W[ 7], 0xAB1C5ED5);
F1(A, B, C, D, E, F, G, H, W[ 8], 0xD807AA98);
F1(H, A, B, C, D, E, F, G, W[ 9], 0x12835B01);
F1(G, H, A, B, C, D, E, F, W[10], 0x243185BE);
F1(F, G, H, A, B, C, D, E, W[11], 0x550C7DC3);
F1(E, F, G, H, A, B, C, D, W[12], 0x72BE5D74);
F1(D, E, F, G, H, A, B, C, W[13], 0x80DEB1FE);
F1(C, D, E, F, G, H, A, B, W[14], 0x9BDC06A7);
F1(B, C, D, E, F, G, H, A, W[15], 0xC19BF174);
F1(A, B, C, D, E, F, G, H, W[16], 0xE49B69C1);
F1(H, A, B, C, D, E, F, G, W[17], 0xEFBE4786);
F1(G, H, A, B, C, D, E, F, W[18], 0x0FC19DC6);
F1(F, G, H, A, B, C, D, E, W[19], 0x240CA1CC);
F1(E, F, G, H, A, B, C, D, W[20], 0x2DE92C6F);
F1(D, E, F, G, H, A, B, C, W[21], 0x4A7484AA);
F1(C, D, E, F, G, H, A, B, W[22], 0x5CB0A9DC);
F1(B, C, D, E, F, G, H, A, W[23], 0x76F988DA);
F1(A, B, C, D, E, F, G, H, W[24], 0x983E5152);
F1(H, A, B, C, D, E, F, G, W[25], 0xA831C66D);
F1(G, H, A, B, C, D, E, F, W[26], 0xB00327C8);
F1(F, G, H, A, B, C, D, E, W[27], 0xBF597FC7);
F1(E, F, G, H, A, B, C, D, W[28], 0xC6E00BF3);
F1(D, E, F, G, H, A, B, C, W[29], 0xD5A79147);
F1(C, D, E, F, G, H, A, B, W[30], 0x06CA6351);
F1(B, C, D, E, F, G, H, A, W[31], 0x14292967);
F1(A, B, C, D, E, F, G, H, W[32], 0x27B70A85);
F1(H, A, B, C, D, E, F, G, W[33], 0x2E1B2138);
F1(G, H, A, B, C, D, E, F, W[34], 0x4D2C6DFC);
F1(F, G, H, A, B, C, D, E, W[35], 0x53380D13);
F1(E, F, G, H, A, B, C, D, W[36], 0x650A7354);
F1(D, E, F, G, H, A, B, C, W[37], 0x766A0ABB);
F1(C, D, E, F, G, H, A, B, W[38], 0x81C2C92E);
F1(B, C, D, E, F, G, H, A, W[39], 0x92722C85);
F1(A, B, C, D, E, F, G, H, W[40], 0xA2BFE8A1);
F1(H, A, B, C, D, E, F, G, W[41], 0xA81A664B);
F1(G, H, A, B, C, D, E, F, W[42], 0xC24B8B70);
F1(F, G, H, A, B, C, D, E, W[43], 0xC76C51A3);
F1(E, F, G, H, A, B, C, D, W[44], 0xD192E819);
F1(D, E, F, G, H, A, B, C, W[45], 0xD6990624);
F1(C, D, E, F, G, H, A, B, W[46], 0xF40E3585);
F1(B, C, D, E, F, G, H, A, W[47], 0x106AA070);
F1(A, B, C, D, E, F, G, H, W[48], 0x19A4C116);
F1(H, A, B, C, D, E, F, G, W[49], 0x1E376C08);
F1(G, H, A, B, C, D, E, F, W[50], 0x2748774C);
F1(F, G, H, A, B, C, D, E, W[51], 0x34B0BCB5);
F1(E, F, G, H, A, B, C, D, W[52], 0x391C0CB3);
F1(D, E, F, G, H, A, B, C, W[53], 0x4ED8AA4A);
F1(C, D, E, F, G, H, A, B, W[54], 0x5B9CCA4F);
F1(B, C, D, E, F, G, H, A, W[55], 0x682E6FF3);
F1(A, B, C, D, E, F, G, H, W[56], 0x748F82EE);
F1(H, A, B, C, D, E, F, G, W[57], 0x78A5636F);
F1(G, H, A, B, C, D, E, F, W[58], 0x84C87814);
F1(F, G, H, A, B, C, D, E, W[59], 0x8CC70208);
F1(E, F, G, H, A, B, C, D, W[60], 0x90BEFFFA);
F1(D, E, F, G, H, A, B, C, W[61], 0xA4506CEB);
F1(C, D, E, F, G, H, A, B, W[62], 0xBEF9A3F7);
F1(B, C, D, E, F, G, H, A, W[63], 0xC67178F2);
A = (digest[0] += A);
B = (digest[1] += B);
C = (digest[2] += C);
D = (digest[3] += D);
E = (digest[4] += E);
F = (digest[5] += F);
G = (digest[6] += G);
H = (digest[7] += H);
input += HASH_BLOCK_SIZE;
}
}
/*
* Copy out the digest
*/
void SHA_224_256_BASE::copy_out(byte output[])
{
for(u32bit j = 0; j != OUTPUT_LENGTH; j += 4)
store_be(digest[j/4], output + j);
}
/*
* Clear memory of sensitive data
*/
void SHA_224_256_BASE::clear()
{
MDx_HashFunction::clear();
W.clear();
}
/*
* Clear memory of sensitive data
*/
void SHA_224::clear()
{
SHA_224_256_BASE::clear();
digest[0] = 0xC1059ED8;
digest[1] = 0x367CD507;
digest[2] = 0x3070DD17;
digest[3] = 0xF70E5939;
digest[4] = 0xFFC00B31;
digest[5] = 0x68581511;
digest[6] = 0x64F98FA7;
digest[7] = 0xBEFA4FA4;
}
/*
* Clear memory of sensitive data
*/
void SHA_256::clear()
{
SHA_224_256_BASE::clear();
digest[0] = 0x6A09E667;
digest[1] = 0xBB67AE85;
digest[2] = 0x3C6EF372;
digest[3] = 0xA54FF53A;
digest[4] = 0x510E527F;
digest[5] = 0x9B05688C;
digest[6] = 0x1F83D9AB;
digest[7] = 0x5BE0CD19;
}
}
Slightly cleaner SHA-256 F1 func; ~1% faster
/*
* SHA-{224,256}
* (C) 1999-2008 Jack Lloyd
* 2007 FlexSecure GmbH
*
* Distributed under the terms of the Botan license
*/
#include <botan/sha2_32.h>
#include <botan/loadstor.h>
#include <botan/rotate.h>
namespace Botan {
namespace {
/*
* SHA-256 Rho Function
*/
inline u32bit rho(u32bit X, u32bit rot1, u32bit rot2, u32bit rot3)
{
return (rotate_right(X, rot1) ^ rotate_right(X, rot2) ^
rotate_right(X, rot3));
}
/*
* SHA-256 Sigma Function
*/
inline u32bit sigma(u32bit X, u32bit rot1, u32bit rot2, u32bit shift)
{
return (rotate_right(X, rot1) ^ rotate_right(X, rot2) ^ (X >> shift));
}
/*
* SHA-256 F1 Function
*/
inline void F1(u32bit A, u32bit B, u32bit C, u32bit& D,
u32bit E, u32bit F, u32bit G, u32bit& H,
u32bit msg, u32bit magic)
{
H += magic + rho(E, 6, 11, 25) + ((E & F) ^ (~E & G)) + msg;
D += H;
H += rho(A, 2, 13, 22) + ((A & B) | ((A | B) & C));
}
}
/*
* SHA-256 Compression Function
*/
void SHA_224_256_BASE::compress_n(const byte input[], u32bit blocks)
{
u32bit A = digest[0], B = digest[1], C = digest[2],
D = digest[3], E = digest[4], F = digest[5],
G = digest[6], H = digest[7];
for(u32bit i = 0; i != blocks; ++i)
{
load_be(W.begin(), input, 16);
for(u32bit j = 16; j != 64; j += 8)
{
W[j ] = sigma(W[j- 2], 17, 19, 10) + W[j-7] +
sigma(W[j-15], 7, 18, 3) + W[j-16];
W[j+1] = sigma(W[j- 1], 17, 19, 10) + W[j-6] +
sigma(W[j-14], 7, 18, 3) + W[j-15];
W[j+2] = sigma(W[j ], 17, 19, 10) + W[j-5] +
sigma(W[j-13], 7, 18, 3) + W[j-14];
W[j+3] = sigma(W[j+ 1], 17, 19, 10) + W[j-4] +
sigma(W[j-12], 7, 18, 3) + W[j-13];
W[j+4] = sigma(W[j+ 2], 17, 19, 10) + W[j-3] +
sigma(W[j-11], 7, 18, 3) + W[j-12];
W[j+5] = sigma(W[j+ 3], 17, 19, 10) + W[j-2] +
sigma(W[j-10], 7, 18, 3) + W[j-11];
W[j+6] = sigma(W[j+ 4], 17, 19, 10) + W[j-1] +
sigma(W[j- 9], 7, 18, 3) + W[j-10];
W[j+7] = sigma(W[j+ 5], 17, 19, 10) + W[j ] +
sigma(W[j- 8], 7, 18, 3) + W[j- 9];
}
F1(A, B, C, D, E, F, G, H, W[ 0], 0x428A2F98);
F1(H, A, B, C, D, E, F, G, W[ 1], 0x71374491);
F1(G, H, A, B, C, D, E, F, W[ 2], 0xB5C0FBCF);
F1(F, G, H, A, B, C, D, E, W[ 3], 0xE9B5DBA5);
F1(E, F, G, H, A, B, C, D, W[ 4], 0x3956C25B);
F1(D, E, F, G, H, A, B, C, W[ 5], 0x59F111F1);
F1(C, D, E, F, G, H, A, B, W[ 6], 0x923F82A4);
F1(B, C, D, E, F, G, H, A, W[ 7], 0xAB1C5ED5);
F1(A, B, C, D, E, F, G, H, W[ 8], 0xD807AA98);
F1(H, A, B, C, D, E, F, G, W[ 9], 0x12835B01);
F1(G, H, A, B, C, D, E, F, W[10], 0x243185BE);
F1(F, G, H, A, B, C, D, E, W[11], 0x550C7DC3);
F1(E, F, G, H, A, B, C, D, W[12], 0x72BE5D74);
F1(D, E, F, G, H, A, B, C, W[13], 0x80DEB1FE);
F1(C, D, E, F, G, H, A, B, W[14], 0x9BDC06A7);
F1(B, C, D, E, F, G, H, A, W[15], 0xC19BF174);
F1(A, B, C, D, E, F, G, H, W[16], 0xE49B69C1);
F1(H, A, B, C, D, E, F, G, W[17], 0xEFBE4786);
F1(G, H, A, B, C, D, E, F, W[18], 0x0FC19DC6);
F1(F, G, H, A, B, C, D, E, W[19], 0x240CA1CC);
F1(E, F, G, H, A, B, C, D, W[20], 0x2DE92C6F);
F1(D, E, F, G, H, A, B, C, W[21], 0x4A7484AA);
F1(C, D, E, F, G, H, A, B, W[22], 0x5CB0A9DC);
F1(B, C, D, E, F, G, H, A, W[23], 0x76F988DA);
F1(A, B, C, D, E, F, G, H, W[24], 0x983E5152);
F1(H, A, B, C, D, E, F, G, W[25], 0xA831C66D);
F1(G, H, A, B, C, D, E, F, W[26], 0xB00327C8);
F1(F, G, H, A, B, C, D, E, W[27], 0xBF597FC7);
F1(E, F, G, H, A, B, C, D, W[28], 0xC6E00BF3);
F1(D, E, F, G, H, A, B, C, W[29], 0xD5A79147);
F1(C, D, E, F, G, H, A, B, W[30], 0x06CA6351);
F1(B, C, D, E, F, G, H, A, W[31], 0x14292967);
F1(A, B, C, D, E, F, G, H, W[32], 0x27B70A85);
F1(H, A, B, C, D, E, F, G, W[33], 0x2E1B2138);
F1(G, H, A, B, C, D, E, F, W[34], 0x4D2C6DFC);
F1(F, G, H, A, B, C, D, E, W[35], 0x53380D13);
F1(E, F, G, H, A, B, C, D, W[36], 0x650A7354);
F1(D, E, F, G, H, A, B, C, W[37], 0x766A0ABB);
F1(C, D, E, F, G, H, A, B, W[38], 0x81C2C92E);
F1(B, C, D, E, F, G, H, A, W[39], 0x92722C85);
F1(A, B, C, D, E, F, G, H, W[40], 0xA2BFE8A1);
F1(H, A, B, C, D, E, F, G, W[41], 0xA81A664B);
F1(G, H, A, B, C, D, E, F, W[42], 0xC24B8B70);
F1(F, G, H, A, B, C, D, E, W[43], 0xC76C51A3);
F1(E, F, G, H, A, B, C, D, W[44], 0xD192E819);
F1(D, E, F, G, H, A, B, C, W[45], 0xD6990624);
F1(C, D, E, F, G, H, A, B, W[46], 0xF40E3585);
F1(B, C, D, E, F, G, H, A, W[47], 0x106AA070);
F1(A, B, C, D, E, F, G, H, W[48], 0x19A4C116);
F1(H, A, B, C, D, E, F, G, W[49], 0x1E376C08);
F1(G, H, A, B, C, D, E, F, W[50], 0x2748774C);
F1(F, G, H, A, B, C, D, E, W[51], 0x34B0BCB5);
F1(E, F, G, H, A, B, C, D, W[52], 0x391C0CB3);
F1(D, E, F, G, H, A, B, C, W[53], 0x4ED8AA4A);
F1(C, D, E, F, G, H, A, B, W[54], 0x5B9CCA4F);
F1(B, C, D, E, F, G, H, A, W[55], 0x682E6FF3);
F1(A, B, C, D, E, F, G, H, W[56], 0x748F82EE);
F1(H, A, B, C, D, E, F, G, W[57], 0x78A5636F);
F1(G, H, A, B, C, D, E, F, W[58], 0x84C87814);
F1(F, G, H, A, B, C, D, E, W[59], 0x8CC70208);
F1(E, F, G, H, A, B, C, D, W[60], 0x90BEFFFA);
F1(D, E, F, G, H, A, B, C, W[61], 0xA4506CEB);
F1(C, D, E, F, G, H, A, B, W[62], 0xBEF9A3F7);
F1(B, C, D, E, F, G, H, A, W[63], 0xC67178F2);
A = (digest[0] += A);
B = (digest[1] += B);
C = (digest[2] += C);
D = (digest[3] += D);
E = (digest[4] += E);
F = (digest[5] += F);
G = (digest[6] += G);
H = (digest[7] += H);
input += HASH_BLOCK_SIZE;
}
}
/*
* Copy out the digest
*/
void SHA_224_256_BASE::copy_out(byte output[])
{
for(u32bit j = 0; j != OUTPUT_LENGTH; j += 4)
store_be(digest[j/4], output + j);
}
/*
* Clear memory of sensitive data
*/
void SHA_224_256_BASE::clear()
{
MDx_HashFunction::clear();
W.clear();
}
/*
* Clear memory of sensitive data
*/
void SHA_224::clear()
{
SHA_224_256_BASE::clear();
digest[0] = 0xC1059ED8;
digest[1] = 0x367CD507;
digest[2] = 0x3070DD17;
digest[3] = 0xF70E5939;
digest[4] = 0xFFC00B31;
digest[5] = 0x68581511;
digest[6] = 0x64F98FA7;
digest[7] = 0xBEFA4FA4;
}
/*
* Clear memory of sensitive data
*/
void SHA_256::clear()
{
SHA_224_256_BASE::clear();
digest[0] = 0x6A09E667;
digest[1] = 0xBB67AE85;
digest[2] = 0x3C6EF372;
digest[3] = 0xA54FF53A;
digest[4] = 0x510E527F;
digest[5] = 0x9B05688C;
digest[6] = 0x1F83D9AB;
digest[7] = 0x5BE0CD19;
}
}
|
/*
* 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.
*/
/*!
* \file codegen_opencl.cc
*/
#include "codegen_opencl.h"
#include <cmath>
#include <string>
#include <vector>
#include "../../runtime/opencl/opencl_module.h"
#include "../../runtime/texture.h"
#include "../../runtime/thread_storage_scope.h"
#include "../build_common.h"
namespace tvm {
namespace codegen {
class InferTextureAccess : public StmtExprVisitor {
public:
static constexpr const uint8_t kReadAccess = 1;
static constexpr const uint8_t kWriteAccess = 2;
InferTextureAccess() {}
std::unordered_map<const VarNode*, std::string> Infer(const Stmt& n) {
StmtExprVisitor::VisitStmt(n);
std::unordered_map<const VarNode*, std::string> storage_scope_qualifiers;
for (auto& texture : var_access_map_) {
if (texture.second == kReadAccess) {
storage_scope_qualifiers.insert({texture.first, "texture_read"});
} else if (texture.second == kWriteAccess) {
storage_scope_qualifiers.insert({texture.first, "texture_write"});
} else if (texture.second == (kReadAccess | kWriteAccess)) {
storage_scope_qualifiers.insert({texture.first, ""});
}
}
return storage_scope_qualifiers;
}
void VisitExpr_(const CallNode* op) {
if (op->op.same_as(builtin::texture2d_load())) {
var_access_map_[op->args[0].as<VarNode>()] |= kReadAccess;
} else if (op->op.same_as(builtin::texture2d_store())) {
var_access_map_[op->args[0].as<VarNode>()] |= kWriteAccess;
} else {
StmtExprVisitor::VisitExpr_(op);
}
StmtExprVisitor::VisitExpr_(op);
}
private:
std::unordered_map<const VarNode*, uint8_t> var_access_map_;
};
CodeGenOpenCL::CodeGenOpenCL() {
// Set OpenCL specific restrict keyword
restrict_keyword_ = "restrict";
}
void CodeGenOpenCL::InitFuncState(const PrimFunc& f) {
CodeGenC::InitFuncState(f);
this->SetTextureScope(InferTextureAccess().Infer(f->body));
for (Var arg : f->params) {
auto ptr_type = arg->type_annotation.as<PointerTypeNode>();
if (ptr_type && runtime::IsTextureStorage(std::string(ptr_type->storage_scope))) {
// Storage scope qualifiers for textures are inferred
// and set prior to function codegen.
continue;
} else if (arg.dtype().is_handle()) {
alloc_storage_scope_[arg.get()] = "global";
}
}
}
void CodeGenOpenCL::PrintFuncPrefix() { stream << "__kernel void"; }
std::string CodeGenOpenCL::Finish() {
// inject extension enable pragma for fp16 and fp64
if (enable_fp16_) {
decl_stream << "#ifdef cl_khr_fp16\n"
"#pragma OPENCL EXTENSION cl_khr_fp16 : enable\n"
"#elif defined(cl_amd_fp16)\n"
"#pragma OPENCL EXTENSION cl_amd_fp16 : enable\n"
"#else\n"
"#error \"Half precision floating point not supported"
"by OpenCL implementation on your device.\" \n"
"#endif\n\n";
}
if (enable_fp64_) {
decl_stream << "#ifdef cl_khr_fp64\n"
"#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n"
"#elif defined(cl_amd_fp64)\n"
"#pragma OPENCL EXTENSION cl_amd_fp64 : enable\n"
"#else\n"
"#error \"Double precision floating point not supported"
"by OpenCL implementation on your device.\" \n"
"#endif\n\n";
}
// Enable atomic_add used by get_valid_counts. Only needed for OpenCL < 1.1.
if (enable_atomics_) {
decl_stream << "#pragma OPENCL EXTENSION cl_khr_global_int32_base_atomics : enable\n"
"#pragma OPENCL EXTENSION cl_khr_global_int32_extended_atomics : enable\n\n";
}
// Enable OpenCL 1.2 sampler-less texture reads, but utilize
// provided sampler in OpenCL 2.0.
if (enable_compliant_texture_reads_) {
// TODO(csullivan, lunderberg): Extend device attribute querying to support remote devices
// generically through the device API such that a target can be created from a specific device's
// attributes and utilized during codegen. Potential generlization of #8127 (c02cafb) for remote
// devices.
//
// E.g. Only provide an image sampler when the local or remote device supports OpenCL 2.0,
// see below for context.
//
// For backwards compatibility with OpenCL 1.2, sampler-less read_image calls are used.
// By default in sampler-less read_image calls OpenCL defaults to
// sampler_ = "CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_NONE | CLK_FILTER_NEAREST";
// See section 6.12.14.3 Built-in Image Sampler-less Read Functions in the OpenCL 1.2
// specification. For OpenCL 2.0 it can be preferable to use,
// sampler_ = "CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_NEAREST";
// For now we rely on OpenCL preprocessor directives to utilize the correct behavior
// depending on the OpenCL version detected at OpenCL compile time.
decl_stream << "#ifdef __OPENCL_VERSION__\n"
<< "#if __OPENCL_VERSION__ == CL_VERSION_2_0\n"
<< "#define READ_IMAGEH(image, sampler, coord) "
<< "read_imageh(image, sampler, coord)\n"
<< "#define READ_IMAGEF(image, sampler, coord) "
<< "read_imagef(image, sampler, coord)\n"
<< "#else\n"
<< "#define READ_IMAGEH(image, sampler, coord) "
<< "read_imageh(image, coord)\n"
<< "#define READ_IMAGEF(image, sampler, coord) "
<< "read_imagef(image, coord)\n"
<< "#endif\n"
<< "#endif\n\n";
}
return CodeGenC::Finish();
}
void CodeGenOpenCL::BindThreadIndex(const IterVar& iv) {
ICHECK(!var_idmap_.count(iv->var.get()));
runtime::ThreadScope ts = runtime::ThreadScope::Create(iv->thread_tag);
std::ostringstream os;
if (ts.rank == 1) {
os << "get_local_id(" << ts.dim_index << ")";
} else {
os << "get_group_id(" << ts.dim_index << ")";
}
var_idmap_[iv->var.get()] = CastFromTo(os.str(), DataType::UInt(64), iv->var.dtype());
}
void CodeGenOpenCL::PrintType(DataType t, std::ostream& os) { // NOLINT(*)
int lanes = t.lanes();
if (t.is_handle()) {
ICHECK_EQ(lanes, 1) << "do not yet support vector types";
os << "void*";
return;
}
if (t == DataType::Bool()) {
os << "bool";
return;
}
bool fail = false;
if (t.is_float()) {
switch (t.bits()) {
case 16:
os << "half";
enable_fp16_ = true;
break;
case 32:
os << "float";
break;
case 64:
os << "double";
enable_fp64_ = true;
break;
default:
fail = true;
break;
}
if (!fail && lanes == 1) return;
if (!fail && ((lanes >= 2 && lanes <= 4) || lanes == 8 || lanes == 16)) {
os << lanes;
return;
}
} else if (t.is_uint() || t.is_int()) {
if (t.is_uint()) {
os << 'u';
}
if (t.bits() == 8 && t.lanes() == 4) {
// directly 4 8 bit int in integer.
os << "int";
return;
}
switch (t.bits()) {
case 8:
os << "char";
break;
case 16:
os << "short";
break;
case 32:
os << "int";
break;
case 64:
os << "long";
break;
case 1:
os << "int";
break;
default:
fail = true;
break;
}
if (!fail && lanes == 1) return;
if (!fail && ((lanes >= 2 && lanes <= 4) || lanes == 8 || lanes == 16)) {
os << lanes;
return;
}
}
LOG(FATAL) << "Cannot convert type " << t << " to OpenCL type";
}
void CodeGenOpenCL::PrintType(const Type& type, std::ostream& os) { // NOLINT(*)
if (auto* ptr = type.as<PrimTypeNode>()) {
return PrintType(ptr->dtype, os);
} else if (auto* ptr = type.as<PointerTypeNode>()) {
if (runtime::IsTextureStorage(std::string(ptr->storage_scope))) {
os << "image2d_t";
} else {
PrintType(ptr->element_type, os);
os << '*';
}
} else if (IsVoidType(type)) {
os << "void";
} else {
LOG(FATAL) << "Type " << type << " does not have a corresponding C Type";
}
}
void CodeGenOpenCL::PrintVecAddr(const VarNode* buffer, DataType t, PrimExpr base,
std::ostream& os) { // NOLINT(*)
if (!HandleTypeMatch(buffer, t.element_of())) {
os << '(';
auto it = alloc_storage_scope_.find(buffer);
if (it != alloc_storage_scope_.end()) {
PrintStorageScope(it->second, os);
}
PrintType(t.element_of(), os);
os << "*)";
}
os << GetVarID(buffer) << " + ";
PrintExpr(base, os);
}
std::string CodeGenOpenCL::GetVecLoad(DataType t, const VarNode* buffer, PrimExpr base) {
std::ostringstream os;
os << "vload" << t.lanes() << "(0, ";
PrintVecAddr(buffer, t, base, os);
os << ")";
return os.str();
}
void CodeGenOpenCL::PrintVecStore(const VarNode* buffer, DataType t, PrimExpr base,
const std::string& value) {
this->PrintIndent();
stream << "vstore" << t.lanes() << "(" << value << ", 0, ";
PrintVecAddr(buffer, t, base, stream);
stream << ");\n";
}
void CodeGenOpenCL::PrintStorageSync(const CallNode* op) {
const std::string& sync = op->args[0].as<StringImmNode>()->value;
if (sync == "warp") {
this->PrintIndent();
this->stream << "barrier(CLK_LOCAL_MEM_FENCE);\n";
} else if (sync == "shared") {
this->PrintIndent();
this->stream << "barrier(CLK_LOCAL_MEM_FENCE);\n";
} else if (sync == "global") {
LOG(FATAL) << "not supported";
}
}
void CodeGenOpenCL::PrintStorageScope(const std::string& scope, std::ostream& os) { // NOLINT(*)
if (scope == "global") {
os << "__global ";
} else if (scope == "shared") {
os << "__local ";
} else if (scope == "texture_read") {
os << "__read_only ";
} else if (scope == "texture_write") {
os << "__write_only ";
}
}
void CodeGenOpenCL::PrintRestrict(const Var& v, std::ostream& os) {
// Apply restrict qualifer for non-texture types only
if (auto* ptr = v->type_annotation.as<PointerTypeNode>()) {
if (!runtime::IsTextureStorage(std::string(ptr->storage_scope))) {
os << ' ' << restrict_keyword_;
}
}
}
std::string CodeGenOpenCL::CastFromTo(std::string value, DataType from, DataType target) {
if (from == target) return value;
std::ostringstream os;
if (target.lanes() == 1) {
os << "((";
this->PrintType(target, os);
os << ")" << value << ")";
} else { // convert vector type
os << "(";
os << "convert_";
this->PrintType(target, os);
os << "(" << value << "))";
}
return os.str();
}
void CodeGenOpenCL::VisitStmt_(const StoreNode* op) {
if (auto call = op->value.as<CallNode>()) {
if (call->op.same_as(builtin::texture2d_load())) {
need_texture_ssa_ = false;
// If storing a texture load into a buffer, don't use an
// intermediate local unless the buffer allocation is a
// single element selected from the texture read.
auto it = allocation_size_.find(op->buffer_var.get());
if (it != allocation_size_.end() && it->second == 1) {
need_texture_ssa_ = true;
}
}
}
CodeGenC::VisitStmt_(op);
need_texture_ssa_ = true;
}
void CodeGenOpenCL::VisitExpr_(const CastNode* op, std::ostream& os) {
if (auto call = op->value.as<CallNode>()) {
if (call->op.same_as(builtin::texture2d_load())) {
need_texture_ssa_ = false;
}
}
CodeGenC::VisitExpr_(op, os);
need_texture_ssa_ = true;
}
void CodeGenOpenCL::VisitStmt_(const AllocateNode* op) {
allocation_size_.insert(
{op->buffer_var.get(), op->constant_allocation_size() * op->dtype.lanes()});
CodeGenC::VisitStmt_(op);
}
void CodeGenOpenCL::VisitExpr_(const CallNode* op, std::ostream& os) {
if (op->op.same_as(builtin::address_of())) {
// Overload tvm_address_of to add storage scope (e.g. __global).
const LoadNode* load = op->args[0].as<LoadNode>();
ICHECK(op->args.size() == 1 && load);
os << "((";
auto it = alloc_storage_scope_.find(load->buffer_var.get());
if (it != alloc_storage_scope_.end()) {
PrintStorageScope(it->second, os);
}
this->PrintType(load->dtype.element_of(), os);
os << " *)" << this->GetVarID(load->buffer_var.get()) << " + ";
this->PrintExpr(load->index, os);
os << ')';
} else if (op->op.same_as(builtin::texture2d_store())) {
auto* ptr_type = op->args[0].as<VarNode>()->type_annotation.as<PointerTypeNode>();
ICHECK(ptr_type != nullptr) << "Texture Var's must be of PointerType";
ICHECK(runtime::IsTextureStorage(std::string(ptr_type->storage_scope)))
<< "builtin::texture2d_store() only supports storing to texture buffers";
DataType buffer_type = ptr_type->element_type.as<PrimTypeNode>()->dtype;
if (buffer_type.is_float16()) {
os << "write_imageh(";
} else if (buffer_type.is_float()) {
os << "write_imagef(";
} else {
LOG(FATAL) << "Unsupported type: " << buffer_type
<< ", currently only float and half are supported for image2d OpenCL codegen.";
}
this->PrintExpr(op->args[0], os);
os << ", ";
os << "(int2)(";
this->PrintExpr(op->args[1], os);
os << ", ";
this->PrintExpr(op->args[2], os);
os << "), ";
this->PrintExpr(op->args[3], os);
os << ")";
} else if (op->op.same_as(builtin::texture2d_load())) {
enable_compliant_texture_reads_ = true;
std::stringstream ss;
if (op->dtype.is_float16()) {
ss << "READ_IMAGEH(";
} else if (op->dtype.is_float()) {
ss << "READ_IMAGEF(";
} else {
LOG(FATAL) << "Unsupported type: " << op->dtype
<< ", currently only float and half are supported for image2d OpenCL codegen.";
}
this->PrintExpr(op->args[0], ss);
ss << ", ";
ss << "CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_NEAREST, ";
ss << "((int2)(";
this->PrintExpr(op->args[1], ss);
ss << ", ";
this->PrintExpr(op->args[2], ss);
ss << ")))";
// Only use local SSA if texture is not already being stored
if (need_texture_ssa_) {
std::string rhs = SSAGetID(ss.str(), op->dtype.with_lanes(4));
if (op->args.back().as<RampNode>()) {
os << rhs;
} else {
os << "((";
this->PrintType(op->dtype.with_lanes(1), os);
os << "*)&" << rhs << ")[";
this->PrintExpr(op->args.back(), os);
os << "]";
}
} else {
os << ss.str();
}
} else if (op->op.same_as(builtin_call_extern_)) {
auto func = Downcast<StringImm>(op->args[0]);
// Enable atomics extension if used.
if (func->value == "atomic_add") {
enable_atomics_ = true;
}
CodeGenC::VisitExpr_(op, os);
} else {
CodeGenC::VisitExpr_(op, os);
}
}
void CodeGenOpenCL::VisitExpr_(const BroadcastNode* op, std::ostream& os) { // NOLINT(*)
std::string v = PrintExpr(op->value);
os << "((";
PrintType(op->dtype, os);
os << ")(";
for (int i = 0; i < op->lanes; ++i) {
if (i != 0) os << ", ";
os << v;
}
os << "))";
}
void CodeGenOpenCL::VisitExpr_(const FloatImmNode* op, std::ostream& os) { // NOLINT(*)
if (std::isinf(op->value)) {
if (op->value < 0) {
os << "-";
}
os << "INFINITY";
} else if (std::isnan(op->value)) {
os << "NAN";
} else {
CodeGenC::VisitExpr_(op, os);
}
}
void CodeGenOpenCL::SetTextureScope(
const std::unordered_map<const VarNode*, std::string>& scope) { // NOLINT(*)
for (auto& texture : scope) {
alloc_storage_scope_.insert(texture);
}
}
runtime::Module BuildOpenCL(IRModule mod, Target target) {
using tvm::runtime::Registry;
bool output_ssa = false;
std::stringstream code;
const auto* fpostproc = Registry::Get("tvm_callback_opencl_postproc");
for (auto kv : mod->functions) {
ICHECK(kv.second->IsInstance<PrimFuncNode>()) << "CodeGenOpenCL: Can only take PrimFunc";
code << "// Function: " << kv.first->name_hint << std::endl;
CodeGenOpenCL cg;
cg.Init(output_ssa);
auto f = Downcast<PrimFunc>(kv.second);
auto calling_conv = f->GetAttr<Integer>(tvm::attr::kCallingConv);
ICHECK(calling_conv == CallingConv::kDeviceKernelLaunch)
<< "CodeGenOpenCL: expect calling_conv equals CallingConv::kDeviceKernelLaunch";
cg.AddFunction(f);
std::string fsource = cg.Finish();
if (fpostproc) {
fsource = (*fpostproc)(fsource).operator std::string();
}
code << fsource;
}
return OpenCLModuleCreate(code.str(), "cl", ExtractFuncInfo(mod), code.str());
}
TVM_REGISTER_GLOBAL("target.build.opencl").set_body_typed(BuildOpenCL);
} // namespace codegen
} // namespace tvm
[OpenCL] Remove redundant visit statement in CodeGen. (#9144)
Fixes regression with some models on which compilation
doesn't terminate.
/*
* 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.
*/
/*!
* \file codegen_opencl.cc
*/
#include "codegen_opencl.h"
#include <cmath>
#include <string>
#include <vector>
#include "../../runtime/opencl/opencl_module.h"
#include "../../runtime/texture.h"
#include "../../runtime/thread_storage_scope.h"
#include "../build_common.h"
namespace tvm {
namespace codegen {
class InferTextureAccess : public StmtExprVisitor {
public:
static constexpr const uint8_t kReadAccess = 1;
static constexpr const uint8_t kWriteAccess = 2;
InferTextureAccess() {}
std::unordered_map<const VarNode*, std::string> Infer(const Stmt& n) {
StmtExprVisitor::VisitStmt(n);
std::unordered_map<const VarNode*, std::string> storage_scope_qualifiers;
for (auto& texture : var_access_map_) {
if (texture.second == kReadAccess) {
storage_scope_qualifiers.insert({texture.first, "texture_read"});
} else if (texture.second == kWriteAccess) {
storage_scope_qualifiers.insert({texture.first, "texture_write"});
} else if (texture.second == (kReadAccess | kWriteAccess)) {
storage_scope_qualifiers.insert({texture.first, ""});
}
}
return storage_scope_qualifiers;
}
void VisitExpr_(const CallNode* op) {
if (op->op.same_as(builtin::texture2d_load())) {
var_access_map_[op->args[0].as<VarNode>()] |= kReadAccess;
} else if (op->op.same_as(builtin::texture2d_store())) {
var_access_map_[op->args[0].as<VarNode>()] |= kWriteAccess;
}
StmtExprVisitor::VisitExpr_(op);
}
private:
std::unordered_map<const VarNode*, uint8_t> var_access_map_;
};
CodeGenOpenCL::CodeGenOpenCL() {
// Set OpenCL specific restrict keyword
restrict_keyword_ = "restrict";
}
void CodeGenOpenCL::InitFuncState(const PrimFunc& f) {
CodeGenC::InitFuncState(f);
this->SetTextureScope(InferTextureAccess().Infer(f->body));
for (Var arg : f->params) {
auto ptr_type = arg->type_annotation.as<PointerTypeNode>();
if (ptr_type && runtime::IsTextureStorage(std::string(ptr_type->storage_scope))) {
// Storage scope qualifiers for textures are inferred
// and set prior to function codegen.
continue;
} else if (arg.dtype().is_handle()) {
alloc_storage_scope_[arg.get()] = "global";
}
}
}
void CodeGenOpenCL::PrintFuncPrefix() { stream << "__kernel void"; }
std::string CodeGenOpenCL::Finish() {
// inject extension enable pragma for fp16 and fp64
if (enable_fp16_) {
decl_stream << "#ifdef cl_khr_fp16\n"
"#pragma OPENCL EXTENSION cl_khr_fp16 : enable\n"
"#elif defined(cl_amd_fp16)\n"
"#pragma OPENCL EXTENSION cl_amd_fp16 : enable\n"
"#else\n"
"#error \"Half precision floating point not supported"
"by OpenCL implementation on your device.\" \n"
"#endif\n\n";
}
if (enable_fp64_) {
decl_stream << "#ifdef cl_khr_fp64\n"
"#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n"
"#elif defined(cl_amd_fp64)\n"
"#pragma OPENCL EXTENSION cl_amd_fp64 : enable\n"
"#else\n"
"#error \"Double precision floating point not supported"
"by OpenCL implementation on your device.\" \n"
"#endif\n\n";
}
// Enable atomic_add used by get_valid_counts. Only needed for OpenCL < 1.1.
if (enable_atomics_) {
decl_stream << "#pragma OPENCL EXTENSION cl_khr_global_int32_base_atomics : enable\n"
"#pragma OPENCL EXTENSION cl_khr_global_int32_extended_atomics : enable\n\n";
}
// Enable OpenCL 1.2 sampler-less texture reads, but utilize
// provided sampler in OpenCL 2.0.
if (enable_compliant_texture_reads_) {
// TODO(csullivan, lunderberg): Extend device attribute querying to support remote devices
// generically through the device API such that a target can be created from a specific device's
// attributes and utilized during codegen. Potential generlization of #8127 (c02cafb) for remote
// devices.
//
// E.g. Only provide an image sampler when the local or remote device supports OpenCL 2.0,
// see below for context.
//
// For backwards compatibility with OpenCL 1.2, sampler-less read_image calls are used.
// By default in sampler-less read_image calls OpenCL defaults to
// sampler_ = "CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_NONE | CLK_FILTER_NEAREST";
// See section 6.12.14.3 Built-in Image Sampler-less Read Functions in the OpenCL 1.2
// specification. For OpenCL 2.0 it can be preferable to use,
// sampler_ = "CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_NEAREST";
// For now we rely on OpenCL preprocessor directives to utilize the correct behavior
// depending on the OpenCL version detected at OpenCL compile time.
decl_stream << "#ifdef __OPENCL_VERSION__\n"
<< "#if __OPENCL_VERSION__ == CL_VERSION_2_0\n"
<< "#define READ_IMAGEH(image, sampler, coord) "
<< "read_imageh(image, sampler, coord)\n"
<< "#define READ_IMAGEF(image, sampler, coord) "
<< "read_imagef(image, sampler, coord)\n"
<< "#else\n"
<< "#define READ_IMAGEH(image, sampler, coord) "
<< "read_imageh(image, coord)\n"
<< "#define READ_IMAGEF(image, sampler, coord) "
<< "read_imagef(image, coord)\n"
<< "#endif\n"
<< "#endif\n\n";
}
return CodeGenC::Finish();
}
void CodeGenOpenCL::BindThreadIndex(const IterVar& iv) {
ICHECK(!var_idmap_.count(iv->var.get()));
runtime::ThreadScope ts = runtime::ThreadScope::Create(iv->thread_tag);
std::ostringstream os;
if (ts.rank == 1) {
os << "get_local_id(" << ts.dim_index << ")";
} else {
os << "get_group_id(" << ts.dim_index << ")";
}
var_idmap_[iv->var.get()] = CastFromTo(os.str(), DataType::UInt(64), iv->var.dtype());
}
void CodeGenOpenCL::PrintType(DataType t, std::ostream& os) { // NOLINT(*)
int lanes = t.lanes();
if (t.is_handle()) {
ICHECK_EQ(lanes, 1) << "do not yet support vector types";
os << "void*";
return;
}
if (t == DataType::Bool()) {
os << "bool";
return;
}
bool fail = false;
if (t.is_float()) {
switch (t.bits()) {
case 16:
os << "half";
enable_fp16_ = true;
break;
case 32:
os << "float";
break;
case 64:
os << "double";
enable_fp64_ = true;
break;
default:
fail = true;
break;
}
if (!fail && lanes == 1) return;
if (!fail && ((lanes >= 2 && lanes <= 4) || lanes == 8 || lanes == 16)) {
os << lanes;
return;
}
} else if (t.is_uint() || t.is_int()) {
if (t.is_uint()) {
os << 'u';
}
if (t.bits() == 8 && t.lanes() == 4) {
// directly 4 8 bit int in integer.
os << "int";
return;
}
switch (t.bits()) {
case 8:
os << "char";
break;
case 16:
os << "short";
break;
case 32:
os << "int";
break;
case 64:
os << "long";
break;
case 1:
os << "int";
break;
default:
fail = true;
break;
}
if (!fail && lanes == 1) return;
if (!fail && ((lanes >= 2 && lanes <= 4) || lanes == 8 || lanes == 16)) {
os << lanes;
return;
}
}
LOG(FATAL) << "Cannot convert type " << t << " to OpenCL type";
}
void CodeGenOpenCL::PrintType(const Type& type, std::ostream& os) { // NOLINT(*)
if (auto* ptr = type.as<PrimTypeNode>()) {
return PrintType(ptr->dtype, os);
} else if (auto* ptr = type.as<PointerTypeNode>()) {
if (runtime::IsTextureStorage(std::string(ptr->storage_scope))) {
os << "image2d_t";
} else {
PrintType(ptr->element_type, os);
os << '*';
}
} else if (IsVoidType(type)) {
os << "void";
} else {
LOG(FATAL) << "Type " << type << " does not have a corresponding C Type";
}
}
void CodeGenOpenCL::PrintVecAddr(const VarNode* buffer, DataType t, PrimExpr base,
std::ostream& os) { // NOLINT(*)
if (!HandleTypeMatch(buffer, t.element_of())) {
os << '(';
auto it = alloc_storage_scope_.find(buffer);
if (it != alloc_storage_scope_.end()) {
PrintStorageScope(it->second, os);
}
PrintType(t.element_of(), os);
os << "*)";
}
os << GetVarID(buffer) << " + ";
PrintExpr(base, os);
}
std::string CodeGenOpenCL::GetVecLoad(DataType t, const VarNode* buffer, PrimExpr base) {
std::ostringstream os;
os << "vload" << t.lanes() << "(0, ";
PrintVecAddr(buffer, t, base, os);
os << ")";
return os.str();
}
void CodeGenOpenCL::PrintVecStore(const VarNode* buffer, DataType t, PrimExpr base,
const std::string& value) {
this->PrintIndent();
stream << "vstore" << t.lanes() << "(" << value << ", 0, ";
PrintVecAddr(buffer, t, base, stream);
stream << ");\n";
}
void CodeGenOpenCL::PrintStorageSync(const CallNode* op) {
const std::string& sync = op->args[0].as<StringImmNode>()->value;
if (sync == "warp") {
this->PrintIndent();
this->stream << "barrier(CLK_LOCAL_MEM_FENCE);\n";
} else if (sync == "shared") {
this->PrintIndent();
this->stream << "barrier(CLK_LOCAL_MEM_FENCE);\n";
} else if (sync == "global") {
LOG(FATAL) << "not supported";
}
}
void CodeGenOpenCL::PrintStorageScope(const std::string& scope, std::ostream& os) { // NOLINT(*)
if (scope == "global") {
os << "__global ";
} else if (scope == "shared") {
os << "__local ";
} else if (scope == "texture_read") {
os << "__read_only ";
} else if (scope == "texture_write") {
os << "__write_only ";
}
}
void CodeGenOpenCL::PrintRestrict(const Var& v, std::ostream& os) {
// Apply restrict qualifer for non-texture types only
if (auto* ptr = v->type_annotation.as<PointerTypeNode>()) {
if (!runtime::IsTextureStorage(std::string(ptr->storage_scope))) {
os << ' ' << restrict_keyword_;
}
}
}
std::string CodeGenOpenCL::CastFromTo(std::string value, DataType from, DataType target) {
if (from == target) return value;
std::ostringstream os;
if (target.lanes() == 1) {
os << "((";
this->PrintType(target, os);
os << ")" << value << ")";
} else { // convert vector type
os << "(";
os << "convert_";
this->PrintType(target, os);
os << "(" << value << "))";
}
return os.str();
}
void CodeGenOpenCL::VisitStmt_(const StoreNode* op) {
if (auto call = op->value.as<CallNode>()) {
if (call->op.same_as(builtin::texture2d_load())) {
need_texture_ssa_ = false;
// If storing a texture load into a buffer, don't use an
// intermediate local unless the buffer allocation is a
// single element selected from the texture read.
auto it = allocation_size_.find(op->buffer_var.get());
if (it != allocation_size_.end() && it->second == 1) {
need_texture_ssa_ = true;
}
}
}
CodeGenC::VisitStmt_(op);
need_texture_ssa_ = true;
}
void CodeGenOpenCL::VisitExpr_(const CastNode* op, std::ostream& os) {
if (auto call = op->value.as<CallNode>()) {
if (call->op.same_as(builtin::texture2d_load())) {
need_texture_ssa_ = false;
}
}
CodeGenC::VisitExpr_(op, os);
need_texture_ssa_ = true;
}
void CodeGenOpenCL::VisitStmt_(const AllocateNode* op) {
allocation_size_.insert(
{op->buffer_var.get(), op->constant_allocation_size() * op->dtype.lanes()});
CodeGenC::VisitStmt_(op);
}
void CodeGenOpenCL::VisitExpr_(const CallNode* op, std::ostream& os) {
if (op->op.same_as(builtin::address_of())) {
// Overload tvm_address_of to add storage scope (e.g. __global).
const LoadNode* load = op->args[0].as<LoadNode>();
ICHECK(op->args.size() == 1 && load);
os << "((";
auto it = alloc_storage_scope_.find(load->buffer_var.get());
if (it != alloc_storage_scope_.end()) {
PrintStorageScope(it->second, os);
}
this->PrintType(load->dtype.element_of(), os);
os << " *)" << this->GetVarID(load->buffer_var.get()) << " + ";
this->PrintExpr(load->index, os);
os << ')';
} else if (op->op.same_as(builtin::texture2d_store())) {
auto* ptr_type = op->args[0].as<VarNode>()->type_annotation.as<PointerTypeNode>();
ICHECK(ptr_type != nullptr) << "Texture Var's must be of PointerType";
ICHECK(runtime::IsTextureStorage(std::string(ptr_type->storage_scope)))
<< "builtin::texture2d_store() only supports storing to texture buffers";
DataType buffer_type = ptr_type->element_type.as<PrimTypeNode>()->dtype;
if (buffer_type.is_float16()) {
os << "write_imageh(";
} else if (buffer_type.is_float()) {
os << "write_imagef(";
} else {
LOG(FATAL) << "Unsupported type: " << buffer_type
<< ", currently only float and half are supported for image2d OpenCL codegen.";
}
this->PrintExpr(op->args[0], os);
os << ", ";
os << "(int2)(";
this->PrintExpr(op->args[1], os);
os << ", ";
this->PrintExpr(op->args[2], os);
os << "), ";
this->PrintExpr(op->args[3], os);
os << ")";
} else if (op->op.same_as(builtin::texture2d_load())) {
enable_compliant_texture_reads_ = true;
std::stringstream ss;
if (op->dtype.is_float16()) {
ss << "READ_IMAGEH(";
} else if (op->dtype.is_float()) {
ss << "READ_IMAGEF(";
} else {
LOG(FATAL) << "Unsupported type: " << op->dtype
<< ", currently only float and half are supported for image2d OpenCL codegen.";
}
this->PrintExpr(op->args[0], ss);
ss << ", ";
ss << "CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_NEAREST, ";
ss << "((int2)(";
this->PrintExpr(op->args[1], ss);
ss << ", ";
this->PrintExpr(op->args[2], ss);
ss << ")))";
// Only use local SSA if texture is not already being stored
if (need_texture_ssa_) {
std::string rhs = SSAGetID(ss.str(), op->dtype.with_lanes(4));
if (op->args.back().as<RampNode>()) {
os << rhs;
} else {
os << "((";
this->PrintType(op->dtype.with_lanes(1), os);
os << "*)&" << rhs << ")[";
this->PrintExpr(op->args.back(), os);
os << "]";
}
} else {
os << ss.str();
}
} else if (op->op.same_as(builtin_call_extern_)) {
auto func = Downcast<StringImm>(op->args[0]);
// Enable atomics extension if used.
if (func->value == "atomic_add") {
enable_atomics_ = true;
}
CodeGenC::VisitExpr_(op, os);
} else {
CodeGenC::VisitExpr_(op, os);
}
}
void CodeGenOpenCL::VisitExpr_(const BroadcastNode* op, std::ostream& os) { // NOLINT(*)
std::string v = PrintExpr(op->value);
os << "((";
PrintType(op->dtype, os);
os << ")(";
for (int i = 0; i < op->lanes; ++i) {
if (i != 0) os << ", ";
os << v;
}
os << "))";
}
void CodeGenOpenCL::VisitExpr_(const FloatImmNode* op, std::ostream& os) { // NOLINT(*)
if (std::isinf(op->value)) {
if (op->value < 0) {
os << "-";
}
os << "INFINITY";
} else if (std::isnan(op->value)) {
os << "NAN";
} else {
CodeGenC::VisitExpr_(op, os);
}
}
void CodeGenOpenCL::SetTextureScope(
const std::unordered_map<const VarNode*, std::string>& scope) { // NOLINT(*)
for (auto& texture : scope) {
alloc_storage_scope_.insert(texture);
}
}
runtime::Module BuildOpenCL(IRModule mod, Target target) {
using tvm::runtime::Registry;
bool output_ssa = false;
std::stringstream code;
const auto* fpostproc = Registry::Get("tvm_callback_opencl_postproc");
for (auto kv : mod->functions) {
ICHECK(kv.second->IsInstance<PrimFuncNode>()) << "CodeGenOpenCL: Can only take PrimFunc";
code << "// Function: " << kv.first->name_hint << std::endl;
CodeGenOpenCL cg;
cg.Init(output_ssa);
auto f = Downcast<PrimFunc>(kv.second);
auto calling_conv = f->GetAttr<Integer>(tvm::attr::kCallingConv);
ICHECK(calling_conv == CallingConv::kDeviceKernelLaunch)
<< "CodeGenOpenCL: expect calling_conv equals CallingConv::kDeviceKernelLaunch";
cg.AddFunction(f);
std::string fsource = cg.Finish();
if (fpostproc) {
fsource = (*fpostproc)(fsource).operator std::string();
}
code << fsource;
}
return OpenCLModuleCreate(code.str(), "cl", ExtractFuncInfo(mod), code.str());
}
TVM_REGISTER_GLOBAL("target.build.opencl").set_body_typed(BuildOpenCL);
} // namespace codegen
} // namespace tvm
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Hunspell, based on MySpell.
*
* The Initial Developers of the Original Code are
* Kevin Hendricks (MySpell) and Németh László (Hunspell).
* Portions created by the Initial Developers are Copyright (C) 2002-2005
* the Initial Developers. All Rights Reserved.
*
* Contributor(s): David Einstein, Davide Prina, Giuseppe Modugno,
* Gianluca Turconi, Simon Brouwer, Noll János, Bíró Árpád,
* Goldman Eleonóra, Sarlós Tamás, Bencsáth Boldizsár, Halácsy Péter,
* Dvornik László, Gefferth András, Nagy Viktor, Varga Dániel, Chris Halls,
* Rene Engelhard, Bram Moolenaar, Dafydd Jones, Harri Pitkänen
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
* Copyright 2002 Kevin B. Hendricks, Stratford, Ontario, Canada
* 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:
*
* 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.
*
* 3. All modifications to the source code must be clearly marked as
* such. Binary redistributions based on modified source code
* must be clearly marked as modified versions in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY KEVIN B. HENDRICKS 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
* KEVIN B. HENDRICKS 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 <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "hunspell.hxx"
#include "hunspell.h"
#ifndef MOZILLA_CLIENT
#include "config.h"
#endif
#include "csutil.hxx"
#include <limits>
#include <string>
Hunspell::Hunspell(const char* affpath, const char* dpath, const char* key) {
encoding = NULL;
csconv = NULL;
utf8 = 0;
complexprefixes = 0;
affixpath = mystrdup(affpath);
maxdic = 0;
/* first set up the hash manager */
pHMgr[0] = new HashMgr(dpath, affpath, key);
if (pHMgr[0])
maxdic = 1;
/* next set up the affix manager */
/* it needs access to the hash manager lookup methods */
pAMgr = new AffixMgr(affpath, pHMgr, &maxdic, key);
/* get the preferred try string and the dictionary */
/* encoding from the Affix Manager for that dictionary */
char* try_string = pAMgr->get_try_string();
encoding = pAMgr->get_encoding();
langnum = pAMgr->get_langnum();
utf8 = pAMgr->get_utf8();
if (!utf8)
csconv = get_current_cs(encoding);
complexprefixes = pAMgr->get_complexprefixes();
wordbreak = pAMgr->get_breaktable();
/* and finally set up the suggestion manager */
pSMgr = new SuggestMgr(try_string, MAXSUGGESTION, pAMgr);
if (try_string)
free(try_string);
}
Hunspell::~Hunspell() {
delete pSMgr;
delete pAMgr;
for (int i = 0; i < maxdic; i++)
delete pHMgr[i];
maxdic = 0;
pSMgr = NULL;
pAMgr = NULL;
#ifdef MOZILLA_CLIENT
delete[] csconv;
#endif
csconv = NULL;
if (encoding)
free(encoding);
encoding = NULL;
if (affixpath)
free(affixpath);
affixpath = NULL;
}
// load extra dictionaries
int Hunspell::add_dic(const char* dpath, const char* key) {
if (maxdic == MAXDIC || !affixpath)
return 1;
pHMgr[maxdic] = new HashMgr(dpath, affixpath, key);
if (pHMgr[maxdic])
maxdic++;
else
return 1;
return 0;
}
// make a copy of src at destination while removing all leading
// blanks and removing any trailing periods after recording
// their presence with the abbreviation flag
// also since already going through character by character,
// set the capitalization type
// return the length of the "cleaned" (and UTF-8 encoded) word
int Hunspell::cleanword2(char* dest,
const char* src,
w_char* dest_utf,
int* nc,
int* pcaptype,
int* pabbrev) {
unsigned char* p = (unsigned char*)dest;
const unsigned char* q = (const unsigned char*)src;
// first skip over any leading blanks
while ((*q != '\0') && (*q == ' '))
q++;
// now strip off any trailing periods (recording their presence)
*pabbrev = 0;
int nl = strlen((const char*)q);
while ((nl > 0) && (*(q + nl - 1) == '.')) {
nl--;
(*pabbrev)++;
}
// if no characters are left it can't be capitalized
if (nl <= 0) {
*pcaptype = NOCAP;
*p = '\0';
return 0;
}
strncpy(dest, (char*)q, nl);
*(dest + nl) = '\0';
nl = strlen(dest);
if (utf8) {
*nc = u8_u16(dest_utf, MAXWORDLEN, dest);
// don't check too long words
if (*nc >= MAXWORDLEN)
return 0;
if (*nc == -1) { // big Unicode character (non BMP area)
*pcaptype = NOCAP;
return nl;
}
*pcaptype = get_captype_utf8(dest_utf, *nc, langnum);
} else {
*pcaptype = get_captype(dest, nl, csconv);
*nc = nl;
}
return nl;
}
int Hunspell::cleanword(char* dest,
const char* src,
int* pcaptype,
int* pabbrev) {
unsigned char* p = (unsigned char*)dest;
const unsigned char* q = (const unsigned char*)src;
int firstcap = 0;
// first skip over any leading blanks
while ((*q != '\0') && (*q == ' '))
q++;
// now strip off any trailing periods (recording their presence)
*pabbrev = 0;
int nl = strlen((const char*)q);
while ((nl > 0) && (*(q + nl - 1) == '.')) {
nl--;
(*pabbrev)++;
}
// if no characters are left it can't be capitalized
if (nl <= 0) {
*pcaptype = NOCAP;
*p = '\0';
return 0;
}
// now determine the capitalization type of the first nl letters
int ncap = 0;
int nneutral = 0;
int nc = 0;
if (!utf8) {
while (nl > 0) {
nc++;
if (csconv[(*q)].ccase)
ncap++;
if (csconv[(*q)].cupper == csconv[(*q)].clower)
nneutral++;
*p++ = *q++;
nl--;
}
// remember to terminate the destination string
*p = '\0';
firstcap = csconv[(unsigned char)(*dest)].ccase;
} else {
unsigned short idx;
w_char t[MAXWORDLEN];
nc = u8_u16(t, MAXWORDLEN, src);
for (int i = 0; i < nc; i++) {
idx = (t[i].h << 8) + t[i].l;
unsigned short low = unicodetolower(idx, langnum);
if (idx != low)
ncap++;
if (unicodetoupper(idx, langnum) == low)
nneutral++;
}
u16_u8(dest, MAXWORDUTF8LEN, t, nc);
if (ncap) {
idx = (t[0].h << 8) + t[0].l;
firstcap = (idx != unicodetolower(idx, langnum));
}
}
// now finally set the captype
if (ncap == 0) {
*pcaptype = NOCAP;
} else if ((ncap == 1) && firstcap) {
*pcaptype = INITCAP;
} else if ((ncap == nc) || ((ncap + nneutral) == nc)) {
*pcaptype = ALLCAP;
} else if ((ncap > 1) && firstcap) {
*pcaptype = HUHINITCAP;
} else {
*pcaptype = HUHCAP;
}
return strlen(dest);
}
void Hunspell::mkallcap(char* p) {
if (utf8) {
w_char u[MAXWORDLEN];
int nc = u8_u16(u, MAXWORDLEN, p);
unsigned short idx;
for (int i = 0; i < nc; i++) {
idx = (u[i].h << 8) + u[i].l;
if (idx != unicodetoupper(idx, langnum)) {
u[i].h = (unsigned char)(unicodetoupper(idx, langnum) >> 8);
u[i].l = (unsigned char)(unicodetoupper(idx, langnum) & 0x00FF);
}
}
u16_u8(p, MAXWORDUTF8LEN, u, nc);
} else {
while (*p != '\0') {
*p = csconv[((unsigned char)*p)].cupper;
p++;
}
}
}
int Hunspell::mkallcap2(char* p, w_char* u, int nc) {
if (utf8) {
unsigned short idx;
for (int i = 0; i < nc; i++) {
idx = (u[i].h << 8) + u[i].l;
unsigned short up = unicodetoupper(idx, langnum);
if (idx != up) {
u[i].h = (unsigned char)(up >> 8);
u[i].l = (unsigned char)(up & 0x00FF);
}
}
u16_u8(p, MAXWORDUTF8LEN, u, nc);
return strlen(p);
} else {
while (*p != '\0') {
*p = csconv[((unsigned char)*p)].cupper;
p++;
}
}
return nc;
}
void Hunspell::mkallsmall(char* p) {
while (*p != '\0') {
*p = csconv[((unsigned char)*p)].clower;
p++;
}
}
int Hunspell::mkallsmall2(char* p, w_char* u, int nc) {
if (utf8) {
unsigned short idx;
for (int i = 0; i < nc; i++) {
idx = (u[i].h << 8) + u[i].l;
unsigned short low = unicodetolower(idx, langnum);
if (idx != low) {
u[i].h = (unsigned char)(low >> 8);
u[i].l = (unsigned char)(low & 0x00FF);
}
}
u16_u8(p, MAXWORDUTF8LEN, u, nc);
return strlen(p);
} else {
while (*p != '\0') {
*p = csconv[((unsigned char)*p)].clower;
p++;
}
}
return nc;
}
// convert UTF-8 sharp S codes to latin 1
char* Hunspell::sharps_u8_l1(char* dest, char* source) {
char* p = dest;
*p = *source;
for (p++, source++; *(source - 1); p++, source++) {
*p = *source;
if (*source == '\x9F')
*--p = '\xDF';
}
return dest;
}
// recursive search for right ss - sharp s permutations
hentry* Hunspell::spellsharps(char* base,
char* pos,
int n,
int repnum,
char* tmp,
int* info,
char** root) {
pos = strstr(pos, "ss");
if (pos && (n < MAXSHARPS)) {
*pos = '\xC3';
*(pos + 1) = '\x9F';
hentry* h = spellsharps(base, pos + 2, n + 1, repnum + 1, tmp, info, root);
if (h)
return h;
*pos = 's';
*(pos + 1) = 's';
h = spellsharps(base, pos + 2, n + 1, repnum, tmp, info, root);
if (h)
return h;
} else if (repnum > 0) {
if (utf8)
return checkword(base, info, root);
return checkword(sharps_u8_l1(tmp, base), info, root);
}
return NULL;
}
int Hunspell::is_keepcase(const hentry* rv) {
return pAMgr && rv->astr && pAMgr->get_keepcase() &&
TESTAFF(rv->astr, pAMgr->get_keepcase(), rv->alen);
}
/* insert a word to the beginning of the suggestion array and return ns */
int Hunspell::insert_sug(char*** slst, char* word, int ns) {
if (!*slst)
return ns;
char* dup = mystrdup(word);
if (!dup)
return ns;
if (ns == MAXSUGGESTION) {
ns--;
free((*slst)[ns]);
}
for (int k = ns; k > 0; k--)
(*slst)[k] = (*slst)[k - 1];
(*slst)[0] = dup;
return ns + 1;
}
int Hunspell::spell(const char* word, int* info, char** root) {
struct hentry* rv = NULL;
// need larger vector. For example, Turkish capital letter I converted a
// 2-byte UTF-8 character (dotless i) by mkallsmall.
char cw[MAXWORDUTF8LEN];
char wspace[MAXWORDUTF8LEN];
w_char unicw[MAXWORDLEN];
int info2 = 0;
if (!info)
info = &info2;
else
*info = 0;
// Hunspell supports XML input of the simplified API (see manual)
if (strcmp(word, SPELL_XML) == 0)
return 1;
int nc = strlen(word);
int wl2 = 0;
if (utf8) {
if (nc >= MAXWORDUTF8LEN)
return 0;
} else {
if (nc >= MAXWORDLEN)
return 0;
}
int captype = 0;
int abbv = 0;
int wl = 0;
// input conversion
RepList* rl = (pAMgr) ? pAMgr->get_iconvtable() : NULL;
int convstatus = rl ? rl->conv(word, wspace, MAXWORDUTF8LEN) : 0;
if (convstatus < 0)
return 0;
else if (convstatus > 0)
wl = cleanword2(cw, wspace, unicw, &nc, &captype, &abbv);
else
wl = cleanword2(cw, word, unicw, &nc, &captype, &abbv);
#ifdef MOZILLA_CLIENT
// accept the abbreviated words without dots
// workaround for the incomplete tokenization of Mozilla
abbv = 1;
#endif
if (wl == 0 || maxdic == 0)
return 1;
if (root)
*root = NULL;
// allow numbers with dots, dashes and commas (but forbid double separators:
// "..", "--" etc.)
enum { NBEGIN, NNUM, NSEP };
int nstate = NBEGIN;
int i;
for (i = 0; (i < wl); i++) {
if ((cw[i] <= '9') && (cw[i] >= '0')) {
nstate = NNUM;
} else if ((cw[i] == ',') || (cw[i] == '.') || (cw[i] == '-')) {
if ((nstate == NSEP) || (i == 0))
break;
nstate = NSEP;
} else
break;
}
if ((i == wl) && (nstate == NNUM))
return 1;
switch (captype) {
case HUHCAP:
/* FALLTHROUGH */
case HUHINITCAP:
*info += SPELL_ORIGCAP;
/* FALLTHROUGH */
case NOCAP:
rv = checkword(cw, info, root);
if ((abbv) && !(rv)) {
memcpy(wspace, cw, wl);
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
rv = checkword(wspace, info, root);
}
break;
case ALLCAP: {
*info += SPELL_ORIGCAP;
rv = checkword(cw, info, root);
if (rv)
break;
if (abbv) {
memcpy(wspace, cw, wl);
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
rv = checkword(wspace, info, root);
if (rv)
break;
}
// Spec. prefix handling for Catalan, French, Italian:
// prefixes separated by apostrophe (SANT'ELIA -> Sant'+Elia).
if (pAMgr && strchr(cw, '\'')) {
mkallsmall2(cw, unicw, nc);
// There are no really sane circumstances where this could fail,
// but anyway...
if (char* apostrophe = strchr(cw, '\'')) {
if (utf8) {
w_char tmpword[MAXWORDLEN];
*apostrophe = '\0';
wl2 = u8_u16(tmpword, MAXWORDLEN, cw);
*apostrophe = '\'';
if (wl2 >= 0 && wl2 < nc) {
mkinitcap2(apostrophe + 1, unicw + wl2 + 1, nc - wl2 - 1);
rv = checkword(cw, info, root);
if (rv)
break;
}
} else {
mkinitcap2(apostrophe + 1, unicw, nc);
rv = checkword(cw, info, root);
if (rv)
break;
}
}
mkinitcap2(cw, unicw, nc);
rv = checkword(cw, info, root);
if (rv)
break;
}
if (pAMgr && pAMgr->get_checksharps() && strstr(cw, "SS")) {
char tmpword[MAXWORDUTF8LEN];
wl = mkallsmall2(cw, unicw, nc);
memcpy(wspace, cw, (wl + 1));
rv = spellsharps(wspace, wspace, 0, 0, tmpword, info, root);
if (!rv) {
wl2 = mkinitcap2(cw, unicw, nc);
rv = spellsharps(cw, cw, 0, 0, tmpword, info, root);
}
if ((abbv) && !(rv)) {
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
rv = spellsharps(wspace, wspace, 0, 0, tmpword, info, root);
if (!rv) {
memcpy(wspace, cw, wl2);
*(wspace + wl2) = '.';
*(wspace + wl2 + 1) = '\0';
rv = spellsharps(wspace, wspace, 0, 0, tmpword, info, root);
}
}
if (rv)
break;
}
}
case INITCAP: {
*info += SPELL_ORIGCAP;
wl = mkallsmall2(cw, unicw, nc);
memcpy(wspace, cw, (wl + 1));
wl2 = mkinitcap2(cw, unicw, nc);
if (captype == INITCAP)
*info += SPELL_INITCAP;
rv = checkword(cw, info, root);
if (captype == INITCAP)
*info -= SPELL_INITCAP;
// forbid bad capitalization
// (for example, ijs -> Ijs instead of IJs in Dutch)
// use explicit forms in dic: Ijs/F (F = FORBIDDENWORD flag)
if (*info & SPELL_FORBIDDEN) {
rv = NULL;
break;
}
if (rv && is_keepcase(rv) && (captype == ALLCAP))
rv = NULL;
if (rv)
break;
rv = checkword(wspace, info, root);
if (abbv && !rv) {
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
rv = checkword(wspace, info, root);
if (!rv) {
memcpy(wspace, cw, wl2);
*(wspace + wl2) = '.';
*(wspace + wl2 + 1) = '\0';
if (captype == INITCAP)
*info += SPELL_INITCAP;
rv = checkword(wspace, info, root);
if (captype == INITCAP)
*info -= SPELL_INITCAP;
if (rv && is_keepcase(rv) && (captype == ALLCAP))
rv = NULL;
break;
}
}
if (rv && is_keepcase(rv) &&
((captype == ALLCAP) ||
// if CHECKSHARPS: KEEPCASE words with \xDF are allowed
// in INITCAP form, too.
!(pAMgr->get_checksharps() &&
((utf8 && strstr(wspace, "\xC3\x9F")) ||
(!utf8 && strchr(wspace, '\xDF'))))))
rv = NULL;
break;
}
}
if (rv) {
if (pAMgr && pAMgr->get_warn() && rv->astr &&
TESTAFF(rv->astr, pAMgr->get_warn(), rv->alen)) {
*info += SPELL_WARN;
if (pAMgr->get_forbidwarn())
return 0;
return HUNSPELL_OK_WARN;
}
return HUNSPELL_OK;
}
// recursive breaking at break points
if (wordbreak) {
char* s;
char r;
int nbr = 0;
wl = strlen(cw);
int numbreak = pAMgr ? pAMgr->get_numbreak() : 0;
// calculate break points for recursion limit
for (int j = 0; j < numbreak; j++) {
s = cw;
do {
s = (char*)strstr(s, wordbreak[j]);
if (s) {
nbr++;
s++;
}
} while (s);
}
if (nbr >= 10)
return 0;
// check boundary patterns (^begin and end$)
for (int j = 0; j < numbreak; j++) {
int plen = strlen(wordbreak[j]);
if (plen == 1 || plen > wl)
continue;
if (wordbreak[j][0] == '^' &&
strncmp(cw, wordbreak[j] + 1, plen - 1) == 0 && spell(cw + plen - 1))
return 1;
if (wordbreak[j][plen - 1] == '$' &&
strncmp(cw + wl - plen + 1, wordbreak[j], plen - 1) == 0) {
r = cw[wl - plen + 1];
cw[wl - plen + 1] = '\0';
if (spell(cw))
return 1;
cw[wl - plen + 1] = r;
}
}
// other patterns
for (int j = 0; j < numbreak; j++) {
int plen = strlen(wordbreak[j]);
s = (char*)strstr(cw, wordbreak[j]);
if (s && (s > cw) && (s < cw + wl - plen)) {
if (!spell(s + plen))
continue;
r = *s;
*s = '\0';
// examine 2 sides of the break point
if (spell(cw))
return 1;
*s = r;
// LANG_hu: spec. dash rule
if (langnum == LANG_hu && strcmp(wordbreak[j], "-") == 0) {
r = s[1];
s[1] = '\0';
if (spell(cw))
return 1; // check the first part with dash
s[1] = r;
}
// end of LANG speficic region
}
}
}
return 0;
}
struct hentry* Hunspell::checkword(const char* w, int* info, char** root) {
struct hentry* he = NULL;
bool usebuffer = false;
int len, i;
std::string w2;
const char* word;
char* ignoredchars = pAMgr ? pAMgr->get_ignore() : NULL;
if (ignoredchars != NULL) {
w2.assign(w);
if (utf8) {
int ignoredchars_utf16_len;
unsigned short* ignoredchars_utf16 =
pAMgr->get_ignore_utf16(&ignoredchars_utf16_len);
remove_ignored_chars_utf(w2, ignoredchars_utf16, ignoredchars_utf16_len);
} else {
remove_ignored_chars(w2, ignoredchars);
}
word = w2.c_str();
usebuffer = true;
} else
word = w;
len = strlen(word);
if (!len)
return NULL;
// word reversing wrapper for complex prefixes
if (complexprefixes) {
if (!usebuffer) {
w2.assign(word);
usebuffer = true;
}
if (utf8)
reverseword_utf(w2);
else
reverseword(w2);
}
if (usebuffer) {
word = w2.c_str();
}
// look word in hash table
for (i = 0; (i < maxdic) && !he; i++) {
he = (pHMgr[i])->lookup(word);
// check forbidden and onlyincompound words
if ((he) && (he->astr) && (pAMgr) &&
TESTAFF(he->astr, pAMgr->get_forbiddenword(), he->alen)) {
if (info)
*info += SPELL_FORBIDDEN;
// LANG_hu section: set dash information for suggestions
if (langnum == LANG_hu) {
if (pAMgr->get_compoundflag() &&
TESTAFF(he->astr, pAMgr->get_compoundflag(), he->alen)) {
if (info)
*info += SPELL_COMPOUND;
}
}
return NULL;
}
// he = next not needaffix, onlyincompound homonym or onlyupcase word
while (he && (he->astr) && pAMgr &&
((pAMgr->get_needaffix() &&
TESTAFF(he->astr, pAMgr->get_needaffix(), he->alen)) ||
(pAMgr->get_onlyincompound() &&
TESTAFF(he->astr, pAMgr->get_onlyincompound(), he->alen)) ||
(info && (*info & SPELL_INITCAP) &&
TESTAFF(he->astr, ONLYUPCASEFLAG, he->alen))))
he = he->next_homonym;
}
// check with affixes
if (!he && pAMgr) {
// try stripping off affixes */
he = pAMgr->affix_check(word, len, 0);
// check compound restriction and onlyupcase
if (he && he->astr &&
((pAMgr->get_onlyincompound() &&
TESTAFF(he->astr, pAMgr->get_onlyincompound(), he->alen)) ||
(info && (*info & SPELL_INITCAP) &&
TESTAFF(he->astr, ONLYUPCASEFLAG, he->alen)))) {
he = NULL;
}
if (he) {
if ((he->astr) && (pAMgr) &&
TESTAFF(he->astr, pAMgr->get_forbiddenword(), he->alen)) {
if (info)
*info += SPELL_FORBIDDEN;
return NULL;
}
if (root) {
*root = mystrdup(he->word);
if (*root && complexprefixes) {
if (utf8)
reverseword_utf(*root);
else
reverseword(*root);
}
}
// try check compound word
} else if (pAMgr->get_compound()) {
he = pAMgr->compound_check(word, len, 0, 0, 100, 0, NULL, 0, 0, info);
// LANG_hu section: `moving rule' with last dash
if ((!he) && (langnum == LANG_hu) && (word[len - 1] == '-')) {
char* dup = mystrdup(word);
if (!dup)
return NULL;
dup[len - 1] = '\0';
he = pAMgr->compound_check(dup, len - 1, -5, 0, 100, 0, NULL, 1, 0,
info);
free(dup);
}
// end of LANG speficic region
if (he) {
if (root) {
*root = mystrdup(he->word);
if (*root && complexprefixes) {
if (utf8)
reverseword_utf(*root);
else
reverseword(*root);
}
}
if (info)
*info += SPELL_COMPOUND;
}
}
}
return he;
}
int Hunspell::suggest(char*** slst, const char* word) {
int onlycmpdsug = 0;
char cw[MAXWORDUTF8LEN];
char wspace[MAXWORDUTF8LEN];
if (!pSMgr || maxdic == 0)
return 0;
w_char unicw[MAXWORDLEN];
*slst = NULL;
// process XML input of the simplified API (see manual)
if (strncmp(word, SPELL_XML, sizeof(SPELL_XML) - 3) == 0) {
return spellml(slst, word);
}
int nc = strlen(word);
if (utf8) {
if (nc >= MAXWORDUTF8LEN)
return 0;
} else {
if (nc >= MAXWORDLEN)
return 0;
}
int captype = 0;
int abbv = 0;
int wl = 0;
// input conversion
RepList* rl = (pAMgr) ? pAMgr->get_iconvtable() : NULL;
int convstatus = rl ? rl->conv(word, wspace, MAXWORDUTF8LEN) : 0;
if (convstatus < 0)
return 0;
else if (convstatus > 0)
wl = cleanword2(cw, wspace, unicw, &nc, &captype, &abbv);
else
wl = cleanword2(cw, word, unicw, &nc, &captype, &abbv);
if (wl == 0)
return 0;
int ns = 0;
int capwords = 0;
// check capitalized form for FORCEUCASE
if (pAMgr && captype == NOCAP && pAMgr->get_forceucase()) {
int info = SPELL_ORIGCAP;
char** wlst;
if (checkword(cw, &info, NULL)) {
if (*slst) {
wlst = *slst;
} else {
wlst = (char**)malloc(MAXSUGGESTION * sizeof(char*));
if (wlst == NULL)
return -1;
*slst = wlst;
for (int i = 0; i < MAXSUGGESTION; i++) {
wlst[i] = NULL;
}
}
wlst[0] = mystrdup(cw);
mkinitcap(wlst[0]);
return 1;
}
}
switch (captype) {
case NOCAP: {
ns = pSMgr->suggest(slst, cw, ns, &onlycmpdsug);
break;
}
case INITCAP: {
capwords = 1;
ns = pSMgr->suggest(slst, cw, ns, &onlycmpdsug);
if (ns == -1)
break;
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
ns = pSMgr->suggest(slst, wspace, ns, &onlycmpdsug);
break;
}
case HUHINITCAP:
capwords = 1;
case HUHCAP: {
ns = pSMgr->suggest(slst, cw, ns, &onlycmpdsug);
if (ns != -1) {
int prevns;
// something.The -> something. The
char* dot = strchr(cw, '.');
if (dot && (dot > cw)) {
int captype_;
if (utf8) {
w_char w_[MAXWORDLEN];
int wl_ = u8_u16(w_, MAXWORDLEN, dot + 1);
captype_ = get_captype_utf8(w_, wl_, langnum);
} else
captype_ = get_captype(dot + 1, strlen(dot + 1), csconv);
if (captype_ == INITCAP) {
char* st = mystrdup(cw);
if (st) {
char* newst = (char*)realloc(st, wl + 2);
if (newst == NULL)
free(st);
st = newst;
}
if (st) {
st[(dot - cw) + 1] = ' ';
strcpy(st + (dot - cw) + 2, dot + 1);
ns = insert_sug(slst, st, ns);
free(st);
}
}
}
if (captype == HUHINITCAP) {
// TheOpenOffice.org -> The OpenOffice.org
memcpy(wspace, cw, (wl + 1));
mkinitsmall2(wspace, unicw, nc);
ns = pSMgr->suggest(slst, wspace, ns, &onlycmpdsug);
}
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
if (spell(wspace))
ns = insert_sug(slst, wspace, ns);
prevns = ns;
ns = pSMgr->suggest(slst, wspace, ns, &onlycmpdsug);
if (captype == HUHINITCAP) {
mkinitcap2(wspace, unicw, nc);
if (spell(wspace))
ns = insert_sug(slst, wspace, ns);
ns = pSMgr->suggest(slst, wspace, ns, &onlycmpdsug);
}
// aNew -> "a New" (instead of "a new")
for (int j = prevns; j < ns; j++) {
char* space = strchr((*slst)[j], ' ');
if (space) {
int slen = strlen(space + 1);
// different case after space (need capitalisation)
if ((slen < wl) && strcmp(cw + wl - slen, space + 1)) {
w_char w[MAXWORDLEN];
int wc = 0;
char* r = (*slst)[j];
if (utf8)
wc = u8_u16(w, MAXWORDLEN, space + 1);
mkinitcap2(space + 1, w, wc);
// set as first suggestion
for (int k = j; k > 0; k--)
(*slst)[k] = (*slst)[k - 1];
(*slst)[0] = r;
}
}
}
}
break;
}
case ALLCAP: {
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
ns = pSMgr->suggest(slst, wspace, ns, &onlycmpdsug);
if (ns == -1)
break;
if (pAMgr && pAMgr->get_keepcase() && spell(wspace))
ns = insert_sug(slst, wspace, ns);
mkinitcap2(wspace, unicw, nc);
ns = pSMgr->suggest(slst, wspace, ns, &onlycmpdsug);
for (int j = 0; j < ns; j++) {
mkallcap((*slst)[j]);
if (pAMgr && pAMgr->get_checksharps()) {
char* pos;
if (utf8) {
pos = strstr((*slst)[j], "\xC3\x9F");
while (pos) {
*pos = 'S';
*(pos + 1) = 'S';
pos = strstr(pos + 2, "\xC3\x9F");
}
} else {
pos = strchr((*slst)[j], '\xDF');
while (pos) {
(*slst)[j] = (char*)realloc((*slst)[j], strlen((*slst)[j]) + 2);
mystrrep((*slst)[j], "\xDF", "SS");
pos = strchr((*slst)[j], '\xDF');
}
}
}
}
break;
}
}
// LANG_hu section: replace '-' with ' ' in Hungarian
if (langnum == LANG_hu) {
for (int j = 0; j < ns; j++) {
char* pos = strchr((*slst)[j], '-');
if (pos) {
int info;
char w[MAXWORDUTF8LEN];
*pos = '\0';
strcpy(w, (*slst)[j]);
strcat(w, pos + 1);
(void)spell(w, &info, NULL);
if ((info & SPELL_COMPOUND) && (info & SPELL_FORBIDDEN)) {
*pos = ' ';
} else
*pos = '-';
}
}
}
// END OF LANG_hu section
// try ngram approach since found nothing or only compound words
if (pAMgr && (ns == 0 || onlycmpdsug) && (pAMgr->get_maxngramsugs() != 0) &&
(*slst)) {
switch (captype) {
case NOCAP: {
ns = pSMgr->ngsuggest(*slst, cw, ns, pHMgr, maxdic);
break;
}
case HUHINITCAP:
capwords = 1;
case HUHCAP: {
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
ns = pSMgr->ngsuggest(*slst, wspace, ns, pHMgr, maxdic);
break;
}
case INITCAP: {
capwords = 1;
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
ns = pSMgr->ngsuggest(*slst, wspace, ns, pHMgr, maxdic);
break;
}
case ALLCAP: {
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
int oldns = ns;
ns = pSMgr->ngsuggest(*slst, wspace, ns, pHMgr, maxdic);
for (int j = oldns; j < ns; j++)
mkallcap((*slst)[j]);
break;
}
}
}
// try dash suggestion (Afo-American -> Afro-American)
if (char* pos = strchr(cw, '-')) {
char* ppos = cw;
int nodashsug = 1;
char** nlst = NULL;
int nn = 0;
int last = 0;
if (*slst) {
for (int j = 0; j < ns && nodashsug == 1; j++) {
if (strchr((*slst)[j], '-'))
nodashsug = 0;
}
}
while (nodashsug && !last) {
if (*pos == '\0')
last = 1;
else
*pos = '\0';
if (!spell(ppos)) {
nn = suggest(&nlst, ppos);
for (int j = nn - 1; j >= 0; j--) {
strncpy(wspace, cw, ppos - cw);
strcpy(wspace + (ppos - cw), nlst[j]);
if (!last) {
strcat(wspace, "-");
strcat(wspace, pos + 1);
}
ns = insert_sug(slst, wspace, ns);
free(nlst[j]);
}
if (nlst != NULL)
free(nlst);
nodashsug = 0;
}
if (!last) {
*pos = '-';
ppos = pos + 1;
pos = strchr(ppos, '-');
}
if (!pos)
pos = cw + strlen(cw);
}
}
// word reversing wrapper for complex prefixes
if (complexprefixes) {
for (int j = 0; j < ns; j++) {
if (utf8)
reverseword_utf((*slst)[j]);
else
reverseword((*slst)[j]);
}
}
// capitalize
if (capwords)
for (int j = 0; j < ns; j++) {
mkinitcap((*slst)[j]);
}
// expand suggestions with dot(s)
if (abbv && pAMgr && pAMgr->get_sugswithdots()) {
for (int j = 0; j < ns; j++) {
(*slst)[j] = (char*)realloc((*slst)[j], strlen((*slst)[j]) + 1 + abbv);
strcat((*slst)[j], word + strlen(word) - abbv);
}
}
// remove bad capitalized and forbidden forms
if (pAMgr && (pAMgr->get_keepcase() || pAMgr->get_forbiddenword())) {
switch (captype) {
case INITCAP:
case ALLCAP: {
int l = 0;
for (int j = 0; j < ns; j++) {
if (!strchr((*slst)[j], ' ') && !spell((*slst)[j])) {
char s[MAXSWUTF8L];
w_char w[MAXSWL];
int len;
if (utf8) {
len = u8_u16(w, MAXSWL, (*slst)[j]);
} else {
strcpy(s, (*slst)[j]);
len = strlen(s);
}
mkallsmall2(s, w, len);
free((*slst)[j]);
if (spell(s)) {
(*slst)[l] = mystrdup(s);
if ((*slst)[l])
l++;
} else {
mkinitcap2(s, w, len);
if (spell(s)) {
(*slst)[l] = mystrdup(s);
if ((*slst)[l])
l++;
}
}
} else {
(*slst)[l] = (*slst)[j];
l++;
}
}
ns = l;
}
}
}
// remove duplications
int l = 0;
for (int j = 0; j < ns; j++) {
(*slst)[l] = (*slst)[j];
for (int k = 0; k < l; k++) {
if (strcmp((*slst)[k], (*slst)[j]) == 0) {
free((*slst)[j]);
l--;
break;
}
}
l++;
}
ns = l;
// output conversion
rl = (pAMgr) ? pAMgr->get_oconvtable() : NULL;
for (int j = 0; rl && j < ns; j++) {
if (rl->conv((*slst)[j], wspace, MAXWORDUTF8LEN) > 0) {
free((*slst)[j]);
(*slst)[j] = mystrdup(wspace);
}
}
// if suggestions removed by nosuggest, onlyincompound parameters
if (l == 0 && *slst) {
free(*slst);
*slst = NULL;
}
return l;
}
void Hunspell::free_list(char*** slst, int n) {
freelist(slst, n);
}
char* Hunspell::get_dic_encoding() {
return encoding;
}
#ifdef HUNSPELL_EXPERIMENTAL
// XXX UTF-8 support is OK?
int Hunspell::suggest_auto(char*** slst, const char* word) {
char cw[MAXWORDUTF8LEN];
char wspace[MAXWORDUTF8LEN];
if (!pSMgr || maxdic == 0)
return 0;
w_char unicw[MAXWORDLEN];
int nc = strlen(word);
if (utf8) {
if (nc >= MAXWORDUTF8LEN)
return 0;
} else {
if (nc >= MAXWORDLEN)
return 0;
}
int captype = 0;
int abbv = 0;
int wl = 0;
// input conversion
RepList* rl = (pAMgr) ? pAMgr->get_iconvtable() : NULL;
int convstatus = rl ? rl->conv(word, wspace) : 0;
if (convstatus < 0)
return 0;
else if (convstatus > 0)
wl = cleanword2(cw, wspace, unicw, &nc, &captype, &abbv);
else
wl = cleanword2(cw, word, unicw, &nc, &captype, &abbv);
if (wl == 0)
return 0;
int ns = 0;
*slst = NULL; // HU, nsug in pSMgr->suggest
switch (captype) {
case NOCAP: {
ns = pSMgr->suggest_auto(slst, cw, ns);
if (ns > 0)
break;
break;
}
case INITCAP: {
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
ns = pSMgr->suggest_auto(slst, wspace, ns);
for (int j = 0; j < ns; j++)
mkinitcap((*slst)[j]);
ns = pSMgr->suggest_auto(slst, cw, ns);
break;
}
case HUHINITCAP:
case HUHCAP: {
ns = pSMgr->suggest_auto(slst, cw, ns);
if (ns == 0) {
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
ns = pSMgr->suggest_auto(slst, wspace, ns);
}
break;
}
case ALLCAP: {
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
ns = pSMgr->suggest_auto(slst, wspace, ns);
mkinitcap(wspace);
ns = pSMgr->suggest_auto(slst, wspace, ns);
for (int j = 0; j < ns; j++)
mkallcap((*slst)[j]);
break;
}
}
// word reversing wrapper for complex prefixes
if (complexprefixes) {
for (int j = 0; j < ns; j++) {
if (utf8)
reverseword_utf((*slst)[j]);
else
reverseword((*slst)[j]);
}
}
// expand suggestions with dot(s)
if (abbv && pAMgr && pAMgr->get_sugswithdots()) {
for (int j = 0; j < ns; j++) {
(*slst)[j] = (char*)realloc((*slst)[j], strlen((*slst)[j]) + 1 + abbv);
strcat((*slst)[j], word + strlen(word) - abbv);
}
}
// LANG_hu section: replace '-' with ' ' in Hungarian
if (langnum == LANG_hu) {
for (int j = 0; j < ns; j++) {
char* pos = strchr((*slst)[j], '-');
if (pos) {
int info;
char w[MAXWORDUTF8LEN];
*pos = '\0';
strcpy(w, (*slst)[j]);
strcat(w, pos + 1);
spell(w, &info, NULL);
if ((info & SPELL_COMPOUND) && (info & SPELL_FORBIDDEN)) {
*pos = ' ';
} else
*pos = '-';
}
}
}
// output conversion
rl = (pAMgr) ? pAMgr->get_oconvtable() : NULL;
for (int j = 0; rl && j < ns; j++) {
if (rl->conv((*slst)[j], wspace) > 0) {
free((*slst)[j]);
(*slst)[j] = mystrdup(wspace);
}
}
// END OF LANG_hu section
return ns;
}
#endif
int Hunspell::stem(char*** slst, char** desc, int n) {
char result[MAXLNLEN];
char result2[MAXLNLEN];
*slst = NULL;
if (n == 0)
return 0;
*result2 = '\0';
for (int i = 0; i < n; i++) {
*result = '\0';
// add compound word parts (except the last one)
char* s = (char*)desc[i];
char* part = strstr(s, MORPH_PART);
if (part) {
char* nextpart = strstr(part + 1, MORPH_PART);
while (nextpart) {
copy_field(result + strlen(result), part, MORPH_PART);
part = nextpart;
nextpart = strstr(part + 1, MORPH_PART);
}
s = part;
}
char** pl;
std::string tok(s);
size_t alt = 0;
while ((alt = tok.find(" | ", alt)) != std::string::npos) {
tok[alt + 1] = MSEP_ALT;
}
int pln = line_tok(tok.c_str(), &pl, MSEP_ALT);
for (int k = 0; k < pln; k++) {
// add derivational suffixes
if (strstr(pl[k], MORPH_DERI_SFX)) {
// remove inflectional suffixes
char* is = strstr(pl[k], MORPH_INFL_SFX);
if (is)
*is = '\0';
char* sg = pSMgr->suggest_gen(&(pl[k]), 1, pl[k]);
if (sg) {
char** gen;
int genl = line_tok(sg, &gen, MSEP_REC);
free(sg);
for (int j = 0; j < genl; j++) {
sprintf(result2 + strlen(result2), "%c%s%s", MSEP_REC, result,
gen[j]);
}
freelist(&gen, genl);
}
} else {
sprintf(result2 + strlen(result2), "%c%s", MSEP_REC, result);
if (strstr(pl[k], MORPH_SURF_PFX)) {
copy_field(result2 + strlen(result2), pl[k], MORPH_SURF_PFX);
}
copy_field(result2 + strlen(result2), pl[k], MORPH_STEM);
}
}
freelist(&pl, pln);
}
int sln = line_tok(result2, slst, MSEP_REC);
return uniqlist(*slst, sln);
}
int Hunspell::stem(char*** slst, const char* word) {
char** pl;
int pln = analyze(&pl, word);
int pln2 = stem(slst, pl, pln);
freelist(&pl, pln);
return pln2;
}
#ifdef HUNSPELL_EXPERIMENTAL
int Hunspell::suggest_pos_stems(char*** slst, const char* word) {
char cw[MAXWORDUTF8LEN];
char wspace[MAXWORDUTF8LEN];
if (!pSMgr || maxdic == 0)
return 0;
w_char unicw[MAXWORDLEN];
int nc = strlen(word);
if (utf8) {
if (nc >= MAXWORDUTF8LEN)
return 0;
} else {
if (nc >= MAXWORDLEN)
return 0;
}
int captype = 0;
int abbv = 0;
int wl = 0;
// input conversion
RepList* rl = (pAMgr) ? pAMgr->get_iconvtable() : NULL;
int convstatus = rl ? rl->conv(word, wspace) : 0;
if (convstatus < 0)
return 0;
else if (convstatus > 0)
wl = cleanword2(cw, wspace, unicw, &nc, &captype, &abbv);
else
wl = cleanword2(cw, word, unicw, &nc, &captype, &abbv);
if (wl == 0)
return 0;
int ns = 0; // ns=0 = normalized input
*slst = NULL; // HU, nsug in pSMgr->suggest
switch (captype) {
case HUHCAP:
case NOCAP: {
ns = pSMgr->suggest_pos_stems(slst, cw, ns);
if ((abbv) && (ns == 0)) {
memcpy(wspace, cw, wl);
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
ns = pSMgr->suggest_pos_stems(slst, wspace, ns);
}
break;
}
case INITCAP: {
ns = pSMgr->suggest_pos_stems(slst, cw, ns);
if (ns == 0 || ((*slst)[0][0] == '#')) {
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
ns = pSMgr->suggest_pos_stems(slst, wspace, ns);
}
break;
}
case ALLCAP: {
ns = pSMgr->suggest_pos_stems(slst, cw, ns);
if (ns != 0)
break;
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
ns = pSMgr->suggest_pos_stems(slst, wspace, ns);
if (ns == 0) {
mkinitcap(wspace);
ns = pSMgr->suggest_pos_stems(slst, wspace, ns);
}
break;
}
}
// output conversion
rl = (pAMgr) ? pAMgr->get_oconvtable() : NULL;
for (int j = 0; rl && j < ns; j++) {
if (rl->conv((*slst)[j], wspace) > 0) {
free((*slst)[j]);
(*slst)[j] = mystrdup(wspace);
}
}
return ns;
}
#endif // END OF HUNSPELL_EXPERIMENTAL CODE
const char* Hunspell::get_wordchars() {
return pAMgr->get_wordchars();
}
unsigned short* Hunspell::get_wordchars_utf16(int* len) {
return pAMgr->get_wordchars_utf16(len);
}
void Hunspell::mkinitcap(char* p) {
if (!utf8) {
if (*p != '\0')
*p = csconv[((unsigned char)*p)].cupper;
} else {
int len;
w_char u[MAXWORDLEN];
len = u8_u16(u, MAXWORDLEN, p);
unsigned short i = unicodetoupper((u[0].h << 8) + u[0].l, langnum);
u[0].h = (unsigned char)(i >> 8);
u[0].l = (unsigned char)(i & 0x00FF);
u16_u8(p, MAXWORDUTF8LEN, u, len);
}
}
int Hunspell::mkinitcap2(char* p, w_char* u, int nc) {
if (!utf8) {
if (*p != '\0')
*p = csconv[((unsigned char)*p)].cupper;
} else if (nc > 0) {
unsigned short i = unicodetoupper((u[0].h << 8) + u[0].l, langnum);
u[0].h = (unsigned char)(i >> 8);
u[0].l = (unsigned char)(i & 0x00FF);
u16_u8(p, MAXWORDUTF8LEN, u, nc);
return strlen(p);
}
return nc;
}
int Hunspell::mkinitsmall2(char* p, w_char* u, int nc) {
if (!utf8) {
if (*p != '\0')
*p = csconv[((unsigned char)*p)].clower;
} else if (nc > 0) {
unsigned short i = unicodetolower((u[0].h << 8) + u[0].l, langnum);
u[0].h = (unsigned char)(i >> 8);
u[0].l = (unsigned char)(i & 0x00FF);
u16_u8(p, MAXWORDUTF8LEN, u, nc);
return strlen(p);
}
return nc;
}
int Hunspell::add(const char* word) {
if (pHMgr[0])
return (pHMgr[0])->add(word);
return 0;
}
int Hunspell::add_with_affix(const char* word, const char* example) {
if (pHMgr[0])
return (pHMgr[0])->add_with_affix(word, example);
return 0;
}
int Hunspell::remove(const char* word) {
if (pHMgr[0])
return (pHMgr[0])->remove(word);
return 0;
}
const char* Hunspell::get_version() {
return pAMgr->get_version();
}
struct cs_info* Hunspell::get_csconv() {
return csconv;
}
void Hunspell::cat_result(char* result, char* st) {
if (st) {
if (*result)
mystrcat(result, "\n", MAXLNLEN);
mystrcat(result, st, MAXLNLEN);
free(st);
}
}
int Hunspell::analyze(char*** slst, const char* word) {
char cw[MAXWORDUTF8LEN];
char wspace[MAXWORDUTF8LEN];
w_char unicw[MAXWORDLEN];
int wl2 = 0;
*slst = NULL;
if (!pSMgr || maxdic == 0)
return 0;
int nc = strlen(word);
if (utf8) {
if (nc >= MAXWORDUTF8LEN)
return 0;
} else {
if (nc >= MAXWORDLEN)
return 0;
}
int captype = 0;
int abbv = 0;
int wl = 0;
// input conversion
RepList* rl = (pAMgr) ? pAMgr->get_iconvtable() : NULL;
int convstatus = rl ? rl->conv(word, wspace, MAXWORDUTF8LEN) : 0;
if (convstatus < 0)
return 0;
else if (convstatus > 0)
wl = cleanword2(cw, wspace, unicw, &nc, &captype, &abbv);
else
wl = cleanword2(cw, word, unicw, &nc, &captype, &abbv);
if (wl == 0) {
if (abbv) {
for (wl = 0; wl < abbv; wl++)
cw[wl] = '.';
cw[wl] = '\0';
abbv = 0;
} else
return 0;
}
char result[MAXLNLEN];
char* st = NULL;
*result = '\0';
int n = 0;
int n2 = 0;
int n3 = 0;
// test numbers
// LANG_hu section: set dash information for suggestions
if (langnum == LANG_hu) {
while ((n < wl) && (((cw[n] <= '9') && (cw[n] >= '0')) ||
(((cw[n] == '.') || (cw[n] == ',')) && (n > 0)))) {
n++;
if ((cw[n] == '.') || (cw[n] == ',')) {
if (((n2 == 0) && (n > 3)) ||
((n2 > 0) && ((cw[n - 1] == '.') || (cw[n - 1] == ','))))
break;
n2++;
n3 = n;
}
}
if ((n == wl) && (n3 > 0) && (n - n3 > 3))
return 0;
if ((n == wl) || ((n > 0) && ((cw[n] == '%') || (cw[n] == '\xB0')) &&
checkword(cw + n, NULL, NULL))) {
mystrcat(result, cw, MAXLNLEN);
result[n - 1] = '\0';
if (n == wl)
cat_result(result, pSMgr->suggest_morph(cw + n - 1));
else {
char sign = cw[n];
cw[n] = '\0';
cat_result(result, pSMgr->suggest_morph(cw + n - 1));
mystrcat(result, "+", MAXLNLEN); // XXX SPEC. MORPHCODE
cw[n] = sign;
cat_result(result, pSMgr->suggest_morph(cw + n));
}
return line_tok(result, slst, MSEP_REC);
}
}
// END OF LANG_hu section
switch (captype) {
case HUHCAP:
case HUHINITCAP:
case NOCAP: {
cat_result(result, pSMgr->suggest_morph(cw));
if (abbv) {
memcpy(wspace, cw, wl);
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
cat_result(result, pSMgr->suggest_morph(wspace));
}
break;
}
case INITCAP: {
wl = mkallsmall2(cw, unicw, nc);
memcpy(wspace, cw, (wl + 1));
wl2 = mkinitcap2(cw, unicw, nc);
cat_result(result, pSMgr->suggest_morph(wspace));
cat_result(result, pSMgr->suggest_morph(cw));
if (abbv) {
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
cat_result(result, pSMgr->suggest_morph(wspace));
memcpy(wspace, cw, wl2);
*(wspace + wl2) = '.';
*(wspace + wl2 + 1) = '\0';
cat_result(result, pSMgr->suggest_morph(wspace));
}
break;
}
case ALLCAP: {
cat_result(result, pSMgr->suggest_morph(cw));
if (abbv) {
memcpy(wspace, cw, wl);
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
cat_result(result, pSMgr->suggest_morph(cw));
}
wl = mkallsmall2(cw, unicw, nc);
memcpy(wspace, cw, (wl + 1));
wl2 = mkinitcap2(cw, unicw, nc);
cat_result(result, pSMgr->suggest_morph(wspace));
cat_result(result, pSMgr->suggest_morph(cw));
if (abbv) {
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
cat_result(result, pSMgr->suggest_morph(wspace));
memcpy(wspace, cw, wl2);
*(wspace + wl2) = '.';
*(wspace + wl2 + 1) = '\0';
cat_result(result, pSMgr->suggest_morph(wspace));
}
break;
}
}
if (*result) {
// word reversing wrapper for complex prefixes
if (complexprefixes) {
if (utf8)
reverseword_utf(result);
else
reverseword(result);
}
return line_tok(result, slst, MSEP_REC);
}
// compound word with dash (HU) I18n
char* dash = NULL;
int nresult = 0;
// LANG_hu section: set dash information for suggestions
if (langnum == LANG_hu)
dash = (char*)strchr(cw, '-');
if ((langnum == LANG_hu) && dash) {
*dash = '\0';
// examine 2 sides of the dash
if (dash[1] == '\0') { // base word ending with dash
if (spell(cw)) {
char* p = pSMgr->suggest_morph(cw);
if (p) {
int ret = line_tok(p, slst, MSEP_REC);
free(p);
return ret;
}
}
} else if ((dash[1] == 'e') && (dash[2] == '\0')) { // XXX (HU) -e hat.
if (spell(cw) && (spell("-e"))) {
st = pSMgr->suggest_morph(cw);
if (st) {
mystrcat(result, st, MAXLNLEN);
free(st);
}
mystrcat(result, "+", MAXLNLEN); // XXX spec. separator in MORPHCODE
st = pSMgr->suggest_morph("-e");
if (st) {
mystrcat(result, st, MAXLNLEN);
free(st);
}
return line_tok(result, slst, MSEP_REC);
}
} else {
// first word ending with dash: word- XXX ???
char r2 = *(dash + 1);
dash[0] = '-';
dash[1] = '\0';
nresult = spell(cw);
dash[1] = r2;
dash[0] = '\0';
if (nresult && spell(dash + 1) &&
((strlen(dash + 1) > 1) || ((dash[1] > '0') && (dash[1] < '9')))) {
st = pSMgr->suggest_morph(cw);
if (st) {
mystrcat(result, st, MAXLNLEN);
free(st);
mystrcat(result, "+", MAXLNLEN); // XXX spec. separator in MORPHCODE
}
st = pSMgr->suggest_morph(dash + 1);
if (st) {
mystrcat(result, st, MAXLNLEN);
free(st);
}
return line_tok(result, slst, MSEP_REC);
}
}
// affixed number in correct word
if (nresult && (dash > cw) &&
(((*(dash - 1) <= '9') && (*(dash - 1) >= '0')) ||
(*(dash - 1) == '.'))) {
*dash = '-';
n = 1;
if (*(dash - n) == '.')
n++;
// search first not a number character to left from dash
while (((dash - n) >= cw) && ((*(dash - n) == '0') || (n < 3)) &&
(n < 6)) {
n++;
}
if ((dash - n) < cw)
n--;
// numbers: valami1000000-hoz
// examine 100000-hoz, 10000-hoz 1000-hoz, 10-hoz,
// 56-hoz, 6-hoz
for (; n >= 1; n--) {
if ((*(dash - n) >= '0') && (*(dash - n) <= '9') &&
checkword(dash - n, NULL, NULL)) {
mystrcat(result, cw, MAXLNLEN);
result[dash - cw - n] = '\0';
st = pSMgr->suggest_morph(dash - n);
if (st) {
mystrcat(result, st, MAXLNLEN);
free(st);
}
return line_tok(result, slst, MSEP_REC);
}
}
}
}
return 0;
}
int Hunspell::generate(char*** slst, const char* word, char** pl, int pln) {
*slst = NULL;
if (!pSMgr || !pln)
return 0;
char** pl2;
int pl2n = analyze(&pl2, word);
int captype = 0;
int abbv = 0;
char cw[MAXWORDUTF8LEN];
cleanword(cw, word, &captype, &abbv);
char result[MAXLNLEN];
*result = '\0';
for (int i = 0; i < pln; i++) {
cat_result(result, pSMgr->suggest_gen(pl2, pl2n, pl[i]));
}
freelist(&pl2, pl2n);
if (*result) {
// allcap
if (captype == ALLCAP)
mkallcap(result);
// line split
int linenum = line_tok(result, slst, MSEP_REC);
// capitalize
if (captype == INITCAP || captype == HUHINITCAP) {
for (int j = 0; j < linenum; j++)
mkinitcap((*slst)[j]);
}
// temporary filtering of prefix related errors (eg.
// generate("undrinkable", "eats") --> "undrinkables" and "*undrinks")
int r = 0;
for (int j = 0; j < linenum; j++) {
if (!spell((*slst)[j])) {
free((*slst)[j]);
(*slst)[j] = NULL;
} else {
if (r < j)
(*slst)[r] = (*slst)[j];
r++;
}
}
if (r > 0)
return r;
free(*slst);
*slst = NULL;
}
return 0;
}
int Hunspell::generate(char*** slst, const char* word, const char* pattern) {
char** pl;
int pln = analyze(&pl, pattern);
int n = generate(slst, word, pl, pln);
freelist(&pl, pln);
return uniqlist(*slst, n);
}
// minimal XML parser functions
int Hunspell::get_xml_par(char* dest, const char* par, int max) {
char* d = dest;
if (!par)
return 0;
char end = *par;
char* dmax = dest + max;
if (end == '>')
end = '<';
else if (end != '\'' && end != '"')
return 0; // bad XML
for (par++; d < dmax && *par != '\0' && *par != end; par++, d++)
*d = *par;
*d = '\0';
mystrrep(dest, "<", "<");
mystrrep(dest, "&", "&");
return (int)(d - dest);
}
int Hunspell::get_langnum() const {
return langnum;
}
int Hunspell::input_conv(const char* word, char* dest, size_t destsize) {
RepList* rl = (pAMgr) ? pAMgr->get_iconvtable() : NULL;
return (rl && rl->conv(word, dest, destsize) > 0);
}
// return the beginning of the element (attr == NULL) or the attribute
const char* Hunspell::get_xml_pos(const char* s, const char* attr) {
const char* end = strchr(s, '>');
const char* p = s;
if (attr == NULL)
return end;
do {
p = strstr(p, attr);
if (!p || p >= end)
return 0;
} while (*(p - 1) != ' ' && *(p - 1) != '\n');
return p + strlen(attr);
}
int Hunspell::check_xml_par(const char* q,
const char* attr,
const char* value) {
char cw[MAXWORDUTF8LEN];
if (get_xml_par(cw, get_xml_pos(q, attr), MAXWORDUTF8LEN - 1) &&
strcmp(cw, value) == 0)
return 1;
return 0;
}
int Hunspell::get_xml_list(char*** slst, char* list, const char* tag) {
int n = 0;
char* p;
if (!list)
return 0;
for (p = list; ((p = strstr(p, tag)) != NULL); p++)
n++;
if (n == 0)
return 0;
*slst = (char**)malloc(sizeof(char*) * n);
if (!*slst)
return 0;
for (p = list, n = 0; ((p = strstr(p, tag)) != NULL); p++, n++) {
int l = strlen(p);
(*slst)[n] = (char*)malloc(l + 1);
if (!(*slst)[n])
return n;
if (!get_xml_par((*slst)[n], p + strlen(tag) - 1, l)) {
free((*slst)[n]);
break;
}
}
return n;
}
int Hunspell::spellml(char*** slst, const char* word) {
char *q, *q2;
char cw[MAXWORDUTF8LEN], cw2[MAXWORDUTF8LEN];
q = (char*)strstr(word, "<query");
if (!q)
return 0; // bad XML input
q2 = strchr(q, '>');
if (!q2)
return 0; // bad XML input
q2 = strstr(q2, "<word");
if (!q2)
return 0; // bad XML input
if (check_xml_par(q, "type=", "analyze")) {
int n = 0;
if (get_xml_par(cw, strchr(q2, '>'), MAXWORDUTF8LEN - 10))
n = analyze(slst, cw);
if (n == 0)
return 0;
// convert the result to <code><a>ana1</a><a>ana2</a></code> format
std::string r;
r.append("<code>");
for (int i = 0; i < n; i++) {
r.append("<a>");
std::string entry((*slst)[i]);
free((*slst)[i]);
mystrrep(entry, "\t", " ");
mystrrep(entry, "&", "&");
mystrrep(entry, "<", "<");
r.append(entry);
r.append("</a>");
}
r.append("</code>");
(*slst)[0] = mystrdup(r.c_str());
return 1;
} else if (check_xml_par(q, "type=", "stem")) {
if (get_xml_par(cw, strchr(q2, '>'), MAXWORDUTF8LEN - 1))
return stem(slst, cw);
} else if (check_xml_par(q, "type=", "generate")) {
int n = get_xml_par(cw, strchr(q2, '>'), MAXWORDUTF8LEN - 1);
if (n == 0)
return 0;
char* q3 = strstr(q2 + 1, "<word");
if (q3) {
if (get_xml_par(cw2, strchr(q3, '>'), MAXWORDUTF8LEN - 1)) {
return generate(slst, cw, cw2);
}
} else {
if ((q2 = strstr(q2 + 1, "<code")) != NULL) {
char** slst2;
if ((n = get_xml_list(&slst2, strchr(q2, '>'), "<a>")) != 0) {
int n2 = generate(slst, cw, slst2, n);
freelist(&slst2, n);
return uniqlist(*slst, n2);
}
freelist(&slst2, n);
}
}
}
return 0;
}
#ifdef HUNSPELL_EXPERIMENTAL
// XXX is UTF-8 support OK?
char* Hunspell::morph_with_correction(const char* word) {
char cw[MAXWORDUTF8LEN];
char wspace[MAXWORDUTF8LEN];
if (!pSMgr || maxdic == 0)
return NULL;
w_char unicw[MAXWORDLEN];
int nc = strlen(word);
if (utf8) {
if (nc >= MAXWORDUTF8LEN)
return NULL;
} else {
if (nc >= MAXWORDLEN)
return NULL;
}
int captype = 0;
int abbv = 0;
int wl = 0;
// input conversion
RepList* rl = (pAMgr) ? pAMgr->get_iconvtable() : NULL;
int convstatus = rl ? rl->conv(word, wspace) : 0;
if (convstatus < 0)
return 0;
else if (convstatus > 0)
wl = cleanword2(cw, wspace, unicw, &nc, &captype, &abbv);
else
wl = cleanword2(cw, word, unicw, &nc, &captype, &abbv);
if (wl == 0)
return NULL;
char result[MAXLNLEN];
char* st = NULL;
*result = '\0';
switch (captype) {
case NOCAP: {
st = pSMgr->suggest_morph_for_spelling_error(cw);
if (st) {
mystrcat(result, st, MAXLNLEN);
free(st);
}
if (abbv) {
memcpy(wspace, cw, wl);
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
st = pSMgr->suggest_morph_for_spelling_error(wspace);
if (st) {
if (*result)
mystrcat(result, "\n", MAXLNLEN);
mystrcat(result, st, MAXLNLEN);
free(st);
}
}
break;
}
case INITCAP: {
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
st = pSMgr->suggest_morph_for_spelling_error(wspace);
if (st) {
mystrcat(result, st, MAXLNLEN);
free(st);
}
st = pSMgr->suggest_morph_for_spelling_error(cw);
if (st) {
if (*result)
mystrcat(result, "\n", MAXLNLEN);
mystrcat(result, st, MAXLNLEN);
free(st);
}
if (abbv) {
memcpy(wspace, cw, wl);
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
mkallsmall2(wspace, unicw, nc);
st = pSMgr->suggest_morph_for_spelling_error(wspace);
if (st) {
if (*result)
mystrcat(result, "\n", MAXLNLEN);
mystrcat(result, st, MAXLNLEN);
free(st);
}
mkinitcap(wspace);
st = pSMgr->suggest_morph_for_spelling_error(wspace);
if (st) {
if (*result)
mystrcat(result, "\n", MAXLNLEN);
mystrcat(result, st, MAXLNLEN);
free(st);
}
}
break;
}
case HUHCAP: {
st = pSMgr->suggest_morph_for_spelling_error(cw);
if (st) {
mystrcat(result, st, MAXLNLEN);
free(st);
}
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
st = pSMgr->suggest_morph_for_spelling_error(wspace);
if (st) {
if (*result)
mystrcat(result, "\n", MAXLNLEN);
mystrcat(result, st, MAXLNLEN);
free(st);
}
break;
}
case ALLCAP: {
memcpy(wspace, cw, (wl + 1));
st = pSMgr->suggest_morph_for_spelling_error(wspace);
if (st) {
mystrcat(result, st, MAXLNLEN);
free(st);
}
mkallsmall2(wspace, unicw, nc);
st = pSMgr->suggest_morph_for_spelling_error(wspace);
if (st) {
if (*result)
mystrcat(result, "\n", MAXLNLEN);
mystrcat(result, st, MAXLNLEN);
free(st);
}
mkinitcap(wspace);
st = pSMgr->suggest_morph_for_spelling_error(wspace);
if (st) {
if (*result)
mystrcat(result, "\n", MAXLNLEN);
mystrcat(result, st, MAXLNLEN);
free(st);
}
if (abbv) {
memcpy(wspace, cw, (wl + 1));
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
if (*result)
mystrcat(result, "\n", MAXLNLEN);
st = pSMgr->suggest_morph_for_spelling_error(wspace);
if (st) {
mystrcat(result, st, MAXLNLEN);
free(st);
}
mkallsmall2(wspace, unicw, nc);
st = pSMgr->suggest_morph_for_spelling_error(wspace);
if (st) {
if (*result)
mystrcat(result, "\n", MAXLNLEN);
mystrcat(result, st, MAXLNLEN);
free(st);
}
mkinitcap(wspace);
st = pSMgr->suggest_morph_for_spelling_error(wspace);
if (st) {
if (*result)
mystrcat(result, "\n", MAXLNLEN);
mystrcat(result, st, MAXLNLEN);
free(st);
}
}
break;
}
}
if (*result)
return mystrdup(result);
return NULL;
}
#endif // END OF HUNSPELL_EXPERIMENTAL CODE
Hunhandle* Hunspell_create(const char* affpath, const char* dpath) {
return (Hunhandle*)(new Hunspell(affpath, dpath));
}
Hunhandle* Hunspell_create_key(const char* affpath,
const char* dpath,
const char* key) {
return (Hunhandle*)(new Hunspell(affpath, dpath, key));
}
void Hunspell_destroy(Hunhandle* pHunspell) {
delete (Hunspell*)(pHunspell);
}
int Hunspell_add_dic(Hunhandle* pHunspell, const char* dpath) {
return ((Hunspell*)pHunspell)->add_dic(dpath);
}
int Hunspell_spell(Hunhandle* pHunspell, const char* word) {
return ((Hunspell*)pHunspell)->spell(word);
}
char* Hunspell_get_dic_encoding(Hunhandle* pHunspell) {
return ((Hunspell*)pHunspell)->get_dic_encoding();
}
int Hunspell_suggest(Hunhandle* pHunspell, char*** slst, const char* word) {
return ((Hunspell*)pHunspell)->suggest(slst, word);
}
int Hunspell_analyze(Hunhandle* pHunspell, char*** slst, const char* word) {
return ((Hunspell*)pHunspell)->analyze(slst, word);
}
int Hunspell_stem(Hunhandle* pHunspell, char*** slst, const char* word) {
return ((Hunspell*)pHunspell)->stem(slst, word);
}
int Hunspell_stem2(Hunhandle* pHunspell, char*** slst, char** desc, int n) {
return ((Hunspell*)pHunspell)->stem(slst, desc, n);
}
int Hunspell_generate(Hunhandle* pHunspell,
char*** slst,
const char* word,
const char* word2) {
return ((Hunspell*)pHunspell)->generate(slst, word, word2);
}
int Hunspell_generate2(Hunhandle* pHunspell,
char*** slst,
const char* word,
char** desc,
int n) {
return ((Hunspell*)pHunspell)->generate(slst, word, desc, n);
}
/* functions for run-time modification of the dictionary */
/* add word to the run-time dictionary */
int Hunspell_add(Hunhandle* pHunspell, const char* word) {
return ((Hunspell*)pHunspell)->add(word);
}
/* add word to the run-time dictionary with affix flags of
* the example (a dictionary word): Hunspell will recognize
* affixed forms of the new word, too.
*/
int Hunspell_add_with_affix(Hunhandle* pHunspell,
const char* word,
const char* example) {
return ((Hunspell*)pHunspell)->add_with_affix(word, example);
}
/* remove word from the run-time dictionary */
int Hunspell_remove(Hunhandle* pHunspell, const char* word) {
return ((Hunspell*)pHunspell)->remove(word);
}
void Hunspell_free_list(Hunhandle*, char*** slst, int n) {
freelist(slst, n);
}
int Hunspell::suffix_suggest(char*** slst, const char* root_word) {
struct hentry* he = NULL;
int len;
std::string w2;
const char* word;
char* ignoredchars = pAMgr->get_ignore();
if (ignoredchars != NULL) {
w2.assign(root_word);
if (utf8) {
int ignoredchars_utf16_len;
unsigned short* ignoredchars_utf16 =
pAMgr->get_ignore_utf16(&ignoredchars_utf16_len);
remove_ignored_chars_utf(w2, ignoredchars_utf16, ignoredchars_utf16_len);
} else {
remove_ignored_chars(w2, ignoredchars);
}
word = w2.c_str();
} else
word = root_word;
len = strlen(word);
if (!len)
return 0;
char** wlst = (char**)malloc(MAXSUGGESTION * sizeof(char*));
if (wlst == NULL)
return -1;
*slst = wlst;
for (int i = 0; i < MAXSUGGESTION; i++) {
wlst[i] = NULL;
}
for (int i = 0; (i < maxdic) && !he; i++) {
he = (pHMgr[i])->lookup(word);
}
if (he) {
return pAMgr->get_suffix_words(he->astr, he->alen, root_word, *slst);
}
return 0;
}
reorg use of scratch wspace buffer
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Hunspell, based on MySpell.
*
* The Initial Developers of the Original Code are
* Kevin Hendricks (MySpell) and Németh László (Hunspell).
* Portions created by the Initial Developers are Copyright (C) 2002-2005
* the Initial Developers. All Rights Reserved.
*
* Contributor(s): David Einstein, Davide Prina, Giuseppe Modugno,
* Gianluca Turconi, Simon Brouwer, Noll János, Bíró Árpád,
* Goldman Eleonóra, Sarlós Tamás, Bencsáth Boldizsár, Halácsy Péter,
* Dvornik László, Gefferth András, Nagy Viktor, Varga Dániel, Chris Halls,
* Rene Engelhard, Bram Moolenaar, Dafydd Jones, Harri Pitkänen
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
* Copyright 2002 Kevin B. Hendricks, Stratford, Ontario, Canada
* 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:
*
* 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.
*
* 3. All modifications to the source code must be clearly marked as
* such. Binary redistributions based on modified source code
* must be clearly marked as modified versions in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY KEVIN B. HENDRICKS 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
* KEVIN B. HENDRICKS 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 <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "hunspell.hxx"
#include "hunspell.h"
#ifndef MOZILLA_CLIENT
#include "config.h"
#endif
#include "csutil.hxx"
#include <limits>
#include <string>
Hunspell::Hunspell(const char* affpath, const char* dpath, const char* key) {
encoding = NULL;
csconv = NULL;
utf8 = 0;
complexprefixes = 0;
affixpath = mystrdup(affpath);
maxdic = 0;
/* first set up the hash manager */
pHMgr[0] = new HashMgr(dpath, affpath, key);
if (pHMgr[0])
maxdic = 1;
/* next set up the affix manager */
/* it needs access to the hash manager lookup methods */
pAMgr = new AffixMgr(affpath, pHMgr, &maxdic, key);
/* get the preferred try string and the dictionary */
/* encoding from the Affix Manager for that dictionary */
char* try_string = pAMgr->get_try_string();
encoding = pAMgr->get_encoding();
langnum = pAMgr->get_langnum();
utf8 = pAMgr->get_utf8();
if (!utf8)
csconv = get_current_cs(encoding);
complexprefixes = pAMgr->get_complexprefixes();
wordbreak = pAMgr->get_breaktable();
/* and finally set up the suggestion manager */
pSMgr = new SuggestMgr(try_string, MAXSUGGESTION, pAMgr);
if (try_string)
free(try_string);
}
Hunspell::~Hunspell() {
delete pSMgr;
delete pAMgr;
for (int i = 0; i < maxdic; i++)
delete pHMgr[i];
maxdic = 0;
pSMgr = NULL;
pAMgr = NULL;
#ifdef MOZILLA_CLIENT
delete[] csconv;
#endif
csconv = NULL;
if (encoding)
free(encoding);
encoding = NULL;
if (affixpath)
free(affixpath);
affixpath = NULL;
}
// load extra dictionaries
int Hunspell::add_dic(const char* dpath, const char* key) {
if (maxdic == MAXDIC || !affixpath)
return 1;
pHMgr[maxdic] = new HashMgr(dpath, affixpath, key);
if (pHMgr[maxdic])
maxdic++;
else
return 1;
return 0;
}
// make a copy of src at destination while removing all leading
// blanks and removing any trailing periods after recording
// their presence with the abbreviation flag
// also since already going through character by character,
// set the capitalization type
// return the length of the "cleaned" (and UTF-8 encoded) word
int Hunspell::cleanword2(char* dest,
const char* src,
w_char* dest_utf,
int* nc,
int* pcaptype,
int* pabbrev) {
unsigned char* p = (unsigned char*)dest;
const unsigned char* q = (const unsigned char*)src;
// first skip over any leading blanks
while ((*q != '\0') && (*q == ' '))
q++;
// now strip off any trailing periods (recording their presence)
*pabbrev = 0;
int nl = strlen((const char*)q);
while ((nl > 0) && (*(q + nl - 1) == '.')) {
nl--;
(*pabbrev)++;
}
// if no characters are left it can't be capitalized
if (nl <= 0) {
*pcaptype = NOCAP;
*p = '\0';
return 0;
}
strncpy(dest, (char*)q, nl);
*(dest + nl) = '\0';
nl = strlen(dest);
if (utf8) {
*nc = u8_u16(dest_utf, MAXWORDLEN, dest);
// don't check too long words
if (*nc >= MAXWORDLEN)
return 0;
if (*nc == -1) { // big Unicode character (non BMP area)
*pcaptype = NOCAP;
return nl;
}
*pcaptype = get_captype_utf8(dest_utf, *nc, langnum);
} else {
*pcaptype = get_captype(dest, nl, csconv);
*nc = nl;
}
return nl;
}
int Hunspell::cleanword(char* dest,
const char* src,
int* pcaptype,
int* pabbrev) {
unsigned char* p = (unsigned char*)dest;
const unsigned char* q = (const unsigned char*)src;
int firstcap = 0;
// first skip over any leading blanks
while ((*q != '\0') && (*q == ' '))
q++;
// now strip off any trailing periods (recording their presence)
*pabbrev = 0;
int nl = strlen((const char*)q);
while ((nl > 0) && (*(q + nl - 1) == '.')) {
nl--;
(*pabbrev)++;
}
// if no characters are left it can't be capitalized
if (nl <= 0) {
*pcaptype = NOCAP;
*p = '\0';
return 0;
}
// now determine the capitalization type of the first nl letters
int ncap = 0;
int nneutral = 0;
int nc = 0;
if (!utf8) {
while (nl > 0) {
nc++;
if (csconv[(*q)].ccase)
ncap++;
if (csconv[(*q)].cupper == csconv[(*q)].clower)
nneutral++;
*p++ = *q++;
nl--;
}
// remember to terminate the destination string
*p = '\0';
firstcap = csconv[(unsigned char)(*dest)].ccase;
} else {
unsigned short idx;
w_char t[MAXWORDLEN];
nc = u8_u16(t, MAXWORDLEN, src);
for (int i = 0; i < nc; i++) {
idx = (t[i].h << 8) + t[i].l;
unsigned short low = unicodetolower(idx, langnum);
if (idx != low)
ncap++;
if (unicodetoupper(idx, langnum) == low)
nneutral++;
}
u16_u8(dest, MAXWORDUTF8LEN, t, nc);
if (ncap) {
idx = (t[0].h << 8) + t[0].l;
firstcap = (idx != unicodetolower(idx, langnum));
}
}
// now finally set the captype
if (ncap == 0) {
*pcaptype = NOCAP;
} else if ((ncap == 1) && firstcap) {
*pcaptype = INITCAP;
} else if ((ncap == nc) || ((ncap + nneutral) == nc)) {
*pcaptype = ALLCAP;
} else if ((ncap > 1) && firstcap) {
*pcaptype = HUHINITCAP;
} else {
*pcaptype = HUHCAP;
}
return strlen(dest);
}
void Hunspell::mkallcap(char* p) {
if (utf8) {
w_char u[MAXWORDLEN];
int nc = u8_u16(u, MAXWORDLEN, p);
unsigned short idx;
for (int i = 0; i < nc; i++) {
idx = (u[i].h << 8) + u[i].l;
if (idx != unicodetoupper(idx, langnum)) {
u[i].h = (unsigned char)(unicodetoupper(idx, langnum) >> 8);
u[i].l = (unsigned char)(unicodetoupper(idx, langnum) & 0x00FF);
}
}
u16_u8(p, MAXWORDUTF8LEN, u, nc);
} else {
while (*p != '\0') {
*p = csconv[((unsigned char)*p)].cupper;
p++;
}
}
}
int Hunspell::mkallcap2(char* p, w_char* u, int nc) {
if (utf8) {
unsigned short idx;
for (int i = 0; i < nc; i++) {
idx = (u[i].h << 8) + u[i].l;
unsigned short up = unicodetoupper(idx, langnum);
if (idx != up) {
u[i].h = (unsigned char)(up >> 8);
u[i].l = (unsigned char)(up & 0x00FF);
}
}
u16_u8(p, MAXWORDUTF8LEN, u, nc);
return strlen(p);
} else {
while (*p != '\0') {
*p = csconv[((unsigned char)*p)].cupper;
p++;
}
}
return nc;
}
void Hunspell::mkallsmall(char* p) {
while (*p != '\0') {
*p = csconv[((unsigned char)*p)].clower;
p++;
}
}
int Hunspell::mkallsmall2(char* p, w_char* u, int nc) {
if (utf8) {
unsigned short idx;
for (int i = 0; i < nc; i++) {
idx = (u[i].h << 8) + u[i].l;
unsigned short low = unicodetolower(idx, langnum);
if (idx != low) {
u[i].h = (unsigned char)(low >> 8);
u[i].l = (unsigned char)(low & 0x00FF);
}
}
u16_u8(p, MAXWORDUTF8LEN, u, nc);
return strlen(p);
} else {
while (*p != '\0') {
*p = csconv[((unsigned char)*p)].clower;
p++;
}
}
return nc;
}
// convert UTF-8 sharp S codes to latin 1
char* Hunspell::sharps_u8_l1(char* dest, char* source) {
char* p = dest;
*p = *source;
for (p++, source++; *(source - 1); p++, source++) {
*p = *source;
if (*source == '\x9F')
*--p = '\xDF';
}
return dest;
}
// recursive search for right ss - sharp s permutations
hentry* Hunspell::spellsharps(char* base,
char* pos,
int n,
int repnum,
char* tmp,
int* info,
char** root) {
pos = strstr(pos, "ss");
if (pos && (n < MAXSHARPS)) {
*pos = '\xC3';
*(pos + 1) = '\x9F';
hentry* h = spellsharps(base, pos + 2, n + 1, repnum + 1, tmp, info, root);
if (h)
return h;
*pos = 's';
*(pos + 1) = 's';
h = spellsharps(base, pos + 2, n + 1, repnum, tmp, info, root);
if (h)
return h;
} else if (repnum > 0) {
if (utf8)
return checkword(base, info, root);
return checkword(sharps_u8_l1(tmp, base), info, root);
}
return NULL;
}
int Hunspell::is_keepcase(const hentry* rv) {
return pAMgr && rv->astr && pAMgr->get_keepcase() &&
TESTAFF(rv->astr, pAMgr->get_keepcase(), rv->alen);
}
/* insert a word to the beginning of the suggestion array and return ns */
int Hunspell::insert_sug(char*** slst, char* word, int ns) {
if (!*slst)
return ns;
char* dup = mystrdup(word);
if (!dup)
return ns;
if (ns == MAXSUGGESTION) {
ns--;
free((*slst)[ns]);
}
for (int k = ns; k > 0; k--)
(*slst)[k] = (*slst)[k - 1];
(*slst)[0] = dup;
return ns + 1;
}
int Hunspell::spell(const char* word, int* info, char** root) {
struct hentry* rv = NULL;
// need larger vector. For example, Turkish capital letter I converted a
// 2-byte UTF-8 character (dotless i) by mkallsmall.
char cw[MAXWORDUTF8LEN];
char wspace[MAXWORDUTF8LEN];
w_char unicw[MAXWORDLEN];
int info2 = 0;
if (!info)
info = &info2;
else
*info = 0;
// Hunspell supports XML input of the simplified API (see manual)
if (strcmp(word, SPELL_XML) == 0)
return 1;
int nc = strlen(word);
int wl2 = 0;
if (utf8) {
if (nc >= MAXWORDUTF8LEN)
return 0;
} else {
if (nc >= MAXWORDLEN)
return 0;
}
int captype = 0;
int abbv = 0;
int wl = 0;
// input conversion
RepList* rl = (pAMgr) ? pAMgr->get_iconvtable() : NULL;
int convstatus = rl ? rl->conv(word, wspace, MAXWORDUTF8LEN) : 0;
if (convstatus < 0)
return 0;
else if (convstatus > 0)
wl = cleanword2(cw, wspace, unicw, &nc, &captype, &abbv);
else
wl = cleanword2(cw, word, unicw, &nc, &captype, &abbv);
#ifdef MOZILLA_CLIENT
// accept the abbreviated words without dots
// workaround for the incomplete tokenization of Mozilla
abbv = 1;
#endif
if (wl == 0 || maxdic == 0)
return 1;
if (root)
*root = NULL;
// allow numbers with dots, dashes and commas (but forbid double separators:
// "..", "--" etc.)
enum { NBEGIN, NNUM, NSEP };
int nstate = NBEGIN;
int i;
for (i = 0; (i < wl); i++) {
if ((cw[i] <= '9') && (cw[i] >= '0')) {
nstate = NNUM;
} else if ((cw[i] == ',') || (cw[i] == '.') || (cw[i] == '-')) {
if ((nstate == NSEP) || (i == 0))
break;
nstate = NSEP;
} else
break;
}
if ((i == wl) && (nstate == NNUM))
return 1;
switch (captype) {
case HUHCAP:
/* FALLTHROUGH */
case HUHINITCAP:
*info += SPELL_ORIGCAP;
/* FALLTHROUGH */
case NOCAP:
rv = checkword(cw, info, root);
if ((abbv) && !(rv)) {
memcpy(wspace, cw, wl);
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
rv = checkword(wspace, info, root);
}
break;
case ALLCAP: {
*info += SPELL_ORIGCAP;
rv = checkword(cw, info, root);
if (rv)
break;
if (abbv) {
memcpy(wspace, cw, wl);
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
rv = checkword(wspace, info, root);
if (rv)
break;
}
// Spec. prefix handling for Catalan, French, Italian:
// prefixes separated by apostrophe (SANT'ELIA -> Sant'+Elia).
if (pAMgr && strchr(cw, '\'')) {
mkallsmall2(cw, unicw, nc);
// There are no really sane circumstances where this could fail,
// but anyway...
if (char* apostrophe = strchr(cw, '\'')) {
if (utf8) {
w_char tmpword[MAXWORDLEN];
*apostrophe = '\0';
wl2 = u8_u16(tmpword, MAXWORDLEN, cw);
*apostrophe = '\'';
if (wl2 >= 0 && wl2 < nc) {
mkinitcap2(apostrophe + 1, unicw + wl2 + 1, nc - wl2 - 1);
rv = checkword(cw, info, root);
if (rv)
break;
}
} else {
mkinitcap2(apostrophe + 1, unicw, nc);
rv = checkword(cw, info, root);
if (rv)
break;
}
}
mkinitcap2(cw, unicw, nc);
rv = checkword(cw, info, root);
if (rv)
break;
}
if (pAMgr && pAMgr->get_checksharps() && strstr(cw, "SS")) {
char tmpword[MAXWORDUTF8LEN];
wl = mkallsmall2(cw, unicw, nc);
memcpy(wspace, cw, (wl + 1));
rv = spellsharps(wspace, wspace, 0, 0, tmpword, info, root);
if (!rv) {
wl2 = mkinitcap2(cw, unicw, nc);
rv = spellsharps(cw, cw, 0, 0, tmpword, info, root);
}
if ((abbv) && !(rv)) {
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
rv = spellsharps(wspace, wspace, 0, 0, tmpword, info, root);
if (!rv) {
memcpy(wspace, cw, wl2);
*(wspace + wl2) = '.';
*(wspace + wl2 + 1) = '\0';
rv = spellsharps(wspace, wspace, 0, 0, tmpword, info, root);
}
}
if (rv)
break;
}
}
case INITCAP: {
*info += SPELL_ORIGCAP;
wl = mkallsmall2(cw, unicw, nc);
memcpy(wspace, cw, (wl + 1));
wl2 = mkinitcap2(cw, unicw, nc);
if (captype == INITCAP)
*info += SPELL_INITCAP;
rv = checkword(cw, info, root);
if (captype == INITCAP)
*info -= SPELL_INITCAP;
// forbid bad capitalization
// (for example, ijs -> Ijs instead of IJs in Dutch)
// use explicit forms in dic: Ijs/F (F = FORBIDDENWORD flag)
if (*info & SPELL_FORBIDDEN) {
rv = NULL;
break;
}
if (rv && is_keepcase(rv) && (captype == ALLCAP))
rv = NULL;
if (rv)
break;
rv = checkword(wspace, info, root);
if (abbv && !rv) {
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
rv = checkword(wspace, info, root);
if (!rv) {
memcpy(wspace, cw, wl2);
*(wspace + wl2) = '.';
*(wspace + wl2 + 1) = '\0';
if (captype == INITCAP)
*info += SPELL_INITCAP;
rv = checkword(wspace, info, root);
if (captype == INITCAP)
*info -= SPELL_INITCAP;
if (rv && is_keepcase(rv) && (captype == ALLCAP))
rv = NULL;
break;
}
}
if (rv && is_keepcase(rv) &&
((captype == ALLCAP) ||
// if CHECKSHARPS: KEEPCASE words with \xDF are allowed
// in INITCAP form, too.
!(pAMgr->get_checksharps() &&
((utf8 && strstr(wspace, "\xC3\x9F")) ||
(!utf8 && strchr(wspace, '\xDF'))))))
rv = NULL;
break;
}
}
if (rv) {
if (pAMgr && pAMgr->get_warn() && rv->astr &&
TESTAFF(rv->astr, pAMgr->get_warn(), rv->alen)) {
*info += SPELL_WARN;
if (pAMgr->get_forbidwarn())
return 0;
return HUNSPELL_OK_WARN;
}
return HUNSPELL_OK;
}
// recursive breaking at break points
if (wordbreak) {
char* s;
char r;
int nbr = 0;
wl = strlen(cw);
int numbreak = pAMgr ? pAMgr->get_numbreak() : 0;
// calculate break points for recursion limit
for (int j = 0; j < numbreak; j++) {
s = cw;
do {
s = (char*)strstr(s, wordbreak[j]);
if (s) {
nbr++;
s++;
}
} while (s);
}
if (nbr >= 10)
return 0;
// check boundary patterns (^begin and end$)
for (int j = 0; j < numbreak; j++) {
int plen = strlen(wordbreak[j]);
if (plen == 1 || plen > wl)
continue;
if (wordbreak[j][0] == '^' &&
strncmp(cw, wordbreak[j] + 1, plen - 1) == 0 && spell(cw + plen - 1))
return 1;
if (wordbreak[j][plen - 1] == '$' &&
strncmp(cw + wl - plen + 1, wordbreak[j], plen - 1) == 0) {
r = cw[wl - plen + 1];
cw[wl - plen + 1] = '\0';
if (spell(cw))
return 1;
cw[wl - plen + 1] = r;
}
}
// other patterns
for (int j = 0; j < numbreak; j++) {
int plen = strlen(wordbreak[j]);
s = (char*)strstr(cw, wordbreak[j]);
if (s && (s > cw) && (s < cw + wl - plen)) {
if (!spell(s + plen))
continue;
r = *s;
*s = '\0';
// examine 2 sides of the break point
if (spell(cw))
return 1;
*s = r;
// LANG_hu: spec. dash rule
if (langnum == LANG_hu && strcmp(wordbreak[j], "-") == 0) {
r = s[1];
s[1] = '\0';
if (spell(cw))
return 1; // check the first part with dash
s[1] = r;
}
// end of LANG speficic region
}
}
}
return 0;
}
struct hentry* Hunspell::checkword(const char* w, int* info, char** root) {
struct hentry* he = NULL;
bool usebuffer = false;
int len, i;
std::string w2;
const char* word;
char* ignoredchars = pAMgr ? pAMgr->get_ignore() : NULL;
if (ignoredchars != NULL) {
w2.assign(w);
if (utf8) {
int ignoredchars_utf16_len;
unsigned short* ignoredchars_utf16 =
pAMgr->get_ignore_utf16(&ignoredchars_utf16_len);
remove_ignored_chars_utf(w2, ignoredchars_utf16, ignoredchars_utf16_len);
} else {
remove_ignored_chars(w2, ignoredchars);
}
word = w2.c_str();
usebuffer = true;
} else
word = w;
len = strlen(word);
if (!len)
return NULL;
// word reversing wrapper for complex prefixes
if (complexprefixes) {
if (!usebuffer) {
w2.assign(word);
usebuffer = true;
}
if (utf8)
reverseword_utf(w2);
else
reverseword(w2);
}
if (usebuffer) {
word = w2.c_str();
}
// look word in hash table
for (i = 0; (i < maxdic) && !he; i++) {
he = (pHMgr[i])->lookup(word);
// check forbidden and onlyincompound words
if ((he) && (he->astr) && (pAMgr) &&
TESTAFF(he->astr, pAMgr->get_forbiddenword(), he->alen)) {
if (info)
*info += SPELL_FORBIDDEN;
// LANG_hu section: set dash information for suggestions
if (langnum == LANG_hu) {
if (pAMgr->get_compoundflag() &&
TESTAFF(he->astr, pAMgr->get_compoundflag(), he->alen)) {
if (info)
*info += SPELL_COMPOUND;
}
}
return NULL;
}
// he = next not needaffix, onlyincompound homonym or onlyupcase word
while (he && (he->astr) && pAMgr &&
((pAMgr->get_needaffix() &&
TESTAFF(he->astr, pAMgr->get_needaffix(), he->alen)) ||
(pAMgr->get_onlyincompound() &&
TESTAFF(he->astr, pAMgr->get_onlyincompound(), he->alen)) ||
(info && (*info & SPELL_INITCAP) &&
TESTAFF(he->astr, ONLYUPCASEFLAG, he->alen))))
he = he->next_homonym;
}
// check with affixes
if (!he && pAMgr) {
// try stripping off affixes */
he = pAMgr->affix_check(word, len, 0);
// check compound restriction and onlyupcase
if (he && he->astr &&
((pAMgr->get_onlyincompound() &&
TESTAFF(he->astr, pAMgr->get_onlyincompound(), he->alen)) ||
(info && (*info & SPELL_INITCAP) &&
TESTAFF(he->astr, ONLYUPCASEFLAG, he->alen)))) {
he = NULL;
}
if (he) {
if ((he->astr) && (pAMgr) &&
TESTAFF(he->astr, pAMgr->get_forbiddenword(), he->alen)) {
if (info)
*info += SPELL_FORBIDDEN;
return NULL;
}
if (root) {
*root = mystrdup(he->word);
if (*root && complexprefixes) {
if (utf8)
reverseword_utf(*root);
else
reverseword(*root);
}
}
// try check compound word
} else if (pAMgr->get_compound()) {
he = pAMgr->compound_check(word, len, 0, 0, 100, 0, NULL, 0, 0, info);
// LANG_hu section: `moving rule' with last dash
if ((!he) && (langnum == LANG_hu) && (word[len - 1] == '-')) {
char* dup = mystrdup(word);
if (!dup)
return NULL;
dup[len - 1] = '\0';
he = pAMgr->compound_check(dup, len - 1, -5, 0, 100, 0, NULL, 1, 0,
info);
free(dup);
}
// end of LANG speficic region
if (he) {
if (root) {
*root = mystrdup(he->word);
if (*root && complexprefixes) {
if (utf8)
reverseword_utf(*root);
else
reverseword(*root);
}
}
if (info)
*info += SPELL_COMPOUND;
}
}
}
return he;
}
int Hunspell::suggest(char*** slst, const char* word) {
int onlycmpdsug = 0;
char cw[MAXWORDUTF8LEN];
if (!pSMgr || maxdic == 0)
return 0;
w_char unicw[MAXWORDLEN];
*slst = NULL;
// process XML input of the simplified API (see manual)
if (strncmp(word, SPELL_XML, sizeof(SPELL_XML) - 3) == 0) {
return spellml(slst, word);
}
int nc = strlen(word);
if (utf8) {
if (nc >= MAXWORDUTF8LEN)
return 0;
} else {
if (nc >= MAXWORDLEN)
return 0;
}
int captype = 0;
int abbv = 0;
int wl = 0;
// input conversion
RepList* rl = (pAMgr) ? pAMgr->get_iconvtable() : NULL;
{
char wspace[MAXWORDUTF8LEN];
int convstatus = rl ? rl->conv(word, wspace, MAXWORDUTF8LEN) : 0;
if (convstatus < 0)
return 0;
else if (convstatus > 0)
wl = cleanword2(cw, wspace, unicw, &nc, &captype, &abbv);
else
wl = cleanword2(cw, word, unicw, &nc, &captype, &abbv);
if (wl == 0)
return 0;
}
int ns = 0;
int capwords = 0;
// check capitalized form for FORCEUCASE
if (pAMgr && captype == NOCAP && pAMgr->get_forceucase()) {
int info = SPELL_ORIGCAP;
char** wlst;
if (checkword(cw, &info, NULL)) {
if (*slst) {
wlst = *slst;
} else {
wlst = (char**)malloc(MAXSUGGESTION * sizeof(char*));
if (wlst == NULL)
return -1;
*slst = wlst;
for (int i = 0; i < MAXSUGGESTION; i++) {
wlst[i] = NULL;
}
}
wlst[0] = mystrdup(cw);
mkinitcap(wlst[0]);
return 1;
}
}
switch (captype) {
case NOCAP: {
ns = pSMgr->suggest(slst, cw, ns, &onlycmpdsug);
break;
}
case INITCAP: {
capwords = 1;
ns = pSMgr->suggest(slst, cw, ns, &onlycmpdsug);
if (ns == -1)
break;
char wspace[MAXWORDUTF8LEN];
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
ns = pSMgr->suggest(slst, wspace, ns, &onlycmpdsug);
break;
}
case HUHINITCAP:
capwords = 1;
case HUHCAP: {
ns = pSMgr->suggest(slst, cw, ns, &onlycmpdsug);
if (ns != -1) {
int prevns;
// something.The -> something. The
char* dot = strchr(cw, '.');
if (dot && (dot > cw)) {
int captype_;
if (utf8) {
w_char w_[MAXWORDLEN];
int wl_ = u8_u16(w_, MAXWORDLEN, dot + 1);
captype_ = get_captype_utf8(w_, wl_, langnum);
} else
captype_ = get_captype(dot + 1, strlen(dot + 1), csconv);
if (captype_ == INITCAP) {
char* st = mystrdup(cw);
if (st) {
char* newst = (char*)realloc(st, wl + 2);
if (newst == NULL)
free(st);
st = newst;
}
if (st) {
st[(dot - cw) + 1] = ' ';
strcpy(st + (dot - cw) + 2, dot + 1);
ns = insert_sug(slst, st, ns);
free(st);
}
}
}
if (captype == HUHINITCAP) {
// TheOpenOffice.org -> The OpenOffice.org
char wspace[MAXWORDUTF8LEN];
memcpy(wspace, cw, (wl + 1));
mkinitsmall2(wspace, unicw, nc);
ns = pSMgr->suggest(slst, wspace, ns, &onlycmpdsug);
}
char wspace[MAXWORDUTF8LEN];
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
if (spell(wspace))
ns = insert_sug(slst, wspace, ns);
prevns = ns;
ns = pSMgr->suggest(slst, wspace, ns, &onlycmpdsug);
if (captype == HUHINITCAP) {
mkinitcap2(wspace, unicw, nc);
if (spell(wspace))
ns = insert_sug(slst, wspace, ns);
ns = pSMgr->suggest(slst, wspace, ns, &onlycmpdsug);
}
// aNew -> "a New" (instead of "a new")
for (int j = prevns; j < ns; j++) {
char* space = strchr((*slst)[j], ' ');
if (space) {
int slen = strlen(space + 1);
// different case after space (need capitalisation)
if ((slen < wl) && strcmp(cw + wl - slen, space + 1)) {
w_char w[MAXWORDLEN];
int wc = 0;
char* r = (*slst)[j];
if (utf8)
wc = u8_u16(w, MAXWORDLEN, space + 1);
mkinitcap2(space + 1, w, wc);
// set as first suggestion
for (int k = j; k > 0; k--)
(*slst)[k] = (*slst)[k - 1];
(*slst)[0] = r;
}
}
}
}
break;
}
case ALLCAP: {
char wspace[MAXWORDUTF8LEN];
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
ns = pSMgr->suggest(slst, wspace, ns, &onlycmpdsug);
if (ns == -1)
break;
if (pAMgr && pAMgr->get_keepcase() && spell(wspace))
ns = insert_sug(slst, wspace, ns);
mkinitcap2(wspace, unicw, nc);
ns = pSMgr->suggest(slst, wspace, ns, &onlycmpdsug);
for (int j = 0; j < ns; j++) {
mkallcap((*slst)[j]);
if (pAMgr && pAMgr->get_checksharps()) {
char* pos;
if (utf8) {
pos = strstr((*slst)[j], "\xC3\x9F");
while (pos) {
*pos = 'S';
*(pos + 1) = 'S';
pos = strstr(pos + 2, "\xC3\x9F");
}
} else {
pos = strchr((*slst)[j], '\xDF');
while (pos) {
(*slst)[j] = (char*)realloc((*slst)[j], strlen((*slst)[j]) + 2);
mystrrep((*slst)[j], "\xDF", "SS");
pos = strchr((*slst)[j], '\xDF');
}
}
}
}
break;
}
}
// LANG_hu section: replace '-' with ' ' in Hungarian
if (langnum == LANG_hu) {
for (int j = 0; j < ns; j++) {
char* pos = strchr((*slst)[j], '-');
if (pos) {
int info;
char w[MAXWORDUTF8LEN];
*pos = '\0';
strcpy(w, (*slst)[j]);
strcat(w, pos + 1);
(void)spell(w, &info, NULL);
if ((info & SPELL_COMPOUND) && (info & SPELL_FORBIDDEN)) {
*pos = ' ';
} else
*pos = '-';
}
}
}
// END OF LANG_hu section
// try ngram approach since found nothing or only compound words
if (pAMgr && (ns == 0 || onlycmpdsug) && (pAMgr->get_maxngramsugs() != 0) &&
(*slst)) {
switch (captype) {
case NOCAP: {
ns = pSMgr->ngsuggest(*slst, cw, ns, pHMgr, maxdic);
break;
}
case HUHINITCAP:
capwords = 1;
case HUHCAP: {
char wspace[MAXWORDUTF8LEN];
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
ns = pSMgr->ngsuggest(*slst, wspace, ns, pHMgr, maxdic);
break;
}
case INITCAP: {
capwords = 1;
char wspace[MAXWORDUTF8LEN];
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
ns = pSMgr->ngsuggest(*slst, wspace, ns, pHMgr, maxdic);
break;
}
case ALLCAP: {
char wspace[MAXWORDUTF8LEN];
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
int oldns = ns;
ns = pSMgr->ngsuggest(*slst, wspace, ns, pHMgr, maxdic);
for (int j = oldns; j < ns; j++)
mkallcap((*slst)[j]);
break;
}
}
}
// try dash suggestion (Afo-American -> Afro-American)
if (char* pos = strchr(cw, '-')) {
char* ppos = cw;
int nodashsug = 1;
char** nlst = NULL;
int nn = 0;
int last = 0;
if (*slst) {
for (int j = 0; j < ns && nodashsug == 1; j++) {
if (strchr((*slst)[j], '-'))
nodashsug = 0;
}
}
while (nodashsug && !last) {
if (*pos == '\0')
last = 1;
else
*pos = '\0';
if (!spell(ppos)) {
nn = suggest(&nlst, ppos);
for (int j = nn - 1; j >= 0; j--) {
char wspace[MAXWORDUTF8LEN];
strncpy(wspace, cw, ppos - cw);
strcpy(wspace + (ppos - cw), nlst[j]);
if (!last) {
strcat(wspace, "-");
strcat(wspace, pos + 1);
}
ns = insert_sug(slst, wspace, ns);
free(nlst[j]);
}
if (nlst != NULL)
free(nlst);
nodashsug = 0;
}
if (!last) {
*pos = '-';
ppos = pos + 1;
pos = strchr(ppos, '-');
}
if (!pos)
pos = cw + strlen(cw);
}
}
// word reversing wrapper for complex prefixes
if (complexprefixes) {
for (int j = 0; j < ns; j++) {
if (utf8)
reverseword_utf((*slst)[j]);
else
reverseword((*slst)[j]);
}
}
// capitalize
if (capwords)
for (int j = 0; j < ns; j++) {
mkinitcap((*slst)[j]);
}
// expand suggestions with dot(s)
if (abbv && pAMgr && pAMgr->get_sugswithdots()) {
for (int j = 0; j < ns; j++) {
(*slst)[j] = (char*)realloc((*slst)[j], strlen((*slst)[j]) + 1 + abbv);
strcat((*slst)[j], word + strlen(word) - abbv);
}
}
// remove bad capitalized and forbidden forms
if (pAMgr && (pAMgr->get_keepcase() || pAMgr->get_forbiddenword())) {
switch (captype) {
case INITCAP:
case ALLCAP: {
int l = 0;
for (int j = 0; j < ns; j++) {
if (!strchr((*slst)[j], ' ') && !spell((*slst)[j])) {
char s[MAXSWUTF8L];
w_char w[MAXSWL];
int len;
if (utf8) {
len = u8_u16(w, MAXSWL, (*slst)[j]);
} else {
strcpy(s, (*slst)[j]);
len = strlen(s);
}
mkallsmall2(s, w, len);
free((*slst)[j]);
if (spell(s)) {
(*slst)[l] = mystrdup(s);
if ((*slst)[l])
l++;
} else {
mkinitcap2(s, w, len);
if (spell(s)) {
(*slst)[l] = mystrdup(s);
if ((*slst)[l])
l++;
}
}
} else {
(*slst)[l] = (*slst)[j];
l++;
}
}
ns = l;
}
}
}
// remove duplications
int l = 0;
for (int j = 0; j < ns; j++) {
(*slst)[l] = (*slst)[j];
for (int k = 0; k < l; k++) {
if (strcmp((*slst)[k], (*slst)[j]) == 0) {
free((*slst)[j]);
l--;
break;
}
}
l++;
}
ns = l;
// output conversion
rl = (pAMgr) ? pAMgr->get_oconvtable() : NULL;
for (int j = 0; rl && j < ns; j++) {
char wspace[MAXWORDUTF8LEN];
if (rl->conv((*slst)[j], wspace, MAXWORDUTF8LEN) > 0) {
free((*slst)[j]);
(*slst)[j] = mystrdup(wspace);
}
}
// if suggestions removed by nosuggest, onlyincompound parameters
if (l == 0 && *slst) {
free(*slst);
*slst = NULL;
}
return l;
}
void Hunspell::free_list(char*** slst, int n) {
freelist(slst, n);
}
char* Hunspell::get_dic_encoding() {
return encoding;
}
#ifdef HUNSPELL_EXPERIMENTAL
// XXX UTF-8 support is OK?
int Hunspell::suggest_auto(char*** slst, const char* word) {
char cw[MAXWORDUTF8LEN];
char wspace[MAXWORDUTF8LEN];
if (!pSMgr || maxdic == 0)
return 0;
w_char unicw[MAXWORDLEN];
int nc = strlen(word);
if (utf8) {
if (nc >= MAXWORDUTF8LEN)
return 0;
} else {
if (nc >= MAXWORDLEN)
return 0;
}
int captype = 0;
int abbv = 0;
int wl = 0;
// input conversion
RepList* rl = (pAMgr) ? pAMgr->get_iconvtable() : NULL;
int convstatus = rl ? rl->conv(word, wspace) : 0;
if (convstatus < 0)
return 0;
else if (convstatus > 0)
wl = cleanword2(cw, wspace, unicw, &nc, &captype, &abbv);
else
wl = cleanword2(cw, word, unicw, &nc, &captype, &abbv);
if (wl == 0)
return 0;
int ns = 0;
*slst = NULL; // HU, nsug in pSMgr->suggest
switch (captype) {
case NOCAP: {
ns = pSMgr->suggest_auto(slst, cw, ns);
if (ns > 0)
break;
break;
}
case INITCAP: {
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
ns = pSMgr->suggest_auto(slst, wspace, ns);
for (int j = 0; j < ns; j++)
mkinitcap((*slst)[j]);
ns = pSMgr->suggest_auto(slst, cw, ns);
break;
}
case HUHINITCAP:
case HUHCAP: {
ns = pSMgr->suggest_auto(slst, cw, ns);
if (ns == 0) {
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
ns = pSMgr->suggest_auto(slst, wspace, ns);
}
break;
}
case ALLCAP: {
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
ns = pSMgr->suggest_auto(slst, wspace, ns);
mkinitcap(wspace);
ns = pSMgr->suggest_auto(slst, wspace, ns);
for (int j = 0; j < ns; j++)
mkallcap((*slst)[j]);
break;
}
}
// word reversing wrapper for complex prefixes
if (complexprefixes) {
for (int j = 0; j < ns; j++) {
if (utf8)
reverseword_utf((*slst)[j]);
else
reverseword((*slst)[j]);
}
}
// expand suggestions with dot(s)
if (abbv && pAMgr && pAMgr->get_sugswithdots()) {
for (int j = 0; j < ns; j++) {
(*slst)[j] = (char*)realloc((*slst)[j], strlen((*slst)[j]) + 1 + abbv);
strcat((*slst)[j], word + strlen(word) - abbv);
}
}
// LANG_hu section: replace '-' with ' ' in Hungarian
if (langnum == LANG_hu) {
for (int j = 0; j < ns; j++) {
char* pos = strchr((*slst)[j], '-');
if (pos) {
int info;
char w[MAXWORDUTF8LEN];
*pos = '\0';
strcpy(w, (*slst)[j]);
strcat(w, pos + 1);
spell(w, &info, NULL);
if ((info & SPELL_COMPOUND) && (info & SPELL_FORBIDDEN)) {
*pos = ' ';
} else
*pos = '-';
}
}
}
// output conversion
rl = (pAMgr) ? pAMgr->get_oconvtable() : NULL;
for (int j = 0; rl && j < ns; j++) {
if (rl->conv((*slst)[j], wspace) > 0) {
free((*slst)[j]);
(*slst)[j] = mystrdup(wspace);
}
}
// END OF LANG_hu section
return ns;
}
#endif
int Hunspell::stem(char*** slst, char** desc, int n) {
char result[MAXLNLEN];
char result2[MAXLNLEN];
*slst = NULL;
if (n == 0)
return 0;
*result2 = '\0';
for (int i = 0; i < n; i++) {
*result = '\0';
// add compound word parts (except the last one)
char* s = (char*)desc[i];
char* part = strstr(s, MORPH_PART);
if (part) {
char* nextpart = strstr(part + 1, MORPH_PART);
while (nextpart) {
copy_field(result + strlen(result), part, MORPH_PART);
part = nextpart;
nextpart = strstr(part + 1, MORPH_PART);
}
s = part;
}
char** pl;
std::string tok(s);
size_t alt = 0;
while ((alt = tok.find(" | ", alt)) != std::string::npos) {
tok[alt + 1] = MSEP_ALT;
}
int pln = line_tok(tok.c_str(), &pl, MSEP_ALT);
for (int k = 0; k < pln; k++) {
// add derivational suffixes
if (strstr(pl[k], MORPH_DERI_SFX)) {
// remove inflectional suffixes
char* is = strstr(pl[k], MORPH_INFL_SFX);
if (is)
*is = '\0';
char* sg = pSMgr->suggest_gen(&(pl[k]), 1, pl[k]);
if (sg) {
char** gen;
int genl = line_tok(sg, &gen, MSEP_REC);
free(sg);
for (int j = 0; j < genl; j++) {
sprintf(result2 + strlen(result2), "%c%s%s", MSEP_REC, result,
gen[j]);
}
freelist(&gen, genl);
}
} else {
sprintf(result2 + strlen(result2), "%c%s", MSEP_REC, result);
if (strstr(pl[k], MORPH_SURF_PFX)) {
copy_field(result2 + strlen(result2), pl[k], MORPH_SURF_PFX);
}
copy_field(result2 + strlen(result2), pl[k], MORPH_STEM);
}
}
freelist(&pl, pln);
}
int sln = line_tok(result2, slst, MSEP_REC);
return uniqlist(*slst, sln);
}
int Hunspell::stem(char*** slst, const char* word) {
char** pl;
int pln = analyze(&pl, word);
int pln2 = stem(slst, pl, pln);
freelist(&pl, pln);
return pln2;
}
#ifdef HUNSPELL_EXPERIMENTAL
int Hunspell::suggest_pos_stems(char*** slst, const char* word) {
char cw[MAXWORDUTF8LEN];
char wspace[MAXWORDUTF8LEN];
if (!pSMgr || maxdic == 0)
return 0;
w_char unicw[MAXWORDLEN];
int nc = strlen(word);
if (utf8) {
if (nc >= MAXWORDUTF8LEN)
return 0;
} else {
if (nc >= MAXWORDLEN)
return 0;
}
int captype = 0;
int abbv = 0;
int wl = 0;
// input conversion
RepList* rl = (pAMgr) ? pAMgr->get_iconvtable() : NULL;
int convstatus = rl ? rl->conv(word, wspace) : 0;
if (convstatus < 0)
return 0;
else if (convstatus > 0)
wl = cleanword2(cw, wspace, unicw, &nc, &captype, &abbv);
else
wl = cleanword2(cw, word, unicw, &nc, &captype, &abbv);
if (wl == 0)
return 0;
int ns = 0; // ns=0 = normalized input
*slst = NULL; // HU, nsug in pSMgr->suggest
switch (captype) {
case HUHCAP:
case NOCAP: {
ns = pSMgr->suggest_pos_stems(slst, cw, ns);
if ((abbv) && (ns == 0)) {
memcpy(wspace, cw, wl);
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
ns = pSMgr->suggest_pos_stems(slst, wspace, ns);
}
break;
}
case INITCAP: {
ns = pSMgr->suggest_pos_stems(slst, cw, ns);
if (ns == 0 || ((*slst)[0][0] == '#')) {
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
ns = pSMgr->suggest_pos_stems(slst, wspace, ns);
}
break;
}
case ALLCAP: {
ns = pSMgr->suggest_pos_stems(slst, cw, ns);
if (ns != 0)
break;
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
ns = pSMgr->suggest_pos_stems(slst, wspace, ns);
if (ns == 0) {
mkinitcap(wspace);
ns = pSMgr->suggest_pos_stems(slst, wspace, ns);
}
break;
}
}
// output conversion
rl = (pAMgr) ? pAMgr->get_oconvtable() : NULL;
for (int j = 0; rl && j < ns; j++) {
if (rl->conv((*slst)[j], wspace) > 0) {
free((*slst)[j]);
(*slst)[j] = mystrdup(wspace);
}
}
return ns;
}
#endif // END OF HUNSPELL_EXPERIMENTAL CODE
const char* Hunspell::get_wordchars() {
return pAMgr->get_wordchars();
}
unsigned short* Hunspell::get_wordchars_utf16(int* len) {
return pAMgr->get_wordchars_utf16(len);
}
void Hunspell::mkinitcap(char* p) {
if (!utf8) {
if (*p != '\0')
*p = csconv[((unsigned char)*p)].cupper;
} else {
int len;
w_char u[MAXWORDLEN];
len = u8_u16(u, MAXWORDLEN, p);
unsigned short i = unicodetoupper((u[0].h << 8) + u[0].l, langnum);
u[0].h = (unsigned char)(i >> 8);
u[0].l = (unsigned char)(i & 0x00FF);
u16_u8(p, MAXWORDUTF8LEN, u, len);
}
}
int Hunspell::mkinitcap2(char* p, w_char* u, int nc) {
if (!utf8) {
if (*p != '\0')
*p = csconv[((unsigned char)*p)].cupper;
} else if (nc > 0) {
unsigned short i = unicodetoupper((u[0].h << 8) + u[0].l, langnum);
u[0].h = (unsigned char)(i >> 8);
u[0].l = (unsigned char)(i & 0x00FF);
u16_u8(p, MAXWORDUTF8LEN, u, nc);
return strlen(p);
}
return nc;
}
int Hunspell::mkinitsmall2(char* p, w_char* u, int nc) {
if (!utf8) {
if (*p != '\0')
*p = csconv[((unsigned char)*p)].clower;
} else if (nc > 0) {
unsigned short i = unicodetolower((u[0].h << 8) + u[0].l, langnum);
u[0].h = (unsigned char)(i >> 8);
u[0].l = (unsigned char)(i & 0x00FF);
u16_u8(p, MAXWORDUTF8LEN, u, nc);
return strlen(p);
}
return nc;
}
int Hunspell::add(const char* word) {
if (pHMgr[0])
return (pHMgr[0])->add(word);
return 0;
}
int Hunspell::add_with_affix(const char* word, const char* example) {
if (pHMgr[0])
return (pHMgr[0])->add_with_affix(word, example);
return 0;
}
int Hunspell::remove(const char* word) {
if (pHMgr[0])
return (pHMgr[0])->remove(word);
return 0;
}
const char* Hunspell::get_version() {
return pAMgr->get_version();
}
struct cs_info* Hunspell::get_csconv() {
return csconv;
}
void Hunspell::cat_result(char* result, char* st) {
if (st) {
if (*result)
mystrcat(result, "\n", MAXLNLEN);
mystrcat(result, st, MAXLNLEN);
free(st);
}
}
int Hunspell::analyze(char*** slst, const char* word) {
char cw[MAXWORDUTF8LEN];
char wspace[MAXWORDUTF8LEN];
w_char unicw[MAXWORDLEN];
int wl2 = 0;
*slst = NULL;
if (!pSMgr || maxdic == 0)
return 0;
int nc = strlen(word);
if (utf8) {
if (nc >= MAXWORDUTF8LEN)
return 0;
} else {
if (nc >= MAXWORDLEN)
return 0;
}
int captype = 0;
int abbv = 0;
int wl = 0;
// input conversion
RepList* rl = (pAMgr) ? pAMgr->get_iconvtable() : NULL;
int convstatus = rl ? rl->conv(word, wspace, MAXWORDUTF8LEN) : 0;
if (convstatus < 0)
return 0;
else if (convstatus > 0)
wl = cleanword2(cw, wspace, unicw, &nc, &captype, &abbv);
else
wl = cleanword2(cw, word, unicw, &nc, &captype, &abbv);
if (wl == 0) {
if (abbv) {
for (wl = 0; wl < abbv; wl++)
cw[wl] = '.';
cw[wl] = '\0';
abbv = 0;
} else
return 0;
}
char result[MAXLNLEN];
char* st = NULL;
*result = '\0';
int n = 0;
int n2 = 0;
int n3 = 0;
// test numbers
// LANG_hu section: set dash information for suggestions
if (langnum == LANG_hu) {
while ((n < wl) && (((cw[n] <= '9') && (cw[n] >= '0')) ||
(((cw[n] == '.') || (cw[n] == ',')) && (n > 0)))) {
n++;
if ((cw[n] == '.') || (cw[n] == ',')) {
if (((n2 == 0) && (n > 3)) ||
((n2 > 0) && ((cw[n - 1] == '.') || (cw[n - 1] == ','))))
break;
n2++;
n3 = n;
}
}
if ((n == wl) && (n3 > 0) && (n - n3 > 3))
return 0;
if ((n == wl) || ((n > 0) && ((cw[n] == '%') || (cw[n] == '\xB0')) &&
checkword(cw + n, NULL, NULL))) {
mystrcat(result, cw, MAXLNLEN);
result[n - 1] = '\0';
if (n == wl)
cat_result(result, pSMgr->suggest_morph(cw + n - 1));
else {
char sign = cw[n];
cw[n] = '\0';
cat_result(result, pSMgr->suggest_morph(cw + n - 1));
mystrcat(result, "+", MAXLNLEN); // XXX SPEC. MORPHCODE
cw[n] = sign;
cat_result(result, pSMgr->suggest_morph(cw + n));
}
return line_tok(result, slst, MSEP_REC);
}
}
// END OF LANG_hu section
switch (captype) {
case HUHCAP:
case HUHINITCAP:
case NOCAP: {
cat_result(result, pSMgr->suggest_morph(cw));
if (abbv) {
memcpy(wspace, cw, wl);
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
cat_result(result, pSMgr->suggest_morph(wspace));
}
break;
}
case INITCAP: {
wl = mkallsmall2(cw, unicw, nc);
memcpy(wspace, cw, (wl + 1));
wl2 = mkinitcap2(cw, unicw, nc);
cat_result(result, pSMgr->suggest_morph(wspace));
cat_result(result, pSMgr->suggest_morph(cw));
if (abbv) {
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
cat_result(result, pSMgr->suggest_morph(wspace));
memcpy(wspace, cw, wl2);
*(wspace + wl2) = '.';
*(wspace + wl2 + 1) = '\0';
cat_result(result, pSMgr->suggest_morph(wspace));
}
break;
}
case ALLCAP: {
cat_result(result, pSMgr->suggest_morph(cw));
if (abbv) {
memcpy(wspace, cw, wl);
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
cat_result(result, pSMgr->suggest_morph(cw));
}
wl = mkallsmall2(cw, unicw, nc);
memcpy(wspace, cw, (wl + 1));
wl2 = mkinitcap2(cw, unicw, nc);
cat_result(result, pSMgr->suggest_morph(wspace));
cat_result(result, pSMgr->suggest_morph(cw));
if (abbv) {
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
cat_result(result, pSMgr->suggest_morph(wspace));
memcpy(wspace, cw, wl2);
*(wspace + wl2) = '.';
*(wspace + wl2 + 1) = '\0';
cat_result(result, pSMgr->suggest_morph(wspace));
}
break;
}
}
if (*result) {
// word reversing wrapper for complex prefixes
if (complexprefixes) {
if (utf8)
reverseword_utf(result);
else
reverseword(result);
}
return line_tok(result, slst, MSEP_REC);
}
// compound word with dash (HU) I18n
char* dash = NULL;
int nresult = 0;
// LANG_hu section: set dash information for suggestions
if (langnum == LANG_hu)
dash = (char*)strchr(cw, '-');
if ((langnum == LANG_hu) && dash) {
*dash = '\0';
// examine 2 sides of the dash
if (dash[1] == '\0') { // base word ending with dash
if (spell(cw)) {
char* p = pSMgr->suggest_morph(cw);
if (p) {
int ret = line_tok(p, slst, MSEP_REC);
free(p);
return ret;
}
}
} else if ((dash[1] == 'e') && (dash[2] == '\0')) { // XXX (HU) -e hat.
if (spell(cw) && (spell("-e"))) {
st = pSMgr->suggest_morph(cw);
if (st) {
mystrcat(result, st, MAXLNLEN);
free(st);
}
mystrcat(result, "+", MAXLNLEN); // XXX spec. separator in MORPHCODE
st = pSMgr->suggest_morph("-e");
if (st) {
mystrcat(result, st, MAXLNLEN);
free(st);
}
return line_tok(result, slst, MSEP_REC);
}
} else {
// first word ending with dash: word- XXX ???
char r2 = *(dash + 1);
dash[0] = '-';
dash[1] = '\0';
nresult = spell(cw);
dash[1] = r2;
dash[0] = '\0';
if (nresult && spell(dash + 1) &&
((strlen(dash + 1) > 1) || ((dash[1] > '0') && (dash[1] < '9')))) {
st = pSMgr->suggest_morph(cw);
if (st) {
mystrcat(result, st, MAXLNLEN);
free(st);
mystrcat(result, "+", MAXLNLEN); // XXX spec. separator in MORPHCODE
}
st = pSMgr->suggest_morph(dash + 1);
if (st) {
mystrcat(result, st, MAXLNLEN);
free(st);
}
return line_tok(result, slst, MSEP_REC);
}
}
// affixed number in correct word
if (nresult && (dash > cw) &&
(((*(dash - 1) <= '9') && (*(dash - 1) >= '0')) ||
(*(dash - 1) == '.'))) {
*dash = '-';
n = 1;
if (*(dash - n) == '.')
n++;
// search first not a number character to left from dash
while (((dash - n) >= cw) && ((*(dash - n) == '0') || (n < 3)) &&
(n < 6)) {
n++;
}
if ((dash - n) < cw)
n--;
// numbers: valami1000000-hoz
// examine 100000-hoz, 10000-hoz 1000-hoz, 10-hoz,
// 56-hoz, 6-hoz
for (; n >= 1; n--) {
if ((*(dash - n) >= '0') && (*(dash - n) <= '9') &&
checkword(dash - n, NULL, NULL)) {
mystrcat(result, cw, MAXLNLEN);
result[dash - cw - n] = '\0';
st = pSMgr->suggest_morph(dash - n);
if (st) {
mystrcat(result, st, MAXLNLEN);
free(st);
}
return line_tok(result, slst, MSEP_REC);
}
}
}
}
return 0;
}
int Hunspell::generate(char*** slst, const char* word, char** pl, int pln) {
*slst = NULL;
if (!pSMgr || !pln)
return 0;
char** pl2;
int pl2n = analyze(&pl2, word);
int captype = 0;
int abbv = 0;
char cw[MAXWORDUTF8LEN];
cleanword(cw, word, &captype, &abbv);
char result[MAXLNLEN];
*result = '\0';
for (int i = 0; i < pln; i++) {
cat_result(result, pSMgr->suggest_gen(pl2, pl2n, pl[i]));
}
freelist(&pl2, pl2n);
if (*result) {
// allcap
if (captype == ALLCAP)
mkallcap(result);
// line split
int linenum = line_tok(result, slst, MSEP_REC);
// capitalize
if (captype == INITCAP || captype == HUHINITCAP) {
for (int j = 0; j < linenum; j++)
mkinitcap((*slst)[j]);
}
// temporary filtering of prefix related errors (eg.
// generate("undrinkable", "eats") --> "undrinkables" and "*undrinks")
int r = 0;
for (int j = 0; j < linenum; j++) {
if (!spell((*slst)[j])) {
free((*slst)[j]);
(*slst)[j] = NULL;
} else {
if (r < j)
(*slst)[r] = (*slst)[j];
r++;
}
}
if (r > 0)
return r;
free(*slst);
*slst = NULL;
}
return 0;
}
int Hunspell::generate(char*** slst, const char* word, const char* pattern) {
char** pl;
int pln = analyze(&pl, pattern);
int n = generate(slst, word, pl, pln);
freelist(&pl, pln);
return uniqlist(*slst, n);
}
// minimal XML parser functions
int Hunspell::get_xml_par(char* dest, const char* par, int max) {
char* d = dest;
if (!par)
return 0;
char end = *par;
char* dmax = dest + max;
if (end == '>')
end = '<';
else if (end != '\'' && end != '"')
return 0; // bad XML
for (par++; d < dmax && *par != '\0' && *par != end; par++, d++)
*d = *par;
*d = '\0';
mystrrep(dest, "<", "<");
mystrrep(dest, "&", "&");
return (int)(d - dest);
}
int Hunspell::get_langnum() const {
return langnum;
}
int Hunspell::input_conv(const char* word, char* dest, size_t destsize) {
RepList* rl = (pAMgr) ? pAMgr->get_iconvtable() : NULL;
return (rl && rl->conv(word, dest, destsize) > 0);
}
// return the beginning of the element (attr == NULL) or the attribute
const char* Hunspell::get_xml_pos(const char* s, const char* attr) {
const char* end = strchr(s, '>');
const char* p = s;
if (attr == NULL)
return end;
do {
p = strstr(p, attr);
if (!p || p >= end)
return 0;
} while (*(p - 1) != ' ' && *(p - 1) != '\n');
return p + strlen(attr);
}
int Hunspell::check_xml_par(const char* q,
const char* attr,
const char* value) {
char cw[MAXWORDUTF8LEN];
if (get_xml_par(cw, get_xml_pos(q, attr), MAXWORDUTF8LEN - 1) &&
strcmp(cw, value) == 0)
return 1;
return 0;
}
int Hunspell::get_xml_list(char*** slst, char* list, const char* tag) {
int n = 0;
char* p;
if (!list)
return 0;
for (p = list; ((p = strstr(p, tag)) != NULL); p++)
n++;
if (n == 0)
return 0;
*slst = (char**)malloc(sizeof(char*) * n);
if (!*slst)
return 0;
for (p = list, n = 0; ((p = strstr(p, tag)) != NULL); p++, n++) {
int l = strlen(p);
(*slst)[n] = (char*)malloc(l + 1);
if (!(*slst)[n])
return n;
if (!get_xml_par((*slst)[n], p + strlen(tag) - 1, l)) {
free((*slst)[n]);
break;
}
}
return n;
}
int Hunspell::spellml(char*** slst, const char* word) {
char *q, *q2;
char cw[MAXWORDUTF8LEN], cw2[MAXWORDUTF8LEN];
q = (char*)strstr(word, "<query");
if (!q)
return 0; // bad XML input
q2 = strchr(q, '>');
if (!q2)
return 0; // bad XML input
q2 = strstr(q2, "<word");
if (!q2)
return 0; // bad XML input
if (check_xml_par(q, "type=", "analyze")) {
int n = 0;
if (get_xml_par(cw, strchr(q2, '>'), MAXWORDUTF8LEN - 10))
n = analyze(slst, cw);
if (n == 0)
return 0;
// convert the result to <code><a>ana1</a><a>ana2</a></code> format
std::string r;
r.append("<code>");
for (int i = 0; i < n; i++) {
r.append("<a>");
std::string entry((*slst)[i]);
free((*slst)[i]);
mystrrep(entry, "\t", " ");
mystrrep(entry, "&", "&");
mystrrep(entry, "<", "<");
r.append(entry);
r.append("</a>");
}
r.append("</code>");
(*slst)[0] = mystrdup(r.c_str());
return 1;
} else if (check_xml_par(q, "type=", "stem")) {
if (get_xml_par(cw, strchr(q2, '>'), MAXWORDUTF8LEN - 1))
return stem(slst, cw);
} else if (check_xml_par(q, "type=", "generate")) {
int n = get_xml_par(cw, strchr(q2, '>'), MAXWORDUTF8LEN - 1);
if (n == 0)
return 0;
char* q3 = strstr(q2 + 1, "<word");
if (q3) {
if (get_xml_par(cw2, strchr(q3, '>'), MAXWORDUTF8LEN - 1)) {
return generate(slst, cw, cw2);
}
} else {
if ((q2 = strstr(q2 + 1, "<code")) != NULL) {
char** slst2;
if ((n = get_xml_list(&slst2, strchr(q2, '>'), "<a>")) != 0) {
int n2 = generate(slst, cw, slst2, n);
freelist(&slst2, n);
return uniqlist(*slst, n2);
}
freelist(&slst2, n);
}
}
}
return 0;
}
#ifdef HUNSPELL_EXPERIMENTAL
// XXX is UTF-8 support OK?
char* Hunspell::morph_with_correction(const char* word) {
char cw[MAXWORDUTF8LEN];
char wspace[MAXWORDUTF8LEN];
if (!pSMgr || maxdic == 0)
return NULL;
w_char unicw[MAXWORDLEN];
int nc = strlen(word);
if (utf8) {
if (nc >= MAXWORDUTF8LEN)
return NULL;
} else {
if (nc >= MAXWORDLEN)
return NULL;
}
int captype = 0;
int abbv = 0;
int wl = 0;
// input conversion
RepList* rl = (pAMgr) ? pAMgr->get_iconvtable() : NULL;
int convstatus = rl ? rl->conv(word, wspace) : 0;
if (convstatus < 0)
return 0;
else if (convstatus > 0)
wl = cleanword2(cw, wspace, unicw, &nc, &captype, &abbv);
else
wl = cleanword2(cw, word, unicw, &nc, &captype, &abbv);
if (wl == 0)
return NULL;
char result[MAXLNLEN];
char* st = NULL;
*result = '\0';
switch (captype) {
case NOCAP: {
st = pSMgr->suggest_morph_for_spelling_error(cw);
if (st) {
mystrcat(result, st, MAXLNLEN);
free(st);
}
if (abbv) {
memcpy(wspace, cw, wl);
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
st = pSMgr->suggest_morph_for_spelling_error(wspace);
if (st) {
if (*result)
mystrcat(result, "\n", MAXLNLEN);
mystrcat(result, st, MAXLNLEN);
free(st);
}
}
break;
}
case INITCAP: {
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
st = pSMgr->suggest_morph_for_spelling_error(wspace);
if (st) {
mystrcat(result, st, MAXLNLEN);
free(st);
}
st = pSMgr->suggest_morph_for_spelling_error(cw);
if (st) {
if (*result)
mystrcat(result, "\n", MAXLNLEN);
mystrcat(result, st, MAXLNLEN);
free(st);
}
if (abbv) {
memcpy(wspace, cw, wl);
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
mkallsmall2(wspace, unicw, nc);
st = pSMgr->suggest_morph_for_spelling_error(wspace);
if (st) {
if (*result)
mystrcat(result, "\n", MAXLNLEN);
mystrcat(result, st, MAXLNLEN);
free(st);
}
mkinitcap(wspace);
st = pSMgr->suggest_morph_for_spelling_error(wspace);
if (st) {
if (*result)
mystrcat(result, "\n", MAXLNLEN);
mystrcat(result, st, MAXLNLEN);
free(st);
}
}
break;
}
case HUHCAP: {
st = pSMgr->suggest_morph_for_spelling_error(cw);
if (st) {
mystrcat(result, st, MAXLNLEN);
free(st);
}
memcpy(wspace, cw, (wl + 1));
mkallsmall2(wspace, unicw, nc);
st = pSMgr->suggest_morph_for_spelling_error(wspace);
if (st) {
if (*result)
mystrcat(result, "\n", MAXLNLEN);
mystrcat(result, st, MAXLNLEN);
free(st);
}
break;
}
case ALLCAP: {
memcpy(wspace, cw, (wl + 1));
st = pSMgr->suggest_morph_for_spelling_error(wspace);
if (st) {
mystrcat(result, st, MAXLNLEN);
free(st);
}
mkallsmall2(wspace, unicw, nc);
st = pSMgr->suggest_morph_for_spelling_error(wspace);
if (st) {
if (*result)
mystrcat(result, "\n", MAXLNLEN);
mystrcat(result, st, MAXLNLEN);
free(st);
}
mkinitcap(wspace);
st = pSMgr->suggest_morph_for_spelling_error(wspace);
if (st) {
if (*result)
mystrcat(result, "\n", MAXLNLEN);
mystrcat(result, st, MAXLNLEN);
free(st);
}
if (abbv) {
memcpy(wspace, cw, (wl + 1));
*(wspace + wl) = '.';
*(wspace + wl + 1) = '\0';
if (*result)
mystrcat(result, "\n", MAXLNLEN);
st = pSMgr->suggest_morph_for_spelling_error(wspace);
if (st) {
mystrcat(result, st, MAXLNLEN);
free(st);
}
mkallsmall2(wspace, unicw, nc);
st = pSMgr->suggest_morph_for_spelling_error(wspace);
if (st) {
if (*result)
mystrcat(result, "\n", MAXLNLEN);
mystrcat(result, st, MAXLNLEN);
free(st);
}
mkinitcap(wspace);
st = pSMgr->suggest_morph_for_spelling_error(wspace);
if (st) {
if (*result)
mystrcat(result, "\n", MAXLNLEN);
mystrcat(result, st, MAXLNLEN);
free(st);
}
}
break;
}
}
if (*result)
return mystrdup(result);
return NULL;
}
#endif // END OF HUNSPELL_EXPERIMENTAL CODE
Hunhandle* Hunspell_create(const char* affpath, const char* dpath) {
return (Hunhandle*)(new Hunspell(affpath, dpath));
}
Hunhandle* Hunspell_create_key(const char* affpath,
const char* dpath,
const char* key) {
return (Hunhandle*)(new Hunspell(affpath, dpath, key));
}
void Hunspell_destroy(Hunhandle* pHunspell) {
delete (Hunspell*)(pHunspell);
}
int Hunspell_add_dic(Hunhandle* pHunspell, const char* dpath) {
return ((Hunspell*)pHunspell)->add_dic(dpath);
}
int Hunspell_spell(Hunhandle* pHunspell, const char* word) {
return ((Hunspell*)pHunspell)->spell(word);
}
char* Hunspell_get_dic_encoding(Hunhandle* pHunspell) {
return ((Hunspell*)pHunspell)->get_dic_encoding();
}
int Hunspell_suggest(Hunhandle* pHunspell, char*** slst, const char* word) {
return ((Hunspell*)pHunspell)->suggest(slst, word);
}
int Hunspell_analyze(Hunhandle* pHunspell, char*** slst, const char* word) {
return ((Hunspell*)pHunspell)->analyze(slst, word);
}
int Hunspell_stem(Hunhandle* pHunspell, char*** slst, const char* word) {
return ((Hunspell*)pHunspell)->stem(slst, word);
}
int Hunspell_stem2(Hunhandle* pHunspell, char*** slst, char** desc, int n) {
return ((Hunspell*)pHunspell)->stem(slst, desc, n);
}
int Hunspell_generate(Hunhandle* pHunspell,
char*** slst,
const char* word,
const char* word2) {
return ((Hunspell*)pHunspell)->generate(slst, word, word2);
}
int Hunspell_generate2(Hunhandle* pHunspell,
char*** slst,
const char* word,
char** desc,
int n) {
return ((Hunspell*)pHunspell)->generate(slst, word, desc, n);
}
/* functions for run-time modification of the dictionary */
/* add word to the run-time dictionary */
int Hunspell_add(Hunhandle* pHunspell, const char* word) {
return ((Hunspell*)pHunspell)->add(word);
}
/* add word to the run-time dictionary with affix flags of
* the example (a dictionary word): Hunspell will recognize
* affixed forms of the new word, too.
*/
int Hunspell_add_with_affix(Hunhandle* pHunspell,
const char* word,
const char* example) {
return ((Hunspell*)pHunspell)->add_with_affix(word, example);
}
/* remove word from the run-time dictionary */
int Hunspell_remove(Hunhandle* pHunspell, const char* word) {
return ((Hunspell*)pHunspell)->remove(word);
}
void Hunspell_free_list(Hunhandle*, char*** slst, int n) {
freelist(slst, n);
}
int Hunspell::suffix_suggest(char*** slst, const char* root_word) {
struct hentry* he = NULL;
int len;
std::string w2;
const char* word;
char* ignoredchars = pAMgr->get_ignore();
if (ignoredchars != NULL) {
w2.assign(root_word);
if (utf8) {
int ignoredchars_utf16_len;
unsigned short* ignoredchars_utf16 =
pAMgr->get_ignore_utf16(&ignoredchars_utf16_len);
remove_ignored_chars_utf(w2, ignoredchars_utf16, ignoredchars_utf16_len);
} else {
remove_ignored_chars(w2, ignoredchars);
}
word = w2.c_str();
} else
word = root_word;
len = strlen(word);
if (!len)
return 0;
char** wlst = (char**)malloc(MAXSUGGESTION * sizeof(char*));
if (wlst == NULL)
return -1;
*slst = wlst;
for (int i = 0; i < MAXSUGGESTION; i++) {
wlst[i] = NULL;
}
for (int i = 0; (i < maxdic) && !he; i++) {
he = (pHMgr[i])->lookup(word);
}
if (he) {
return pAMgr->get_suffix_words(he->astr, he->alen, root_word, *slst);
}
return 0;
}
|
/*
* Copyright (C) 2011 Ivan Cukic <ivan.cukic(at)kde.org>
*
* 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 (at your option) any later version, as published by the Free
* Software Foundation
*
* 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 "connman-manager.h"
#include "connman-service.h"
#include "ConnmanNetworkNotifier.h"
#include "connmannetworknotifieradaptor.h"
#include <config-features.h>
#include <KDebug>
// #define CONNMAN_DBUS_SERVICE "org.moblin.connman"
#define CONNMAN_DBUS_SERVICE "net.connman"
REGISTER_NETWORK_NOTIFIER(ConnmanNetworkNotifier)
class ConnmanNetworkNotifier::Private {
public:
Private()
: iface(0), watcher(0)
{}
NetConnmanManagerInterface * iface;
QDBusServiceWatcher * watcher;
};
ConnmanNetworkNotifier::ConnmanNetworkNotifier(QObject * parent)
: NetworkNotifier(parent), d(new Private())
{
}
ConnmanNetworkNotifier::~ConnmanNetworkNotifier()
{
delete d;
}
void ConnmanNetworkNotifier::init()
{
// Hmh, connman doesn't show up when registered. Lets hope it will be online
// before the location manager is started
if (!QDBusConnection::systemBus().interface()->isServiceRegistered(CONNMAN_DBUS_SERVICE)) {
kDebug() << "Watching for" << CONNMAN_DBUS_SERVICE << "to arrive";
d->watcher = new QDBusServiceWatcher(
CONNMAN_DBUS_SERVICE,
QDBusConnection::systemBus(),
QDBusServiceWatcher::WatchForRegistration |
QDBusServiceWatcher::WatchForUnregistration |
QDBusServiceWatcher::WatchForOwnerChange,
this
);
kDebug() << "Connecting" <<
connect(d->watcher, SIGNAL(serviceRegistered(QString)),
this, SLOT(enable()));
} else {
enable();
}
}
void ConnmanNetworkNotifier::enable()
{
kDebug() << "Starting connman listener";
(void) new ConnmanNetworkNotifierAdaptor(this);
QDBusConnection::sessionBus().registerObject(
QLatin1String("/ConnmanInterface"), this);
delete d->iface;
d->iface = new NetConnmanManagerInterface(CONNMAN_DBUS_SERVICE, QLatin1String("/"), QDBusConnection::systemBus(), this);
connect(d->iface, SIGNAL(PropertyChanged(QString,QDBusVariant)), SLOT(propertyChanged(QString,QDBusVariant)));
QDBusReply<QVariantMap> reply = d->iface->GetProperties();
if (!reply.isValid()) {
return;
}
QVariantMap properties = reply.value();
//kDebug() << "Initial state: " << properties["State"].toString();
propertyChanged("State", QDBusVariant(properties["State"]));
}
// monitor when connman connects to a network, or disconnects from it.
// On those events, this method passes the info to the locationmanager daemon
// via the dummy network notifier.
void ConnmanNetworkNotifier::propertyChanged(const QString &name, const QDBusVariant &value)
{
//kDebug() << name << ": " << value.variant().toString();
if (name != QLatin1String("State")) {
return;
}
// we are offline
if (value.variant().toString() != QLatin1String("online")) {
kDebug() << "OFFLINE";
setWifiName("");
return;
}
QDBusReply<QVariantMap> reply = d->iface->GetProperties();
if (!reply.isValid()) {
kDebug() << reply.error().message();
return;
}
QVariantMap properties = reply.value();
//kDebug() << "got properties:" << properties.count();
//kDebug() << "Services ==" << properties["Services"];
QList<QDBusObjectPath> services = qdbus_cast<QList<QDBusObjectPath> >(properties["Services"]);
//kDebug() << services.count() << "services";
// searching for active wifi info
foreach (const QDBusObjectPath &s, services) {
//kDebug() << "testing service" << s.path();
NetConnmanServiceInterface service(CONNMAN_DBUS_SERVICE, s.path(), QDBusConnection::systemBus());
if (!service.isValid()) {
continue;
}
//kDebug() << "testing service" << s.path() << "getting properties";
QDBusReply<QVariantMap> reply = service.GetProperties();
if (!reply.isValid()) {
continue;
}
//kDebug() << "testing service" << s.path() << "testing state";
QVariantMap serviceProperties = reply.value();
if (serviceProperties["State"].toString() == QLatin1String("ready")) {
kDebug() << "CONNECTED TO:" << serviceProperties["Name"];
setWifiName(serviceProperties["Name"].toString());
return;
}
}
}
void ConnmanNetworkNotifier::setWifiName(const QString & accessPoint)
{
setActiveAccessPoint(accessPoint);
}
Added some debugging output
/*
* Copyright (C) 2011, 2012 Ivan Cukic <ivan.cukic(at)kde.org>
*
* 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 (at your option) any later version, as published by the Free
* Software Foundation
*
* 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 "connman-manager.h"
#include "connman-service.h"
#include "ConnmanNetworkNotifier.h"
#include "connmannetworknotifieradaptor.h"
#include <config-features.h>
#include <KDebug>
// #define CONNMAN_DBUS_SERVICE "org.moblin.connman"
#define CONNMAN_DBUS_SERVICE "net.connman"
REGISTER_NETWORK_NOTIFIER(ConnmanNetworkNotifier)
class ConnmanNetworkNotifier::Private {
public:
Private()
: iface(0), watcher(0)
{}
NetConnmanManagerInterface * iface;
QDBusServiceWatcher * watcher;
};
ConnmanNetworkNotifier::ConnmanNetworkNotifier(QObject * parent)
: NetworkNotifier(parent), d(new Private())
{
}
ConnmanNetworkNotifier::~ConnmanNetworkNotifier()
{
delete d;
}
void ConnmanNetworkNotifier::init()
{
// Hmh, connman doesn't show up when registered. Lets hope it will be online
// before the location manager is started
if (!QDBusConnection::systemBus().interface()->isServiceRegistered(CONNMAN_DBUS_SERVICE)) {
kDebug() << "Watching for" << CONNMAN_DBUS_SERVICE << "to arrive";
d->watcher = new QDBusServiceWatcher(
CONNMAN_DBUS_SERVICE,
QDBusConnection::systemBus(),
QDBusServiceWatcher::WatchForRegistration |
QDBusServiceWatcher::WatchForUnregistration |
QDBusServiceWatcher::WatchForOwnerChange,
this
);
kDebug() << "Connecting" <<
connect(d->watcher, SIGNAL(serviceRegistered(QString)),
this, SLOT(enable()));
} else {
enable();
}
}
void ConnmanNetworkNotifier::enable()
{
kDebug() << "Starting connman listener";
(void) new ConnmanNetworkNotifierAdaptor(this);
QDBusConnection::sessionBus().registerObject(
QLatin1String("/ConnmanInterface"), this);
delete d->iface;
d->iface = new NetConnmanManagerInterface(CONNMAN_DBUS_SERVICE, QLatin1String("/"), QDBusConnection::systemBus(), this);
connect(d->iface, SIGNAL(PropertyChanged(QString,QDBusVariant)), SLOT(propertyChanged(QString,QDBusVariant)));
QDBusReply<QVariantMap> reply = d->iface->GetProperties();
if (!reply.isValid()) {
kDebug() << "GetProperties reply was invalid";
return;
}
QVariantMap properties = reply.value();
//kDebug() << "Initial state: " << properties["State"].toString();
propertyChanged("State", QDBusVariant(properties["State"]));
}
// monitor when connman connects to a network, or disconnects from it.
// On those events, this method passes the info to the locationmanager daemon
// via the dummy network notifier.
void ConnmanNetworkNotifier::propertyChanged(const QString &name, const QDBusVariant &value)
{
//kDebug() << name << ": " << value.variant().toString();
if (name != QLatin1String("State")) {
kDebug() << "Property" << name << "ignored";
return;
}
// we are offline
if (value.variant().toString() != QLatin1String("online")) {
kDebug() << "OFFLINE";
setWifiName("");
return;
}
QDBusReply<QVariantMap> reply = d->iface->GetProperties();
if (!reply.isValid()) {
kDebug() << "GetProperties failed" << reply.error().message();
return;
}
QVariantMap properties = reply.value();
//kDebug() << "got properties:" << properties.count();
//kDebug() << "Services ==" << properties["Services"];
QList<QDBusObjectPath> services = qdbus_cast<QList<QDBusObjectPath> >(properties["Services"]);
//kDebug() << services.count() << "services";
// searching for active wifi info
foreach (const QDBusObjectPath &s, services) {
kDebug() << "testing service" << s.path();
NetConnmanServiceInterface service(CONNMAN_DBUS_SERVICE, s.path(), QDBusConnection::systemBus());
if (!service.isValid()) {
kDebug() << "Service" << s.path() << "is not valid";
continue;
}
QDBusReply<QVariantMap> reply = service.GetProperties();
if (!reply.isValid()) {
kDebug() << "GetProperties failed for";
continue;
}
QVariantMap serviceProperties = reply.value();
if (serviceProperties["State"].toString() == QLatin1String("ready")) {
kDebug() << "CONNECTED TO:" << serviceProperties["Name"];
setWifiName(serviceProperties["Name"].toString());
return;
}
}
}
void ConnmanNetworkNotifier::setWifiName(const QString & accessPoint)
{
setActiveAccessPoint(accessPoint);
}
|
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <cassert>
#include <sstream>
#include <algorithm>
#include <fstream>
#include <boost/program_options.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string.hpp>
using std::string;
using std::ostream;
using std::ofstream;
namespace po=boost::program_options;
const string HELP_K = "help";
const string CONFIG_K = "config";
const string INPUT_K = "input";
const string OUTPUT_K = "output";
const string OPERATION_K = "operation";
const string SELECT_K = "select";
const string SPLIT_K = "split";
const string TRANSPOSE_K = "transpose";
const string COMBINE_K = "combine";
const string FORMAT_K = "format";
const string PREFIX_K = "prefix";
const string VALUE_K = "value";
const string KEYS_K = "keys";
const string JSON_K = "json";
const string GNUPLOT_K = "gnuplot";
const string OUTPUT_FORMAT_K = OUTPUT_K + "." + FORMAT_K;
const string OUTPUT_PREFIX_K = OUTPUT_K + "." + PREFIX_K;
const string INPUT_VALUE_K = INPUT_K + "." + VALUE_K;
int parse_configuration( int argc, char ** argv, boost::property_tree::ptree & cfg );
int command_line( int argc, char ** argv, po::variables_map & vm );
int transform( po::variables_map & vm, boost::property_tree::ptree & p );
void parse_data( boost::property_tree::ptree & cfg );
typedef void (*parser_op)( boost::property_tree::ptree & parameters );
// select keys from each input file into a
void select_op( boost::property_tree::ptree & parameters );
void select_op_gnuplot( boost::property_tree::ptree & params );
// combine all keys from each input file into a single output file
void combine_op( boost::property_tree::ptree & parameters );
void combine_op_json( boost::property_tree::ptree & parameters );
void transpose_op( boost::property_tree::ptree & params );
void write_json( const std::string & path, boost::property_tree::ptree & results );
void write_gnuplot( const std::string & path, const std::string & header, boost::property_tree::ptree & results );
int main( int argc, char ** argv ) {
boost::property_tree::ptree cfg;
int res = 0;
if( (res = parse_configuration( argc, argv, cfg )) ) {
return res;
}
BOOST_FOREACH( auto& c, cfg ) {
std::cerr << c.first << std::endl;
parse_data( c.second );
}
}
void parse_data( boost::property_tree::ptree & cfg ) {
string op = cfg.get< string >( OPERATION_K, "");
if( op.empty() ) return;
if( op == SELECT_K ) {
select_op( cfg );
} else if ( op == COMBINE_K ) {
// combine_op( cfg );
} else if( op == TRANSPOSE_K ) {
// transpose_op( cfg );
}
}
int parse_configuration( int argc, char ** argv, boost::property_tree::ptree & cfg ) {
po::variables_map vm;
int res = command_line( argc, argv, vm );
if( res ) {
return res;
}
string config_file = vm[ CONFIG_K ].as< string >();
if( config_file.empty() ) {
res = transform( vm, cfg );
} else {
boost::property_tree::read_json( config_file, cfg );
}
return res;
}
int command_line( int argc, char ** argv, po::variables_map & vm ) {
po::options_description gen( "General" );
gen.add_options()
((HELP_K + ",h").c_str(), "Print this" )
;
po::options_description io_params("I/O Parameters");
io_params.add_options()
( (CONFIG_K + ",c" ).c_str(), po::value< string >()->default_value(""), "Configuration file containing files to be parsed" )
;
po::options_description cmdline;
cmdline.add( gen ).add( io_params );
po::store( po::command_line_parser( argc, argv ).options(cmdline).run(), vm );
if( vm.count( HELP_K ) ) {
std::cout << cmdline << std::endl;
return 1;
}
return 0;
}
int transform( po::variables_map & vm, boost::property_tree::ptree & p ) {
return 0;
}
void select_op( boost::property_tree::ptree & params ) {
string frmt = params.get< string >( OUTPUT_FORMAT_K, "" );
string output = params.get< string >( OUTPUT_PREFIX_K, "" );
std::vector< string > keys;
BOOST_FOREACH( auto& v, params.get_child( KEYS_K ) ) {
std::ostringstream oss;
oss << v.second.data();
keys.push_back( oss.str() );
}
BOOST_FOREACH( auto& v, params.get_child( INPUT_K ) ) {
std::ostringstream oss;
oss << v.second.data();
string path = oss.str();
if( boost::algorithm::iends_with(path, "." + JSON_K) ) {
std::cerr << "Parsing input JSON file: " << path << std::endl;
string tmp_path = path.substr(0, path.size() - (JSON_K.size() + 1));
boost::property_tree::ptree infile;
boost::property_tree::read_json( path, infile );
BOOST_FOREACH( auto& k, keys ) {
if( infile.get_child_optional( k ) != boost::none ) {
// string tmp = tmp_path + "." + k;
// results.add_child( k, infile.get_child( k ) );
//
if( boost::iequals( frmt, JSON_K ) ) {
write_json( output, infile.get_child(k) );
} else if( boost::iequals( frmt, GNUPLOT_K ) ) {
write_gnuplot( output, k, infile.get_child(k) );
}
}
}
}
}
}
/*
void combine_op_json( boost::property_tree::ptree & params ) {
boost::property_tree::ptree results;
assert( params.get_child_optional( INPUT_K ) != boost::none );
assert( params.get_child_optional( KEYS_K ) != boost::none );
std::vector< string > keys;
BOOST_FOREACH( auto& v, params.get_child( KEYS_K ) ) {
std::ostringstream oss;
oss << v.second.data();
keys.push_back( oss.str() );
}
BOOST_FOREACH( auto& v, params.get_child( INPUT_K ) ) {
std::ostringstream oss;
oss << v.second.data();
string path = oss.str();
if( boost::algorithm::iends_with(path, "." + JSON_K) ) {
std::cerr << "Parsing input JSON file: " << path << std::endl;
string tmp_path = path.substr(0, path.size() - (JSON_K.size() + 1));
boost::property_tree::ptree infile;
boost::property_tree::read_json( path, infile );
BOOST_FOREACH( auto& k, keys ) {
if( infile.get_child_optional( k ) != boost::none ) {
string tmp = tmp_path + "." + k;
results.add_child( tmp, infile.get_child( k ) );
}
}
}
}
if( output.empty() ) {
boost::property_tree::write_json(std::cout, results );
} else {
boost::property_tree::write_json( output + "." + JSON_K, results );
}
}
void select_op_gnuplot( boost::property_tree::ptree & params ) {
}
void transpose_op( boost::property_tree::ptree & params ) {
assert( params.get_child_optional( OUTPUT_FORMAT_K ) != boost::none );
string frmt = params.get< string >( OUTPUT_FORMAT_K, "" );
string output = params.get< string >( OUTPUT_PREFIX_K, "" );
if( boost::iequals( frmt, GNUPLOT_K ) ) {
assert( params.get_child_optional( INPUT_K ) != boost::none );
assert( params.get_child_optional( KEYS_K ) != boost::none );
std::vector< string > keys;
BOOST_FOREACH( auto& v, params.get_child( KEYS_K ) ) {
std::ostringstream oss;
oss << v.second.data();
keys.push_back( oss.str() );
}
BOOST_FOREACH( auto& v, params.get_child( INPUT_K ) ) {
std::ostringstream oss;
oss << v.second.data();
string path = oss.str();
typedef std::vector< string > row_type;
typedef std::map< string, std::vector< row_type > > value_map_type;
value_map_type data;
if( boost::algorithm::iends_with(path, "." + JSON_K) ) {
std::cerr << "Parsing input JSON file: " << path << std::endl;
string tmp_path = path.substr(0, path.size() - (JSON_K.size() + 1));
boost::property_tree::ptree infile;
boost::property_tree::read_json( path, infile );
BOOST_FOREACH( auto& k, keys ) {
if( infile.get_child_optional( k ) != boost::none ) {
// string tmp = tmp_path + "." + k;
value_map_type::iterator it = data.find( k );
if( it == data.end() ) {
std::pair< value_map_type::iterator, bool > res = data.insert( std::make_pair(k, std::vector<row_type>() ));
assert( res.second );
it = res.first;
}
unsigned int max_columns = 0;
unsigned int j = 0;
BOOST_FOREACH( auto& dval, infile.get_child(k) ) {
unsigned int i = 0;
row_type r;
BOOST_FOREACH( auto& pval, dval.second ) {
std::ostringstream oss;
oss << pval.second.data();
r.push_back( oss.str() );
++i;
}
if( i > max_columns ) { max_columns = i; }
it->second.push_back(r);
++j;
}
}
}
}
if( output.empty() ) {
BOOST_FOREACH( auto& dval, data) {
std::cout << "# " << dval.first << std::endl;
unsigned int i = 0;
BOOST_FOREACH( auto& r, dval.second ) {
std::cout << i++;
BOOST_FOREACH( auto& c, r ) {
std::cout << "," << c;
}
std::cout << std::endl;
}
std::cout << std::endl;
}
}
}
}
}
void combine_op( boost::property_tree::ptree & params ) {
assert( params.get_child_optional( OUTPUT_FORMAT_K ) != boost::none );
string frmt = params.get< string >( OUTPUT_FORMAT_K, "" );
string output = params.get< string >( OUTPUT_PREFIX_K, "" );
if( boost::iequals( frmt, JSON_K ) ) {
boost::property_tree::ptree results;
assert( params.get_child_optional( INPUT_K ) != boost::none );
assert( params.get_child_optional( KEYS_K ) != boost::none );
std::vector< string > keys;
BOOST_FOREACH( auto& v, params.get_child( KEYS_K ) ) {
std::ostringstream oss;
oss << v.second.data();
keys.push_back( oss.str() );
}
BOOST_FOREACH( auto& v, params.get_child( INPUT_K ) ) {
std::ostringstream oss;
oss << v.second.data();
string path = oss.str();
if( boost::algorithm::iends_with(path, "." + JSON_K) ) {
std::cerr << "Parsing input JSON file: " << path << std::endl;
string tmp_path = path.substr(0, path.size() - (JSON_K.size() + 1));
boost::property_tree::ptree infile;
boost::property_tree::read_json( path, infile );
BOOST_FOREACH( auto& k, keys ) {
if( infile.get_child_optional( k ) != boost::none ) {
string tmp = tmp_path + "." + k;
results.add_child( tmp, infile.get_child( k ) );
}
}
}
}
}
}*/
void write_json( const string & path, boost::property_tree::ptree & results ) {
if( path.empty() ) {
boost::property_tree::write_json( std::cout, results );
} else {
boost::property_tree::write_json( path + "." + JSON_K, results );
}
}
/*
void write( ostream * out, boost::property_tree::ptree::value_type & node ) {
if( node.first.empty() ) {
(*out) << "\n";
BOOST_FOREACH( auto & pval, node.second ) {
std::ostringstream oss;
oss << pval.second.data();
(*out) << oss.str() << ",";
}
} else {
(*out) << "." << node.first;
BOOST_FOREACH( auto& c, node.second ) {
write( out, c );
(*out) << "\n";
}
}
}*/
void write_data( ostream * out, boost::property_tree::ptree & data ) {
unsigned int i = 0;
if( data.empty() ) {
//(*out) << i << "," << data.data() << "\n";
(*out) << "," << data.data();
} else {
BOOST_FOREACH( auto& c, data ) {
if( c.second.empty() ) {
(*out) << "," << c.second.data();
} else {
(*out) << ++i;
write_data( out, c.second);
(*out) << "\n";
}
}
}
}
void write( ostream * out, string path, boost::property_tree::ptree & tr ) {
unsigned int i = 0;
if( tr.empty() ) {
(*out) << ++i << "," << tr.data() << "\n";
} else {
BOOST_FOREACH( auto& c, tr ) {
if( c.first.empty() ) {
(*out) << ++i;
write_data(out, c.second);
(*out) << "\n";
} else {
write( out, path + "." + c.first, c.second );
}
}
}
}
void write_gnuplot( const string & path, const string & header, boost::property_tree::ptree & results ) {
ostream * out;
if( path.empty() ) {
out = &std::cout;
} else {
out = new ofstream(path + ".dat");
}
(*out) << "# " << header << "\n";
write(out, "", results );
if( out != &std::cout ) {
((ofstream *)out)->close();
}
}
Formatting
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <cassert>
#include <sstream>
#include <algorithm>
#include <fstream>
#include <boost/program_options.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string.hpp>
using std::string;
using std::ostream;
using std::ofstream;
namespace po=boost::program_options;
const string HELP_K = "help";
const string CONFIG_K = "config";
const string INPUT_K = "input";
const string OUTPUT_K = "output";
const string OPERATION_K = "operation";
const string SELECT_K = "select";
const string SPLIT_K = "split";
const string TRANSPOSE_K = "transpose";
const string COMBINE_K = "combine";
const string FORMAT_K = "format";
const string PREFIX_K = "prefix";
const string VALUE_K = "value";
const string KEYS_K = "keys";
const string JSON_K = "json";
const string GNUPLOT_K = "gnuplot";
const string OUTPUT_FORMAT_K = OUTPUT_K + "." + FORMAT_K;
const string OUTPUT_PREFIX_K = OUTPUT_K + "." + PREFIX_K;
const string INPUT_VALUE_K = INPUT_K + "." + VALUE_K;
int parse_configuration( int argc, char ** argv, boost::property_tree::ptree & cfg );
int command_line( int argc, char ** argv, po::variables_map & vm );
int transform( po::variables_map & vm, boost::property_tree::ptree & p );
void parse_data( boost::property_tree::ptree & cfg );
typedef void (*parser_op)( boost::property_tree::ptree & parameters );
// select keys from each input file into a
void select_op( boost::property_tree::ptree & parameters );
void select_op_gnuplot( boost::property_tree::ptree & params );
// combine all keys from each input file into a single output file
void combine_op( boost::property_tree::ptree & parameters );
void combine_op_json( boost::property_tree::ptree & parameters );
void transpose_op( boost::property_tree::ptree & params );
void write_json( const std::string & path, boost::property_tree::ptree & results );
void write_gnuplot( const std::string & path, const std::string & header, boost::property_tree::ptree & results );
int main( int argc, char ** argv ) {
boost::property_tree::ptree cfg;
int res = 0;
if( (res = parse_configuration( argc, argv, cfg )) ) {
return res;
}
BOOST_FOREACH( auto& c, cfg ) {
std::cerr << c.first << std::endl;
parse_data( c.second );
}
}
void parse_data( boost::property_tree::ptree & cfg ) {
string op = cfg.get< string >( OPERATION_K, "");
if( op.empty() ) return;
if( op == SELECT_K ) {
select_op( cfg );
} else if ( op == COMBINE_K ) {
// combine_op( cfg );
} else if( op == TRANSPOSE_K ) {
// transpose_op( cfg );
}
}
int parse_configuration( int argc, char ** argv, boost::property_tree::ptree & cfg ) {
po::variables_map vm;
int res = command_line( argc, argv, vm );
if( res ) {
return res;
}
string config_file = vm[ CONFIG_K ].as< string >();
if( config_file.empty() ) {
res = transform( vm, cfg );
} else {
boost::property_tree::read_json( config_file, cfg );
}
return res;
}
int command_line( int argc, char ** argv, po::variables_map & vm ) {
po::options_description gen( "General" );
gen.add_options()
((HELP_K + ",h").c_str(), "Print this" )
;
po::options_description io_params("I/O Parameters");
io_params.add_options()
( (CONFIG_K + ",c" ).c_str(), po::value< string >()->default_value(""), "Configuration file containing files to be parsed" )
;
po::options_description cmdline;
cmdline.add( gen ).add( io_params );
po::store( po::command_line_parser( argc, argv ).options(cmdline).run(), vm );
if( vm.count( HELP_K ) ) {
std::cout << cmdline << std::endl;
return 1;
}
return 0;
}
int transform( po::variables_map & vm, boost::property_tree::ptree & p ) {
return 0;
}
void select_op( boost::property_tree::ptree & params ) {
string frmt = params.get< string >( OUTPUT_FORMAT_K, "" );
string output = params.get< string >( OUTPUT_PREFIX_K, "" );
std::vector< string > keys;
BOOST_FOREACH( auto& v, params.get_child( KEYS_K ) ) {
std::ostringstream oss;
oss << v.second.data();
keys.push_back( oss.str() );
}
BOOST_FOREACH( auto& v, params.get_child( INPUT_K ) ) {
std::ostringstream oss;
oss << v.second.data();
string path = oss.str();
if( boost::algorithm::iends_with(path, "." + JSON_K) ) {
std::cerr << "Parsing input JSON file: " << path << std::endl;
string tmp_path = path.substr(0, path.size() - (JSON_K.size() + 1));
boost::property_tree::ptree infile;
boost::property_tree::read_json( path, infile );
BOOST_FOREACH( auto& k, keys ) {
if( infile.get_child_optional( k ) != boost::none ) {
// string tmp = tmp_path + "." + k;
// results.add_child( k, infile.get_child( k ) );
//
if( boost::iequals( frmt, JSON_K ) ) {
write_json( output, infile.get_child(k) );
} else if( boost::iequals( frmt, GNUPLOT_K ) ) {
write_gnuplot( output, k, infile.get_child(k) );
}
}
}
}
}
}
/*
void combine_op_json( boost::property_tree::ptree & params ) {
boost::property_tree::ptree results;
assert( params.get_child_optional( INPUT_K ) != boost::none );
assert( params.get_child_optional( KEYS_K ) != boost::none );
std::vector< string > keys;
BOOST_FOREACH( auto& v, params.get_child( KEYS_K ) ) {
std::ostringstream oss;
oss << v.second.data();
keys.push_back( oss.str() );
}
BOOST_FOREACH( auto& v, params.get_child( INPUT_K ) ) {
std::ostringstream oss;
oss << v.second.data();
string path = oss.str();
if( boost::algorithm::iends_with(path, "." + JSON_K) ) {
std::cerr << "Parsing input JSON file: " << path << std::endl;
string tmp_path = path.substr(0, path.size() - (JSON_K.size() + 1));
boost::property_tree::ptree infile;
boost::property_tree::read_json( path, infile );
BOOST_FOREACH( auto& k, keys ) {
if( infile.get_child_optional( k ) != boost::none ) {
string tmp = tmp_path + "." + k;
results.add_child( tmp, infile.get_child( k ) );
}
}
}
}
if( output.empty() ) {
boost::property_tree::write_json(std::cout, results );
} else {
boost::property_tree::write_json( output + "." + JSON_K, results );
}
}
void select_op_gnuplot( boost::property_tree::ptree & params ) {
}
void transpose_op( boost::property_tree::ptree & params ) {
assert( params.get_child_optional( OUTPUT_FORMAT_K ) != boost::none );
string frmt = params.get< string >( OUTPUT_FORMAT_K, "" );
string output = params.get< string >( OUTPUT_PREFIX_K, "" );
if( boost::iequals( frmt, GNUPLOT_K ) ) {
assert( params.get_child_optional( INPUT_K ) != boost::none );
assert( params.get_child_optional( KEYS_K ) != boost::none );
std::vector< string > keys;
BOOST_FOREACH( auto& v, params.get_child( KEYS_K ) ) {
std::ostringstream oss;
oss << v.second.data();
keys.push_back( oss.str() );
}
BOOST_FOREACH( auto& v, params.get_child( INPUT_K ) ) {
std::ostringstream oss;
oss << v.second.data();
string path = oss.str();
typedef std::vector< string > row_type;
typedef std::map< string, std::vector< row_type > > value_map_type;
value_map_type data;
if( boost::algorithm::iends_with(path, "." + JSON_K) ) {
std::cerr << "Parsing input JSON file: " << path << std::endl;
string tmp_path = path.substr(0, path.size() - (JSON_K.size() + 1));
boost::property_tree::ptree infile;
boost::property_tree::read_json( path, infile );
BOOST_FOREACH( auto& k, keys ) {
if( infile.get_child_optional( k ) != boost::none ) {
// string tmp = tmp_path + "." + k;
value_map_type::iterator it = data.find( k );
if( it == data.end() ) {
std::pair< value_map_type::iterator, bool > res = data.insert( std::make_pair(k, std::vector<row_type>() ));
assert( res.second );
it = res.first;
}
unsigned int max_columns = 0;
unsigned int j = 0;
BOOST_FOREACH( auto& dval, infile.get_child(k) ) {
unsigned int i = 0;
row_type r;
BOOST_FOREACH( auto& pval, dval.second ) {
std::ostringstream oss;
oss << pval.second.data();
r.push_back( oss.str() );
++i;
}
if( i > max_columns ) { max_columns = i; }
it->second.push_back(r);
++j;
}
}
}
}
if( output.empty() ) {
BOOST_FOREACH( auto& dval, data) {
std::cout << "# " << dval.first << std::endl;
unsigned int i = 0;
BOOST_FOREACH( auto& r, dval.second ) {
std::cout << i++;
BOOST_FOREACH( auto& c, r ) {
std::cout << "," << c;
}
std::cout << std::endl;
}
std::cout << std::endl;
}
}
}
}
}
void combine_op( boost::property_tree::ptree & params ) {
assert( params.get_child_optional( OUTPUT_FORMAT_K ) != boost::none );
string frmt = params.get< string >( OUTPUT_FORMAT_K, "" );
string output = params.get< string >( OUTPUT_PREFIX_K, "" );
if( boost::iequals( frmt, JSON_K ) ) {
boost::property_tree::ptree results;
assert( params.get_child_optional( INPUT_K ) != boost::none );
assert( params.get_child_optional( KEYS_K ) != boost::none );
std::vector< string > keys;
BOOST_FOREACH( auto& v, params.get_child( KEYS_K ) ) {
std::ostringstream oss;
oss << v.second.data();
keys.push_back( oss.str() );
}
BOOST_FOREACH( auto& v, params.get_child( INPUT_K ) ) {
std::ostringstream oss;
oss << v.second.data();
string path = oss.str();
if( boost::algorithm::iends_with(path, "." + JSON_K) ) {
std::cerr << "Parsing input JSON file: " << path << std::endl;
string tmp_path = path.substr(0, path.size() - (JSON_K.size() + 1));
boost::property_tree::ptree infile;
boost::property_tree::read_json( path, infile );
BOOST_FOREACH( auto& k, keys ) {
if( infile.get_child_optional( k ) != boost::none ) {
string tmp = tmp_path + "." + k;
results.add_child( tmp, infile.get_child( k ) );
}
}
}
}
}
}*/
void write_json( const string & path, boost::property_tree::ptree & results ) {
if( path.empty() ) {
boost::property_tree::write_json( std::cout, results );
} else {
boost::property_tree::write_json( path + "." + JSON_K, results );
}
}
/*
void write( ostream * out, boost::property_tree::ptree::value_type & node ) {
if( node.first.empty() ) {
(*out) << "\n";
BOOST_FOREACH( auto & pval, node.second ) {
std::ostringstream oss;
oss << pval.second.data();
(*out) << oss.str() << ",";
}
} else {
(*out) << "." << node.first;
BOOST_FOREACH( auto& c, node.second ) {
write( out, c );
(*out) << "\n";
}
}
}*/
void write_data( ostream * out, boost::property_tree::ptree & data ) {
unsigned int i = 0;
if( data.empty() ) {
//(*out) << i << "," << data.data() << "\n";
(*out) << "," << data.data();
} else {
BOOST_FOREACH( auto& c, data ) {
if( c.second.empty() ) {
(*out) << "," << c.second.data();
} else {
(*out) << ++i;
write_data( out, c.second);
(*out) << "\n";
}
}
}
}
void write( ostream * out, string path, boost::property_tree::ptree & tr ) {
unsigned int i = 0;
if( tr.empty() ) {
(*out) << ++i << "," << tr.data() << "\n";
} else {
BOOST_FOREACH( auto& c, tr ) {
if( c.first.empty() ) {
(*out) << ++i;
write_data(out, c.second);
(*out) << "\n";
} else {
write( out, path + "." + c.first, c.second );
}
}
}
}
void write_gnuplot( const string & path, const string & header, boost::property_tree::ptree & results ) {
ostream * out;
if( path.empty() ) {
out = &std::cout;
} else {
out = new ofstream(path + ".dat");
}
(*out) << "# " << header << "\n";
write(out, "", results );
if( out != &std::cout ) {
((ofstream *)out)->close();
}
}
|
// ========================================================================== //
// This file is part of Sara, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2018 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
//! @example
#include <set>
#include <DO/Sara/Graphics.hpp>
#include <DO/Sara/ImageIO.hpp>
#include <DO/Sara/ImageProcessing.hpp>
#include <DO/Sara/VideoIO.hpp>
#include <DO/Sara/Geometry/Algorithms/RobustEstimation/LineSolver.hpp>
#include <DO/Sara/Geometry/Algorithms/RobustEstimation/RANSAC.hpp>
#include <DO/Sara/Geometry/Objects/LineSegment.hpp>
using namespace std;
using namespace DO::Sara;
auto to_map(const std::map<int, std::vector<Eigen::Vector2i>>& contours,
const Eigen::Vector2i& image_sizes)
{
auto labeled_edges = Image<int>{image_sizes};
labeled_edges.flat_array().fill(-1);
for (const auto& [label, points] : contours)
{
for (const auto& p : points)
labeled_edges(p) = label;
}
return labeled_edges;
}
auto random_colors(const std::map<int, std::vector<Eigen::Vector2i>>& contours)
{
auto colors = std::map<int, Rgb8>{};
for (const auto& c : contours)
colors[c.first] = Rgb8(rand() % 255, rand() % 255, rand() % 255);
return colors;
}
auto fit_line(const std::vector<Eigen::Vector2i>& curve_points,
float error_threshold = 1.5f) -> std::tuple<bool, LineSegment>
{
enum class Axis : std::uint8_t
{
X = 0,
Y = 1
};
if (curve_points.size() < 2)
return {false, {}};
auto line_solver = LineSolver2D<float>{};
auto inlier_predicate = InlierPredicate<LinePointDistance2D<float>>{
.distance = {}, //
.error_threshold = error_threshold //
};
auto points = Tensor_<float, 2>(curve_points.size(), 3);
auto point_matrix = points.matrix();
for (auto r = 0u; r < curve_points.size(); ++r)
point_matrix.row(r) = curve_points[r] //
.transpose() //
.homogeneous() //
.cast<float>(); //
const auto num_iterations = std::clamp( //
static_cast<int>(curve_points.size() * 0.20) + 1, //
5, 20);
const auto [line, inliers, subset_best] = ransac(points, //
line_solver, //
inlier_predicate, //
num_iterations);
const Eigen::Vector2f t = Projective::tangent(line).cwiseAbs();
const auto fast_axis = t.x() > t.y() ? Axis::X : Axis::Y;
const auto first_inlier = std::find(inliers.begin(), inliers.end(), 1);
if (first_inlier == inliers.end())
return {false, LineSegment{}};
auto i = std::size_t(first_inlier - inliers.begin());
auto tl = Eigen::Vector2f{};
auto br = Eigen::Vector2f{};
tl = br = point_matrix.row(i).transpose();
for (++i; i < inliers.size(); ++i)
{
if (!inliers(i))
continue;
if (fast_axis == Axis::X)
{
if (tl.x() > point_matrix(i, 0))
tl = point_matrix.row(i).hnormalized().transpose();
if (br.x() < point_matrix(i, 0))
br = point_matrix.row(i).hnormalized().transpose();
}
else
{
if (tl.y() > point_matrix(i, 1))
tl = point_matrix.row(i).hnormalized().transpose();
if (br.y() < point_matrix(i, 1))
br = point_matrix.row(i).hnormalized().transpose();
}
}
return {true, {tl.cast<double>(), br.cast<double>()}};
}
auto test_on_image()
{
// Read an image.
const auto image =
imread<float>(src_path("../../../../data/sunflowerField.jpg"));
auto sigma = sqrt(pow(1.6f, 2) - pow(0.5f, 2));
auto image_curr = deriche_blur(image, sigma);
constexpr auto high_threshold_ratio = 5e-2f;
constexpr auto low_threshold_ratio = 2e-2f;
constexpr auto angular_threshold = 20. / 180.f * M_PI;
create_window(image.sizes());
display(image_curr);
for (auto s = 0; s < 500; ++s)
{
// Blur.
const auto grad = gradient(image_curr);
const auto grad_mag = grad.cwise_transform( //
[](const auto& v) { return v.norm(); });
const auto grad_ori = grad.cwise_transform(
[](const auto& v) { return std::atan2(v.y(), v.x()); });
// Canny.
const auto& grad_mag_max = grad_mag.flat_array().maxCoeff();
const auto& high_thres = grad_mag_max * high_threshold_ratio;
const auto& low_thres = grad_mag_max * low_threshold_ratio;
auto edges = suppress_non_maximum_edgels(grad_mag, grad_ori, //
high_thres, low_thres);
hysteresis(edges);
// Extract quasi-straight curve.
const auto curves = connected_components(edges, grad_ori, angular_threshold);
const auto labeled_curves = to_map(curves, edges.sizes());
const auto curve_colors = random_colors(curves);
// Fit a line to each curve.
auto line_segments = std::map<int, LineSegment>{};
for (const auto& [curve_id, curve_points] : curves)
{
if (curve_points.size() < 5)
continue;
const auto [success, line_segment] = fit_line(curve_points);
if (success)
line_segments[curve_id] = line_segment;
}
// Display the fitted lines.
fill_rect(0, 0, image_curr.width(), image_curr.height(), Black8);
for (const auto& [curve_id, line]: line_segments)
draw_line(line.p1(), line.p2(), curve_colors.at(curve_id), 2);
millisleep(1);
const auto delta = std::pow(2., 1. / 100.);
const auto sigma = 1.6 * sqrt(pow(delta, 2 * s + 2) - pow(delta, 2 * s));
image_curr = deriche_blur(image_curr, sigma);
}
get_key();
}
auto test_on_video()
{
using namespace std::string_literals;
#ifdef _WIN32
const auto video_filepath =
"C:/Users/David/Desktop/david-archives/gopro-backup-2/GOPR0542.MP4"s;
#elif __APPLE__
// const auto video_filepath = "/Users/david/Desktop/Datasets/sfm/Family.mp4"s;
const auto video_filepath =
//"/Users/david/Desktop/Datasets/videos/sample1.mp4"s;
"/Users/david/Desktop/Datasets/videos/sample4.mp4"s;
// //"/Users/david/Desktop/Datasets/videos/sample10.mp4"s;
#else
const auto video_filepath = "/home/david/Desktop/Datasets/sfm/Family.mp4"s;
#endif
// Input and output from Sara.
VideoStream video_stream(video_filepath);
auto frame = video_stream.frame();
auto frame_gray32f = Image<float>{frame.sizes()};
// Show the local extrema.
create_window(frame.sizes());
set_antialiasing();
constexpr auto high_threshold_ratio = 5e-2f;
constexpr auto low_threshold_ratio = 2e-2f;
constexpr auto angular_threshold = 20. / 180.f * M_PI;
auto frames_read = 0;
const auto skip = 2;
while (true)
{
if (!video_stream.read())
{
std::cout << "Reached the end of the video!" << std::endl;
break;
}
++frames_read;
if (frames_read % (skip + 1) != 0)
continue;
frame_gray32f = frame.convert<float>();
// Blur.
inplace_deriche_blur(frame_gray32f, std::sqrt(std::pow(1.6f, 2) - 1));
// Canny.
const auto& grad = gradient(frame_gray32f);
const auto& grad_mag = grad.cwise_transform( //
[](const auto& v) { return v.norm(); });
const auto& grad_ori = grad.cwise_transform(
[](const auto& v) { return std::atan2(v.y(), v.x()); });
const auto& grad_mag_max = grad_mag.flat_array().maxCoeff();
const auto& high_thres = grad_mag_max * high_threshold_ratio;
const auto& low_thres = grad_mag_max * low_threshold_ratio;
auto edges = suppress_non_maximum_edgels(grad_mag, grad_ori, //
high_thres, low_thres);
hysteresis(edges);
// Extract quasi-straight curve.
const auto curves = connected_components(edges, grad_ori, angular_threshold);
const auto labeled_curves = to_map(curves, edges.sizes());
const auto curve_colors = random_colors(curves);
// Fit a line to each curve.
auto line_segments = std::map<int, LineSegment>{};
for (const auto& [curve_id, curve_points] : curves)
{
if (curve_points.size() < 5)
continue;
const auto [success, line_segment] = fit_line(curve_points);
if (success)
line_segments[curve_id] = line_segment;
}
// Display the fitted lines.
fill_rect(0, 0, frame.width(), frame.height(), Black8);
for (const auto& [curve_id, line]: line_segments)
draw_line(line.p1(), line.p2(), curve_colors.at(curve_id), 2);
}
}
GRAPHICS_MAIN()
{
// test_on_image();
test_on_video();
return 0;
}
MAINT: clean up results.
// ========================================================================== //
// This file is part of Sara, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2018 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
//! @example
#include <set>
#include <DO/Sara/Graphics.hpp>
#include <DO/Sara/ImageIO.hpp>
#include <DO/Sara/ImageProcessing.hpp>
#include <DO/Sara/VideoIO.hpp>
#include <DO/Sara/Geometry/Algorithms/RobustEstimation/LineSolver.hpp>
#include <DO/Sara/Geometry/Algorithms/RobustEstimation/RANSAC.hpp>
#include <DO/Sara/Geometry/Objects/LineSegment.hpp>
using namespace std;
using namespace DO::Sara;
auto to_map(const std::map<int, std::vector<Eigen::Vector2i>>& contours,
const Eigen::Vector2i& image_sizes)
{
auto labeled_edges = Image<int>{image_sizes};
labeled_edges.flat_array().fill(-1);
for (const auto& [label, points] : contours)
{
for (const auto& p : points)
labeled_edges(p) = label;
}
return labeled_edges;
}
auto random_colors(const std::map<int, std::vector<Eigen::Vector2i>>& contours)
{
auto colors = std::map<int, Rgb8>{};
for (const auto& c : contours)
colors[c.first] = Rgb8(rand() % 255, rand() % 255, rand() % 255);
return colors;
}
auto fit_line(const std::vector<Eigen::Vector2i>& curve_points,
float error_threshold = 1.5f) -> std::tuple<bool, LineSegment>
{
enum class Axis : std::uint8_t
{
X = 0,
Y = 1
};
if (curve_points.size() < 2)
return {false, {}};
auto line_solver = LineSolver2D<float>{};
auto inlier_predicate = InlierPredicate<LinePointDistance2D<float>>{
.distance = {}, //
.error_threshold = error_threshold //
};
auto points = Tensor_<float, 2>(curve_points.size(), 3);
auto point_matrix = points.matrix();
for (auto r = 0u; r < curve_points.size(); ++r)
point_matrix.row(r) = curve_points[r] //
.transpose() //
.homogeneous() //
.cast<float>(); //
const auto num_iterations = std::clamp( //
static_cast<int>(curve_points.size() * 0.20) + 1, //
5, 20);
const auto [line, inliers, subset_best] = ransac(points, //
line_solver, //
inlier_predicate, //
num_iterations);
if (inliers.flat_array().count() < 0.50 * curve_points.size())
return {false, {}};
const Eigen::Vector2f t = Projective::tangent(line).cwiseAbs();
const auto fast_axis = t.x() > t.y() ? Axis::X : Axis::Y;
const auto first_inlier = std::find(inliers.begin(), inliers.end(), 1);
if (first_inlier == inliers.end())
return {false, LineSegment{}};
auto i = std::size_t(first_inlier - inliers.begin());
auto tl = Eigen::Vector2f{};
auto br = Eigen::Vector2f{};
tl = br = point_matrix.row(i).transpose();
for (++i; i < inliers.size(); ++i)
{
if (!inliers(i))
continue;
if (fast_axis == Axis::X)
{
if (tl.x() > point_matrix(i, 0))
tl = point_matrix.row(i).hnormalized().transpose();
if (br.x() < point_matrix(i, 0))
br = point_matrix.row(i).hnormalized().transpose();
}
else
{
if (tl.y() > point_matrix(i, 1))
tl = point_matrix.row(i).hnormalized().transpose();
if (br.y() < point_matrix(i, 1))
br = point_matrix.row(i).hnormalized().transpose();
}
}
return {true, {tl.cast<double>(), br.cast<double>()}};
}
auto test_on_image()
{
// Read an image.
const auto image =
imread<float>(src_path("../../../../data/sunflowerField.jpg"));
auto sigma = sqrt(pow(1.6f, 2) - pow(0.5f, 2));
auto image_curr = deriche_blur(image, sigma);
constexpr auto high_threshold_ratio = 5e-2f;
constexpr auto low_threshold_ratio = 2e-2f;
constexpr auto angular_threshold = 20. / 180.f * M_PI;
create_window(image.sizes());
display(image_curr);
for (auto s = 0; s < 500; ++s)
{
// Blur.
const auto grad = gradient(image_curr);
const auto grad_mag = grad.cwise_transform( //
[](const auto& v) { return v.norm(); });
const auto grad_ori = grad.cwise_transform(
[](const auto& v) { return std::atan2(v.y(), v.x()); });
// Canny.
const auto& grad_mag_max = grad_mag.flat_array().maxCoeff();
const auto& high_thres = grad_mag_max * high_threshold_ratio;
const auto& low_thres = grad_mag_max * low_threshold_ratio;
auto edges = suppress_non_maximum_edgels(grad_mag, grad_ori, //
high_thres, low_thres);
hysteresis(edges);
// Extract quasi-straight curve.
const auto curves = connected_components(edges, grad_ori, angular_threshold);
const auto labeled_curves = to_map(curves, edges.sizes());
const auto curve_colors = random_colors(curves);
// Fit a line to each curve.
auto line_segments = std::map<int, LineSegment>{};
for (const auto& [curve_id, curve_points] : curves)
{
if (curve_points.size() < 5)
continue;
const auto [success, line_segment] = fit_line(curve_points);
if (success)
line_segments[curve_id] = line_segment;
}
// Display the fitted lines.
fill_rect(0, 0, image_curr.width(), image_curr.height(), Black8);
for (const auto& [curve_id, line]: line_segments)
draw_line(line.p1(), line.p2(), curve_colors.at(curve_id), 2);
millisleep(1);
const auto delta = std::pow(2., 1. / 100.);
const auto sigma = 1.6 * sqrt(pow(delta, 2 * s + 2) - pow(delta, 2 * s));
image_curr = deriche_blur(image_curr, sigma);
}
get_key();
}
auto test_on_video()
{
using namespace std::string_literals;
#ifdef _WIN32
const auto video_filepath =
"C:/Users/David/Desktop/david-archives/gopro-backup-2/GOPR0542.MP4"s;
#elif __APPLE__
// const auto video_filepath = "/Users/david/Desktop/Datasets/sfm/Family.mp4"s;
const auto video_filepath =
//"/Users/david/Desktop/Datasets/videos/sample1.mp4"s;
"/Users/david/Desktop/Datasets/videos/sample4.mp4"s;
// //"/Users/david/Desktop/Datasets/videos/sample10.mp4"s;
#else
const auto video_filepath = "/home/david/Desktop/Datasets/sfm/Family.mp4"s;
#endif
// Input and output from Sara.
VideoStream video_stream(video_filepath);
auto frame = video_stream.frame();
auto frame_gray32f = Image<float>{frame.sizes()};
// Show the local extrema.
create_window(frame.sizes());
set_antialiasing();
constexpr auto high_threshold_ratio = 5e-2f;
constexpr auto low_threshold_ratio = 2e-2f;
constexpr auto angular_threshold = 20. / 180.f * M_PI;
auto frames_read = 0;
const auto skip = 2;
while (true)
{
if (!video_stream.read())
{
std::cout << "Reached the end of the video!" << std::endl;
break;
}
++frames_read;
if (frames_read % (skip + 1) != 0)
continue;
frame_gray32f = frame.convert<float>();
// Blur.
inplace_deriche_blur(frame_gray32f, std::sqrt(std::pow(1.6f, 2) - 1));
// Canny.
const auto& grad = gradient(frame_gray32f);
const auto& grad_mag = grad.cwise_transform( //
[](const auto& v) { return v.norm(); });
const auto& grad_ori = grad.cwise_transform(
[](const auto& v) { return std::atan2(v.y(), v.x()); });
const auto& grad_mag_max = grad_mag.flat_array().maxCoeff();
const auto& high_thres = grad_mag_max * high_threshold_ratio;
const auto& low_thres = grad_mag_max * low_threshold_ratio;
auto edges = suppress_non_maximum_edgels(grad_mag, grad_ori, //
high_thres, low_thres);
hysteresis(edges);
// Extract quasi-straight curve.
const auto curves = connected_components(edges, grad_ori, angular_threshold);
const auto labeled_curves = to_map(curves, edges.sizes());
const auto curve_colors = random_colors(curves);
// Fit a line to each curve.
auto line_segments = std::map<int, LineSegment>{};
for (const auto& [curve_id, curve_points] : curves)
{
if (curve_points.size() < 5)
continue;
const auto [success, line_segment] = fit_line(curve_points);
if (success)
line_segments[curve_id] = line_segment;
}
// Display the fitted lines.
fill_rect(0, 0, frame.width(), frame.height(), Black8);
for (const auto& [curve_id, line]: line_segments)
draw_line(line.p1(), line.p2(), curve_colors.at(curve_id), 2);
}
}
GRAPHICS_MAIN()
{
// test_on_image();
test_on_video();
return 0;
}
|
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <qtextstream.h>
#include <QtNetwork/qlocalsocket.h>
#include <QtNetwork/qlocalserver.h>
#include "../../shared/util.h"
#ifdef Q_OS_SYMBIAN
#include <unistd.h>
#endif
//TESTED_CLASS=QLocalServer, QLocalSocket
//TESTED_FILES=network/socket/qlocalserver.cpp network/socket/qlocalsocket.cpp
#ifdef Q_OS_SYMBIAN
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define SRCDIR "C:/Private/" TOSTRING(SYMBIAN_SRCDIR_UID) "/"
#endif
Q_DECLARE_METATYPE(QLocalSocket::LocalSocketError)
Q_DECLARE_METATYPE(QLocalSocket::LocalSocketState)
class tst_QLocalSocket : public QObject
{
Q_OBJECT
public:
tst_QLocalSocket();
virtual ~tst_QLocalSocket();
public Q_SLOTS:
void init();
void cleanup();
private slots:
// basics
void server_basic();
void server_connectionsCount();
void socket_basic();
void listen_data();
void listen();
void listenAndConnect_data();
void listenAndConnect();
void sendData_data();
void sendData();
void fullPath();
void hitMaximumConnections_data();
void hitMaximumConnections();
void setSocketDescriptor();
void threadedConnection_data();
void threadedConnection();
void processConnection_data();
void processConnection();
void longPath();
void waitForDisconnect();
void removeServer();
void recycleServer();
void debug();
#ifdef Q_OS_SYMBIAN
private:
void unlink(QString serverName);
#endif
};
tst_QLocalSocket::tst_QLocalSocket()
{
if (!QFile::exists("lackey/lackey"
#ifdef Q_OS_WIN
".exe"
#endif
))
qWarning() << "lackey executable doesn't exists!";
}
tst_QLocalSocket::~tst_QLocalSocket()
{
}
void tst_QLocalSocket::init()
{
qRegisterMetaType<QLocalSocket::LocalSocketState>("QLocalSocket::LocalSocketState");
qRegisterMetaType<QLocalSocket::LocalSocketError>("QLocalSocket::LocalSocketError");
}
void tst_QLocalSocket::cleanup()
{
}
class LocalServer : public QLocalServer
{
Q_OBJECT
public:
LocalServer() : QLocalServer()
{
connect(this, SIGNAL(newConnection()), this, SLOT(slotNewConnection()));
};
QList<int> hits;
protected:
void incomingConnection(quintptr socketDescriptor)
{
hits.append(socketDescriptor);
QLocalServer::incomingConnection(socketDescriptor);
}
private slots:
void slotNewConnection() {
QVERIFY(!hits.isEmpty());
QVERIFY(hasPendingConnections());
}
};
class LocalSocket : public QLocalSocket
{
Q_OBJECT
public:
LocalSocket(QObject *parent = 0) : QLocalSocket(parent)
{
connect(this, SIGNAL(connected()),
this, SLOT(slotConnected()));
connect(this, SIGNAL(disconnected()),
this, SLOT(slotDisconnected()));
connect(this, SIGNAL(error(QLocalSocket::LocalSocketError)),
this, SLOT(slotError(QLocalSocket::LocalSocketError)));
connect(this, SIGNAL(stateChanged(QLocalSocket::LocalSocketState)),
this, SLOT(slotStateChanged(QLocalSocket::LocalSocketState)));
connect(this, SIGNAL(readyRead()),
this, SLOT(slotReadyRead()));
}
private slots:
void slotConnected()
{
QCOMPARE(state(), QLocalSocket::ConnectedState);
}
void slotDisconnected()
{
QCOMPARE(state(), QLocalSocket::UnconnectedState);
}
void slotError(QLocalSocket::LocalSocketError newError)
{
QVERIFY(errorString() != "Unknown error");
QCOMPARE(error(), newError);
}
void slotStateChanged(QLocalSocket::LocalSocketState newState)
{
QCOMPARE(state(), newState);
}
void slotReadyRead()
{
QVERIFY(bytesAvailable() > 0);
}
};
// basic test make sure no segfaults and check default values
void tst_QLocalSocket::server_basic()
{
LocalServer server;
QSignalSpy spyNewConnection(&server, SIGNAL(newConnection()));
server.close();
QCOMPARE(server.errorString(), QString());
QCOMPARE(server.hasPendingConnections(), false);
QCOMPARE(server.isListening(), false);
QCOMPARE(server.maxPendingConnections(), 30);
QCOMPARE(server.nextPendingConnection(), (QLocalSocket*)0);
QCOMPARE(server.serverName(), QString());
QCOMPARE(server.fullServerName(), QString());
QCOMPARE(server.serverError(), QAbstractSocket::UnknownSocketError);
server.setMaxPendingConnections(20);
bool timedOut = true;
QCOMPARE(server.waitForNewConnection(3000, &timedOut), false);
QVERIFY(!timedOut);
QCOMPARE(server.listen(QString()), false);
QCOMPARE(server.hits.count(), 0);
QCOMPARE(spyNewConnection.count(), 0);
}
void tst_QLocalSocket::server_connectionsCount()
{
LocalServer server;
server.setMaxPendingConnections(10);
QCOMPARE(server.maxPendingConnections(), 10);
}
// basic test make sure no segfaults and check default values
void tst_QLocalSocket::socket_basic()
{
LocalSocket socket;
QSignalSpy spyConnected(&socket, SIGNAL(connected()));
QSignalSpy spyDisconnected(&socket, SIGNAL(disconnected()));
QSignalSpy spyError(&socket, SIGNAL(error(QLocalSocket::LocalSocketError)));
QSignalSpy spyStateChanged(&socket, SIGNAL(stateChanged(QLocalSocket::LocalSocketState)));
QSignalSpy spyReadyRead(&socket, SIGNAL(readyRead()));
QCOMPARE(socket.serverName(), QString());
QCOMPARE(socket.fullServerName(), QString());
socket.abort();
QVERIFY(socket.bytesAvailable() == 0);
QVERIFY(socket.bytesToWrite() == 0);
QCOMPARE(socket.canReadLine(), false);
socket.close();
socket.disconnectFromServer();
QCOMPARE(QLocalSocket::UnknownSocketError, socket.error());
QVERIFY(socket.errorString() != QString());
QCOMPARE(socket.flush(), false);
QCOMPARE(socket.isValid(), false);
QVERIFY(socket.readBufferSize() == 0);
socket.setReadBufferSize(0);
//QCOMPARE(socket.socketDescriptor(), -1);
QCOMPARE(socket.state(), QLocalSocket::UnconnectedState);
QCOMPARE(socket.waitForConnected(0), false);
QCOMPARE(socket.waitForDisconnected(0), false);
QCOMPARE(socket.waitForReadyRead(0), false);
QCOMPARE(spyConnected.count(), 0);
QCOMPARE(spyDisconnected.count(), 0);
QCOMPARE(spyError.count(), 0);
QCOMPARE(spyStateChanged.count(), 0);
QCOMPARE(spyReadyRead.count(), 0);
}
void tst_QLocalSocket::listen_data()
{
QTest::addColumn<QString>("name");
QTest::addColumn<bool>("canListen");
QTest::addColumn<bool>("close");
QTest::newRow("null") << QString() << false << false;
QTest::newRow("tst_localsocket") << "tst_localsocket" << true << true;
QTest::newRow("tst_localsocket") << "tst_localsocket" << true << false;
}
// start a server that listens, but don't connect a socket, make sure everything is in order
void tst_QLocalSocket::listen()
{
LocalServer server;
QSignalSpy spyNewConnection(&server, SIGNAL(newConnection()));
QFETCH(QString, name);
#ifdef Q_OS_SYMBIAN
unlink(name);
#endif
QFETCH(bool, canListen);
QFETCH(bool, close);
QVERIFY2((server.listen(name) == canListen), server.errorString().toLatin1().constData());
// test listening
QCOMPARE(server.serverName(), name);
QVERIFY(server.fullServerName().contains(name));
QCOMPARE(server.isListening(), canListen);
QCOMPARE(server.hasPendingConnections(), false);
QCOMPARE(server.nextPendingConnection(), (QLocalSocket*)0);
QCOMPARE(server.hits.count(), 0);
QCOMPARE(spyNewConnection.count(), 0);
if (canListen) {
QVERIFY(server.errorString() == QString());
QCOMPARE(server.serverError(), QAbstractSocket::UnknownSocketError);
// already isListening
QVERIFY(!server.listen(name));
} else {
QVERIFY(server.errorString() != QString());
QCOMPARE(server.serverError(), QAbstractSocket::HostNotFoundError);
}
QCOMPARE(server.maxPendingConnections(), 30);
bool timedOut = false;
QCOMPARE(server.waitForNewConnection(3000, &timedOut), false);
QCOMPARE(timedOut, canListen);
if (close)
server.close();
}
void tst_QLocalSocket::listenAndConnect_data()
{
QTest::addColumn<QString>("name");
QTest::addColumn<bool>("canListen");
QTest::addColumn<int>("connections");
for (int i = 0; i < 3; ++i) {
int connections = i;
if (i == 2)
connections = 5;
QTest::newRow(QString("null %1").arg(i).toLatin1()) << QString() << false << connections;
QTest::newRow(QString("tst_localsocket %1").arg(i).toLatin1()) << "tst_localsocket" << true << connections;
}
}
void tst_QLocalSocket::listenAndConnect()
{
LocalServer server;
QSignalSpy spyNewConnection(&server, SIGNAL(newConnection()));
QFETCH(QString, name);
QFETCH(bool, canListen);
#ifdef Q_OS_SYMBIAN
unlink(name);
#endif
QCOMPARE(server.listen(name), canListen);
QTest::qWait(1000);
//QVERIFY(!server.errorString().isEmpty());
QCOMPARE(server.serverError(),
canListen ? QAbstractSocket::UnknownSocketError : QAbstractSocket::HostNotFoundError);
// test creating connection(s)
QFETCH(int, connections);
QList<QLocalSocket*> sockets;
for (int i = 0; i < connections; ++i) {
LocalSocket *socket = new LocalSocket;
QSignalSpy spyConnected(socket, SIGNAL(connected()));
QSignalSpy spyDisconnected(socket, SIGNAL(disconnected()));
QSignalSpy spyError(socket, SIGNAL(error(QLocalSocket::LocalSocketError)));
QSignalSpy spyStateChanged(socket, SIGNAL(stateChanged(QLocalSocket::LocalSocketState)));
QSignalSpy spyReadyRead(socket, SIGNAL(readyRead()));
socket->connectToServer(name);
#if defined(QT_LOCALSOCKET_TCP) || defined (Q_OS_SYMBIAN)
QTest::qWait(250);
#endif
QCOMPARE(socket->serverName(), name);
QVERIFY(socket->fullServerName().contains(name));
sockets.append(socket);
if (canListen) {
QCOMPARE(socket->errorString(), QString("Unknown error"));
QCOMPARE(socket->error(), QLocalSocket::UnknownSocketError);
QCOMPARE(socket->state(), QLocalSocket::ConnectedState);
//QVERIFY(socket->socketDescriptor() != -1);
QCOMPARE(spyError.count(), 0);
} else {
QVERIFY(socket->errorString() != QString());
QVERIFY(socket->error() != QLocalSocket::UnknownSocketError);
QCOMPARE(socket->state(), QLocalSocket::UnconnectedState);
//QVERIFY(socket->socketDescriptor() == -1);
QCOMPARE(qVariantValue<QLocalSocket::LocalSocketError>(spyError.first()[0]),
QLocalSocket::ServerNotFoundError);
}
QVERIFY(socket->bytesAvailable() == 0);
QVERIFY(socket->bytesToWrite() == 0);
QCOMPARE(socket->canReadLine(), false);
QCOMPARE(socket->flush(), false);
QCOMPARE(socket->isValid(), canListen);
QCOMPARE(socket->readBufferSize(), (qint64)0);
QCOMPARE(socket->waitForConnected(0), canListen);
QCOMPARE(socket->waitForReadyRead(0), false);
QTRY_COMPARE(spyConnected.count(), canListen ? 1 : 0);
QCOMPARE(spyDisconnected.count(), 0);
// error signals
QVERIFY(spyError.count() >= 0);
if (canListen) {
if (spyError.count() > 0)
QCOMPARE(qVariantValue<QLocalSocket::LocalSocketError>(spyError.first()[0]),
QLocalSocket::SocketTimeoutError);
} else {
QCOMPARE(qVariantValue<QLocalSocket::LocalSocketError>(spyError.first()[0]),
QLocalSocket::ServerNotFoundError);
}
// Check first and last state
QCOMPARE(qVariantValue<QLocalSocket::LocalSocketState>(spyStateChanged.first()[0]),
QLocalSocket::ConnectingState);
#if 0
for (int j = 0; j < spyStateChanged.count(); ++j) {
QLocalSocket::LocalSocketState s;
s = qVariantValue<QLocalSocket::LocalSocketState>(spyStateChanged.at(j).at(0));
qDebug() << s;
}
#endif
if (canListen)
QCOMPARE(qVariantValue<QLocalSocket::LocalSocketState>(spyStateChanged.last()[0]),
QLocalSocket::ConnectedState);
QCOMPARE(spyStateChanged.count(), 2);
QCOMPARE(spyReadyRead.count(), 0);
bool timedOut = true;
QCOMPARE(server.waitForNewConnection(3000, &timedOut), canListen);
QVERIFY(!timedOut);
QCOMPARE(server.hasPendingConnections(), canListen);
QCOMPARE(server.isListening(), canListen);
// NOTE: socket disconnecting is not tested here
// server checks post connection
if (canListen) {
QCOMPARE(server.serverName(), name);
QVERIFY(server.fullServerName().contains(name));
QVERIFY(server.nextPendingConnection() != (QLocalSocket*)0);
QTRY_COMPARE(server.hits.count(), i + 1);
QCOMPARE(spyNewConnection.count(), i + 1);
QVERIFY(server.errorString() == QString());
QCOMPARE(server.serverError(), QAbstractSocket::UnknownSocketError);
} else {
QVERIFY(server.serverName().isEmpty());
QVERIFY(server.fullServerName().isEmpty());
QVERIFY(server.nextPendingConnection() == (QLocalSocket*)0);
QCOMPARE(spyNewConnection.count(), 0);
QCOMPARE(server.hits.count(), 0);
QVERIFY(server.errorString() != QString());
QCOMPARE(server.serverError(), QAbstractSocket::HostNotFoundError);
}
}
qDeleteAll(sockets.begin(), sockets.end());
server.close();
QCOMPARE(server.hits.count(), (canListen ? connections : 0));
QCOMPARE(spyNewConnection.count(), (canListen ? connections : 0));
}
void tst_QLocalSocket::sendData_data()
{
listenAndConnect_data();
}
void tst_QLocalSocket::sendData()
{
QFETCH(QString, name);
#ifdef Q_OS_SYMBIAN
unlink(name);
#endif
QFETCH(bool, canListen);
LocalServer server;
QSignalSpy spy(&server, SIGNAL(newConnection()));
QCOMPARE(server.listen(name), canListen);
LocalSocket socket;
QSignalSpy spyConnected(&socket, SIGNAL(connected()));
QSignalSpy spyDisconnected(&socket, SIGNAL(disconnected()));
QSignalSpy spyError(&socket, SIGNAL(error(QLocalSocket::LocalSocketError)));
QSignalSpy spyStateChanged(&socket, SIGNAL(stateChanged(QLocalSocket::LocalSocketState)));
QSignalSpy spyReadyRead(&socket, SIGNAL(readyRead()));
// test creating a connection
socket.connectToServer(name);
bool timedOut = true;
QCOMPARE(server.waitForNewConnection(3000, &timedOut), canListen);
#if defined(QT_LOCALSOCKET_TCP) || defined(Q_OS_SYMBIAN)
QTest::qWait(250);
#endif
QVERIFY(!timedOut);
QCOMPARE(spyConnected.count(), canListen ? 1 : 0);
QCOMPARE(socket.state(), canListen ? QLocalSocket::ConnectedState : QLocalSocket::UnconnectedState);
// test sending/receiving data
if (server.hasPendingConnections()) {
QString testLine = "test";
#ifdef Q_OS_SYMBIAN
for (int i = 0; i < 25 * 1024; ++i)
#else
for (int i = 0; i < 50000; ++i)
#endif
testLine += "a";
QLocalSocket *serverSocket = server.nextPendingConnection();
QVERIFY(serverSocket);
QCOMPARE(serverSocket->state(), QLocalSocket::ConnectedState);
QTextStream out(serverSocket);
QTextStream in(&socket);
out << testLine << endl;
bool wrote = serverSocket->waitForBytesWritten(3000);
if (!socket.canReadLine())
QVERIFY(socket.waitForReadyRead());
QVERIFY(socket.bytesAvailable() >= 0);
QCOMPARE(socket.bytesToWrite(), (qint64)0);
QCOMPARE(socket.flush(), false);
QCOMPARE(socket.isValid(), canListen);
QCOMPARE(socket.readBufferSize(), (qint64)0);
QCOMPARE(spyReadyRead.count(), 1);
QVERIFY(testLine.startsWith(in.readLine()));
QVERIFY(wrote || serverSocket->waitForBytesWritten(1000));
QCOMPARE(serverSocket->errorString(), QString("Unknown error"));
QCOMPARE(socket.errorString(), QString("Unknown error"));
}
socket.disconnectFromServer();
QCOMPARE(spyConnected.count(), canListen ? 1 : 0);
QCOMPARE(spyDisconnected.count(), canListen ? 1 : 0);
QCOMPARE(spyError.count(), canListen ? 0 : 1);
QCOMPARE(spyStateChanged.count(), canListen ? 4 : 2);
QCOMPARE(spyReadyRead.count(), canListen ? 1 : 0);
server.close();
QCOMPARE(server.hits.count(), (canListen ? 1 : 0));
QCOMPARE(spy.count(), (canListen ? 1 : 0));
}
// QLocalSocket/Server can take a name or path, check that it works as expected
void tst_QLocalSocket::fullPath()
{
QLocalServer server;
QString name = "qlocalsocket_pathtest";
#if defined(Q_OS_SYMBIAN)
QString path = "";
#elif defined(QT_LOCALSOCKET_TCP)
QString path = "QLocalServer";
#elif defined(Q_OS_WIN)
QString path = "\\\\.\\pipe\\";
#else
QString path = "/tmp";
#endif
QString serverName = path + '/' + name;
QVERIFY2(server.listen(serverName), server.errorString().toLatin1().constData());
QCOMPARE(server.serverName(), serverName);
QCOMPARE(server.fullServerName(), serverName);
LocalSocket socket;
socket.connectToServer(serverName);
#if defined (Q_OS_SYMBIAN)
QTest::qWait(250);
#endif
QCOMPARE(socket.serverName(), serverName);
QCOMPARE(socket.fullServerName(), serverName);
socket.disconnectFromServer();
#ifdef QT_LOCALSOCKET_TCP
QTest::qWait(250);
#endif
QCOMPARE(socket.serverName(), QString());
QCOMPARE(socket.fullServerName(), QString());
}
void tst_QLocalSocket::hitMaximumConnections_data()
{
QTest::addColumn<int>("max");
QTest::newRow("none") << 0;
QTest::newRow("1") << 1;
QTest::newRow("3") << 3;
}
void tst_QLocalSocket::hitMaximumConnections()
{
QFETCH(int, max);
LocalServer server;
QString name = "tst_localsocket";
#ifdef Q_OS_SYMBIAN
unlink(name);
#endif
server.setMaxPendingConnections(max);
QVERIFY2(server.listen(name), server.errorString().toLatin1().constData());
int connections = server.maxPendingConnections() + 1;
QList<QLocalSocket*> sockets;
for (int i = 0; i < connections; ++i) {
LocalSocket *socket = new LocalSocket;
sockets.append(socket);
socket->connectToServer(name);
}
bool timedOut = true;
QVERIFY(server.waitForNewConnection(3000, &timedOut));
QVERIFY(!timedOut);
QVERIFY(server.hits.count() > 0);
qDeleteAll(sockets.begin(), sockets.end());
}
// check that state and mode are kept
void tst_QLocalSocket::setSocketDescriptor()
{
LocalSocket socket;
quintptr minusOne = -1;
socket.setSocketDescriptor(minusOne, QLocalSocket::ConnectingState, QIODevice::Append);
QCOMPARE(socket.socketDescriptor(), minusOne);
QCOMPARE(socket.state(), QLocalSocket::ConnectingState);
QVERIFY((socket.openMode() & QIODevice::Append) != 0);
}
class Client : public QThread
{
public:
void run()
{
QString testLine = "test";
LocalSocket socket;
QSignalSpy spyReadyRead(&socket, SIGNAL(readyRead()));
int tries = 0;
do {
socket.connectToServer("qlocalsocket_threadtest");
if (socket.error() != QLocalSocket::ServerNotFoundError
&& socket.error() != QLocalSocket::ConnectionRefusedError)
break;
QTest::qWait(100);
++tries;
} while ((socket.error() == QLocalSocket::ServerNotFoundError
|| socket.error() == QLocalSocket::ConnectionRefusedError)
&& tries < 1000);
if (tries == 0 && socket.state() != QLocalSocket::ConnectedState) {
QVERIFY(socket.waitForConnected(3000));
QVERIFY(socket.state() == QLocalSocket::ConnectedState);
}
// We should *not* have this signal yet!
if (tries == 0)
QCOMPARE(spyReadyRead.count(), 0);
socket.waitForReadyRead();
QCOMPARE(spyReadyRead.count(), 1);
QTextStream in(&socket);
QCOMPARE(in.readLine(), testLine);
socket.close();
}
};
class Server : public QThread
{
public:
int clients;
void run()
{
QString testLine = "test";
LocalServer server;
server.setMaxPendingConnections(10);
QVERIFY2(server.listen("qlocalsocket_threadtest"),
server.errorString().toLatin1().constData());
int done = clients;
while (done > 0) {
bool timedOut = true;
QVERIFY(server.waitForNewConnection(3000, &timedOut));
QVERIFY(!timedOut);
QLocalSocket *serverSocket = server.nextPendingConnection();
QVERIFY(serverSocket);
QTextStream out(serverSocket);
out << testLine << endl;
QCOMPARE(serverSocket->state(), QLocalSocket::ConnectedState);
QVERIFY2(serverSocket->waitForBytesWritten(), serverSocket->errorString().toLatin1().constData());
QCOMPARE(serverSocket->errorString(), QString("Unknown error"));
--done;
delete serverSocket;
}
QCOMPARE(server.hits.count(), clients);
}
};
void tst_QLocalSocket::threadedConnection_data()
{
QTest::addColumn<int>("threads");
QTest::newRow("1 client") << 1;
QTest::newRow("2 clients") << 2;
#ifdef Q_OS_WINCE
QTest::newRow("4 clients") << 4;
#endif
#ifndef Q_OS_WIN
QTest::newRow("5 clients") << 5;
QTest::newRow("10 clients") << 10;
#endif
#ifndef Q_OS_WINCE
QTest::newRow("20 clients") << 20;
#endif
}
void tst_QLocalSocket::threadedConnection()
{
#ifdef Q_OS_SYMBIAN
unlink("qlocalsocket_threadtest");
#endif
QFETCH(int, threads);
Server server;
#if defined(Q_OS_SYMBIAN)
server.setStackSize(0x14000);
#endif
server.clients = threads;
server.start();
QList<Client*> clients;
for (int i = 0; i < threads; ++i) {
clients.append(new Client());
#if defined(Q_OS_SYMBIAN)
clients.last()->setStackSize(0x14000);
#endif
clients.last()->start();
}
server.wait();
while (!clients.isEmpty()) {
QVERIFY(clients.first()->wait(30000));
Client *client =clients.takeFirst();
client->terminate();
delete client;
}
}
void tst_QLocalSocket::processConnection_data()
{
QTest::addColumn<int>("processes");
QTest::newRow("1 client") << 1;
#ifndef Q_OS_WIN
QTest::newRow("2 clients") << 2;
QTest::newRow("5 clients") << 5;
#endif
QTest::newRow("30 clients") << 30;
}
/*!
Create external processes that produce and consume.
*/
void tst_QLocalSocket::processConnection()
{
#if defined(QT_NO_PROCESS) || defined(Q_CC_NOKIAX86)
QSKIP("Qt was compiled with QT_NO_PROCESS", SkipAll);
#else
QFETCH(int, processes);
QStringList serverArguments = QStringList() << SRCDIR "lackey/scripts/server.js" << QString::number(processes);
QProcess producer;
producer.setProcessChannelMode(QProcess::ForwardedChannels);
#ifdef Q_WS_QWS
serverArguments << "-qws";
#endif
QList<QProcess*> consumers;
producer.start("lackey/lackey", serverArguments);
QVERIFY(producer.waitForStarted(-1));
QTest::qWait(2000);
for (int i = 0; i < processes; ++i) {
QStringList arguments = QStringList() << SRCDIR "lackey/scripts/client.js";
#ifdef Q_WS_QWS
arguments << "-qws";
#endif
QProcess *p = new QProcess;
p->setProcessChannelMode(QProcess::ForwardedChannels);
consumers.append(p);
p->start("lackey/lackey", arguments);
}
while (!consumers.isEmpty()) {
consumers.first()->waitForFinished(20000);
QCOMPARE(consumers.first()->exitStatus(), QProcess::NormalExit);
QCOMPARE(consumers.first()->exitCode(), 0);
QProcess *consumer = consumers.takeFirst();
consumer->terminate();
delete consumer;
}
producer.waitForFinished(15000);
#endif
}
void tst_QLocalSocket::longPath()
{
#ifndef Q_OS_WIN
QString name;
for (int i = 0; i < 256; ++i)
name += 'a';
LocalServer server;
QVERIFY(!server.listen(name));
LocalSocket socket;
socket.connectToServer(name);
QCOMPARE(socket.state(), QLocalSocket::UnconnectedState);
#endif
}
void tst_QLocalSocket::waitForDisconnect()
{
QString name = "tst_localsocket";
#ifdef Q_OS_SYMBIAN
unlink(name);
#endif
LocalServer server;
QVERIFY(server.listen(name));
LocalSocket socket;
socket.connectToServer(name);
QVERIFY(socket.waitForConnected(3000));
QVERIFY(server.waitForNewConnection(3000));
QLocalSocket *serverSocket = server.nextPendingConnection();
QVERIFY(serverSocket);
socket.disconnectFromServer();
QTime timer;
timer.start();
QVERIFY(serverSocket->waitForDisconnected(3000));
QVERIFY(timer.elapsed() < 2000);
}
void tst_QLocalSocket::removeServer()
{
// this is a hostile takeover, but recovering from a crash results in the same
QLocalServer server, server2;
QVERIFY(QLocalServer::removeServer("cleanuptest"));
QVERIFY(server.listen("cleanuptest"));
#ifndef Q_OS_WIN
// on Windows, there can be several sockets listening on the same pipe
// on Unix, there can only be one socket instance
QVERIFY(! server2.listen("cleanuptest"));
#endif
QVERIFY(QLocalServer::removeServer("cleanuptest"));
QVERIFY(server2.listen("cleanuptest"));
}
void tst_QLocalSocket::recycleServer()
{
#ifdef Q_OS_SYMBIAN
unlink("recycletest1");
#endif
QLocalServer server;
QLocalSocket client;
QVERIFY(server.listen("recycletest1"));
client.connectToServer("recycletest1");
QVERIFY(client.waitForConnected(201));
QVERIFY(server.waitForNewConnection(201));
QVERIFY(server.nextPendingConnection() != 0);
server.close();
client.disconnectFromServer();
qApp->processEvents();
QVERIFY(server.listen("recycletest2"));
client.connectToServer("recycletest2");
QVERIFY(client.waitForConnected(202));
QVERIFY(server.waitForNewConnection(202));
QVERIFY(server.nextPendingConnection() != 0);
}
void tst_QLocalSocket::debug()
{
// Make sure this compiles
qDebug() << QLocalSocket::ConnectionRefusedError << QLocalSocket::UnconnectedState;
}
#ifdef Q_OS_SYMBIAN
void tst_QLocalSocket::unlink(QString name)
{
if(name.length() == 0)
return;
QString fullName;
// determine the full server path
if (name.startsWith(QLatin1Char('/'))) {
fullName = name;
} else {
fullName = QDir::cleanPath(QDir::tempPath());
fullName += QLatin1Char('/') + name;
fullName = QDir::toNativeSeparators(fullName);
}
int result = ::unlink(fullName.toUtf8().data());
if(result != 0) {
qWarning() << "Unlinking " << fullName << " failed with " << strerror(errno);
}
}
#endif
QTEST_MAIN(tst_QLocalSocket)
#include "tst_qlocalsocket.moc"
Cleaning test cases.
In some situations we had different setup on Symbian platform.
Moslty when it comes to the timing issues.
We want to revert those where possible.
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <qtextstream.h>
#include <QtNetwork/qlocalsocket.h>
#include <QtNetwork/qlocalserver.h>
#include "../../shared/util.h"
#ifdef Q_OS_SYMBIAN
#include <unistd.h>
#endif
//TESTED_CLASS=QLocalServer, QLocalSocket
//TESTED_FILES=network/socket/qlocalserver.cpp network/socket/qlocalsocket.cpp
#ifdef Q_OS_SYMBIAN
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define SRCDIR "C:/Private/" TOSTRING(SYMBIAN_SRCDIR_UID) "/"
#endif
Q_DECLARE_METATYPE(QLocalSocket::LocalSocketError)
Q_DECLARE_METATYPE(QLocalSocket::LocalSocketState)
class tst_QLocalSocket : public QObject
{
Q_OBJECT
public:
tst_QLocalSocket();
virtual ~tst_QLocalSocket();
public Q_SLOTS:
void init();
void cleanup();
private slots:
// basics
void server_basic();
void server_connectionsCount();
void socket_basic();
void listen_data();
void listen();
void listenAndConnect_data();
void listenAndConnect();
void sendData_data();
void sendData();
void fullPath();
void hitMaximumConnections_data();
void hitMaximumConnections();
void setSocketDescriptor();
void threadedConnection_data();
void threadedConnection();
void processConnection_data();
void processConnection();
void longPath();
void waitForDisconnect();
void removeServer();
void recycleServer();
void debug();
#ifdef Q_OS_SYMBIAN
private:
void unlink(QString serverName);
#endif
};
tst_QLocalSocket::tst_QLocalSocket()
{
if (!QFile::exists("lackey/lackey"
#ifdef Q_OS_WIN
".exe"
#endif
))
qWarning() << "lackey executable doesn't exists!";
}
tst_QLocalSocket::~tst_QLocalSocket()
{
}
void tst_QLocalSocket::init()
{
qRegisterMetaType<QLocalSocket::LocalSocketState>("QLocalSocket::LocalSocketState");
qRegisterMetaType<QLocalSocket::LocalSocketError>("QLocalSocket::LocalSocketError");
}
void tst_QLocalSocket::cleanup()
{
}
class LocalServer : public QLocalServer
{
Q_OBJECT
public:
LocalServer() : QLocalServer()
{
connect(this, SIGNAL(newConnection()), this, SLOT(slotNewConnection()));
};
QList<int> hits;
protected:
void incomingConnection(quintptr socketDescriptor)
{
hits.append(socketDescriptor);
QLocalServer::incomingConnection(socketDescriptor);
}
private slots:
void slotNewConnection() {
QVERIFY(!hits.isEmpty());
QVERIFY(hasPendingConnections());
}
};
class LocalSocket : public QLocalSocket
{
Q_OBJECT
public:
LocalSocket(QObject *parent = 0) : QLocalSocket(parent)
{
connect(this, SIGNAL(connected()),
this, SLOT(slotConnected()));
connect(this, SIGNAL(disconnected()),
this, SLOT(slotDisconnected()));
connect(this, SIGNAL(error(QLocalSocket::LocalSocketError)),
this, SLOT(slotError(QLocalSocket::LocalSocketError)));
connect(this, SIGNAL(stateChanged(QLocalSocket::LocalSocketState)),
this, SLOT(slotStateChanged(QLocalSocket::LocalSocketState)));
connect(this, SIGNAL(readyRead()),
this, SLOT(slotReadyRead()));
}
private slots:
void slotConnected()
{
QCOMPARE(state(), QLocalSocket::ConnectedState);
}
void slotDisconnected()
{
QCOMPARE(state(), QLocalSocket::UnconnectedState);
}
void slotError(QLocalSocket::LocalSocketError newError)
{
QVERIFY(errorString() != "Unknown error");
QCOMPARE(error(), newError);
}
void slotStateChanged(QLocalSocket::LocalSocketState newState)
{
QCOMPARE(state(), newState);
}
void slotReadyRead()
{
QVERIFY(bytesAvailable() > 0);
}
};
// basic test make sure no segfaults and check default values
void tst_QLocalSocket::server_basic()
{
LocalServer server;
QSignalSpy spyNewConnection(&server, SIGNAL(newConnection()));
server.close();
QCOMPARE(server.errorString(), QString());
QCOMPARE(server.hasPendingConnections(), false);
QCOMPARE(server.isListening(), false);
QCOMPARE(server.maxPendingConnections(), 30);
QCOMPARE(server.nextPendingConnection(), (QLocalSocket*)0);
QCOMPARE(server.serverName(), QString());
QCOMPARE(server.fullServerName(), QString());
QCOMPARE(server.serverError(), QAbstractSocket::UnknownSocketError);
server.setMaxPendingConnections(20);
bool timedOut = true;
QCOMPARE(server.waitForNewConnection(3000, &timedOut), false);
QVERIFY(!timedOut);
QCOMPARE(server.listen(QString()), false);
QCOMPARE(server.hits.count(), 0);
QCOMPARE(spyNewConnection.count(), 0);
}
void tst_QLocalSocket::server_connectionsCount()
{
LocalServer server;
server.setMaxPendingConnections(10);
QCOMPARE(server.maxPendingConnections(), 10);
}
// basic test make sure no segfaults and check default values
void tst_QLocalSocket::socket_basic()
{
LocalSocket socket;
QSignalSpy spyConnected(&socket, SIGNAL(connected()));
QSignalSpy spyDisconnected(&socket, SIGNAL(disconnected()));
QSignalSpy spyError(&socket, SIGNAL(error(QLocalSocket::LocalSocketError)));
QSignalSpy spyStateChanged(&socket, SIGNAL(stateChanged(QLocalSocket::LocalSocketState)));
QSignalSpy spyReadyRead(&socket, SIGNAL(readyRead()));
QCOMPARE(socket.serverName(), QString());
QCOMPARE(socket.fullServerName(), QString());
socket.abort();
QVERIFY(socket.bytesAvailable() == 0);
QVERIFY(socket.bytesToWrite() == 0);
QCOMPARE(socket.canReadLine(), false);
socket.close();
socket.disconnectFromServer();
QCOMPARE(QLocalSocket::UnknownSocketError, socket.error());
QVERIFY(socket.errorString() != QString());
QCOMPARE(socket.flush(), false);
QCOMPARE(socket.isValid(), false);
QVERIFY(socket.readBufferSize() == 0);
socket.setReadBufferSize(0);
//QCOMPARE(socket.socketDescriptor(), -1);
QCOMPARE(socket.state(), QLocalSocket::UnconnectedState);
QCOMPARE(socket.waitForConnected(0), false);
QCOMPARE(socket.waitForDisconnected(0), false);
QCOMPARE(socket.waitForReadyRead(0), false);
QCOMPARE(spyConnected.count(), 0);
QCOMPARE(spyDisconnected.count(), 0);
QCOMPARE(spyError.count(), 0);
QCOMPARE(spyStateChanged.count(), 0);
QCOMPARE(spyReadyRead.count(), 0);
}
void tst_QLocalSocket::listen_data()
{
QTest::addColumn<QString>("name");
QTest::addColumn<bool>("canListen");
QTest::addColumn<bool>("close");
QTest::newRow("null") << QString() << false << false;
QTest::newRow("tst_localsocket") << "tst_localsocket" << true << true;
QTest::newRow("tst_localsocket") << "tst_localsocket" << true << false;
}
// start a server that listens, but don't connect a socket, make sure everything is in order
void tst_QLocalSocket::listen()
{
LocalServer server;
QSignalSpy spyNewConnection(&server, SIGNAL(newConnection()));
QFETCH(QString, name);
#ifdef Q_OS_SYMBIAN
unlink(name);
#endif
QFETCH(bool, canListen);
QFETCH(bool, close);
QVERIFY2((server.listen(name) == canListen), server.errorString().toLatin1().constData());
// test listening
QCOMPARE(server.serverName(), name);
QVERIFY(server.fullServerName().contains(name));
QCOMPARE(server.isListening(), canListen);
QCOMPARE(server.hasPendingConnections(), false);
QCOMPARE(server.nextPendingConnection(), (QLocalSocket*)0);
QCOMPARE(server.hits.count(), 0);
QCOMPARE(spyNewConnection.count(), 0);
if (canListen) {
QVERIFY(server.errorString() == QString());
QCOMPARE(server.serverError(), QAbstractSocket::UnknownSocketError);
// already isListening
QVERIFY(!server.listen(name));
} else {
QVERIFY(server.errorString() != QString());
QCOMPARE(server.serverError(), QAbstractSocket::HostNotFoundError);
}
QCOMPARE(server.maxPendingConnections(), 30);
bool timedOut = false;
QCOMPARE(server.waitForNewConnection(3000, &timedOut), false);
QCOMPARE(timedOut, canListen);
if (close)
server.close();
}
void tst_QLocalSocket::listenAndConnect_data()
{
QTest::addColumn<QString>("name");
QTest::addColumn<bool>("canListen");
QTest::addColumn<int>("connections");
for (int i = 0; i < 3; ++i) {
int connections = i;
if (i == 2)
connections = 5;
QTest::newRow(QString("null %1").arg(i).toLatin1()) << QString() << false << connections;
QTest::newRow(QString("tst_localsocket %1").arg(i).toLatin1()) << "tst_localsocket" << true << connections;
}
}
void tst_QLocalSocket::listenAndConnect()
{
LocalServer server;
QSignalSpy spyNewConnection(&server, SIGNAL(newConnection()));
QFETCH(QString, name);
QFETCH(bool, canListen);
#ifdef Q_OS_SYMBIAN
unlink(name);
#endif
QCOMPARE(server.listen(name), canListen);
QTest::qWait(1000);
//QVERIFY(!server.errorString().isEmpty());
QCOMPARE(server.serverError(),
canListen ? QAbstractSocket::UnknownSocketError : QAbstractSocket::HostNotFoundError);
// test creating connection(s)
QFETCH(int, connections);
QList<QLocalSocket*> sockets;
for (int i = 0; i < connections; ++i) {
LocalSocket *socket = new LocalSocket;
QSignalSpy spyConnected(socket, SIGNAL(connected()));
QSignalSpy spyDisconnected(socket, SIGNAL(disconnected()));
QSignalSpy spyError(socket, SIGNAL(error(QLocalSocket::LocalSocketError)));
QSignalSpy spyStateChanged(socket, SIGNAL(stateChanged(QLocalSocket::LocalSocketState)));
QSignalSpy spyReadyRead(socket, SIGNAL(readyRead()));
socket->connectToServer(name);
#if defined(QT_LOCALSOCKET_TCP)
QTest::qWait(250);
#endif
QCOMPARE(socket->serverName(), name);
QVERIFY(socket->fullServerName().contains(name));
sockets.append(socket);
if (canListen) {
QCOMPARE(socket->errorString(), QString("Unknown error"));
QCOMPARE(socket->error(), QLocalSocket::UnknownSocketError);
QCOMPARE(socket->state(), QLocalSocket::ConnectedState);
//QVERIFY(socket->socketDescriptor() != -1);
QCOMPARE(spyError.count(), 0);
} else {
QVERIFY(socket->errorString() != QString());
QVERIFY(socket->error() != QLocalSocket::UnknownSocketError);
QCOMPARE(socket->state(), QLocalSocket::UnconnectedState);
//QVERIFY(socket->socketDescriptor() == -1);
QCOMPARE(qVariantValue<QLocalSocket::LocalSocketError>(spyError.first()[0]),
QLocalSocket::ServerNotFoundError);
}
QVERIFY(socket->bytesAvailable() == 0);
QVERIFY(socket->bytesToWrite() == 0);
QCOMPARE(socket->canReadLine(), false);
QCOMPARE(socket->flush(), false);
QCOMPARE(socket->isValid(), canListen);
QCOMPARE(socket->readBufferSize(), (qint64)0);
QCOMPARE(socket->waitForConnected(0), canListen);
QCOMPARE(socket->waitForReadyRead(0), false);
QTRY_COMPARE(spyConnected.count(), canListen ? 1 : 0);
QCOMPARE(spyDisconnected.count(), 0);
// error signals
QVERIFY(spyError.count() >= 0);
if (canListen) {
if (spyError.count() > 0)
QCOMPARE(qVariantValue<QLocalSocket::LocalSocketError>(spyError.first()[0]),
QLocalSocket::SocketTimeoutError);
} else {
QCOMPARE(qVariantValue<QLocalSocket::LocalSocketError>(spyError.first()[0]),
QLocalSocket::ServerNotFoundError);
}
// Check first and last state
QCOMPARE(qVariantValue<QLocalSocket::LocalSocketState>(spyStateChanged.first()[0]),
QLocalSocket::ConnectingState);
#if 0
for (int j = 0; j < spyStateChanged.count(); ++j) {
QLocalSocket::LocalSocketState s;
s = qVariantValue<QLocalSocket::LocalSocketState>(spyStateChanged.at(j).at(0));
qDebug() << s;
}
#endif
if (canListen)
QCOMPARE(qVariantValue<QLocalSocket::LocalSocketState>(spyStateChanged.last()[0]),
QLocalSocket::ConnectedState);
QCOMPARE(spyStateChanged.count(), 2);
QCOMPARE(spyReadyRead.count(), 0);
bool timedOut = true;
QCOMPARE(server.waitForNewConnection(3000, &timedOut), canListen);
QVERIFY(!timedOut);
QCOMPARE(server.hasPendingConnections(), canListen);
QCOMPARE(server.isListening(), canListen);
// NOTE: socket disconnecting is not tested here
// server checks post connection
if (canListen) {
QCOMPARE(server.serverName(), name);
QVERIFY(server.fullServerName().contains(name));
QVERIFY(server.nextPendingConnection() != (QLocalSocket*)0);
QTRY_COMPARE(server.hits.count(), i + 1);
QCOMPARE(spyNewConnection.count(), i + 1);
QVERIFY(server.errorString() == QString());
QCOMPARE(server.serverError(), QAbstractSocket::UnknownSocketError);
} else {
QVERIFY(server.serverName().isEmpty());
QVERIFY(server.fullServerName().isEmpty());
QVERIFY(server.nextPendingConnection() == (QLocalSocket*)0);
QCOMPARE(spyNewConnection.count(), 0);
QCOMPARE(server.hits.count(), 0);
QVERIFY(server.errorString() != QString());
QCOMPARE(server.serverError(), QAbstractSocket::HostNotFoundError);
}
}
qDeleteAll(sockets.begin(), sockets.end());
server.close();
QCOMPARE(server.hits.count(), (canListen ? connections : 0));
QCOMPARE(spyNewConnection.count(), (canListen ? connections : 0));
}
void tst_QLocalSocket::sendData_data()
{
listenAndConnect_data();
}
void tst_QLocalSocket::sendData()
{
QFETCH(QString, name);
#ifdef Q_OS_SYMBIAN
unlink(name);
#endif
QFETCH(bool, canListen);
LocalServer server;
QSignalSpy spy(&server, SIGNAL(newConnection()));
QCOMPARE(server.listen(name), canListen);
LocalSocket socket;
QSignalSpy spyConnected(&socket, SIGNAL(connected()));
QSignalSpy spyDisconnected(&socket, SIGNAL(disconnected()));
QSignalSpy spyError(&socket, SIGNAL(error(QLocalSocket::LocalSocketError)));
QSignalSpy spyStateChanged(&socket, SIGNAL(stateChanged(QLocalSocket::LocalSocketState)));
QSignalSpy spyReadyRead(&socket, SIGNAL(readyRead()));
// test creating a connection
socket.connectToServer(name);
bool timedOut = true;
QCOMPARE(server.waitForNewConnection(3000, &timedOut), canListen);
#if defined(QT_LOCALSOCKET_TCP)
QTest::qWait(250);
#endif
QVERIFY(!timedOut);
QCOMPARE(spyConnected.count(), canListen ? 1 : 0);
QCOMPARE(socket.state(), canListen ? QLocalSocket::ConnectedState : QLocalSocket::UnconnectedState);
// test sending/receiving data
if (server.hasPendingConnections()) {
QString testLine = "test";
#ifdef Q_OS_SYMBIAN
for (int i = 0; i < 25 * 1024; ++i)
#else
for (int i = 0; i < 50000; ++i)
#endif
testLine += "a";
QLocalSocket *serverSocket = server.nextPendingConnection();
QVERIFY(serverSocket);
QCOMPARE(serverSocket->state(), QLocalSocket::ConnectedState);
QTextStream out(serverSocket);
QTextStream in(&socket);
out << testLine << endl;
bool wrote = serverSocket->waitForBytesWritten(3000);
if (!socket.canReadLine())
QVERIFY(socket.waitForReadyRead());
QVERIFY(socket.bytesAvailable() >= 0);
QCOMPARE(socket.bytesToWrite(), (qint64)0);
QCOMPARE(socket.flush(), false);
QCOMPARE(socket.isValid(), canListen);
QCOMPARE(socket.readBufferSize(), (qint64)0);
QCOMPARE(spyReadyRead.count(), 1);
QVERIFY(testLine.startsWith(in.readLine()));
QVERIFY(wrote || serverSocket->waitForBytesWritten(1000));
QCOMPARE(serverSocket->errorString(), QString("Unknown error"));
QCOMPARE(socket.errorString(), QString("Unknown error"));
}
socket.disconnectFromServer();
QCOMPARE(spyConnected.count(), canListen ? 1 : 0);
QCOMPARE(spyDisconnected.count(), canListen ? 1 : 0);
QCOMPARE(spyError.count(), canListen ? 0 : 1);
QCOMPARE(spyStateChanged.count(), canListen ? 4 : 2);
QCOMPARE(spyReadyRead.count(), canListen ? 1 : 0);
server.close();
QCOMPARE(server.hits.count(), (canListen ? 1 : 0));
QCOMPARE(spy.count(), (canListen ? 1 : 0));
}
// QLocalSocket/Server can take a name or path, check that it works as expected
void tst_QLocalSocket::fullPath()
{
QLocalServer server;
QString name = "qlocalsocket_pathtest";
#if defined(Q_OS_SYMBIAN)
QString path = "";
#elif defined(QT_LOCALSOCKET_TCP)
QString path = "QLocalServer";
#elif defined(Q_OS_WIN)
QString path = "\\\\.\\pipe\\";
#else
QString path = "/tmp";
#endif
QString serverName = path + '/' + name;
QVERIFY2(server.listen(serverName), server.errorString().toLatin1().constData());
QCOMPARE(server.serverName(), serverName);
QCOMPARE(server.fullServerName(), serverName);
LocalSocket socket;
socket.connectToServer(serverName);
QCOMPARE(socket.serverName(), serverName);
QCOMPARE(socket.fullServerName(), serverName);
socket.disconnectFromServer();
#ifdef QT_LOCALSOCKET_TCP
QTest::qWait(250);
#endif
QCOMPARE(socket.serverName(), QString());
QCOMPARE(socket.fullServerName(), QString());
}
void tst_QLocalSocket::hitMaximumConnections_data()
{
QTest::addColumn<int>("max");
QTest::newRow("none") << 0;
QTest::newRow("1") << 1;
QTest::newRow("3") << 3;
}
void tst_QLocalSocket::hitMaximumConnections()
{
QFETCH(int, max);
LocalServer server;
QString name = "tst_localsocket";
#ifdef Q_OS_SYMBIAN
unlink(name);
#endif
server.setMaxPendingConnections(max);
QVERIFY2(server.listen(name), server.errorString().toLatin1().constData());
int connections = server.maxPendingConnections() + 1;
QList<QLocalSocket*> sockets;
for (int i = 0; i < connections; ++i) {
LocalSocket *socket = new LocalSocket;
sockets.append(socket);
socket->connectToServer(name);
}
bool timedOut = true;
QVERIFY(server.waitForNewConnection(3000, &timedOut));
QVERIFY(!timedOut);
QVERIFY(server.hits.count() > 0);
qDeleteAll(sockets.begin(), sockets.end());
}
// check that state and mode are kept
void tst_QLocalSocket::setSocketDescriptor()
{
LocalSocket socket;
quintptr minusOne = -1;
socket.setSocketDescriptor(minusOne, QLocalSocket::ConnectingState, QIODevice::Append);
QCOMPARE(socket.socketDescriptor(), minusOne);
QCOMPARE(socket.state(), QLocalSocket::ConnectingState);
QVERIFY((socket.openMode() & QIODevice::Append) != 0);
}
class Client : public QThread
{
public:
void run()
{
QString testLine = "test";
LocalSocket socket;
QSignalSpy spyReadyRead(&socket, SIGNAL(readyRead()));
int tries = 0;
do {
socket.connectToServer("qlocalsocket_threadtest");
if (socket.error() != QLocalSocket::ServerNotFoundError
&& socket.error() != QLocalSocket::ConnectionRefusedError)
break;
QTest::qWait(100);
++tries;
} while ((socket.error() == QLocalSocket::ServerNotFoundError
|| socket.error() == QLocalSocket::ConnectionRefusedError)
&& tries < 1000);
if (tries == 0 && socket.state() != QLocalSocket::ConnectedState) {
QVERIFY(socket.waitForConnected(3000));
QVERIFY(socket.state() == QLocalSocket::ConnectedState);
}
// We should *not* have this signal yet!
if (tries == 0)
QCOMPARE(spyReadyRead.count(), 0);
socket.waitForReadyRead();
QCOMPARE(spyReadyRead.count(), 1);
QTextStream in(&socket);
QCOMPARE(in.readLine(), testLine);
socket.close();
}
};
class Server : public QThread
{
public:
int clients;
void run()
{
QString testLine = "test";
LocalServer server;
server.setMaxPendingConnections(10);
QVERIFY2(server.listen("qlocalsocket_threadtest"),
server.errorString().toLatin1().constData());
int done = clients;
while (done > 0) {
bool timedOut = true;
QVERIFY(server.waitForNewConnection(3000, &timedOut));
QVERIFY(!timedOut);
QLocalSocket *serverSocket = server.nextPendingConnection();
QVERIFY(serverSocket);
QTextStream out(serverSocket);
out << testLine << endl;
QCOMPARE(serverSocket->state(), QLocalSocket::ConnectedState);
QVERIFY2(serverSocket->waitForBytesWritten(), serverSocket->errorString().toLatin1().constData());
QCOMPARE(serverSocket->errorString(), QString("Unknown error"));
--done;
delete serverSocket;
}
QCOMPARE(server.hits.count(), clients);
}
};
void tst_QLocalSocket::threadedConnection_data()
{
QTest::addColumn<int>("threads");
QTest::newRow("1 client") << 1;
QTest::newRow("2 clients") << 2;
#ifdef Q_OS_WINCE
QTest::newRow("4 clients") << 4;
#endif
#ifndef Q_OS_WIN
QTest::newRow("5 clients") << 5;
QTest::newRow("10 clients") << 10;
#endif
#ifndef Q_OS_WINCE
QTest::newRow("20 clients") << 20;
#endif
}
void tst_QLocalSocket::threadedConnection()
{
#ifdef Q_OS_SYMBIAN
unlink("qlocalsocket_threadtest");
#endif
QFETCH(int, threads);
Server server;
#if defined(Q_OS_SYMBIAN)
server.setStackSize(0x14000);
#endif
server.clients = threads;
server.start();
QList<Client*> clients;
for (int i = 0; i < threads; ++i) {
clients.append(new Client());
#if defined(Q_OS_SYMBIAN)
clients.last()->setStackSize(0x14000);
#endif
clients.last()->start();
}
server.wait();
while (!clients.isEmpty()) {
QVERIFY(clients.first()->wait(3000));
Client *client =clients.takeFirst();
client->terminate();
delete client;
}
}
void tst_QLocalSocket::processConnection_data()
{
QTest::addColumn<int>("processes");
QTest::newRow("1 client") << 1;
#ifndef Q_OS_WIN
QTest::newRow("2 clients") << 2;
QTest::newRow("5 clients") << 5;
#endif
QTest::newRow("30 clients") << 30;
}
/*!
Create external processes that produce and consume.
*/
void tst_QLocalSocket::processConnection()
{
#if defined(QT_NO_PROCESS) || defined(Q_CC_NOKIAX86)
QSKIP("Qt was compiled with QT_NO_PROCESS", SkipAll);
#else
QFETCH(int, processes);
QStringList serverArguments = QStringList() << SRCDIR "lackey/scripts/server.js" << QString::number(processes);
QProcess producer;
producer.setProcessChannelMode(QProcess::ForwardedChannels);
#ifdef Q_WS_QWS
serverArguments << "-qws";
#endif
QList<QProcess*> consumers;
producer.start("lackey/lackey", serverArguments);
QVERIFY(producer.waitForStarted(-1));
QTest::qWait(2000);
for (int i = 0; i < processes; ++i) {
QStringList arguments = QStringList() << SRCDIR "lackey/scripts/client.js";
#ifdef Q_WS_QWS
arguments << "-qws";
#endif
QProcess *p = new QProcess;
p->setProcessChannelMode(QProcess::ForwardedChannels);
consumers.append(p);
p->start("lackey/lackey", arguments);
}
while (!consumers.isEmpty()) {
consumers.first()->waitForFinished(20000);
QCOMPARE(consumers.first()->exitStatus(), QProcess::NormalExit);
QCOMPARE(consumers.first()->exitCode(), 0);
QProcess *consumer = consumers.takeFirst();
consumer->terminate();
delete consumer;
}
producer.waitForFinished(15000);
#endif
}
void tst_QLocalSocket::longPath()
{
#ifndef Q_OS_WIN
QString name;
for (int i = 0; i < 256; ++i)
name += 'a';
LocalServer server;
QVERIFY(!server.listen(name));
LocalSocket socket;
socket.connectToServer(name);
QCOMPARE(socket.state(), QLocalSocket::UnconnectedState);
#endif
}
void tst_QLocalSocket::waitForDisconnect()
{
QString name = "tst_localsocket";
#ifdef Q_OS_SYMBIAN
unlink(name);
#endif
LocalServer server;
QVERIFY(server.listen(name));
LocalSocket socket;
socket.connectToServer(name);
QVERIFY(socket.waitForConnected(3000));
QVERIFY(server.waitForNewConnection(3000));
QLocalSocket *serverSocket = server.nextPendingConnection();
QVERIFY(serverSocket);
socket.disconnectFromServer();
QTime timer;
timer.start();
QVERIFY(serverSocket->waitForDisconnected(3000));
QVERIFY(timer.elapsed() < 2000);
}
void tst_QLocalSocket::removeServer()
{
// this is a hostile takeover, but recovering from a crash results in the same
QLocalServer server, server2;
QVERIFY(QLocalServer::removeServer("cleanuptest"));
QVERIFY(server.listen("cleanuptest"));
#ifndef Q_OS_WIN
// on Windows, there can be several sockets listening on the same pipe
// on Unix, there can only be one socket instance
QVERIFY(! server2.listen("cleanuptest"));
#endif
QVERIFY(QLocalServer::removeServer("cleanuptest"));
QVERIFY(server2.listen("cleanuptest"));
}
void tst_QLocalSocket::recycleServer()
{
#ifdef Q_OS_SYMBIAN
unlink("recycletest1");
#endif
QLocalServer server;
QLocalSocket client;
QVERIFY(server.listen("recycletest1"));
client.connectToServer("recycletest1");
QVERIFY(client.waitForConnected(201));
QVERIFY(server.waitForNewConnection(201));
QVERIFY(server.nextPendingConnection() != 0);
server.close();
client.disconnectFromServer();
qApp->processEvents();
QVERIFY(server.listen("recycletest2"));
client.connectToServer("recycletest2");
QVERIFY(client.waitForConnected(202));
QVERIFY(server.waitForNewConnection(202));
QVERIFY(server.nextPendingConnection() != 0);
}
void tst_QLocalSocket::debug()
{
// Make sure this compiles
qDebug() << QLocalSocket::ConnectionRefusedError << QLocalSocket::UnconnectedState;
}
#ifdef Q_OS_SYMBIAN
void tst_QLocalSocket::unlink(QString name)
{
if(name.length() == 0)
return;
QString fullName;
// determine the full server path
if (name.startsWith(QLatin1Char('/'))) {
fullName = name;
} else {
fullName = QDir::cleanPath(QDir::tempPath());
fullName += QLatin1Char('/') + name;
fullName = QDir::toNativeSeparators(fullName);
}
int result = ::unlink(fullName.toUtf8().data());
if(result != 0) {
qWarning() << "Unlinking " << fullName << " failed with " << strerror(errno);
}
}
#endif
QTEST_MAIN(tst_QLocalSocket)
#include "tst_qlocalsocket.moc"
|
// 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
#ifndef __PROCESS_NETWORK_HPP__
#define __PROCESS_NETWORK_HPP__
#include <process/address.hpp>
#include <stout/net.hpp>
#include <stout/try.hpp>
#include <stout/os/socket.hpp>
namespace process {
namespace network {
using net::socket;
using SocketError =
#ifndef __WINDOWS__
ErrnoError;
#else
WindowsSocketError;
#endif
// TODO(benh): Remove and defer to Socket::accept.
inline Try<int> accept(int s)
{
struct sockaddr_storage storage;
socklen_t storagelen = sizeof(storage);
int accepted = ::accept(s, (struct sockaddr*) &storage, &storagelen);
if (accepted < 0) {
return ErrnoError("Failed to accept");
}
return accepted;
}
// TODO(benh): Remove and defer to Socket::bind.
inline Try<int> bind(int s, const Address& address)
{
struct sockaddr_storage storage =
net::createSockaddrStorage(address.ip, address.port);
int error = ::bind(s, (struct sockaddr*) &storage, address.size());
if (error < 0) {
return ErrnoError("Failed to bind on " + stringify(address));
}
return error;
}
// TODO(benh): Remove and defer to Socket::connect.
inline Try<int, SocketError> connect(int s, const Address& address)
{
struct sockaddr_storage storage =
net::createSockaddrStorage(address.ip, address.port);
int error = ::connect(s, (struct sockaddr*) &storage, address.size());
if (error < 0) {
return SocketError("Failed to connect to " + stringify(address));
}
return error;
}
/**
* Returns the `Address` with the assigned ip and assigned port.
*
* @return An `Address` or an error if the `getsockname` system call
* fails or the family type is not supported.
*/
inline Try<Address> address(int s)
{
struct sockaddr_storage storage;
socklen_t storagelen = sizeof(storage);
if (::getsockname(s, (struct sockaddr*) &storage, &storagelen) < 0) {
return ErrnoError("Failed to getsockname");
}
return Address::create(storage);
}
/**
* Returns the peer's `Address` for the accepted or connected socket.
*
* @return An `Address` or an error if the `getpeername` system call
* fails or the family type is not supported.
*/
inline Try<Address> peer(int s)
{
struct sockaddr_storage storage;
socklen_t storagelen = sizeof(storage);
if (::getpeername(s, (struct sockaddr*) &storage, &storagelen) < 0) {
return ErrnoError("Failed to getpeername");
}
return Address::create(storage);
}
} // namespace network {
} // namespace process {
#endif // __PROCESS_NETWORK_HPP__
Windows: Moved `SocketError` definition to `stout/error.hpp`.
Review: https://reviews.apache.org/r/46447/
// 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
#ifndef __PROCESS_NETWORK_HPP__
#define __PROCESS_NETWORK_HPP__
#include <process/address.hpp>
#include <stout/net.hpp>
#include <stout/try.hpp>
#include <stout/os/socket.hpp>
namespace process {
namespace network {
using net::socket;
// TODO(benh): Remove and defer to Socket::accept.
inline Try<int> accept(int s)
{
struct sockaddr_storage storage;
socklen_t storagelen = sizeof(storage);
int accepted = ::accept(s, (struct sockaddr*) &storage, &storagelen);
if (accepted < 0) {
return ErrnoError("Failed to accept");
}
return accepted;
}
// TODO(benh): Remove and defer to Socket::bind.
inline Try<int> bind(int s, const Address& address)
{
struct sockaddr_storage storage =
net::createSockaddrStorage(address.ip, address.port);
int error = ::bind(s, (struct sockaddr*) &storage, address.size());
if (error < 0) {
return ErrnoError("Failed to bind on " + stringify(address));
}
return error;
}
// TODO(benh): Remove and defer to Socket::connect.
inline Try<int, SocketError> connect(int s, const Address& address)
{
struct sockaddr_storage storage =
net::createSockaddrStorage(address.ip, address.port);
int error = ::connect(s, (struct sockaddr*) &storage, address.size());
if (error < 0) {
return SocketError("Failed to connect to " + stringify(address));
}
return error;
}
/**
* Returns the `Address` with the assigned ip and assigned port.
*
* @return An `Address` or an error if the `getsockname` system call
* fails or the family type is not supported.
*/
inline Try<Address> address(int s)
{
struct sockaddr_storage storage;
socklen_t storagelen = sizeof(storage);
if (::getsockname(s, (struct sockaddr*) &storage, &storagelen) < 0) {
return ErrnoError("Failed to getsockname");
}
return Address::create(storage);
}
/**
* Returns the peer's `Address` for the accepted or connected socket.
*
* @return An `Address` or an error if the `getpeername` system call
* fails or the family type is not supported.
*/
inline Try<Address> peer(int s)
{
struct sockaddr_storage storage;
socklen_t storagelen = sizeof(storage);
if (::getpeername(s, (struct sockaddr*) &storage, &storagelen) < 0) {
return ErrnoError("Failed to getpeername");
}
return Address::create(storage);
}
} // namespace network {
} // namespace process {
#endif // __PROCESS_NETWORK_HPP__
|
/**
* \file
* \brief SignalsWaitTestCase class implementation
*
* \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2015-02-18
*/
#include "SignalsWaitTestCase.hpp"
#include "priorityTestPhases.hpp"
#include "SequenceAsserter.hpp"
#include "distortos/StaticThread.hpp"
#include "distortos/statistics.hpp"
#include "distortos/ThisThread-Signals.hpp"
namespace distortos
{
namespace test
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// size of stack for test thread, bytes
constexpr size_t testThreadStackSize {384};
/*---------------------------------------------------------------------------------------------------------------------+
| local types
+---------------------------------------------------------------------------------------------------------------------*/
/// type of test thread function
using TestThreadFunction = void(SequenceAsserter&, unsigned int);
/// type of test thread
using TestThread = decltype(makeStaticThread<testThreadStackSize>({}, std::declval<TestThreadFunction>(),
std::ref(std::declval<SequenceAsserter&>()), std::declval<unsigned int>()));
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Test thread.
*
* Marks the first sequence point in SequenceAsserter, waits for any possible signal and uses the accepted signal as the
* last sequence point - marking it in SequenceAsserter.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] firstSequencePoint is the first sequence point of this instance
*/
void thread(SequenceAsserter& sequenceAsserter, const unsigned int firstSequencePoint)
{
sequenceAsserter.sequencePoint(firstSequencePoint);
SignalSet signalSet {SignalSet::full};
const auto waitResult = ThisThread::Signals::wait(signalSet);
if (waitResult.first != 0)
return;
sequenceAsserter.sequencePoint(waitResult.second);
}
/**
* \brief Builder of TestThread objects.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] firstSequencePoint is the first sequence point for this instance - equal to the order in which this
* thread will be started
*
* \return constructed TestThread object
*/
TestThread makeTestThread(SequenceAsserter& sequenceAsserter, const unsigned int firstSequencePoint)
{
return makeStaticThread<testThreadStackSize>(UINT8_MAX, thread, std::ref(sequenceAsserter),
static_cast<unsigned int>(firstSequencePoint));
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool SignalsWaitTestCase::Implementation::run_() const
{
const auto contextSwitchCount = statistics::getContextSwitchCount();
std::remove_const<decltype(contextSwitchCount)>::type expectedContextSwitchCount {};
for (const auto& phase : priorityTestPhases)
{
SequenceAsserter sequenceAsserter;
std::array<TestThread, totalThreads> threads
{{
makeTestThread(sequenceAsserter, 0),
makeTestThread(sequenceAsserter, 1),
makeTestThread(sequenceAsserter, 2),
makeTestThread(sequenceAsserter, 3),
makeTestThread(sequenceAsserter, 4),
makeTestThread(sequenceAsserter, 5),
makeTestThread(sequenceAsserter, 6),
makeTestThread(sequenceAsserter, 7),
makeTestThread(sequenceAsserter, 8),
makeTestThread(sequenceAsserter, 9),
}};
bool result {true};
for (auto& thread : threads)
{
thread.start();
// 2 context switches: "into" the thread and "back" to main thread when test thread blocks on queue
expectedContextSwitchCount += 2;
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
result = false;
}
if (sequenceAsserter.assertSequence(totalThreads) == false)
result = false;
for (size_t i = 0; i < phase.second.size(); ++i)
{
const auto threadIndex = phase.second[i];
const auto ret = threads[threadIndex].generateSignal(totalThreads + i);
if (ret != 0)
result = false;
// 2 context switches: into" the unblocked thread and "back" to main thread when test thread terminates
expectedContextSwitchCount += 2;
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
result = false;
}
for (auto& thread : threads)
thread.join();
if (result == false || sequenceAsserter.assertSequence(totalThreads * 2) == false)
return false;
}
if (statistics::getContextSwitchCount() - contextSwitchCount != 4 * totalThreads * priorityTestPhases.size())
return false;
return true;
}
} // namespace test
} // namespace distortos
SignalsWaitTestCase: enable reception of signals for all test threads
/**
* \file
* \brief SignalsWaitTestCase class implementation
*
* \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2015-03-14
*/
#include "SignalsWaitTestCase.hpp"
#include "priorityTestPhases.hpp"
#include "SequenceAsserter.hpp"
#include "distortos/StaticThread.hpp"
#include "distortos/statistics.hpp"
#include "distortos/ThisThread-Signals.hpp"
namespace distortos
{
namespace test
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// size of stack for test thread, bytes
constexpr size_t testThreadStackSize {384};
/*---------------------------------------------------------------------------------------------------------------------+
| local types
+---------------------------------------------------------------------------------------------------------------------*/
/// type of test thread function
using TestThreadFunction = void(SequenceAsserter&, unsigned int);
/// type of test thread
using TestThread = decltype(makeStaticThread<testThreadStackSize, true>({}, std::declval<TestThreadFunction>(),
std::ref(std::declval<SequenceAsserter&>()), std::declval<unsigned int>()));
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Test thread.
*
* Marks the first sequence point in SequenceAsserter, waits for any possible signal and uses the accepted signal as the
* last sequence point - marking it in SequenceAsserter.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] firstSequencePoint is the first sequence point of this instance
*/
void thread(SequenceAsserter& sequenceAsserter, const unsigned int firstSequencePoint)
{
sequenceAsserter.sequencePoint(firstSequencePoint);
SignalSet signalSet {SignalSet::full};
const auto waitResult = ThisThread::Signals::wait(signalSet);
if (waitResult.first != 0)
return;
sequenceAsserter.sequencePoint(waitResult.second);
}
/**
* \brief Builder of TestThread objects.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] firstSequencePoint is the first sequence point for this instance - equal to the order in which this
* thread will be started
*
* \return constructed TestThread object
*/
TestThread makeTestThread(SequenceAsserter& sequenceAsserter, const unsigned int firstSequencePoint)
{
return makeStaticThread<testThreadStackSize, true>(UINT8_MAX, thread, std::ref(sequenceAsserter),
static_cast<unsigned int>(firstSequencePoint));
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool SignalsWaitTestCase::Implementation::run_() const
{
const auto contextSwitchCount = statistics::getContextSwitchCount();
std::remove_const<decltype(contextSwitchCount)>::type expectedContextSwitchCount {};
for (const auto& phase : priorityTestPhases)
{
SequenceAsserter sequenceAsserter;
std::array<TestThread, totalThreads> threads
{{
makeTestThread(sequenceAsserter, 0),
makeTestThread(sequenceAsserter, 1),
makeTestThread(sequenceAsserter, 2),
makeTestThread(sequenceAsserter, 3),
makeTestThread(sequenceAsserter, 4),
makeTestThread(sequenceAsserter, 5),
makeTestThread(sequenceAsserter, 6),
makeTestThread(sequenceAsserter, 7),
makeTestThread(sequenceAsserter, 8),
makeTestThread(sequenceAsserter, 9),
}};
bool result {true};
for (auto& thread : threads)
{
thread.start();
// 2 context switches: "into" the thread and "back" to main thread when test thread blocks on queue
expectedContextSwitchCount += 2;
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
result = false;
}
if (sequenceAsserter.assertSequence(totalThreads) == false)
result = false;
for (size_t i = 0; i < phase.second.size(); ++i)
{
const auto threadIndex = phase.second[i];
const auto ret = threads[threadIndex].generateSignal(totalThreads + i);
if (ret != 0)
result = false;
// 2 context switches: into" the unblocked thread and "back" to main thread when test thread terminates
expectedContextSwitchCount += 2;
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
result = false;
}
for (auto& thread : threads)
thread.join();
if (result == false || sequenceAsserter.assertSequence(totalThreads * 2) == false)
return false;
}
if (statistics::getContextSwitchCount() - contextSwitchCount != 4 * totalThreads * priorityTestPhases.size())
return false;
return true;
}
} // namespace test
} // namespace distortos
|
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dinfdlg.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2007-07-17 13:37:03 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SFX_DINFDLG_HXX
#define _SFX_DINFDLG_HXX
#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif
#ifndef INCLUDED_SFX2_DLLAPI_H
#include "sfx2/dllapi.h"
#endif
#ifndef _SV_EDIT_HXX //autogen wg. Edit
#include <vcl/edit.hxx>
#endif
#ifndef _SV_FIELD_HXX //autogen wg. NumericField
#include <vcl/field.hxx>
#endif
#ifndef _STDCTRL_HXX //autogen wg. FixedText, FixedInfo
#include <svtools/stdctrl.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen wg. SfxStringItem
#include <svtools/stritem.hxx>
#endif
#ifndef _SVEDIT_HXX //autogen wg. MultiLineEdit
#include <svtools/svmedit.hxx>
#endif
#include "tabdlg.hxx"
#include "docinf.hxx"
// class SfxDocumentInfoItem ---------------------------------------------
class SFX2_DLLPUBLIC SfxDocumentInfoItem : public SfxStringItem
{
private:
SfxDocumentInfo aDocInfo;
sal_Bool bHasTemplate;
sal_Bool bDeleteUserData;
sal_Bool bIsUseUserData;
public:
TYPEINFO();
SfxDocumentInfoItem();
SfxDocumentInfoItem( const String &rFileName, const SfxDocumentInfo&, sal_Bool bUseUserData );
SfxDocumentInfoItem( const SfxDocumentInfoItem& );
virtual ~SfxDocumentInfoItem();
void SetTemplate( BOOL b ) { bHasTemplate = b; }
FASTBOOL HasTemplate() const { return bHasTemplate; }
void SetDeleteUserData( BOOL bSet );
void SetUseUserData( BOOL bSet );
BOOL IsDeleteUserData() const;
BOOL IsUseUserData() const;
SfxDocumentInfo& operator()() { return aDocInfo; }
const SfxDocumentInfo& operator()() const { return aDocInfo; }
SfxDocumentInfo& GetDocInfo() { return aDocInfo; }
const SfxDocumentInfo& GetDocInfo() const { return aDocInfo; }
virtual SfxPoolItem* Clone( SfxItemPool* pPool = NULL ) const;
virtual int operator==( const SfxPoolItem& ) const;
virtual sal_Bool QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
virtual sal_Bool PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
};
// class SfxDocumentPage -------------------------------------------------
class SfxDocumentPage : public SfxTabPage
{
private:
FixedImage aBmp1;
Edit aNameED;
FixedLine aLine1FL;
FixedText aTypeFT;
svt::SelectableFixedText aShowTypeFT;
CheckBox aReadOnlyCB;
FixedText aFileFt;
svt::SelectableFixedText aFileValFt;
FixedText aSizeFT;
svt::SelectableFixedText aShowSizeFT;
FixedLine aLine2FL;
FixedText aCreateFt;
svt::SelectableFixedText aCreateValFt;
FixedText aChangeFt;
svt::SelectableFixedText aChangeValFt;
FixedText aSignedFt;
svt::SelectableFixedText aSignedValFt;
PushButton aSignatureBtn;
FixedText aPrintFt;
svt::SelectableFixedText aPrintValFt;
FixedText aTimeLogFt;
svt::SelectableFixedText aTimeLogValFt;
FixedText aDocNoFt;
svt::SelectableFixedText aDocNoValFt;
CheckBox aUseUserDataCB;
PushButton aDeleteBtn;
FixedLine aLine3FL;
FixedText aTemplFt;
svt::SelectableFixedText aTemplValFt;
String aUnknownSize;
String aMultiSignedStr;
BOOL bEnableUseUserData : 1,
bHandleDelete : 1;
DECL_LINK( DeleteHdl, PushButton * );
DECL_LINK( SignatureHdl, PushButton * );
void ImplUpdateSignatures();
protected:
SfxDocumentPage( Window* pParent, const SfxItemSet& );
virtual BOOL FillItemSet( SfxItemSet& );
virtual void Reset( const SfxItemSet& );
public:
static SfxTabPage* Create( Window* pParent, const SfxItemSet& );
void EnableUseUserData();
};
// class SfxDocumentDescPage ---------------------------------------------
class SfxDocumentDescPage : public SfxTabPage
{
private:
FixedText aTitleFt;
Edit aTitleEd;
FixedText aThemaFt;
Edit aThemaEd;
FixedText aKeywordsFt;
Edit aKeywordsEd;
FixedText aCommentFt;
MultiLineEdit aCommentEd;
SfxDocumentInfoItem* pInfoItem;
protected:
SfxDocumentDescPage( Window* pParent, const SfxItemSet& );
virtual BOOL FillItemSet( SfxItemSet& );
virtual void Reset( const SfxItemSet& );
public:
static SfxTabPage* Create( Window* pParent, const SfxItemSet& );
};
// class SfxDocumentUserPage ---------------------------------------------
class SfxDocumentUserPage : public SfxTabPage
{
private:
BOOL bLabelModified;
FixedText aInfo1Ft;
Edit aInfo1Ed;
FixedText aInfo2Ft;
Edit aInfo2Ed;
FixedText aInfo3Ft;
Edit aInfo3Ed;
FixedText aInfo4Ft;
Edit aInfo4Ed;
PushButton aEditLabelBtn;
SfxDocumentInfoItem* pInfoItem;
#if _SOLAR__PRIVATE
DECL_LINK( EditLabelHdl, PushButton * );
String GetLabelText_Impl( FixedText* pLabel );
void SetLabelText_Impl( FixedText* pLabel, const String& rNewLabel );
#endif
protected:
SfxDocumentUserPage( Window* pParent, const SfxItemSet& );
virtual BOOL FillItemSet( SfxItemSet& );
virtual void Reset( const SfxItemSet& );
public:
static SfxTabPage* Create( Window* pParent, const SfxItemSet& );
};
// class SfxInternetPage -------------------------------------------------
class TargetList;
namespace sfx2
{
class FileDialogHelper;
}
class SfxInternetPage : public SfxTabPage
{
private:
RadioButton aRBNoAutoUpdate;
RadioButton aRBReloadUpdate;
RadioButton aRBForwardUpdate;
FixedText aFTEvery;
NumericField aNFReload;
FixedText aFTReloadSeconds;
FixedText aFTAfter;
NumericField aNFAfter;
FixedText aFTAfterSeconds;
FixedText aFTURL;
Edit aEDForwardURL;
PushButton aPBBrowseURL;
FixedText aFTFrame;
ComboBox aCBFrame;
String aForwardErrorMessg;
String aBaseURL;
SfxDocumentInfoItem* pInfoItem;
sfx2::FileDialogHelper* pFileDlg;
enum STATE { S_Init, S_NoUpdate, S_Reload, S_Forward };
// S_Init is only valid as initial value
STATE eState;
void ChangeState( STATE eNewState ); // S_Init is not a valid value here
// also checks corresponding radiobutton
void EnableNoUpdate( BOOL bEnable );
void EnableReload( BOOL bEnable );
void EnableForward( BOOL bEnable );
DECL_LINK( ClickHdlNoUpdate, Control* );
DECL_LINK( ClickHdlReload, Control* );
DECL_LINK( ClickHdlForward, Control* );
DECL_LINK( ClickHdlBrowseURL, PushButton* );
DECL_LINK( DialogClosedHdl, sfx2::FileDialogHelper* );
using TabPage::DeactivatePage;
protected:
SfxInternetPage( Window* pParent, const SfxItemSet& );
~SfxInternetPage();
virtual BOOL FillItemSet( SfxItemSet& );
virtual void Reset( const SfxItemSet& );
virtual int DeactivatePage( SfxItemSet* pSet = 0 );
public:
static SfxTabPage* Create( Window* pParent, const SfxItemSet& );
};
// class SfxDocumentInfoDialog -------------------------------------------
class SFX2_DLLPUBLIC SfxDocumentInfoDialog : public SfxTabDialog
{
protected:
virtual void PageCreated( USHORT nId, SfxTabPage& rPage );
public:
SfxDocumentInfoDialog( Window* pParent, const SfxItemSet& );
};
#endif
INTEGRATION: CWS custommeta (1.4.66); FILE MERGED
2008/01/28 10:15:28 mst 1.4.66.3: - sfx2/inc/sfx2/dinfdlg.hxx:
+ add missing include
2008/01/25 16:12:10 mst 1.4.66.2: interface change: SfxDocumentInfoItem
- sfx2/inc/sfx2/dinfdlg.hxx, sfx2/source/dialog/dinfdlg.cxx:
+ use XDocumentProperties instead of SfxDocumentInfo
+ also use XDocumentInfo for additional weirdness
+ use UNO types in SfxDocumentInfoItem
2007/12/18 17:43:39 mst 1.4.66.1: - sfx2/inc/sfx2/dinfdlg.hxx, sfx2/source/dialog/dinfdlg.cxx:
+ SfxDocumentInfoItem no longer keeps a DocumentInfo reference;
instead, it has all the individual properties as members
+ new method updateDocumentInfo
+ new method resetUserData
+ fixed bug: editing duration not properly displayed
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dinfdlg.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2008-02-26 14:57:08 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SFX_DINFDLG_HXX
#define _SFX_DINFDLG_HXX
#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif
#ifndef INCLUDED_SFX2_DLLAPI_H
#include "sfx2/dllapi.h"
#endif
#include <com/sun/star/util/DateTime.hpp>
#ifndef _SV_EDIT_HXX //autogen wg. Edit
#include <vcl/edit.hxx>
#endif
#ifndef _SV_FIELD_HXX //autogen wg. NumericField
#include <vcl/field.hxx>
#endif
#ifndef _STDCTRL_HXX //autogen wg. FixedText, FixedInfo
#include <svtools/stdctrl.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen wg. SfxStringItem
#include <svtools/stritem.hxx>
#endif
#ifndef _SVEDIT_HXX //autogen wg. MultiLineEdit
#include <svtools/svmedit.hxx>
#endif
#include "tabdlg.hxx"
namespace com { namespace sun { namespace star {
namespace document {
class XDocumentInfo;
class XDocumentProperties;
}
} } }
// class SfxDocumentInfoItem ---------------------------------------------
class SFX2_DLLPUBLIC SfxDocumentInfoItem : public SfxStringItem
{
private:
sal_Int32 m_AutoloadDelay;
::rtl::OUString m_AutoloadURL;
sal_Bool m_isAutoloadEnabled;
::rtl::OUString m_DefaultTarget;
::rtl::OUString m_TemplateName;
::rtl::OUString m_Author;
::com::sun::star::util::DateTime m_CreationDate;
::rtl::OUString m_ModifiedBy;
::com::sun::star::util::DateTime m_ModificationDate;
String m_PrintedBy;
::com::sun::star::util::DateTime m_PrintDate;
sal_Int16 m_EditingCycles;
sal_Int32 m_EditingDuration;
::rtl::OUString m_Description;
::rtl::OUString m_Keywords;
::rtl::OUString m_Subject;
::rtl::OUString m_Title;
::rtl::OUString m_UserDefinedFieldTitles[4];
::rtl::OUString m_UserDefinedFieldValues[4];
sal_Bool bHasTemplate;
sal_Bool bDeleteUserData;
sal_Bool bIsUseUserData;
public:
TYPEINFO();
SfxDocumentInfoItem();
//FIXME: remove XDocumentInfo when implementing "Custom" tab
SfxDocumentInfoItem( const String &rFileName,
const ::com::sun::star::uno::Reference<
::com::sun::star::document::XDocumentProperties> & i_xDocProps,
const ::com::sun::star::uno::Reference<
::com::sun::star::document::XDocumentInfo> & i_xDocInfo,
sal_Bool bUseUserData );
SfxDocumentInfoItem( const SfxDocumentInfoItem& );
virtual ~SfxDocumentInfoItem();
//FIXME: remove XDocumentInfo when implementing "Custom" tab
/// update i_xDocProps with the data in this object
void updateDocumentInfo(
const ::com::sun::star::uno::Reference<
::com::sun::star::document::XDocumentProperties> & i_xDocProps,
const ::com::sun::star::uno::Reference<
::com::sun::star::document::XDocumentInfo> & i_xDocInfo) const;
sal_Bool isAutoloadEnabled() const { return m_isAutoloadEnabled; }
void setAutoloadEnabled(sal_Bool i_val) { m_isAutoloadEnabled = i_val; }
sal_Int32 getAutoloadDelay() const { return m_AutoloadDelay; }
void setAutoloadDelay(sal_Int32 i_val) { m_AutoloadDelay = i_val; }
::rtl::OUString getAutoloadURL() const { return m_AutoloadURL; }
void setAutoloadURL(::rtl::OUString i_val) { m_AutoloadURL = i_val; }
::rtl::OUString getDefaultTarget() const { return m_DefaultTarget; }
void setDefaultTarget(::rtl::OUString i_val) { m_DefaultTarget = i_val; }
::rtl::OUString getTemplateName() const { return m_TemplateName; }
void setTemplateName(::rtl::OUString i_val) { m_TemplateName = i_val; }
::rtl::OUString getAuthor() const { return m_Author; }
void setAuthor(::rtl::OUString i_val) { m_Author = i_val; }
::com::sun::star::util::DateTime
getCreationDate() const { return m_CreationDate; }
void setCreationDate(::com::sun::star::util::DateTime i_val) {
m_CreationDate = i_val;
}
::rtl::OUString getModifiedBy() const { return m_ModifiedBy; }
void setModifiedBy(::rtl::OUString i_val) { m_ModifiedBy = i_val; }
::com::sun::star::util::DateTime
getModificationDate() const { return m_ModificationDate; }
void setModificationDate(::com::sun::star::util::DateTime i_val) {
m_ModificationDate = i_val;
}
::rtl::OUString getPrintedBy() const { return m_PrintedBy; }
void setPrintedBy(::rtl::OUString i_val) { m_PrintedBy = i_val; }
::com::sun::star::util::DateTime
getPrintDate() const { return m_PrintDate; }
void setPrintDate(::com::sun::star::util::DateTime i_val) {
m_PrintDate = i_val;
}
sal_Int16 getEditingCycles() const { return m_EditingCycles; }
void setEditingCycles(sal_Int16 i_val) { m_EditingCycles = i_val; }
sal_Int32 getEditingDuration() const { return m_EditingDuration; }
void setEditingDuration(sal_Int32 i_val) { m_EditingDuration = i_val; }
::rtl::OUString getDescription() const { return m_Description; }
void setDescription(::rtl::OUString i_val) { m_Description = i_val; }
::rtl::OUString getKeywords() const { return m_Keywords; }
void setKeywords(::rtl::OUString i_val) { m_Keywords = i_val; }
::rtl::OUString getSubject() const { return m_Subject; }
void setSubject(::rtl::OUString i_val) { m_Subject = i_val; }
::rtl::OUString getTitle() const { return m_Title; }
void setTitle(::rtl::OUString i_val) { m_Title = i_val; }
::rtl::OUString getUserDefinedFieldTitle(size_t i_ix) const;
void setUserDefinedFieldTitle(size_t i_ix, ::rtl::OUString i_val);
::rtl::OUString getUserDefinedFieldValue(size_t i_ix) const;
void setUserDefinedFieldValue(size_t i_ix, ::rtl::OUString i_val);
/// reset user-specific data (author, modified-by, ...)
void resetUserData(const ::rtl::OUString & i_rAuthor);
void SetTemplate( BOOL b ) { bHasTemplate = b; }
FASTBOOL HasTemplate() const { return bHasTemplate; }
void SetDeleteUserData( BOOL bSet );
void SetUseUserData( BOOL bSet );
BOOL IsDeleteUserData() const;
BOOL IsUseUserData() const;
virtual SfxPoolItem* Clone( SfxItemPool* pPool = NULL ) const;
virtual int operator==( const SfxPoolItem& ) const;
virtual sal_Bool QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
virtual sal_Bool PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
};
// class SfxDocumentPage -------------------------------------------------
class SfxDocumentPage : public SfxTabPage
{
private:
FixedImage aBmp1;
Edit aNameED;
FixedLine aLine1FL;
FixedText aTypeFT;
svt::SelectableFixedText aShowTypeFT;
CheckBox aReadOnlyCB;
FixedText aFileFt;
svt::SelectableFixedText aFileValFt;
FixedText aSizeFT;
svt::SelectableFixedText aShowSizeFT;
FixedLine aLine2FL;
FixedText aCreateFt;
svt::SelectableFixedText aCreateValFt;
FixedText aChangeFt;
svt::SelectableFixedText aChangeValFt;
FixedText aSignedFt;
svt::SelectableFixedText aSignedValFt;
PushButton aSignatureBtn;
FixedText aPrintFt;
svt::SelectableFixedText aPrintValFt;
FixedText aTimeLogFt;
svt::SelectableFixedText aTimeLogValFt;
FixedText aDocNoFt;
svt::SelectableFixedText aDocNoValFt;
CheckBox aUseUserDataCB;
PushButton aDeleteBtn;
FixedLine aLine3FL;
FixedText aTemplFt;
svt::SelectableFixedText aTemplValFt;
String aUnknownSize;
String aMultiSignedStr;
BOOL bEnableUseUserData : 1,
bHandleDelete : 1;
DECL_LINK( DeleteHdl, PushButton * );
DECL_LINK( SignatureHdl, PushButton * );
void ImplUpdateSignatures();
protected:
SfxDocumentPage( Window* pParent, const SfxItemSet& );
virtual BOOL FillItemSet( SfxItemSet& );
virtual void Reset( const SfxItemSet& );
public:
static SfxTabPage* Create( Window* pParent, const SfxItemSet& );
void EnableUseUserData();
};
// class SfxDocumentDescPage ---------------------------------------------
class SfxDocumentDescPage : public SfxTabPage
{
private:
FixedText aTitleFt;
Edit aTitleEd;
FixedText aThemaFt;
Edit aThemaEd;
FixedText aKeywordsFt;
Edit aKeywordsEd;
FixedText aCommentFt;
MultiLineEdit aCommentEd;
SfxDocumentInfoItem* pInfoItem;
protected:
SfxDocumentDescPage( Window* pParent, const SfxItemSet& );
virtual BOOL FillItemSet( SfxItemSet& );
virtual void Reset( const SfxItemSet& );
public:
static SfxTabPage* Create( Window* pParent, const SfxItemSet& );
};
// class SfxDocumentUserPage ---------------------------------------------
class SfxDocumentUserPage : public SfxTabPage
{
private:
BOOL bLabelModified;
FixedText aInfo1Ft;
Edit aInfo1Ed;
FixedText aInfo2Ft;
Edit aInfo2Ed;
FixedText aInfo3Ft;
Edit aInfo3Ed;
FixedText aInfo4Ft;
Edit aInfo4Ed;
PushButton aEditLabelBtn;
SfxDocumentInfoItem* pInfoItem;
#if _SOLAR__PRIVATE
DECL_LINK( EditLabelHdl, PushButton * );
String GetLabelText_Impl( FixedText* pLabel );
void SetLabelText_Impl( FixedText* pLabel, const String& rNewLabel );
#endif
protected:
SfxDocumentUserPage( Window* pParent, const SfxItemSet& );
virtual BOOL FillItemSet( SfxItemSet& );
virtual void Reset( const SfxItemSet& );
public:
static SfxTabPage* Create( Window* pParent, const SfxItemSet& );
};
// class SfxInternetPage -------------------------------------------------
class TargetList;
namespace sfx2
{
class FileDialogHelper;
}
class SfxInternetPage : public SfxTabPage
{
private:
RadioButton aRBNoAutoUpdate;
RadioButton aRBReloadUpdate;
RadioButton aRBForwardUpdate;
FixedText aFTEvery;
NumericField aNFReload;
FixedText aFTReloadSeconds;
FixedText aFTAfter;
NumericField aNFAfter;
FixedText aFTAfterSeconds;
FixedText aFTURL;
Edit aEDForwardURL;
PushButton aPBBrowseURL;
FixedText aFTFrame;
ComboBox aCBFrame;
String aForwardErrorMessg;
String aBaseURL;
SfxDocumentInfoItem* pInfoItem;
sfx2::FileDialogHelper* pFileDlg;
enum STATE { S_Init, S_NoUpdate, S_Reload, S_Forward };
// S_Init is only valid as initial value
STATE eState;
void ChangeState( STATE eNewState ); // S_Init is not a valid value here
// also checks corresponding radiobutton
void EnableNoUpdate( BOOL bEnable );
void EnableReload( BOOL bEnable );
void EnableForward( BOOL bEnable );
DECL_LINK( ClickHdlNoUpdate, Control* );
DECL_LINK( ClickHdlReload, Control* );
DECL_LINK( ClickHdlForward, Control* );
DECL_LINK( ClickHdlBrowseURL, PushButton* );
DECL_LINK( DialogClosedHdl, sfx2::FileDialogHelper* );
using TabPage::DeactivatePage;
protected:
SfxInternetPage( Window* pParent, const SfxItemSet& );
~SfxInternetPage();
virtual BOOL FillItemSet( SfxItemSet& );
virtual void Reset( const SfxItemSet& );
virtual int DeactivatePage( SfxItemSet* pSet = 0 );
public:
static SfxTabPage* Create( Window* pParent, const SfxItemSet& );
};
// class SfxDocumentInfoDialog -------------------------------------------
class SFX2_DLLPUBLIC SfxDocumentInfoDialog : public SfxTabDialog
{
protected:
virtual void PageCreated( USHORT nId, SfxTabPage& rPage );
public:
SfxDocumentInfoDialog( Window* pParent, const SfxItemSet& );
};
#endif
|
/**
Copyright 2014-2015 Jason R. Wendlandt
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 "Graphics/RenderData.h"
#include "Math/Vector3.h"
namespace alpha
{
RenderData::RenderData(std::string psEntryPoint /*= "PS"*/)
: m_psEntryPoint(psEntryPoint)
{
}
RenderData::~RenderData()
{
}
void SetPosition(const Vector3 & /*pos*/)
{
}
void SetScale(const Vector3 & /*scale*/)
{
}
}
Fixed last undefined reference in linux build.
Will now build and run properly.
/**
Copyright 2014-2015 Jason R. Wendlandt
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 "Graphics/RenderData.h"
#include "Math/Vector3.h"
namespace alpha
{
RenderData::RenderData(std::string psEntryPoint /*= "PS"*/)
: m_psEntryPoint(psEntryPoint)
{
}
RenderData::~RenderData()
{
}
void RenderData::SetPosition(const Vector3 & /*pos*/)
{
}
void RenderData::SetScale(const Vector3 & /*scale*/)
{
}
}
|
/*************************************************************************
*
* Copyright 2016 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**************************************************************************/
#include <iostream>
#include <sstream>
#include <realm.hpp>
#include <realm/query_expression.hpp> // only needed to compile on v2.6.0
#include <realm/string_data.hpp>
#include <realm/util/file.hpp>
#include "compatibility.hpp"
#include "../util/timer.hpp"
#include "../util/random.hpp"
#include "../util/benchmark_results.hpp"
#include "../util/test_path.hpp"
#include "../util/unit_test.hpp"
#if REALM_ENABLE_ENCRYPTION
#include "../util/crypt_key.hpp"
#endif
using namespace compatibility;
using namespace realm;
using namespace realm::util;
using namespace realm::test_util;
namespace {
#define BASE_SIZE 3600
/**
This bechmark suite represents a number of common use cases,
from the perspective of the bindings. It does *not* benchmark
the type-safe C++ API, but only the things that language bindings
are likely to use internally.
This has the following implications:
- All access is done with a SharedGroup in transactions.
- The SharedGroup has full durability (is backed by a file).
(but all benchmarks are also run with MemOnly durability for comparison)
- Cases have been derived from:
https://github.com/realm/realm-java/blob/bp-performance-test/realm/src/androidTest/java/io/realm/RealmPerformanceTest.java
*/
const size_t min_repetitions = 10;
const size_t max_repetitions = 1000;
const double min_duration_s = 0.1;
const double min_warmup_time_s = 0.05;
const char* to_lead_cstr(RealmDurability level);
const char* to_ident_cstr(RealmDurability level);
#ifdef REALM_CLUSTER_IF
#define KEY(x) ObjKey(x)
#else
#define KEY(x) x
using ColKey = size_t;
#endif
struct Benchmark {
Benchmark()
{
}
virtual ~Benchmark()
{
}
virtual const char* name() const = 0;
virtual void before_all(DBRef)
{
}
virtual void after_all(DBRef)
{
}
virtual void before_each(DBRef)
{
}
virtual void after_each(DBRef)
{
#ifdef REALM_CLUSTER_IF
m_keys.clear();
#endif
}
virtual void operator()(DBRef) = 0;
RealmDurability m_durability = RealmDurability::Full;
const char* m_encryption_key = nullptr;
#ifdef REALM_CLUSTER_IF
std::vector<ObjKey> m_keys;
#endif
};
struct BenchmarkUnorderedTableViewClear : Benchmark {
const char* name() const
{
return "UnorderedTableViewClear";
}
void operator()(DBRef group)
{
const size_t rows = 10000;
WriteTransaction tr(group);
TableRef tbl = tr.add_table(name());
auto col = tbl->add_column(type_String, "s", true);
#ifdef REALM_CLUSTER_IF
tbl->create_objects(rows, m_keys);
#else
tbl->add_empty_row(rows);
#endif
tbl->add_search_index(col);
for (size_t t = 0; t < rows / 3; t += 3) {
#ifdef REALM_CLUSTER_IF
tbl->get_object(m_keys[t + 0]).set(col, StringData("foo"));
tbl->get_object(m_keys[t + 1]).set(col, StringData("bar"));
tbl->get_object(m_keys[t + 2]).set(col, StringData("hello"));
#else
tbl->set_string(col, t + 0, StringData("foo"));
tbl->set_string(col, t + 1, StringData("bar"));
tbl->set_string(col, t + 2, StringData("hello"));
#endif
}
TableView tv = (tbl->column<String>(col) == "foo").find_all();
tv.clear();
}
};
struct AddTable : Benchmark {
const char* name() const
{
return "AddTable";
}
void operator()(DBRef group)
{
WriteTransaction tr(group);
TableRef t = tr.add_table(name());
t->add_column(type_String, "first");
t->add_column(type_Int, "second");
t->add_column(type_Float, "third");
tr.commit();
}
void after_each(DBRef group)
{
TransactionRef tr = group->start_write();
tr->remove_table(name());
tr->commit();
}
};
struct BenchmarkWithStringsTable : Benchmark {
void before_all(DBRef group)
{
WriteTransaction tr(group);
TableRef t = tr.add_table("StringOnly");
m_col = t->add_column(type_String, "chars");
tr.commit();
}
void after_all(DBRef group)
{
TransactionRef tr = group->start_write();
tr->remove_table("StringOnly");
tr->commit();
}
ColKey m_col;
};
struct BenchmarkWithStrings : BenchmarkWithStringsTable {
void before_all(DBRef group)
{
BenchmarkWithStringsTable::before_all(group);
WriteTransaction tr(group);
TableRef t = tr.get_table("StringOnly");
for (size_t i = 0; i < BASE_SIZE * 4; ++i) {
std::stringstream ss;
ss << rand();
auto s = ss.str();
#ifdef REALM_CLUSTER_IF
Obj obj = t->create_object();
obj.set<StringData>(m_col, s);
m_keys.push_back(obj.get_key());
#else
auto r = t->add_empty_row();
t->set_string(m_col, r, s);
#endif
}
tr.commit();
}
};
struct BenchmarkWithStringsFewDup : BenchmarkWithStringsTable {
void before_all(DBRef group)
{
BenchmarkWithStringsTable::before_all(group);
WriteTransaction tr(group);
TableRef t = tr.get_table("StringOnly");
Random r;
for (size_t i = 0; i < BASE_SIZE * 4; ++i) {
std::stringstream ss;
ss << r.draw_int(0, BASE_SIZE * 2);
auto s = ss.str();
#ifdef REALM_CLUSTER_IF
Obj obj = t->create_object();
obj.set<StringData>(m_col, s);
m_keys.push_back(obj.get_key());
#else
auto row = t->add_empty_row();
t->set_string(m_col, row, s);
#endif
}
t->add_search_index(m_col);
tr.commit();
}
};
struct BenchmarkWithStringsManyDup : BenchmarkWithStringsTable {
void before_all(DBRef group)
{
BenchmarkWithStringsTable::before_all(group);
WriteTransaction tr(group);
TableRef t = tr.get_table("StringOnly");
Random r;
for (size_t i = 0; i < BASE_SIZE * 4; ++i) {
std::stringstream ss;
ss << r.draw_int(0, 100);
auto s = ss.str();
#ifdef REALM_CLUSTER_IF
Obj obj = t->create_object();
obj.set<StringData>(m_col, s);
m_keys.push_back(obj.get_key());
#else
auto row = t->add_empty_row();
t->set_string(m_col, row, s);
#endif
}
t->add_search_index(m_col);
tr.commit();
}
};
struct BenchmarkDistinctStringFewDupes : BenchmarkWithStringsFewDup {
const char* name() const
{
return "DistinctStringFewDupes";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
ConstTableView view = table->get_distinct_view(m_col);
}
};
struct BenchmarkDistinctStringManyDupes : BenchmarkWithStringsManyDup {
const char* name() const
{
return "DistinctStringManyDupes";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
ConstTableView view = table->get_distinct_view(m_col);
}
};
struct BenchmarkFindAllStringFewDupes : BenchmarkWithStringsFewDup {
const char* name() const
{
return "FindAllStringFewDupes";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
ConstTableView view = table->where().equal(m_col, StringData("10", 2)).find_all();
}
};
struct BenchmarkFindAllStringManyDupes : BenchmarkWithStringsManyDup {
const char* name() const
{
return "FindAllStringManyDupes";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
ConstTableView view = table->where().equal(m_col, StringData("10", 2)).find_all();
}
};
struct BenchmarkFindFirstStringFewDupes : BenchmarkWithStringsFewDup {
const char* name() const
{
return "FindFirstStringFewDupes";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
std::vector<std::string> strs = {
"10", "20", "30", "40", "50", "60", "70", "80", "90", "100",
};
for (auto s : strs) {
table->where().equal(m_col, StringData(s)).find();
}
}
};
struct BenchmarkFindFirstStringManyDupes : BenchmarkWithStringsManyDup {
const char* name() const
{
return "FindFirstStringManyDupes";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
std::vector<std::string> strs = {
"10", "20", "30", "40", "50", "60", "70", "80", "90", "100",
};
for (auto s : strs) {
table->where().equal(m_col, StringData(s)).find();
}
}
};
struct BenchmarkWithLongStrings : BenchmarkWithStrings {
void before_all(DBRef group)
{
BenchmarkWithStrings::before_all(group);
WriteTransaction tr(group);
TableRef t = tr.get_table("StringOnly");
// This should be enough to upgrade the entire array:
static std::string really_long_string = "A really long string, longer than 63 bytes at least, I guess......";
#ifdef REALM_CLUSTER_IF
t->get_object(m_keys[0]).set<StringData>(m_col, really_long_string);
t->get_object(m_keys[BASE_SIZE]).set<StringData>(m_col, really_long_string);
t->get_object(m_keys[BASE_SIZE * 2]).set<StringData>(m_col, really_long_string);
t->get_object(m_keys[BASE_SIZE * 3]).set<StringData>(m_col, really_long_string);
#else
t->insert_empty_row(0);
t->set_string(m_col, 0, really_long_string);
t->set_string(m_col, BASE_SIZE, really_long_string);
t->set_string(m_col, BASE_SIZE * 2, really_long_string);
t->set_string(m_col, BASE_SIZE * 3, really_long_string);
#endif
tr.commit();
}
};
struct BenchmarkWithIntsTable : Benchmark {
void before_all(DBRef group)
{
WriteTransaction tr(group);
TableRef t = tr.add_table("IntOnly");
m_col = t->add_column(type_Int, "ints");
tr.commit();
}
void after_all(DBRef group)
{
TransactionRef tr = group->start_write();
tr->remove_table("IntOnly");
tr->commit();
}
ColKey m_col;
};
struct BenchmarkWithInts : BenchmarkWithIntsTable {
void before_all(DBRef group)
{
BenchmarkWithIntsTable::before_all(group);
WriteTransaction tr(group);
TableRef t = tr.get_table("IntOnly");
Random r;
for (size_t i = 0; i < BASE_SIZE * 4; ++i) {
int64_t val = r.draw_int<int64_t>();
#ifdef REALM_CLUSTER_IF
Obj obj = t->create_object();
obj.set(m_col, val);
m_keys.push_back(obj.get_key());
#else
auto row = t->add_empty_row();
t->set_int(m_col, row, val);
#endif
}
tr.commit();
}
};
struct BenchmarkQuery : BenchmarkWithStrings {
const char* name() const
{
return "Query";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
ConstTableView view = table->find_all_string(m_col, "200");
}
};
struct BenchmarkSize : BenchmarkWithStrings {
const char* name() const
{
return "Size";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
volatile size_t dummy = table->size();
static_cast<void>(dummy);
}
};
struct BenchmarkSort : BenchmarkWithStrings {
const char* name() const
{
return "Sort";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
ConstTableView view = table->get_sorted_view(m_col);
}
};
struct BenchmarkEmptyCommit : Benchmark {
const char* name() const
{
return "EmptyCommit";
}
void operator()(DBRef group)
{
WriteTransaction tr(group);
tr.commit();
}
};
struct BenchmarkSortInt : BenchmarkWithInts {
const char* name() const
{
return "SortInt";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("IntOnly");
ConstTableView view = table->get_sorted_view(m_col);
}
};
struct BenchmarkDistinctIntFewDupes : BenchmarkWithIntsTable {
const char* name() const
{
return "DistinctIntNoDupes";
}
void before_all(DBRef group)
{
BenchmarkWithIntsTable::before_all(group);
WriteTransaction tr(group);
TableRef t = tr.get_table("IntOnly");
Random r;
for (size_t i = 0; i < BASE_SIZE * 4; ++i) {
int64_t val = r.draw_int(0, BASE_SIZE * 2);
#ifdef REALM_CLUSTER_IF
Obj obj = t->create_object();
obj.set(m_col, val);
m_keys.push_back(obj.get_key());
#else
auto row = t->add_empty_row();
t->set_int(m_col, row, val);
#endif
}
t->add_search_index(m_col);
tr.commit();
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("IntOnly");
ConstTableView view = table->get_distinct_view(m_col);
}
};
struct BenchmarkDistinctIntManyDupes : BenchmarkWithIntsTable {
const char* name() const
{
return "DistinctIntManyDupes";
}
void before_all(DBRef group)
{
BenchmarkWithIntsTable::before_all(group);
WriteTransaction tr(group);
TableRef t = tr.get_table("IntOnly");
Random r;
for (size_t i = 0; i < BASE_SIZE * 4; ++i) {
int64_t val = r.draw_int(0, 10);
#ifdef REALM_CLUSTER_IF
Obj obj = t->create_object();
obj.set(m_col, val);
m_keys.push_back(obj.get_key());
#else
auto row = t->add_empty_row();
t->set_int(m_col, row, val);
#endif
}
t->add_search_index(m_col);
tr.commit();
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("IntOnly");
ConstTableView view = table->get_distinct_view(m_col);
}
};
struct BenchmarkInsert : BenchmarkWithStringsTable {
const char* name() const
{
return "Insert";
}
void operator()(DBRef group)
{
WriteTransaction tr(group);
TableRef t = tr.get_table("StringOnly");
for (size_t i = 0; i < 10000; ++i) {
#ifdef REALM_CLUSTER_IF
Obj obj = t->create_object();
obj.set(m_col, "a");
m_keys.push_back(obj.get_key());
#else
auto row = t->add_empty_row();
t->set_string(m_col, row, "a");
#endif
}
tr.commit();
}
};
struct BenchmarkGetString : BenchmarkWithStrings {
const char* name() const
{
return "GetString";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
volatile int dummy = 0;
#ifdef REALM_CLUSTER_IF
for (auto obj : *table) {
StringData str = obj.get<String>(m_col);
dummy += str[0]; // to avoid over-optimization
}
#else
size_t len = table->size();
for (size_t i = 0; i < len; ++i) {
StringData str = table->get_string(m_col, i);
dummy += str[0]; // to avoid over-optimization
}
#endif
}
};
struct BenchmarkSetString : BenchmarkWithStrings {
const char* name() const
{
return "SetString";
}
void operator()(DBRef group)
{
WriteTransaction tr(group);
TableRef table = tr.get_table("StringOnly");
#ifdef REALM_CLUSTER_IF
for (auto obj : *table) {
obj.set<String>(m_col, "c");
}
#else
size_t len = table->size();
for (size_t i = 0; i < len; ++i) {
table->set_string(m_col, i, "c");
}
#endif
tr.commit();
}
};
struct BenchmarkCreateIndex : BenchmarkWithStrings {
const char* name() const
{
return "CreateIndex";
}
void operator()(DBRef group)
{
WriteTransaction tr(group);
TableRef table = tr.get_table("StringOnly");
table->add_search_index(m_col);
tr.commit();
}
};
struct BenchmarkGetLongString : BenchmarkWithLongStrings {
const char* name() const
{
return "GetLongString";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
volatile int dummy = 0;
#ifdef REALM_CLUSTER_IF
for (auto obj : *table) {
StringData str = obj.get<String>(m_col);
dummy += str[0]; // to avoid over-optimization
}
#else
size_t len = table->size();
for (size_t i = 0; i < len; ++i) {
StringData str = table->get_string(m_col, i);
dummy += str[0]; // to avoid over-optimization
}
#endif
}
};
struct BenchmarkQueryLongString : BenchmarkWithStrings {
static constexpr const char* long_string = "This is some other long string, that takes a lot of time to find";
bool ok;
const char* name() const
{
return "QueryLongString";
}
void before_all(DBRef group)
{
BenchmarkWithStrings::before_all(group);
WriteTransaction tr(group);
TableRef t = tr.get_table("StringOnly");
#ifdef REALM_CLUSTER_IF
auto it = t->begin();
it->set<String>(m_col, "Some random string");
++it;
it->set<String>(m_col, long_string);
#else
t->set_string(m_col, 0, "Some random string");
t->set_string(m_col, 1, long_string);
#endif
tr.commit();
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
StringData str(long_string);
ok = true;
auto q = table->where().equal(m_col, str);
for (size_t ndx = 0; ndx < 1000; ndx++) {
auto res = q.find();
if (res != KEY(1)) {
ok = false;
}
}
}
};
struct BenchmarkQueryInsensitiveString : BenchmarkWithStringsTable {
const char* name() const
{
return "QueryInsensitiveString";
}
std::string gen_random_case_string(size_t length)
{
std::stringstream ss;
for (size_t c = 0; c < length; ++c) {
bool lowercase = (rand() % 2) == 0;
// choose characters from a-z or A-Z
ss << char((rand() % 26) + (lowercase ? 97 : 65));
}
return ss.str();
}
std::string shuffle_case(std::string str)
{
for (size_t i = 0; i < str.size(); ++i) {
char c = str[i];
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
bool change_case = (rand() % 2) == 0;
c ^= change_case ? 0x20 : 0;
}
str[i] = c;
}
return str;
}
size_t rand() {
return seeded_rand.draw_int<size_t>();
}
void before_all(DBRef group)
{
BenchmarkWithStringsTable::before_all(group);
// chosen by fair dice roll, guaranteed to be random
static const unsigned long seed = 4;
seeded_rand.seed(seed);
WriteTransaction tr(group);
TableRef t = tr.get_table("StringOnly");
const size_t max_chars_in_string = 100;
for (size_t i = 0; i < BASE_SIZE * 4; ++i) {
size_t num_chars = rand() % max_chars_in_string;
std::string randomly_cased_string = gen_random_case_string(num_chars);
#ifdef REALM_CLUSTER_IF
Obj obj = t->create_object();
obj.set<String>(m_col, randomly_cased_string);
m_keys.push_back(obj.get_key());
#else
auto row = t->add_empty_row();
t->set_string(m_col, row, randomly_cased_string);
#endif
}
tr.commit();
}
std::string needle;
bool successful = false;
Random seeded_rand;
void before_each(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
size_t target_row = rand() % table->size();
#ifdef REALM_CLUSTER_IF
ConstObj obj = table->get_object(m_keys[target_row]);
StringData target_str = obj.get<String>(m_col);
#else
StringData target_str = table->get_string(0, target_row);
#endif
needle = shuffle_case(target_str.data());
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
StringData str(needle);
Query q = table->where().equal(m_col, str, false);
TableView res = q.find_all();
successful = res.size() > 0;
}
};
struct BenchmarkQueryInsensitiveStringIndexed : BenchmarkQueryInsensitiveString {
const char* name() const
{
return "QueryInsensitiveStringIndexed";
}
void before_all(DBRef group)
{
BenchmarkQueryInsensitiveString::before_all(group);
WriteTransaction tr(group);
TableRef t = tr.get_table("StringOnly");
t->add_search_index(m_col);
tr.commit();
}
};
struct BenchmarkSetLongString : BenchmarkWithLongStrings {
const char* name() const
{
return "SetLongString";
}
void operator()(DBRef group)
{
WriteTransaction tr(group);
TableRef table = tr.get_table("StringOnly");
#ifdef REALM_CLUSTER_IF
Obj obj = table->create_object();
obj.set<String>(m_col, "c");
m_keys.push_back(obj.get_key());
#else
size_t len = table->size();
for (size_t i = 0; i < len; ++i) {
table->set_string(m_col, i, "c");
}
#endif
tr.commit();
}
};
struct BenchmarkQueryNot : Benchmark {
const char* name() const
{
return "QueryNot";
}
void before_all(DBRef group)
{
WriteTransaction tr(group);
TableRef table = tr.add_table(name());
m_col = table->add_column(type_Int, "first");
#ifdef REALM_CLUSTER_IF
for (size_t i = 0; i < 1000; ++i) {
table->create_object().set(m_col, 1);
}
#else
table->add_empty_row(1000);
for (size_t i = 0; i < 1000; ++i) {
table->set_int(m_col, i, 1);
}
#endif
tr.commit();
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table(name());
Query q = table->where();
q.not_equal(m_col, 2); // never found, = worst case
TableView results = q.find_all();
results.size();
}
void after_all(DBRef group)
{
TransactionRef tr = group->start_write();
tr->remove_table(name());
tr->commit();
}
ColKey m_col;
};
struct BenchmarkGetLinkList : Benchmark {
const char* name() const
{
return "GetLinkList";
}
static const size_t rows = 10000;
void before_all(DBRef group)
{
WriteTransaction tr(group);
std::string n = std::string(name()) + "_Destination";
TableRef destination_table = tr.add_table(n);
TableRef table = tr.add_table(name());
m_col_link = table->add_column_link(type_LinkList, "linklist", *destination_table);
#ifdef REALM_CLUSTER_IF
table->create_objects(rows, m_keys);
#else
table->add_empty_row(rows);
#endif
tr.commit();
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table(name());
#ifdef REALM_CLUSTER_IF
std::vector<ConstLinkListPtr> linklists(rows);
for (size_t i = 0; i < rows; ++i) {
auto obj = table->get_object(m_keys[i]);
linklists[i] = obj.get_linklist_ptr(m_col_link);
}
for (size_t i = 0; i < rows; ++i) {
auto obj = table->get_object(m_keys[i]);
obj.get_linklist_ptr(m_col_link);
}
for (size_t i = 0; i < rows; ++i) {
linklists[i].reset();
}
#else
std::vector<ConstLinkViewRef> linklists(rows);
for (size_t i = 0; i < rows; ++i) {
linklists[i] = table->get_linklist(m_col_link, i);
}
for (size_t i = 0; i < rows; ++i) {
table->get_linklist(m_col_link, i);
}
for (size_t i = 0; i < rows; ++i) {
linklists[i].reset();
}
#endif
}
void after_all(DBRef group)
{
TransactionRef tr = group->start_write();
tr->remove_table(name());
auto n = std::string(name()) + "_Destination";
tr->remove_table(n);
tr->commit();
}
ColKey m_col_link;
};
struct BenchmarkNonInitatorOpen : Benchmark {
const char* name() const
{
return "NonInitiatorOpen";
}
// the shared realm will be removed after the benchmark finishes
std::unique_ptr<realm::test_util::SharedGroupTestPathGuard> path;
DBRef initiator;
DBRef do_open()
{
const std::string realm_path = *path;
return create_new_shared_group(realm_path, m_durability, m_encryption_key);
}
void before_all(DBRef)
{
// Generate the benchmark result texts:
std::stringstream ident_ss;
ident_ss << "BenchmarkCommonTasks_" << this->name()
<< "_" << to_ident_cstr(m_durability);
std::string ident = ident_ss.str();
realm::test_util::unit_test::TestDetails test_details;
test_details.suite_name = "BenchmarkCommonTasks";
test_details.test_name = ident.c_str();
test_details.file_name = __FILE__;
test_details.line_number = __LINE__;
path = std::unique_ptr<realm::test_util::SharedGroupTestPathGuard>(new realm::test_util::SharedGroupTestPathGuard(ident));
// open once - session initiation
initiator = do_open();
}
void operator()(DBRef)
{
// use groups of 10 to get higher times
for (size_t i = 0; i < 10; ++i) {
do_open();
// let it close, otherwise we get error: too many open files
}
}
};
const char* to_lead_cstr(RealmDurability level)
{
switch (level) {
case RealmDurability::Full:
return "Full ";
case RealmDurability::MemOnly:
return "MemOnly";
#ifndef _WIN32
case RealmDurability::Async:
return "Async ";
#endif
}
return nullptr;
}
const char* to_ident_cstr(RealmDurability level)
{
switch (level) {
case RealmDurability::Full:
return "Full";
case RealmDurability::MemOnly:
return "MemOnly";
#ifndef _WIN32
case RealmDurability::Async:
return "Async";
#endif
}
return nullptr;
}
void run_benchmark_once(Benchmark& benchmark, DBRef sg, Timer& timer)
{
timer.pause();
benchmark.before_each(sg);
timer.unpause();
benchmark(sg);
timer.pause();
benchmark.after_each(sg);
timer.unpause();
}
/// This little piece of likely over-engineering runs the benchmark a number of times,
/// with each durability setting, and reports the results for each run.
template<typename B>
void run_benchmark(BenchmarkResults& results)
{
typedef std::pair<RealmDurability, const char*> config_pair;
std::vector<config_pair> configs;
configs.push_back(config_pair(RealmDurability::MemOnly, nullptr));
#if REALM_ENABLE_ENCRYPTION
configs.push_back(config_pair(RealmDurability::MemOnly, crypt_key(true)));
#endif
configs.push_back(config_pair(RealmDurability::Full, nullptr));
#if REALM_ENABLE_ENCRYPTION
configs.push_back(config_pair(RealmDurability::Full, crypt_key(true)));
#endif
Timer timer(Timer::type_UserTime);
for (auto it = configs.begin(); it != configs.end(); ++it) {
RealmDurability level = it->first;
const char* key = it->second;
B benchmark;
benchmark.m_durability = level;
benchmark.m_encryption_key = key;
// Generate the benchmark result texts:
std::stringstream lead_text_ss;
std::stringstream ident_ss;
lead_text_ss << benchmark.name() << " (" << to_lead_cstr(level) << ", "
<< (key == nullptr ? "EncryptionOff" : "EncryptionOn") << ")";
ident_ss << benchmark.name() << "_" << to_ident_cstr(level)
<< (key == nullptr ? "_EncryptionOff" : "_EncryptionOn");
std::string ident = ident_ss.str();
realm::test_util::unit_test::TestDetails test_details;
test_details.suite_name = "BenchmarkCommonTasks";
test_details.test_name = ident.c_str();
test_details.file_name = __FILE__;
test_details.line_number = __LINE__;
// Open a SharedGroup:
realm::test_util::SharedGroupTestPathGuard realm_path("benchmark_common_tasks" + ident);
DBRef group;
group = create_new_shared_group(realm_path, level, key);
benchmark.before_all(group);
// Warm-up and initial measuring:
size_t num_warmup_reps = 1;
double time_to_execute_warmup_reps = 0;
while (time_to_execute_warmup_reps < min_warmup_time_s && num_warmup_reps < max_repetitions) {
num_warmup_reps *= 10;
Timer t(Timer::type_UserTime);
for (size_t i = 0; i < num_warmup_reps; ++i) {
run_benchmark_once(benchmark, group, t);
}
time_to_execute_warmup_reps = t.get_elapsed_time();
}
size_t required_reps = size_t(min_duration_s / (time_to_execute_warmup_reps / num_warmup_reps));
if (required_reps < min_repetitions) {
required_reps = min_repetitions;
}
if (required_reps > max_repetitions) {
required_reps = max_repetitions;
}
for (size_t rep = 0; rep < required_reps; ++rep) {
Timer t;
run_benchmark_once(benchmark, group, t);
double s = t.get_elapsed_time();
results.submit(ident.c_str(), s);
}
benchmark.after_all(group);
results.finish(ident, lead_text_ss.str());
}
std::cout << std::endl;
}
} // anonymous namespace
extern "C" int benchmark_common_tasks_main();
int benchmark_common_tasks_main()
{
std::string results_file_stem = realm::test_util::get_test_path_prefix() + "results";
BenchmarkResults results(40, results_file_stem.c_str());
#define BENCH(B) run_benchmark<B>(results)
BENCH(BenchmarkUnorderedTableViewClear);
BENCH(BenchmarkEmptyCommit);
BENCH(AddTable);
BENCH(BenchmarkQuery);
BENCH(BenchmarkQueryNot);
BENCH(BenchmarkSize);
BENCH(BenchmarkSort);
BENCH(BenchmarkSortInt);
BENCH(BenchmarkDistinctIntFewDupes);
BENCH(BenchmarkDistinctIntManyDupes);
BENCH(BenchmarkDistinctStringFewDupes);
BENCH(BenchmarkDistinctStringManyDupes);
BENCH(BenchmarkFindAllStringFewDupes);
BENCH(BenchmarkFindAllStringManyDupes);
BENCH(BenchmarkFindFirstStringFewDupes);
BENCH(BenchmarkFindFirstStringManyDupes);
BENCH(BenchmarkInsert);
BENCH(BenchmarkGetString);
BENCH(BenchmarkSetString);
BENCH(BenchmarkCreateIndex);
BENCH(BenchmarkGetLongString);
BENCH(BenchmarkQueryLongString);
BENCH(BenchmarkSetLongString);
BENCH(BenchmarkGetLinkList);
BENCH(BenchmarkQueryInsensitiveString);
BENCH(BenchmarkQueryInsensitiveStringIndexed);
BENCH(BenchmarkNonInitatorOpen);
#undef BENCH
return 0;
}
#if !REALM_IOS
int main(int, const char**)
{
return benchmark_common_tasks_main();
}
#endif
Some more List renaming
Change-Id: If1ff7fc94512d72a4dca134e6368db70bba827d3
/*************************************************************************
*
* Copyright 2016 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**************************************************************************/
#include <iostream>
#include <sstream>
#include <realm.hpp>
#include <realm/query_expression.hpp> // only needed to compile on v2.6.0
#include <realm/string_data.hpp>
#include <realm/util/file.hpp>
#include "compatibility.hpp"
#include "../util/timer.hpp"
#include "../util/random.hpp"
#include "../util/benchmark_results.hpp"
#include "../util/test_path.hpp"
#include "../util/unit_test.hpp"
#if REALM_ENABLE_ENCRYPTION
#include "../util/crypt_key.hpp"
#endif
using namespace compatibility;
using namespace realm;
using namespace realm::util;
using namespace realm::test_util;
namespace {
#define BASE_SIZE 3600
/**
This bechmark suite represents a number of common use cases,
from the perspective of the bindings. It does *not* benchmark
the type-safe C++ API, but only the things that language bindings
are likely to use internally.
This has the following implications:
- All access is done with a SharedGroup in transactions.
- The SharedGroup has full durability (is backed by a file).
(but all benchmarks are also run with MemOnly durability for comparison)
- Cases have been derived from:
https://github.com/realm/realm-java/blob/bp-performance-test/realm/src/androidTest/java/io/realm/RealmPerformanceTest.java
*/
const size_t min_repetitions = 10;
const size_t max_repetitions = 1000;
const double min_duration_s = 0.1;
const double min_warmup_time_s = 0.05;
const char* to_lead_cstr(RealmDurability level);
const char* to_ident_cstr(RealmDurability level);
#ifdef REALM_CLUSTER_IF
#define KEY(x) ObjKey(x)
#else
#define KEY(x) x
using ColKey = size_t;
#endif
struct Benchmark {
Benchmark()
{
}
virtual ~Benchmark()
{
}
virtual const char* name() const = 0;
virtual void before_all(DBRef)
{
}
virtual void after_all(DBRef)
{
}
virtual void before_each(DBRef)
{
}
virtual void after_each(DBRef)
{
#ifdef REALM_CLUSTER_IF
m_keys.clear();
#endif
}
virtual void operator()(DBRef) = 0;
RealmDurability m_durability = RealmDurability::Full;
const char* m_encryption_key = nullptr;
#ifdef REALM_CLUSTER_IF
std::vector<ObjKey> m_keys;
#endif
};
struct BenchmarkUnorderedTableViewClear : Benchmark {
const char* name() const
{
return "UnorderedTableViewClear";
}
void operator()(DBRef group)
{
const size_t rows = 10000;
WriteTransaction tr(group);
TableRef tbl = tr.add_table(name());
auto col = tbl->add_column(type_String, "s", true);
#ifdef REALM_CLUSTER_IF
tbl->create_objects(rows, m_keys);
#else
tbl->add_empty_row(rows);
#endif
tbl->add_search_index(col);
for (size_t t = 0; t < rows / 3; t += 3) {
#ifdef REALM_CLUSTER_IF
tbl->get_object(m_keys[t + 0]).set(col, StringData("foo"));
tbl->get_object(m_keys[t + 1]).set(col, StringData("bar"));
tbl->get_object(m_keys[t + 2]).set(col, StringData("hello"));
#else
tbl->set_string(col, t + 0, StringData("foo"));
tbl->set_string(col, t + 1, StringData("bar"));
tbl->set_string(col, t + 2, StringData("hello"));
#endif
}
TableView tv = (tbl->column<String>(col) == "foo").find_all();
tv.clear();
}
};
struct AddTable : Benchmark {
const char* name() const
{
return "AddTable";
}
void operator()(DBRef group)
{
WriteTransaction tr(group);
TableRef t = tr.add_table(name());
t->add_column(type_String, "first");
t->add_column(type_Int, "second");
t->add_column(type_Float, "third");
tr.commit();
}
void after_each(DBRef group)
{
TransactionRef tr = group->start_write();
tr->remove_table(name());
tr->commit();
}
};
struct BenchmarkWithStringsTable : Benchmark {
void before_all(DBRef group)
{
WriteTransaction tr(group);
TableRef t = tr.add_table("StringOnly");
m_col = t->add_column(type_String, "chars");
tr.commit();
}
void after_all(DBRef group)
{
TransactionRef tr = group->start_write();
tr->remove_table("StringOnly");
tr->commit();
}
ColKey m_col;
};
struct BenchmarkWithStrings : BenchmarkWithStringsTable {
void before_all(DBRef group)
{
BenchmarkWithStringsTable::before_all(group);
WriteTransaction tr(group);
TableRef t = tr.get_table("StringOnly");
for (size_t i = 0; i < BASE_SIZE * 4; ++i) {
std::stringstream ss;
ss << rand();
auto s = ss.str();
#ifdef REALM_CLUSTER_IF
Obj obj = t->create_object();
obj.set<StringData>(m_col, s);
m_keys.push_back(obj.get_key());
#else
auto r = t->add_empty_row();
t->set_string(m_col, r, s);
#endif
}
tr.commit();
}
};
struct BenchmarkWithStringsFewDup : BenchmarkWithStringsTable {
void before_all(DBRef group)
{
BenchmarkWithStringsTable::before_all(group);
WriteTransaction tr(group);
TableRef t = tr.get_table("StringOnly");
Random r;
for (size_t i = 0; i < BASE_SIZE * 4; ++i) {
std::stringstream ss;
ss << r.draw_int(0, BASE_SIZE * 2);
auto s = ss.str();
#ifdef REALM_CLUSTER_IF
Obj obj = t->create_object();
obj.set<StringData>(m_col, s);
m_keys.push_back(obj.get_key());
#else
auto row = t->add_empty_row();
t->set_string(m_col, row, s);
#endif
}
t->add_search_index(m_col);
tr.commit();
}
};
struct BenchmarkWithStringsManyDup : BenchmarkWithStringsTable {
void before_all(DBRef group)
{
BenchmarkWithStringsTable::before_all(group);
WriteTransaction tr(group);
TableRef t = tr.get_table("StringOnly");
Random r;
for (size_t i = 0; i < BASE_SIZE * 4; ++i) {
std::stringstream ss;
ss << r.draw_int(0, 100);
auto s = ss.str();
#ifdef REALM_CLUSTER_IF
Obj obj = t->create_object();
obj.set<StringData>(m_col, s);
m_keys.push_back(obj.get_key());
#else
auto row = t->add_empty_row();
t->set_string(m_col, row, s);
#endif
}
t->add_search_index(m_col);
tr.commit();
}
};
struct BenchmarkDistinctStringFewDupes : BenchmarkWithStringsFewDup {
const char* name() const
{
return "DistinctStringFewDupes";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
ConstTableView view = table->get_distinct_view(m_col);
}
};
struct BenchmarkDistinctStringManyDupes : BenchmarkWithStringsManyDup {
const char* name() const
{
return "DistinctStringManyDupes";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
ConstTableView view = table->get_distinct_view(m_col);
}
};
struct BenchmarkFindAllStringFewDupes : BenchmarkWithStringsFewDup {
const char* name() const
{
return "FindAllStringFewDupes";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
ConstTableView view = table->where().equal(m_col, StringData("10", 2)).find_all();
}
};
struct BenchmarkFindAllStringManyDupes : BenchmarkWithStringsManyDup {
const char* name() const
{
return "FindAllStringManyDupes";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
ConstTableView view = table->where().equal(m_col, StringData("10", 2)).find_all();
}
};
struct BenchmarkFindFirstStringFewDupes : BenchmarkWithStringsFewDup {
const char* name() const
{
return "FindFirstStringFewDupes";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
std::vector<std::string> strs = {
"10", "20", "30", "40", "50", "60", "70", "80", "90", "100",
};
for (auto s : strs) {
table->where().equal(m_col, StringData(s)).find();
}
}
};
struct BenchmarkFindFirstStringManyDupes : BenchmarkWithStringsManyDup {
const char* name() const
{
return "FindFirstStringManyDupes";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
std::vector<std::string> strs = {
"10", "20", "30", "40", "50", "60", "70", "80", "90", "100",
};
for (auto s : strs) {
table->where().equal(m_col, StringData(s)).find();
}
}
};
struct BenchmarkWithLongStrings : BenchmarkWithStrings {
void before_all(DBRef group)
{
BenchmarkWithStrings::before_all(group);
WriteTransaction tr(group);
TableRef t = tr.get_table("StringOnly");
// This should be enough to upgrade the entire array:
static std::string really_long_string = "A really long string, longer than 63 bytes at least, I guess......";
#ifdef REALM_CLUSTER_IF
t->get_object(m_keys[0]).set<StringData>(m_col, really_long_string);
t->get_object(m_keys[BASE_SIZE]).set<StringData>(m_col, really_long_string);
t->get_object(m_keys[BASE_SIZE * 2]).set<StringData>(m_col, really_long_string);
t->get_object(m_keys[BASE_SIZE * 3]).set<StringData>(m_col, really_long_string);
#else
t->insert_empty_row(0);
t->set_string(m_col, 0, really_long_string);
t->set_string(m_col, BASE_SIZE, really_long_string);
t->set_string(m_col, BASE_SIZE * 2, really_long_string);
t->set_string(m_col, BASE_SIZE * 3, really_long_string);
#endif
tr.commit();
}
};
struct BenchmarkWithIntsTable : Benchmark {
void before_all(DBRef group)
{
WriteTransaction tr(group);
TableRef t = tr.add_table("IntOnly");
m_col = t->add_column(type_Int, "ints");
tr.commit();
}
void after_all(DBRef group)
{
TransactionRef tr = group->start_write();
tr->remove_table("IntOnly");
tr->commit();
}
ColKey m_col;
};
struct BenchmarkWithInts : BenchmarkWithIntsTable {
void before_all(DBRef group)
{
BenchmarkWithIntsTable::before_all(group);
WriteTransaction tr(group);
TableRef t = tr.get_table("IntOnly");
Random r;
for (size_t i = 0; i < BASE_SIZE * 4; ++i) {
int64_t val = r.draw_int<int64_t>();
#ifdef REALM_CLUSTER_IF
Obj obj = t->create_object();
obj.set(m_col, val);
m_keys.push_back(obj.get_key());
#else
auto row = t->add_empty_row();
t->set_int(m_col, row, val);
#endif
}
tr.commit();
}
};
struct BenchmarkQuery : BenchmarkWithStrings {
const char* name() const
{
return "Query";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
ConstTableView view = table->find_all_string(m_col, "200");
}
};
struct BenchmarkSize : BenchmarkWithStrings {
const char* name() const
{
return "Size";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
volatile size_t dummy = table->size();
static_cast<void>(dummy);
}
};
struct BenchmarkSort : BenchmarkWithStrings {
const char* name() const
{
return "Sort";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
ConstTableView view = table->get_sorted_view(m_col);
}
};
struct BenchmarkEmptyCommit : Benchmark {
const char* name() const
{
return "EmptyCommit";
}
void operator()(DBRef group)
{
WriteTransaction tr(group);
tr.commit();
}
};
struct BenchmarkSortInt : BenchmarkWithInts {
const char* name() const
{
return "SortInt";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("IntOnly");
ConstTableView view = table->get_sorted_view(m_col);
}
};
struct BenchmarkDistinctIntFewDupes : BenchmarkWithIntsTable {
const char* name() const
{
return "DistinctIntNoDupes";
}
void before_all(DBRef group)
{
BenchmarkWithIntsTable::before_all(group);
WriteTransaction tr(group);
TableRef t = tr.get_table("IntOnly");
Random r;
for (size_t i = 0; i < BASE_SIZE * 4; ++i) {
int64_t val = r.draw_int(0, BASE_SIZE * 2);
#ifdef REALM_CLUSTER_IF
Obj obj = t->create_object();
obj.set(m_col, val);
m_keys.push_back(obj.get_key());
#else
auto row = t->add_empty_row();
t->set_int(m_col, row, val);
#endif
}
t->add_search_index(m_col);
tr.commit();
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("IntOnly");
ConstTableView view = table->get_distinct_view(m_col);
}
};
struct BenchmarkDistinctIntManyDupes : BenchmarkWithIntsTable {
const char* name() const
{
return "DistinctIntManyDupes";
}
void before_all(DBRef group)
{
BenchmarkWithIntsTable::before_all(group);
WriteTransaction tr(group);
TableRef t = tr.get_table("IntOnly");
Random r;
for (size_t i = 0; i < BASE_SIZE * 4; ++i) {
int64_t val = r.draw_int(0, 10);
#ifdef REALM_CLUSTER_IF
Obj obj = t->create_object();
obj.set(m_col, val);
m_keys.push_back(obj.get_key());
#else
auto row = t->add_empty_row();
t->set_int(m_col, row, val);
#endif
}
t->add_search_index(m_col);
tr.commit();
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("IntOnly");
ConstTableView view = table->get_distinct_view(m_col);
}
};
struct BenchmarkInsert : BenchmarkWithStringsTable {
const char* name() const
{
return "Insert";
}
void operator()(DBRef group)
{
WriteTransaction tr(group);
TableRef t = tr.get_table("StringOnly");
for (size_t i = 0; i < 10000; ++i) {
#ifdef REALM_CLUSTER_IF
Obj obj = t->create_object();
obj.set(m_col, "a");
m_keys.push_back(obj.get_key());
#else
auto row = t->add_empty_row();
t->set_string(m_col, row, "a");
#endif
}
tr.commit();
}
};
struct BenchmarkGetString : BenchmarkWithStrings {
const char* name() const
{
return "GetString";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
volatile int dummy = 0;
#ifdef REALM_CLUSTER_IF
for (auto obj : *table) {
StringData str = obj.get<String>(m_col);
dummy += str[0]; // to avoid over-optimization
}
#else
size_t len = table->size();
for (size_t i = 0; i < len; ++i) {
StringData str = table->get_string(m_col, i);
dummy += str[0]; // to avoid over-optimization
}
#endif
}
};
struct BenchmarkSetString : BenchmarkWithStrings {
const char* name() const
{
return "SetString";
}
void operator()(DBRef group)
{
WriteTransaction tr(group);
TableRef table = tr.get_table("StringOnly");
#ifdef REALM_CLUSTER_IF
for (auto obj : *table) {
obj.set<String>(m_col, "c");
}
#else
size_t len = table->size();
for (size_t i = 0; i < len; ++i) {
table->set_string(m_col, i, "c");
}
#endif
tr.commit();
}
};
struct BenchmarkCreateIndex : BenchmarkWithStrings {
const char* name() const
{
return "CreateIndex";
}
void operator()(DBRef group)
{
WriteTransaction tr(group);
TableRef table = tr.get_table("StringOnly");
table->add_search_index(m_col);
tr.commit();
}
};
struct BenchmarkGetLongString : BenchmarkWithLongStrings {
const char* name() const
{
return "GetLongString";
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
volatile int dummy = 0;
#ifdef REALM_CLUSTER_IF
for (auto obj : *table) {
StringData str = obj.get<String>(m_col);
dummy += str[0]; // to avoid over-optimization
}
#else
size_t len = table->size();
for (size_t i = 0; i < len; ++i) {
StringData str = table->get_string(m_col, i);
dummy += str[0]; // to avoid over-optimization
}
#endif
}
};
struct BenchmarkQueryLongString : BenchmarkWithStrings {
static constexpr const char* long_string = "This is some other long string, that takes a lot of time to find";
bool ok;
const char* name() const
{
return "QueryLongString";
}
void before_all(DBRef group)
{
BenchmarkWithStrings::before_all(group);
WriteTransaction tr(group);
TableRef t = tr.get_table("StringOnly");
#ifdef REALM_CLUSTER_IF
auto it = t->begin();
it->set<String>(m_col, "Some random string");
++it;
it->set<String>(m_col, long_string);
#else
t->set_string(m_col, 0, "Some random string");
t->set_string(m_col, 1, long_string);
#endif
tr.commit();
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
StringData str(long_string);
ok = true;
auto q = table->where().equal(m_col, str);
for (size_t ndx = 0; ndx < 1000; ndx++) {
auto res = q.find();
if (res != KEY(1)) {
ok = false;
}
}
}
};
struct BenchmarkQueryInsensitiveString : BenchmarkWithStringsTable {
const char* name() const
{
return "QueryInsensitiveString";
}
std::string gen_random_case_string(size_t length)
{
std::stringstream ss;
for (size_t c = 0; c < length; ++c) {
bool lowercase = (rand() % 2) == 0;
// choose characters from a-z or A-Z
ss << char((rand() % 26) + (lowercase ? 97 : 65));
}
return ss.str();
}
std::string shuffle_case(std::string str)
{
for (size_t i = 0; i < str.size(); ++i) {
char c = str[i];
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
bool change_case = (rand() % 2) == 0;
c ^= change_case ? 0x20 : 0;
}
str[i] = c;
}
return str;
}
size_t rand() {
return seeded_rand.draw_int<size_t>();
}
void before_all(DBRef group)
{
BenchmarkWithStringsTable::before_all(group);
// chosen by fair dice roll, guaranteed to be random
static const unsigned long seed = 4;
seeded_rand.seed(seed);
WriteTransaction tr(group);
TableRef t = tr.get_table("StringOnly");
const size_t max_chars_in_string = 100;
for (size_t i = 0; i < BASE_SIZE * 4; ++i) {
size_t num_chars = rand() % max_chars_in_string;
std::string randomly_cased_string = gen_random_case_string(num_chars);
#ifdef REALM_CLUSTER_IF
Obj obj = t->create_object();
obj.set<String>(m_col, randomly_cased_string);
m_keys.push_back(obj.get_key());
#else
auto row = t->add_empty_row();
t->set_string(m_col, row, randomly_cased_string);
#endif
}
tr.commit();
}
std::string needle;
bool successful = false;
Random seeded_rand;
void before_each(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
size_t target_row = rand() % table->size();
#ifdef REALM_CLUSTER_IF
ConstObj obj = table->get_object(m_keys[target_row]);
StringData target_str = obj.get<String>(m_col);
#else
StringData target_str = table->get_string(0, target_row);
#endif
needle = shuffle_case(target_str.data());
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
StringData str(needle);
Query q = table->where().equal(m_col, str, false);
TableView res = q.find_all();
successful = res.size() > 0;
}
};
struct BenchmarkQueryInsensitiveStringIndexed : BenchmarkQueryInsensitiveString {
const char* name() const
{
return "QueryInsensitiveStringIndexed";
}
void before_all(DBRef group)
{
BenchmarkQueryInsensitiveString::before_all(group);
WriteTransaction tr(group);
TableRef t = tr.get_table("StringOnly");
t->add_search_index(m_col);
tr.commit();
}
};
struct BenchmarkSetLongString : BenchmarkWithLongStrings {
const char* name() const
{
return "SetLongString";
}
void operator()(DBRef group)
{
WriteTransaction tr(group);
TableRef table = tr.get_table("StringOnly");
#ifdef REALM_CLUSTER_IF
Obj obj = table->create_object();
obj.set<String>(m_col, "c");
m_keys.push_back(obj.get_key());
#else
size_t len = table->size();
for (size_t i = 0; i < len; ++i) {
table->set_string(m_col, i, "c");
}
#endif
tr.commit();
}
};
struct BenchmarkQueryNot : Benchmark {
const char* name() const
{
return "QueryNot";
}
void before_all(DBRef group)
{
WriteTransaction tr(group);
TableRef table = tr.add_table(name());
m_col = table->add_column(type_Int, "first");
#ifdef REALM_CLUSTER_IF
for (size_t i = 0; i < 1000; ++i) {
table->create_object().set(m_col, 1);
}
#else
table->add_empty_row(1000);
for (size_t i = 0; i < 1000; ++i) {
table->set_int(m_col, i, 1);
}
#endif
tr.commit();
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table(name());
Query q = table->where();
q.not_equal(m_col, 2); // never found, = worst case
TableView results = q.find_all();
results.size();
}
void after_all(DBRef group)
{
TransactionRef tr = group->start_write();
tr->remove_table(name());
tr->commit();
}
ColKey m_col;
};
struct BenchmarkGetLinkList : Benchmark {
const char* name() const
{
return "GetLinkList";
}
static const size_t rows = 10000;
void before_all(DBRef group)
{
WriteTransaction tr(group);
std::string n = std::string(name()) + "_Destination";
TableRef destination_table = tr.add_table(n);
TableRef table = tr.add_table(name());
m_col_link = table->add_column_link(type_LinkList, "linklist", *destination_table);
#ifdef REALM_CLUSTER_IF
table->create_objects(rows, m_keys);
#else
table->add_empty_row(rows);
#endif
tr.commit();
}
void operator()(DBRef group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table(name());
#ifdef REALM_CLUSTER_IF
std::vector<ConstLnkLstPtr> linklists(rows);
for (size_t i = 0; i < rows; ++i) {
auto obj = table->get_object(m_keys[i]);
linklists[i] = obj.get_linklist_ptr(m_col_link);
}
for (size_t i = 0; i < rows; ++i) {
auto obj = table->get_object(m_keys[i]);
obj.get_linklist_ptr(m_col_link);
}
for (size_t i = 0; i < rows; ++i) {
linklists[i].reset();
}
#else
std::vector<ConstLinkViewRef> linklists(rows);
for (size_t i = 0; i < rows; ++i) {
linklists[i] = table->get_linklist(m_col_link, i);
}
for (size_t i = 0; i < rows; ++i) {
table->get_linklist(m_col_link, i);
}
for (size_t i = 0; i < rows; ++i) {
linklists[i].reset();
}
#endif
}
void after_all(DBRef group)
{
TransactionRef tr = group->start_write();
tr->remove_table(name());
auto n = std::string(name()) + "_Destination";
tr->remove_table(n);
tr->commit();
}
ColKey m_col_link;
};
struct BenchmarkNonInitatorOpen : Benchmark {
const char* name() const
{
return "NonInitiatorOpen";
}
// the shared realm will be removed after the benchmark finishes
std::unique_ptr<realm::test_util::SharedGroupTestPathGuard> path;
DBRef initiator;
DBRef do_open()
{
const std::string realm_path = *path;
return create_new_shared_group(realm_path, m_durability, m_encryption_key);
}
void before_all(DBRef)
{
// Generate the benchmark result texts:
std::stringstream ident_ss;
ident_ss << "BenchmarkCommonTasks_" << this->name()
<< "_" << to_ident_cstr(m_durability);
std::string ident = ident_ss.str();
realm::test_util::unit_test::TestDetails test_details;
test_details.suite_name = "BenchmarkCommonTasks";
test_details.test_name = ident.c_str();
test_details.file_name = __FILE__;
test_details.line_number = __LINE__;
path = std::unique_ptr<realm::test_util::SharedGroupTestPathGuard>(new realm::test_util::SharedGroupTestPathGuard(ident));
// open once - session initiation
initiator = do_open();
}
void operator()(DBRef)
{
// use groups of 10 to get higher times
for (size_t i = 0; i < 10; ++i) {
do_open();
// let it close, otherwise we get error: too many open files
}
}
};
const char* to_lead_cstr(RealmDurability level)
{
switch (level) {
case RealmDurability::Full:
return "Full ";
case RealmDurability::MemOnly:
return "MemOnly";
#ifndef _WIN32
case RealmDurability::Async:
return "Async ";
#endif
}
return nullptr;
}
const char* to_ident_cstr(RealmDurability level)
{
switch (level) {
case RealmDurability::Full:
return "Full";
case RealmDurability::MemOnly:
return "MemOnly";
#ifndef _WIN32
case RealmDurability::Async:
return "Async";
#endif
}
return nullptr;
}
void run_benchmark_once(Benchmark& benchmark, DBRef sg, Timer& timer)
{
timer.pause();
benchmark.before_each(sg);
timer.unpause();
benchmark(sg);
timer.pause();
benchmark.after_each(sg);
timer.unpause();
}
/// This little piece of likely over-engineering runs the benchmark a number of times,
/// with each durability setting, and reports the results for each run.
template<typename B>
void run_benchmark(BenchmarkResults& results)
{
typedef std::pair<RealmDurability, const char*> config_pair;
std::vector<config_pair> configs;
configs.push_back(config_pair(RealmDurability::MemOnly, nullptr));
#if REALM_ENABLE_ENCRYPTION
configs.push_back(config_pair(RealmDurability::MemOnly, crypt_key(true)));
#endif
configs.push_back(config_pair(RealmDurability::Full, nullptr));
#if REALM_ENABLE_ENCRYPTION
configs.push_back(config_pair(RealmDurability::Full, crypt_key(true)));
#endif
Timer timer(Timer::type_UserTime);
for (auto it = configs.begin(); it != configs.end(); ++it) {
RealmDurability level = it->first;
const char* key = it->second;
B benchmark;
benchmark.m_durability = level;
benchmark.m_encryption_key = key;
// Generate the benchmark result texts:
std::stringstream lead_text_ss;
std::stringstream ident_ss;
lead_text_ss << benchmark.name() << " (" << to_lead_cstr(level) << ", "
<< (key == nullptr ? "EncryptionOff" : "EncryptionOn") << ")";
ident_ss << benchmark.name() << "_" << to_ident_cstr(level)
<< (key == nullptr ? "_EncryptionOff" : "_EncryptionOn");
std::string ident = ident_ss.str();
realm::test_util::unit_test::TestDetails test_details;
test_details.suite_name = "BenchmarkCommonTasks";
test_details.test_name = ident.c_str();
test_details.file_name = __FILE__;
test_details.line_number = __LINE__;
// Open a SharedGroup:
realm::test_util::SharedGroupTestPathGuard realm_path("benchmark_common_tasks" + ident);
DBRef group;
group = create_new_shared_group(realm_path, level, key);
benchmark.before_all(group);
// Warm-up and initial measuring:
size_t num_warmup_reps = 1;
double time_to_execute_warmup_reps = 0;
while (time_to_execute_warmup_reps < min_warmup_time_s && num_warmup_reps < max_repetitions) {
num_warmup_reps *= 10;
Timer t(Timer::type_UserTime);
for (size_t i = 0; i < num_warmup_reps; ++i) {
run_benchmark_once(benchmark, group, t);
}
time_to_execute_warmup_reps = t.get_elapsed_time();
}
size_t required_reps = size_t(min_duration_s / (time_to_execute_warmup_reps / num_warmup_reps));
if (required_reps < min_repetitions) {
required_reps = min_repetitions;
}
if (required_reps > max_repetitions) {
required_reps = max_repetitions;
}
for (size_t rep = 0; rep < required_reps; ++rep) {
Timer t;
run_benchmark_once(benchmark, group, t);
double s = t.get_elapsed_time();
results.submit(ident.c_str(), s);
}
benchmark.after_all(group);
results.finish(ident, lead_text_ss.str());
}
std::cout << std::endl;
}
} // anonymous namespace
extern "C" int benchmark_common_tasks_main();
int benchmark_common_tasks_main()
{
std::string results_file_stem = realm::test_util::get_test_path_prefix() + "results";
BenchmarkResults results(40, results_file_stem.c_str());
#define BENCH(B) run_benchmark<B>(results)
BENCH(BenchmarkUnorderedTableViewClear);
BENCH(BenchmarkEmptyCommit);
BENCH(AddTable);
BENCH(BenchmarkQuery);
BENCH(BenchmarkQueryNot);
BENCH(BenchmarkSize);
BENCH(BenchmarkSort);
BENCH(BenchmarkSortInt);
BENCH(BenchmarkDistinctIntFewDupes);
BENCH(BenchmarkDistinctIntManyDupes);
BENCH(BenchmarkDistinctStringFewDupes);
BENCH(BenchmarkDistinctStringManyDupes);
BENCH(BenchmarkFindAllStringFewDupes);
BENCH(BenchmarkFindAllStringManyDupes);
BENCH(BenchmarkFindFirstStringFewDupes);
BENCH(BenchmarkFindFirstStringManyDupes);
BENCH(BenchmarkInsert);
BENCH(BenchmarkGetString);
BENCH(BenchmarkSetString);
BENCH(BenchmarkCreateIndex);
BENCH(BenchmarkGetLongString);
BENCH(BenchmarkQueryLongString);
BENCH(BenchmarkSetLongString);
BENCH(BenchmarkGetLinkList);
BENCH(BenchmarkQueryInsensitiveString);
BENCH(BenchmarkQueryInsensitiveStringIndexed);
BENCH(BenchmarkNonInitatorOpen);
#undef BENCH
return 0;
}
#if !REALM_IOS
int main(int, const char**)
{
return benchmark_common_tasks_main();
}
#endif
|
/*
* Copyright (C) 2017 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/test/unit_test.hpp>
#include <seastar/core/thread.hh>
#include <seastar/core/semaphore.hh>
#include "utils/serialized_action.hh"
#include <seastar/testing/test_case.hh>
#include "utils/phased_barrier.hh"
SEASTAR_TEST_CASE(test_serialized_action_triggering) {
return seastar::async([] {
int current = 0;
std::vector<int> history;
promise<> p;
seastar::semaphore sem{0};
serialized_action act([&] {
sem.signal(1);
auto val = current;
return p.get_future().then([&, val] {
history.push_back(val);
});
});
auto release = [&] {
std::exchange(p, promise<>()).set_value();
};
auto t1 = act.trigger();
sem.wait().get(); // wait for t1 action to block
current = 1;
auto t2 = act.trigger();
auto t3 = act.trigger();
current = 2;
release();
t1.get();
BOOST_REQUIRE(history.size() == 1);
BOOST_REQUIRE(history.back() == 0);
BOOST_REQUIRE(!t2.available());
BOOST_REQUIRE(!t3.available());
sem.wait().get(); // wait for t2 action to block
current = 3;
auto t4 = act.trigger();
release();
t2.get();
t3.get();
BOOST_REQUIRE(history.size() == 2);
BOOST_REQUIRE(history.back() == 2);
BOOST_REQUIRE(!t4.available());
sem.wait().get(); // wait for t4 action to block
current = 4;
release();
t4.get();
BOOST_REQUIRE(history.size() == 3);
BOOST_REQUIRE(history.back() == 3);
current = 5;
auto t5 = act.trigger();
sem.wait().get(); // wait for t5 action to block
release();
t5.get();
BOOST_REQUIRE(history.size() == 4);
BOOST_REQUIRE(history.back() == 5);
});
}
test: serialized_action_test: add test_serialized_action_exception
Tests that the exceptional future returned by the serialized action
is propagated to trigger, reproducing #7352.
The test fails without the previoud patch:
"serialized_action: trigger: include also semaphore status to promise"
Signed-off-by: Benny Halevy <23c997c90eb8537635e9392d48e7af1bf1b2ca22@scylladb.com>
/*
* Copyright (C) 2017 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/test/unit_test.hpp>
#include <seastar/core/thread.hh>
#include <seastar/core/semaphore.hh>
#include "utils/serialized_action.hh"
#include <seastar/testing/test_case.hh>
#include <seastar/testing/thread_test_case.hh>
#include "utils/phased_barrier.hh"
SEASTAR_TEST_CASE(test_serialized_action_triggering) {
return seastar::async([] {
int current = 0;
std::vector<int> history;
promise<> p;
seastar::semaphore sem{0};
serialized_action act([&] {
sem.signal(1);
auto val = current;
return p.get_future().then([&, val] {
history.push_back(val);
});
});
auto release = [&] {
std::exchange(p, promise<>()).set_value();
};
auto t1 = act.trigger();
sem.wait().get(); // wait for t1 action to block
current = 1;
auto t2 = act.trigger();
auto t3 = act.trigger();
current = 2;
release();
t1.get();
BOOST_REQUIRE(history.size() == 1);
BOOST_REQUIRE(history.back() == 0);
BOOST_REQUIRE(!t2.available());
BOOST_REQUIRE(!t3.available());
sem.wait().get(); // wait for t2 action to block
current = 3;
auto t4 = act.trigger();
release();
t2.get();
t3.get();
BOOST_REQUIRE(history.size() == 2);
BOOST_REQUIRE(history.back() == 2);
BOOST_REQUIRE(!t4.available());
sem.wait().get(); // wait for t4 action to block
current = 4;
release();
t4.get();
BOOST_REQUIRE(history.size() == 3);
BOOST_REQUIRE(history.back() == 3);
current = 5;
auto t5 = act.trigger();
sem.wait().get(); // wait for t5 action to block
release();
t5.get();
BOOST_REQUIRE(history.size() == 4);
BOOST_REQUIRE(history.back() == 5);
});
}
SEASTAR_THREAD_TEST_CASE(test_serialized_action_exception) {
class expected_exception : public std::exception {
public:
virtual const char* what() const noexcept override {
return "expected_exception";
}
};
serialized_action simple_action([&] {
return make_exception_future<>(expected_exception());
});
// test that the exception returned by the serialized action
// is propageted to the caller of trigger().
BOOST_REQUIRE_THROW(simple_action.trigger(false).get(), expected_exception);
BOOST_REQUIRE_THROW(simple_action.trigger(true).get(), expected_exception);
int count = 0;
promise<> p;
seastar::semaphore sem{0};
serialized_action triggered_action([&] {
sem.signal(1);
return p.get_future().then([&] {
count++;
return make_exception_future<>(expected_exception());
});
});
auto release = [&] {
std::exchange(p, promise<>()).set_value();
};
// test that the exception returned by the serialized action
// is propageted to pending callers of trigger().
auto t1 = triggered_action.trigger(); // launch the action in the background.
sem.wait().get(); // wait for t1 to block on `p`.
auto t2 = triggered_action.trigger(); // trigger the action again.
auto t3 = triggered_action.trigger(); // trigger the action again. t3 and t2 should share the same future.
release(); // signal t1 to proceed (and return the exception).
BOOST_REQUIRE_THROW(t1.get(), expected_exception);
BOOST_REQUIRE_EQUAL(count, 1);
sem.wait().get(); // wait for t2 to block on `p`.
release(); // signal t2 to proceed (and return the exception).
BOOST_REQUIRE_THROW(t2.get(), expected_exception);
BOOST_REQUIRE_THROW(t3.get(), expected_exception);
BOOST_REQUIRE_EQUAL(count, 2); // verify that `triggered_action` was called only once for t2 and t3.
}
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#include "Connection.hxx"
#include "DatabaseMetaData.hxx"
#include "Driver.hxx"
#include "PreparedStatement.hxx"
#include "Statement.hxx"
#include "Util.hxx"
#include <com/sun/star/document/XDocumentEventBroadcaster.hpp>
#include <com/sun/star/embed/ElementModes.hpp>
#include <com/sun/star/frame/Desktop.hpp>
#include <com/sun/star/frame/FrameSearchFlag.hpp>
#include <com/sun/star/frame/XController.hpp>
#include <com/sun/star/frame/XFrame.hpp>
#include <com/sun/star/frame/XFrames.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/io/TempFile.hpp>
#include <com/sun/star/io/XStream.hpp>
#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/lang/EventObject.hpp>
#include <com/sun/star/sdbc/ColumnValue.hpp>
#include <com/sun/star/sdbc/XRow.hpp>
#include <com/sun/star/sdbc/TransactionIsolation.hpp>
#include <com/sun/star/ucb/SimpleFileAccess.hpp>
#include <com/sun/star/ucb/XSimpleFileAccess2.hpp>
#include "connectivity/dbexception.hxx"
#include "resource/common_res.hrc"
#include "resource/hsqldb_res.hrc"
#include "resource/sharedresources.hxx"
#include <comphelper/processfactory.hxx>
#include <comphelper/storagehelper.hxx>
#include <unotools/tempfile.hxx>
#include <unotools/ucbstreamhelper.hxx>
using namespace connectivity::firebird;
using namespace connectivity;
using namespace ::osl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::document;
using namespace ::com::sun::star::embed;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::uno;
const OUString OConnection::sDBLocation( "firebird.fdb" );
OConnection::OConnection(FirebirdDriver* _pDriver)
:OConnection_BASE(m_aMutex),
OSubComponent<OConnection, OConnection_BASE>((::cppu::OWeakObject*)_pDriver, this),
m_xMetaData(NULL),
m_bIsEmbedded(sal_False),
m_sConnectionURL(),
m_sURL(),
m_sUser(),
m_pDriver(_pDriver),
m_bClosed(sal_False),
m_bUseOldDateFormat(sal_False),
m_bAutoCommit(sal_True),
m_bReadOnly(sal_False),
m_aTransactionIsolation(TransactionIsolation::REPEATABLE_READ),
m_DBHandler(0),
m_transactionHandle(0)
{
SAL_INFO("connectivity.firebird", "OConnection().");
m_pDriver->acquire();
}
OConnection::~OConnection()
{
SAL_INFO("connectivity.firebird", "~OConnection().");
if(!isClosed())
close();
m_pDriver->release();
m_pDriver = NULL;
}
void SAL_CALL OConnection::release() throw()
{
relase_ChildImpl();
}
void OConnection::construct(const ::rtl::OUString& url, const Sequence< PropertyValue >& info)
throw(SQLException)
{
SAL_INFO("connectivity.firebird", "construct().");
osl_atomic_increment( &m_refCount );
m_sConnectionURL = url;
bool bIsNewDatabase = false;
OUString aStorageURL;
if (url.equals("sdbc:embedded:firebird"))
{
m_bIsEmbedded = true;
const PropertyValue* pIter = info.getConstArray();
const PropertyValue* pEnd = pIter + info.getLength();
for (;pIter != pEnd; ++pIter)
{
if ( pIter->Name == "Storage" )
{
m_xEmbeddedStorage.set(pIter->Value,UNO_QUERY);
}
else if ( pIter->Name == "URL" )
{
pIter->Value >>= aStorageURL;
}
}
if ( !m_xEmbeddedStorage.is() )
{
::connectivity::SharedResources aResources;
const OUString sMessage = aResources.getResourceString(STR_NO_STROAGE);
::dbtools::throwGenericSQLException(sMessage ,*this);
}
bIsNewDatabase = !m_xEmbeddedStorage->hasElements();
m_sURL = utl::TempFile::CreateTempName() + ".fdb";
SAL_INFO("connectivity.firebird", "Temporary .fdb location: "
<< OUStringToOString(m_sURL,RTL_TEXTENCODING_UTF8 ).getStr());
if (!bIsNewDatabase)
{
SAL_INFO("connectivity.firebird", "Extracting .fdb from .odb" );
if (!m_xEmbeddedStorage->isStreamElement(sDBLocation))
{
::connectivity::SharedResources aResources;
const OUString sMessage = aResources.getResourceString(STR_ERROR_NEW_VERSION);
::dbtools::throwGenericSQLException(sMessage ,*this);
}
Reference< XStream > xDBStream(m_xEmbeddedStorage->openStreamElement(sDBLocation,
ElementModes::READ));
uno::Reference< ucb::XSimpleFileAccess2 > xFileAccess(
ucb::SimpleFileAccess::create( comphelper::getProcessComponentContext() ),
uno::UNO_QUERY );
if ( !xFileAccess.is() )
{
::connectivity::SharedResources aResources;
const OUString sMessage = aResources.getResourceString(STR_ERROR_NEW_VERSION);
::dbtools::throwGenericSQLException(sMessage ,*this);
}
xFileAccess->writeFile(m_sURL,xDBStream->getInputStream());
}
// TOOO: Get DB properties from XML
}
// External file AND/OR remote connection
else if (url.startsWith("sdbc:firebird:"))
{
m_sURL = url.copy(OUString("sdbc:firebird:").getLength());
if (m_sURL.startsWith("file://")) // TODO: are file urls really like this?
{
uno::Reference< ucb::XSimpleFileAccess > xFileAccess(
ucb::SimpleFileAccess::create(comphelper::getProcessComponentContext()),
uno::UNO_QUERY);
if (!xFileAccess->exists(m_sURL))
bIsNewDatabase = true;
}
}
char dpbBuffer[1 + 3 + 257 + 257 ]; // Expand as needed
int dpbLength = 0;
{
char* dpb;
char userName[256] = "";
char userPassword[256] = "";
dpb = dpbBuffer;
*dpb++ = isc_dpb_version1;
*dpb++ = isc_dpb_sql_dialect;
*dpb++ = 1; // 1 byte long
*dpb++ = FIREBIRD_SQL_DIALECT;
// Do any more dpbBuffer additions here
if (m_bIsEmbedded) // TODO: || m_bIsLocalFile
{
*dpb++ = isc_dpb_trusted_auth;
*dpb++ = 1; // Length of data
*dpb++ = 1; // TRUE
}
else
{
// TODO: parse password from connection string as needed?
}
if (strlen(userName))
{
int nUsernameLength = strlen(userName);
*dpb++ = isc_dpb_user_name;
*dpb++ = (char) nUsernameLength;
strcpy(dpb, userName);
dpb+= nUsernameLength;
}
if (strlen(userPassword))
{
int nPasswordLength = strlen(userPassword);
*dpb++ = isc_dpb_password;
*dpb++ = (char) nPasswordLength;
strcpy(dpb, userPassword);
dpb+= nPasswordLength;
}
dpbLength = dpb - dpbBuffer;
}
ISC_STATUS_ARRAY status; /* status vector */
ISC_STATUS aErr;
if (bIsNewDatabase)
{
aErr = isc_create_database(status,
m_sURL.getLength(),
OUStringToOString(m_sURL,RTL_TEXTENCODING_UTF8).getStr(),
&m_DBHandler,
dpbLength,
dpbBuffer,
0);
if (aErr)
{
evaluateStatusVector(status, "isc_create_database", *this);
}
}
else
{
aErr = isc_attach_database(status,
m_sURL.getLength(),
OUStringToOString(m_sURL, RTL_TEXTENCODING_UTF8).getStr(),
&m_DBHandler,
dpbLength,
dpbBuffer);
if (aErr)
{
evaluateStatusVector(status, "isc_attach_database", *this);
}
}
if (m_bIsEmbedded) // Add DocumentEventListener to save the .fdb as needed
{
uno::Reference< frame::XDesktop2 > xFramesSupplier =
frame::Desktop::create(::comphelper::getProcessComponentContext());
uno::Reference< frame::XFrames > xFrames( xFramesSupplier->getFrames(),
uno::UNO_QUERY);
uno::Sequence< uno::Reference<frame::XFrame> > xFrameList =
xFrames->queryFrames( frame::FrameSearchFlag::ALL );
for (sal_Int32 i = 0; i < xFrameList.getLength(); i++)
{
uno::Reference< frame::XFrame > xf = xFrameList[i];
uno::Reference< XController > xc;
if (xf.is())
xc = xf->getController();
uno::Reference< XModel > xm;
if (xc.is())
xm = xc->getModel();
OUString aURL;
if (xm.is())
aURL = xm->getURL();
if (aURL == aStorageURL)
{
uno::Reference<XDocumentEventBroadcaster> xBroadcaster( xm, UNO_QUERY);
if (xBroadcaster.is())
xBroadcaster->addDocumentEventListener( this );
//TODO: remove in the disposing?
}
}
}
osl_atomic_decrement( &m_refCount );
}
//----- XServiceInfo ---------------------------------------------------------
IMPLEMENT_SERVICE_INFO(OConnection, "com.sun.star.sdbc.drivers.firebird.OConnection",
"com.sun.star.sdbc.Connection")
Reference< XBlob> OConnection::createBlob(ISC_QUAD* pBlobId)
throw(SQLException)
{
SAL_INFO("connectivity.firebird", "createBlob()");
MutexGuard aGuard(m_aMutex);
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
Reference< XBlob > xReturn = new Blob(&m_DBHandler,
&m_transactionHandle,
*pBlobId);
m_aStatements.push_back(WeakReferenceHelper(xReturn));
return xReturn;
}
//----- XConnection ----------------------------------------------------------
Reference< XStatement > SAL_CALL OConnection::createStatement( )
throw(SQLException, RuntimeException)
{
SAL_INFO("connectivity.firebird", "createStatement().");
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
// the pre
if(m_aTypeInfo.empty())
buildTypeInfo();
SAL_INFO("connectivity.firebird", "createStatement(). "
"Creating statement.");
// create a statement
// the statement can only be executed once
Reference< XStatement > xReturn = new OStatement(this);
m_aStatements.push_back(WeakReferenceHelper(xReturn));
return xReturn;
}
Reference< XPreparedStatement > SAL_CALL OConnection::prepareStatement(
const OUString& _sSql)
throw(SQLException, RuntimeException)
{
SAL_INFO("connectivity.firebird", "prepareStatement() "
"called with sql: " << _sSql);
MutexGuard aGuard(m_aMutex);
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
if(m_aTypeInfo.empty())
buildTypeInfo();
Reference< XPreparedStatement > xReturn = new OPreparedStatement(this,
m_aTypeInfo,
_sSql);
m_aStatements.push_back(WeakReferenceHelper(xReturn));
return xReturn;
}
Reference< XPreparedStatement > SAL_CALL OConnection::prepareCall(
const OUString& _sSql ) throw(SQLException, RuntimeException)
{
SAL_INFO("connectivity.firebird", "prepareCall(). "
"_sSql: " << _sSql);
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
// not implemented yet :-) a task to do
return NULL;
}
OUString SAL_CALL OConnection::nativeSQL( const OUString& _sSql )
throw(SQLException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
// We do not need to adapt the SQL for Firebird atm.
return _sSql;
}
void SAL_CALL OConnection::setAutoCommit( sal_Bool autoCommit )
throw(SQLException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
m_bAutoCommit = autoCommit;
if (m_transactionHandle)
{
setupTransaction();
}
}
sal_Bool SAL_CALL OConnection::getAutoCommit() throw(SQLException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
return m_bAutoCommit;
}
void OConnection::setupTransaction()
{
MutexGuard aGuard( m_aMutex );
ISC_STATUS status_vector[20];
// TODO: is this sensible? If we have changed parameters then transaction
// is lost...
if (m_transactionHandle)
{
clearStatements();
isc_rollback_transaction(status_vector, &m_transactionHandle);
}
char aTransactionIsolation = 0;
switch (m_aTransactionIsolation)
{
// TODO: confirm that these are correct.
case(TransactionIsolation::READ_UNCOMMITTED):
aTransactionIsolation = isc_tpb_concurrency;
break;
case(TransactionIsolation::READ_COMMITTED):
aTransactionIsolation = isc_tpb_read_committed;
break;
case(TransactionIsolation::REPEATABLE_READ):
aTransactionIsolation = isc_tpb_consistency;
break;
case(TransactionIsolation::SERIALIZABLE):
aTransactionIsolation = isc_tpb_consistency;
break;
default:
assert( false ); // We must have a valid TransactionIsolation.
}
static char isc_tpb[] = {
isc_tpb_version3,
(char) (m_bAutoCommit ? isc_tpb_autocommit : 0),
(char) (!m_bReadOnly ? isc_tpb_write : isc_tpb_read),
aTransactionIsolation,
isc_tpb_wait
};
isc_start_transaction(status_vector, &m_transactionHandle, 1, &m_DBHandler,
(unsigned short) sizeof(isc_tpb), isc_tpb);
}
isc_tr_handle& OConnection::getTransaction()
{
MutexGuard aGuard( m_aMutex );
if (!m_transactionHandle)
{
setupTransaction();
}
return m_transactionHandle;
}
void SAL_CALL OConnection::commit() throw(SQLException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
ISC_STATUS status_vector[20];
if (!m_bAutoCommit && m_transactionHandle)
{
clearStatements();
isc_commit_transaction(status_vector, &m_transactionHandle);
}
}
void SAL_CALL OConnection::rollback() throw(SQLException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
ISC_STATUS status_vector[20];
if (!m_bAutoCommit && m_transactionHandle)
{
isc_rollback_transaction(status_vector, &m_transactionHandle);
}
}
sal_Bool SAL_CALL OConnection::isClosed( ) throw(SQLException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
// just simple -> we are close when we are disposed taht means someone called dispose(); (XComponent)
return OConnection_BASE::rBHelper.bDisposed;
}
// --------------------------------------------------------------------------------
Reference< XDatabaseMetaData > SAL_CALL OConnection::getMetaData( ) throw(SQLException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
// here we have to create the class with biggest interface
// The answer is 42 :-)
Reference< XDatabaseMetaData > xMetaData = m_xMetaData;
if(!xMetaData.is())
{
xMetaData = new ODatabaseMetaData(this); // need the connection because it can return it
m_xMetaData = xMetaData;
}
return xMetaData;
}
void SAL_CALL OConnection::setReadOnly(sal_Bool readOnly)
throw(SQLException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
m_bReadOnly = readOnly;
setupTransaction();
}
sal_Bool SAL_CALL OConnection::isReadOnly() throw(SQLException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
return m_bReadOnly;
}
void SAL_CALL OConnection::setCatalog(const OUString& catalog)
throw(SQLException, RuntimeException)
{
::dbtools::throwFeatureNotImplementedException( "XConnection::setCatalog", *this );
(void) catalog;
}
OUString SAL_CALL OConnection::getCatalog() throw(SQLException, RuntimeException)
{
// Unsupported
return OUString();
}
void SAL_CALL OConnection::setTransactionIsolation( sal_Int32 level ) throw(SQLException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
m_aTransactionIsolation = level;
setupTransaction();
}
sal_Int32 SAL_CALL OConnection::getTransactionIsolation( ) throw(SQLException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
return m_aTransactionIsolation;
}
Reference< XNameAccess > SAL_CALL OConnection::getTypeMap() throw(SQLException, RuntimeException)
{
::dbtools::throwFeatureNotImplementedException( "XConnection::getTypeMap", *this );
return 0;
}
void SAL_CALL OConnection::setTypeMap(const Reference< XNameAccess >& typeMap)
throw(SQLException, RuntimeException)
{
::dbtools::throwFeatureNotImplementedException( "XConnection::setTypeMap", *this );
(void) typeMap;
}
//----- XCloseable -----------------------------------------------------------
void SAL_CALL OConnection::close( ) throw(SQLException, RuntimeException)
{
SAL_INFO("connectivity.firebird", "close().");
// we just dispose us
{
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
}
dispose();
}
// --------------------------------------------------------------------------------
// XWarningsSupplier
Any SAL_CALL OConnection::getWarnings( ) throw(SQLException, RuntimeException)
{
// when you collected some warnings -> return it
return Any();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnection::clearWarnings( ) throw(SQLException, RuntimeException)
{
// you should clear your collected warnings here
}
// --------------------------------------------------------------------------------
// XDocumentEventListener
void SAL_CALL OConnection::documentEventOccured( const DocumentEvent& _Event )
throw(RuntimeException)
{
if (_Event.EventName == "OnSave" || _Event.EventName == "OnSaveAs")
{
commit(); // Commit and close transaction
if ( m_bIsEmbedded && m_xEmbeddedStorage.is() )
{
SAL_INFO("connectivity.firebird", "Writing .fdb into .odb" );
Reference< XStream > xDBStream(m_xEmbeddedStorage->openStreamElement(sDBLocation,
ElementModes::WRITE));
using namespace ::comphelper;
Reference< XComponentContext > xContext = comphelper::getProcessComponentContext();
Reference< XInputStream > xInputStream;
if (xContext.is())
xInputStream =
OStorageHelper::GetInputStreamFromURL(m_sURL, xContext);
if (xInputStream.is())
OStorageHelper::CopyInputToOutput( xInputStream,
xDBStream->getOutputStream());
// TODO: ensure db is in safe state
}
}
}
// XEventListener
void SAL_CALL OConnection::disposing( const EventObject& Source ) throw (RuntimeException)
{
(void) Source;
}
//--------------------------------------------------------------------
void OConnection::buildTypeInfo() throw( SQLException)
{
SAL_INFO("connectivity.firebird", "buildTypeInfo().");
MutexGuard aGuard( m_aMutex );
Reference< XResultSet> xRs = getMetaData ()->getTypeInfo ();
Reference< XRow> xRow(xRs,UNO_QUERY);
// Information for a single SQL type
// Loop on the result set until we reach end of file
while (xRs->next ())
{
OTypeInfo aInfo;
aInfo.aTypeName = xRow->getString (1);
aInfo.nType = xRow->getShort (2);
aInfo.nPrecision = xRow->getInt (3);
aInfo.aLiteralPrefix = xRow->getString (4);
aInfo.aLiteralSuffix = xRow->getString (5);
aInfo.aCreateParams = xRow->getString (6);
aInfo.bNullable = xRow->getBoolean (7) == ColumnValue::NULLABLE;
aInfo.bCaseSensitive = xRow->getBoolean (8);
aInfo.nSearchType = xRow->getShort (9);
aInfo.bUnsigned = xRow->getBoolean (10);
aInfo.bCurrency = xRow->getBoolean (11);
aInfo.bAutoIncrement = xRow->getBoolean (12);
aInfo.aLocalTypeName = xRow->getString (13);
aInfo.nMinimumScale = xRow->getShort (14);
aInfo.nMaximumScale = xRow->getShort (15);
aInfo.nNumPrecRadix = (sal_Int16)xRow->getInt(18);
// Now that we have the type info, save it
// in the Hashtable if we don't already have an
// entry for this SQL type.
m_aTypeInfo.push_back(aInfo);
}
SAL_INFO("connectivity.firebird", "buildTypeInfo(). "
"Type info built.");
// Close the result set/statement.
Reference< XCloseable> xClose(xRs,UNO_QUERY);
xClose->close();
SAL_INFO("connectivity.firebird", "buildTypeInfo(). "
"Closed.");
}
void OConnection::disposing()
{
SAL_INFO("connectivity.firebird", "disposing().");
MutexGuard aGuard(m_aMutex);
clearStatements();
m_bClosed = sal_True;
m_xMetaData = ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XDatabaseMetaData>();
ISC_STATUS_ARRAY status; /* status vector */
if (m_transactionHandle)
{
// TODO: confirm whether we need to ask the user here.
isc_rollback_transaction(status, &m_transactionHandle);
}
if (isc_detach_database(status, &m_DBHandler))
{
evaluateStatusVector(status, "isc_detach_database", *this);
}
// TODO: write to storage again?
if (m_bIsEmbedded)
{
uno::Reference< ucb::XSimpleFileAccess > xFileAccess(
ucb::SimpleFileAccess::create( comphelper::getProcessComponentContext()),
uno::UNO_QUERY);
if (xFileAccess->exists(m_sURL))
xFileAccess->kill(m_sURL);
}
dispose_ChildImpl();
cppu::WeakComponentImplHelperBase::disposing();
}
void OConnection::clearStatements()
{
MutexGuard aGuard(m_aMutex);
for (OWeakRefArray::iterator i = m_aStatements.begin(); m_aStatements.end() != i; ++i)
{
Reference< XComponent > xComp(i->get(), UNO_QUERY);
if (xComp.is())
xComp->dispose();
}
m_aStatements.clear();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
Only write db to file if we are embedded. (firebird-sdbc)
Change-Id: If6126a8005d666c0c1355efc2a887519da37c891
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#include "Connection.hxx"
#include "DatabaseMetaData.hxx"
#include "Driver.hxx"
#include "PreparedStatement.hxx"
#include "Statement.hxx"
#include "Util.hxx"
#include <com/sun/star/document/XDocumentEventBroadcaster.hpp>
#include <com/sun/star/embed/ElementModes.hpp>
#include <com/sun/star/frame/Desktop.hpp>
#include <com/sun/star/frame/FrameSearchFlag.hpp>
#include <com/sun/star/frame/XController.hpp>
#include <com/sun/star/frame/XFrame.hpp>
#include <com/sun/star/frame/XFrames.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/io/TempFile.hpp>
#include <com/sun/star/io/XStream.hpp>
#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/lang/EventObject.hpp>
#include <com/sun/star/sdbc/ColumnValue.hpp>
#include <com/sun/star/sdbc/XRow.hpp>
#include <com/sun/star/sdbc/TransactionIsolation.hpp>
#include <com/sun/star/ucb/SimpleFileAccess.hpp>
#include <com/sun/star/ucb/XSimpleFileAccess2.hpp>
#include "connectivity/dbexception.hxx"
#include "resource/common_res.hrc"
#include "resource/hsqldb_res.hrc"
#include "resource/sharedresources.hxx"
#include <comphelper/processfactory.hxx>
#include <comphelper/storagehelper.hxx>
#include <unotools/tempfile.hxx>
#include <unotools/ucbstreamhelper.hxx>
using namespace connectivity::firebird;
using namespace connectivity;
using namespace ::osl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::document;
using namespace ::com::sun::star::embed;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::uno;
const OUString OConnection::sDBLocation( "firebird.fdb" );
OConnection::OConnection(FirebirdDriver* _pDriver)
:OConnection_BASE(m_aMutex),
OSubComponent<OConnection, OConnection_BASE>((::cppu::OWeakObject*)_pDriver, this),
m_xMetaData(NULL),
m_bIsEmbedded(sal_False),
m_sConnectionURL(),
m_sURL(),
m_sUser(),
m_pDriver(_pDriver),
m_bClosed(sal_False),
m_bUseOldDateFormat(sal_False),
m_bAutoCommit(sal_True),
m_bReadOnly(sal_False),
m_aTransactionIsolation(TransactionIsolation::REPEATABLE_READ),
m_DBHandler(0),
m_transactionHandle(0)
{
SAL_INFO("connectivity.firebird", "OConnection().");
m_pDriver->acquire();
}
OConnection::~OConnection()
{
SAL_INFO("connectivity.firebird", "~OConnection().");
if(!isClosed())
close();
m_pDriver->release();
m_pDriver = NULL;
}
void SAL_CALL OConnection::release() throw()
{
relase_ChildImpl();
}
void OConnection::construct(const ::rtl::OUString& url, const Sequence< PropertyValue >& info)
throw(SQLException)
{
SAL_INFO("connectivity.firebird", "construct().");
osl_atomic_increment( &m_refCount );
m_sConnectionURL = url;
bool bIsNewDatabase = false;
OUString aStorageURL;
if (url.equals("sdbc:embedded:firebird"))
{
m_bIsEmbedded = true;
const PropertyValue* pIter = info.getConstArray();
const PropertyValue* pEnd = pIter + info.getLength();
for (;pIter != pEnd; ++pIter)
{
if ( pIter->Name == "Storage" )
{
m_xEmbeddedStorage.set(pIter->Value,UNO_QUERY);
}
else if ( pIter->Name == "URL" )
{
pIter->Value >>= aStorageURL;
}
}
if ( !m_xEmbeddedStorage.is() )
{
::connectivity::SharedResources aResources;
const OUString sMessage = aResources.getResourceString(STR_NO_STROAGE);
::dbtools::throwGenericSQLException(sMessage ,*this);
}
bIsNewDatabase = !m_xEmbeddedStorage->hasElements();
m_sURL = utl::TempFile::CreateTempName() + ".fdb";
SAL_INFO("connectivity.firebird", "Temporary .fdb location: "
<< OUStringToOString(m_sURL,RTL_TEXTENCODING_UTF8 ).getStr());
if (!bIsNewDatabase)
{
SAL_INFO("connectivity.firebird", "Extracting .fdb from .odb" );
if (!m_xEmbeddedStorage->isStreamElement(sDBLocation))
{
::connectivity::SharedResources aResources;
const OUString sMessage = aResources.getResourceString(STR_ERROR_NEW_VERSION);
::dbtools::throwGenericSQLException(sMessage ,*this);
}
Reference< XStream > xDBStream(m_xEmbeddedStorage->openStreamElement(sDBLocation,
ElementModes::READ));
uno::Reference< ucb::XSimpleFileAccess2 > xFileAccess(
ucb::SimpleFileAccess::create( comphelper::getProcessComponentContext() ),
uno::UNO_QUERY );
if ( !xFileAccess.is() )
{
::connectivity::SharedResources aResources;
const OUString sMessage = aResources.getResourceString(STR_ERROR_NEW_VERSION);
::dbtools::throwGenericSQLException(sMessage ,*this);
}
xFileAccess->writeFile(m_sURL,xDBStream->getInputStream());
}
// TOOO: Get DB properties from XML
}
// External file AND/OR remote connection
else if (url.startsWith("sdbc:firebird:"))
{
m_sURL = url.copy(OUString("sdbc:firebird:").getLength());
if (m_sURL.startsWith("file://")) // TODO: are file urls really like this?
{
uno::Reference< ucb::XSimpleFileAccess > xFileAccess(
ucb::SimpleFileAccess::create(comphelper::getProcessComponentContext()),
uno::UNO_QUERY);
if (!xFileAccess->exists(m_sURL))
bIsNewDatabase = true;
}
}
char dpbBuffer[1 + 3 + 257 + 257 ]; // Expand as needed
int dpbLength = 0;
{
char* dpb;
char userName[256] = "";
char userPassword[256] = "";
dpb = dpbBuffer;
*dpb++ = isc_dpb_version1;
*dpb++ = isc_dpb_sql_dialect;
*dpb++ = 1; // 1 byte long
*dpb++ = FIREBIRD_SQL_DIALECT;
// Do any more dpbBuffer additions here
if (m_bIsEmbedded) // TODO: || m_bIsLocalFile
{
*dpb++ = isc_dpb_trusted_auth;
*dpb++ = 1; // Length of data
*dpb++ = 1; // TRUE
}
else
{
// TODO: parse password from connection string as needed?
}
if (strlen(userName))
{
int nUsernameLength = strlen(userName);
*dpb++ = isc_dpb_user_name;
*dpb++ = (char) nUsernameLength;
strcpy(dpb, userName);
dpb+= nUsernameLength;
}
if (strlen(userPassword))
{
int nPasswordLength = strlen(userPassword);
*dpb++ = isc_dpb_password;
*dpb++ = (char) nPasswordLength;
strcpy(dpb, userPassword);
dpb+= nPasswordLength;
}
dpbLength = dpb - dpbBuffer;
}
ISC_STATUS_ARRAY status; /* status vector */
ISC_STATUS aErr;
if (bIsNewDatabase)
{
aErr = isc_create_database(status,
m_sURL.getLength(),
OUStringToOString(m_sURL,RTL_TEXTENCODING_UTF8).getStr(),
&m_DBHandler,
dpbLength,
dpbBuffer,
0);
if (aErr)
{
evaluateStatusVector(status, "isc_create_database", *this);
}
}
else
{
aErr = isc_attach_database(status,
m_sURL.getLength(),
OUStringToOString(m_sURL, RTL_TEXTENCODING_UTF8).getStr(),
&m_DBHandler,
dpbLength,
dpbBuffer);
if (aErr)
{
evaluateStatusVector(status, "isc_attach_database", *this);
}
}
if (m_bIsEmbedded) // Add DocumentEventListener to save the .fdb as needed
{
uno::Reference< frame::XDesktop2 > xFramesSupplier =
frame::Desktop::create(::comphelper::getProcessComponentContext());
uno::Reference< frame::XFrames > xFrames( xFramesSupplier->getFrames(),
uno::UNO_QUERY);
uno::Sequence< uno::Reference<frame::XFrame> > xFrameList =
xFrames->queryFrames( frame::FrameSearchFlag::ALL );
for (sal_Int32 i = 0; i < xFrameList.getLength(); i++)
{
uno::Reference< frame::XFrame > xf = xFrameList[i];
uno::Reference< XController > xc;
if (xf.is())
xc = xf->getController();
uno::Reference< XModel > xm;
if (xc.is())
xm = xc->getModel();
OUString aURL;
if (xm.is())
aURL = xm->getURL();
if (aURL == aStorageURL)
{
uno::Reference<XDocumentEventBroadcaster> xBroadcaster( xm, UNO_QUERY);
if (xBroadcaster.is())
xBroadcaster->addDocumentEventListener( this );
//TODO: remove in the disposing?
}
}
}
osl_atomic_decrement( &m_refCount );
}
//----- XServiceInfo ---------------------------------------------------------
IMPLEMENT_SERVICE_INFO(OConnection, "com.sun.star.sdbc.drivers.firebird.OConnection",
"com.sun.star.sdbc.Connection")
Reference< XBlob> OConnection::createBlob(ISC_QUAD* pBlobId)
throw(SQLException)
{
SAL_INFO("connectivity.firebird", "createBlob()");
MutexGuard aGuard(m_aMutex);
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
Reference< XBlob > xReturn = new Blob(&m_DBHandler,
&m_transactionHandle,
*pBlobId);
m_aStatements.push_back(WeakReferenceHelper(xReturn));
return xReturn;
}
//----- XConnection ----------------------------------------------------------
Reference< XStatement > SAL_CALL OConnection::createStatement( )
throw(SQLException, RuntimeException)
{
SAL_INFO("connectivity.firebird", "createStatement().");
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
// the pre
if(m_aTypeInfo.empty())
buildTypeInfo();
SAL_INFO("connectivity.firebird", "createStatement(). "
"Creating statement.");
// create a statement
// the statement can only be executed once
Reference< XStatement > xReturn = new OStatement(this);
m_aStatements.push_back(WeakReferenceHelper(xReturn));
return xReturn;
}
Reference< XPreparedStatement > SAL_CALL OConnection::prepareStatement(
const OUString& _sSql)
throw(SQLException, RuntimeException)
{
SAL_INFO("connectivity.firebird", "prepareStatement() "
"called with sql: " << _sSql);
MutexGuard aGuard(m_aMutex);
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
if(m_aTypeInfo.empty())
buildTypeInfo();
Reference< XPreparedStatement > xReturn = new OPreparedStatement(this,
m_aTypeInfo,
_sSql);
m_aStatements.push_back(WeakReferenceHelper(xReturn));
return xReturn;
}
Reference< XPreparedStatement > SAL_CALL OConnection::prepareCall(
const OUString& _sSql ) throw(SQLException, RuntimeException)
{
SAL_INFO("connectivity.firebird", "prepareCall(). "
"_sSql: " << _sSql);
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
// not implemented yet :-) a task to do
return NULL;
}
OUString SAL_CALL OConnection::nativeSQL( const OUString& _sSql )
throw(SQLException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
// We do not need to adapt the SQL for Firebird atm.
return _sSql;
}
void SAL_CALL OConnection::setAutoCommit( sal_Bool autoCommit )
throw(SQLException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
m_bAutoCommit = autoCommit;
if (m_transactionHandle)
{
setupTransaction();
}
}
sal_Bool SAL_CALL OConnection::getAutoCommit() throw(SQLException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
return m_bAutoCommit;
}
void OConnection::setupTransaction()
{
MutexGuard aGuard( m_aMutex );
ISC_STATUS status_vector[20];
// TODO: is this sensible? If we have changed parameters then transaction
// is lost...
if (m_transactionHandle)
{
clearStatements();
isc_rollback_transaction(status_vector, &m_transactionHandle);
}
char aTransactionIsolation = 0;
switch (m_aTransactionIsolation)
{
// TODO: confirm that these are correct.
case(TransactionIsolation::READ_UNCOMMITTED):
aTransactionIsolation = isc_tpb_concurrency;
break;
case(TransactionIsolation::READ_COMMITTED):
aTransactionIsolation = isc_tpb_read_committed;
break;
case(TransactionIsolation::REPEATABLE_READ):
aTransactionIsolation = isc_tpb_consistency;
break;
case(TransactionIsolation::SERIALIZABLE):
aTransactionIsolation = isc_tpb_consistency;
break;
default:
assert( false ); // We must have a valid TransactionIsolation.
}
static char isc_tpb[] = {
isc_tpb_version3,
(char) (m_bAutoCommit ? isc_tpb_autocommit : 0),
(char) (!m_bReadOnly ? isc_tpb_write : isc_tpb_read),
aTransactionIsolation,
isc_tpb_wait
};
isc_start_transaction(status_vector, &m_transactionHandle, 1, &m_DBHandler,
(unsigned short) sizeof(isc_tpb), isc_tpb);
}
isc_tr_handle& OConnection::getTransaction()
{
MutexGuard aGuard( m_aMutex );
if (!m_transactionHandle)
{
setupTransaction();
}
return m_transactionHandle;
}
void SAL_CALL OConnection::commit() throw(SQLException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
ISC_STATUS status_vector[20];
if (!m_bAutoCommit && m_transactionHandle)
{
clearStatements();
isc_commit_transaction(status_vector, &m_transactionHandle);
}
}
void SAL_CALL OConnection::rollback() throw(SQLException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
ISC_STATUS status_vector[20];
if (!m_bAutoCommit && m_transactionHandle)
{
isc_rollback_transaction(status_vector, &m_transactionHandle);
}
}
sal_Bool SAL_CALL OConnection::isClosed( ) throw(SQLException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
// just simple -> we are close when we are disposed taht means someone called dispose(); (XComponent)
return OConnection_BASE::rBHelper.bDisposed;
}
// --------------------------------------------------------------------------------
Reference< XDatabaseMetaData > SAL_CALL OConnection::getMetaData( ) throw(SQLException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
// here we have to create the class with biggest interface
// The answer is 42 :-)
Reference< XDatabaseMetaData > xMetaData = m_xMetaData;
if(!xMetaData.is())
{
xMetaData = new ODatabaseMetaData(this); // need the connection because it can return it
m_xMetaData = xMetaData;
}
return xMetaData;
}
void SAL_CALL OConnection::setReadOnly(sal_Bool readOnly)
throw(SQLException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
m_bReadOnly = readOnly;
setupTransaction();
}
sal_Bool SAL_CALL OConnection::isReadOnly() throw(SQLException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
return m_bReadOnly;
}
void SAL_CALL OConnection::setCatalog(const OUString& catalog)
throw(SQLException, RuntimeException)
{
::dbtools::throwFeatureNotImplementedException( "XConnection::setCatalog", *this );
(void) catalog;
}
OUString SAL_CALL OConnection::getCatalog() throw(SQLException, RuntimeException)
{
// Unsupported
return OUString();
}
void SAL_CALL OConnection::setTransactionIsolation( sal_Int32 level ) throw(SQLException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
m_aTransactionIsolation = level;
setupTransaction();
}
sal_Int32 SAL_CALL OConnection::getTransactionIsolation( ) throw(SQLException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
return m_aTransactionIsolation;
}
Reference< XNameAccess > SAL_CALL OConnection::getTypeMap() throw(SQLException, RuntimeException)
{
::dbtools::throwFeatureNotImplementedException( "XConnection::getTypeMap", *this );
return 0;
}
void SAL_CALL OConnection::setTypeMap(const Reference< XNameAccess >& typeMap)
throw(SQLException, RuntimeException)
{
::dbtools::throwFeatureNotImplementedException( "XConnection::setTypeMap", *this );
(void) typeMap;
}
//----- XCloseable -----------------------------------------------------------
void SAL_CALL OConnection::close( ) throw(SQLException, RuntimeException)
{
SAL_INFO("connectivity.firebird", "close().");
// we just dispose us
{
MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
}
dispose();
}
// --------------------------------------------------------------------------------
// XWarningsSupplier
Any SAL_CALL OConnection::getWarnings( ) throw(SQLException, RuntimeException)
{
// when you collected some warnings -> return it
return Any();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnection::clearWarnings( ) throw(SQLException, RuntimeException)
{
// you should clear your collected warnings here
}
// --------------------------------------------------------------------------------
// XDocumentEventListener
void SAL_CALL OConnection::documentEventOccured( const DocumentEvent& _Event )
throw(RuntimeException)
{
MutexGuard aGuard(m_aMutex);
if (!m_bIsEmbedded)
return;
if (_Event.EventName == "OnSave" || _Event.EventName == "OnSaveAs")
{
commit(); // Commit and close transaction
if ( m_bIsEmbedded && m_xEmbeddedStorage.is() )
{
SAL_INFO("connectivity.firebird", "Writing .fdb into .odb" );
Reference< XStream > xDBStream(m_xEmbeddedStorage->openStreamElement(sDBLocation,
ElementModes::WRITE));
using namespace ::comphelper;
Reference< XComponentContext > xContext = comphelper::getProcessComponentContext();
Reference< XInputStream > xInputStream;
if (xContext.is())
xInputStream =
OStorageHelper::GetInputStreamFromURL(m_sURL, xContext);
if (xInputStream.is())
OStorageHelper::CopyInputToOutput( xInputStream,
xDBStream->getOutputStream());
// TODO: ensure db is in safe state
}
}
}
// XEventListener
void SAL_CALL OConnection::disposing( const EventObject& Source ) throw (RuntimeException)
{
(void) Source;
}
//--------------------------------------------------------------------
void OConnection::buildTypeInfo() throw( SQLException)
{
SAL_INFO("connectivity.firebird", "buildTypeInfo().");
MutexGuard aGuard( m_aMutex );
Reference< XResultSet> xRs = getMetaData ()->getTypeInfo ();
Reference< XRow> xRow(xRs,UNO_QUERY);
// Information for a single SQL type
// Loop on the result set until we reach end of file
while (xRs->next ())
{
OTypeInfo aInfo;
aInfo.aTypeName = xRow->getString (1);
aInfo.nType = xRow->getShort (2);
aInfo.nPrecision = xRow->getInt (3);
aInfo.aLiteralPrefix = xRow->getString (4);
aInfo.aLiteralSuffix = xRow->getString (5);
aInfo.aCreateParams = xRow->getString (6);
aInfo.bNullable = xRow->getBoolean (7) == ColumnValue::NULLABLE;
aInfo.bCaseSensitive = xRow->getBoolean (8);
aInfo.nSearchType = xRow->getShort (9);
aInfo.bUnsigned = xRow->getBoolean (10);
aInfo.bCurrency = xRow->getBoolean (11);
aInfo.bAutoIncrement = xRow->getBoolean (12);
aInfo.aLocalTypeName = xRow->getString (13);
aInfo.nMinimumScale = xRow->getShort (14);
aInfo.nMaximumScale = xRow->getShort (15);
aInfo.nNumPrecRadix = (sal_Int16)xRow->getInt(18);
// Now that we have the type info, save it
// in the Hashtable if we don't already have an
// entry for this SQL type.
m_aTypeInfo.push_back(aInfo);
}
SAL_INFO("connectivity.firebird", "buildTypeInfo(). "
"Type info built.");
// Close the result set/statement.
Reference< XCloseable> xClose(xRs,UNO_QUERY);
xClose->close();
SAL_INFO("connectivity.firebird", "buildTypeInfo(). "
"Closed.");
}
void OConnection::disposing()
{
SAL_INFO("connectivity.firebird", "disposing().");
MutexGuard aGuard(m_aMutex);
clearStatements();
m_bClosed = sal_True;
m_xMetaData = ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XDatabaseMetaData>();
ISC_STATUS_ARRAY status; /* status vector */
if (m_transactionHandle)
{
// TODO: confirm whether we need to ask the user here.
isc_rollback_transaction(status, &m_transactionHandle);
}
if (isc_detach_database(status, &m_DBHandler))
{
evaluateStatusVector(status, "isc_detach_database", *this);
}
// TODO: write to storage again?
if (m_bIsEmbedded)
{
uno::Reference< ucb::XSimpleFileAccess > xFileAccess(
ucb::SimpleFileAccess::create( comphelper::getProcessComponentContext()),
uno::UNO_QUERY);
if (xFileAccess->exists(m_sURL))
xFileAccess->kill(m_sURL);
}
dispose_ChildImpl();
cppu::WeakComponentImplHelperBase::disposing();
}
void OConnection::clearStatements()
{
MutexGuard aGuard(m_aMutex);
for (OWeakRefArray::iterator i = m_aStatements.begin(); m_aStatements.end() != i; ++i)
{
Reference< XComponent > xComp(i->get(), UNO_QUERY);
if (xComp.is())
xComp->dispose();
}
m_aStatements.clear();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
//===----------------------------------------------------------------------===//
//
// Peloton
//
// type_integrity_test.cpp
//
// Identification: ../peloton-1/test/codegen/type_integrity_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "codegen/testing_codegen_util.h"
#include "codegen/type/type.h"
#include "codegen/type/boolean_type.h"
#include "codegen/type/tinyint_type.h"
#include "codegen/type/smallint_type.h"
#include "codegen/type/integer_type.h"
#include "codegen/type/bigint_type.h"
#include "codegen/type/decimal_type.h"
#include "codegen/type/timestamp_type.h"
#include "codegen/type/date_type.h"
namespace peloton {
namespace test {
class TypeIntegrityTest : public PelotonCodeGenTest {};
TEST_F(TypeIntegrityTest, ImplicitCastTest) {
// Tinyint's can be implicitly casted to any higher-bit integer type
codegen::type::Type input_type = codegen::type::TinyInt::Instance();
EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
input_type, codegen::type::TinyInt::Instance()));
EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
input_type, codegen::type::SmallInt::Instance()));
EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
input_type, codegen::type::Integer::Instance()));
EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
input_type, codegen::type::BigInt::Instance()));
EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
input_type, codegen::type::Decimal::Instance()));
// Small's can be implicitly casted to any higher-bit integer type
input_type = codegen::type::SmallInt::Instance();
EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
input_type, codegen::type::SmallInt::Instance()));
EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
input_type, codegen::type::Integer::Instance()));
EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
input_type, codegen::type::BigInt::Instance()));
EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
input_type, codegen::type::Decimal::Instance()));
// Integer's can be implicitly casted to any higher-bit integer type
input_type = codegen::type::Integer::Instance();
EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
input_type, codegen::type::Integer::Instance()));
EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
input_type, codegen::type::BigInt::Instance()));
EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
input_type, codegen::type::Decimal::Instance()));
// Integer's can be implicitly casted to any higher-bit integer type
input_type = codegen::type::BigInt::Instance();
EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
input_type, codegen::type::BigInt::Instance()));
EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
input_type, codegen::type::Decimal::Instance()));
// Decimal's can only be casted to itself
input_type = codegen::type::Decimal::Instance();
EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
input_type, codegen::type::Decimal::Instance()));
}
// This test performs checks that comparisons between every possible pair of
// (the most important) input types are possible through potentially implicitly
// casting the inputs.
TEST_F(TypeIntegrityTest, ComparisonWithImplicitCastTest) {
const std::vector<codegen::type::Type> types_to_test = {
codegen::type::Boolean::Instance(),
codegen::type::TinyInt::Instance(),
codegen::type::SmallInt::Instance(),
codegen::type::Integer::Instance(),
codegen::type::BigInt::Instance(),
codegen::type::Decimal::Instance(),
codegen::type::Date::Instance(),
codegen::type::Timestamp::Instance()};
for (const auto &left_type : types_to_test) {
for (const auto &right_type : types_to_test) {
const auto &type_system = left_type.GetTypeSystem();
codegen::type::Type type_to_cast_left = left_type;
codegen::type::Type type_to_cast_right = right_type;
const codegen::type::TypeSystem::Comparison *result;
if (codegen::type::TypeSystem::CanImplicitlyCastTo(left_type,
right_type) ||
codegen::type::TypeSystem::CanImplicitlyCastTo(right_type,
left_type)) {
// If the types are implicitly cast-able to one or the other, the
// comparison shouldn't fail
EXPECT_NO_THROW({
result = type_system.GetComparison(left_type, type_to_cast_left,
right_type, type_to_cast_right);
});
EXPECT_NE(nullptr, result);
} else {
// The types are **NOT** implicitly cast-able, this should fail
EXPECT_THROW({
result = type_system.GetComparison(left_type, type_to_cast_left,
right_type, type_to_cast_right);
}, Exception);
}
}
}
}
// TODO: This test only does math ops. We need a generic way to test binary ops.
TEST_F(TypeIntegrityTest, MathOpWithImplicitCastTest) {
const auto binary_ops = {OperatorId::Add, OperatorId::Sub, OperatorId::Mul,
OperatorId::Div, OperatorId::Mod};
const std::vector<codegen::type::Type> types_to_test = {
codegen::type::Boolean::Instance(),
codegen::type::TinyInt::Instance(),
codegen::type::SmallInt::Instance(),
codegen::type::Integer::Instance(),
codegen::type::BigInt::Instance(),
codegen::type::Decimal::Instance(),
codegen::type::Date::Instance(),
codegen::type::Timestamp::Instance()};
const auto IsNumber = [](const codegen::type::Type &type) {
switch (type.type_id) {
case peloton::type::TypeId::TINYINT:
case peloton::type::TypeId::SMALLINT:
case peloton::type::TypeId::INTEGER:
case peloton::type::TypeId::BIGINT:
case peloton::type::TypeId::DECIMAL:
return true;
default:
return false;
}
};
for (auto left_type : types_to_test) {
for (auto right_type : types_to_test) {
for (auto bin_op : binary_ops) {
const auto &type_system = left_type.GetTypeSystem();
codegen::type::Type type_to_cast_left = left_type;
codegen::type::Type type_to_cast_right = right_type;
const codegen::type::TypeSystem::BinaryOperator *result;
if (IsNumber(left_type) && IsNumber(right_type)) {
// If the types are implicitly cast-able to one or the other, the
// comparison shouldn't fail
EXPECT_NO_THROW({
result = type_system.GetBinaryOperator(
bin_op, left_type, type_to_cast_left, right_type,
type_to_cast_right);
});
EXPECT_NE(nullptr, result);
} else {
// The types are **NOT** implicitly cast-able, this should fail
EXPECT_THROW({
result = type_system.GetBinaryOperator(
bin_op, left_type, type_to_cast_left, right_type,
type_to_cast_right);
}, Exception);
}
}
}
}
}
} // namespace test
} // namespace peloton
More type tests
//===----------------------------------------------------------------------===//
//
// Peloton
//
// type_integrity_test.cpp
//
// Identification: ../peloton-1/test/codegen/type_integrity_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "codegen/testing_codegen_util.h"
#include <vector>
#include "codegen/type/array_type.h"
#include "codegen/type/type.h"
#include "codegen/type/bigint_type.h"
#include "codegen/type/boolean_type.h"
#include "codegen/type/date_type.h"
#include "codegen/type/decimal_type.h"
#include "codegen/type/integer_type.h"
#include "codegen/type/smallint_type.h"
#include "codegen/type/timestamp_type.h"
#include "codegen/type/tinyint_type.h"
#include "codegen/type/varbinary_type.h"
#include "codegen/type/varchar_type.h"
namespace peloton {
namespace test {
class TypeIntegrityTest : public PelotonCodeGenTest {};
TEST_F(TypeIntegrityTest, ImplicitCastTest) {
struct ImplicitCastTestCase {
codegen::type::Type source_type;
std::vector<codegen::type::Type> target_types;
ImplicitCastTestCase(const codegen::type::Type &_source_type,
const std::vector<codegen::type::Type> &_target_types)
: source_type(_source_type), target_types(_target_types) {}
bool CanCastTo(const codegen::type::Type &t) const {
return std::find(target_types.begin(), target_types.end(), t) !=
target_types.end();
}
};
// This list contains a list of the the above structs that essentially tracks
// which SQL types can be implicitly casted to which other SQL types
std::vector<ImplicitCastTestCase> implicit_casting_table = {
// Boolean can only be casted to itself
{codegen::type::Boolean::Instance(),
{codegen::type::Boolean::Instance()}},
//////////////////////////////////////////////////////////////////////////
// All other integral types can only be casted to WIDER integral types
//////////////////////////////////////////////////////////////////////////
{codegen::type::TinyInt::Instance(),
{codegen::type::TinyInt::Instance(), codegen::type::SmallInt::Instance(),
codegen::type::Integer::Instance(), codegen::type::BigInt::Instance(),
codegen::type::Decimal::Instance()}},
{codegen::type::SmallInt::Instance(),
{codegen::type::SmallInt::Instance(), codegen::type::Integer::Instance(),
codegen::type::BigInt::Instance(), codegen::type::Decimal::Instance()}},
{codegen::type::Integer::Instance(),
{codegen::type::Integer::Instance(), codegen::type::BigInt::Instance(),
codegen::type::Decimal::Instance()}},
{codegen::type::BigInt::Instance(),
{codegen::type::BigInt::Instance(), codegen::type::Decimal::Instance()}},
{codegen::type::Decimal::Instance(),
{codegen::type::Decimal::Instance()}},
};
const std::vector<codegen::type::Type> types_to_test = {
codegen::type::Boolean::Instance(), codegen::type::TinyInt::Instance(),
codegen::type::SmallInt::Instance(), codegen::type::Integer::Instance(),
codegen::type::BigInt::Instance(), codegen::type::Decimal::Instance(),
codegen::type::Date::Instance(), codegen::type::Timestamp::Instance(),
codegen::type::Varchar::Instance(), codegen::type::Varbinary::Instance(),
codegen::type::Array::Instance()};
// Check that all the proper types can be casted when allowed
for (const auto &test_case : implicit_casting_table) {
const auto &src_type = test_case.source_type;
for (const auto &target_type : types_to_test) {
if (test_case.CanCastTo(target_type)) {
EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
src_type, target_type));
} else {
EXPECT_FALSE(codegen::type::TypeSystem::CanImplicitlyCastTo(
src_type, target_type));
}
}
}
}
// This test performs checks that comparisons between every possible pair of
// (the most important) input types are possible through potentially implicitly
// casting the inputs.
TEST_F(TypeIntegrityTest, ComparisonWithImplicitCastTest) {
const std::vector<codegen::type::Type> types_to_test = {
codegen::type::Boolean::Instance(),
codegen::type::TinyInt::Instance(),
codegen::type::SmallInt::Instance(),
codegen::type::Integer::Instance(),
codegen::type::BigInt::Instance(),
codegen::type::Decimal::Instance(),
codegen::type::Date::Instance(),
codegen::type::Timestamp::Instance()};
for (const auto &left_type : types_to_test) {
for (const auto &right_type : types_to_test) {
const auto &type_system = left_type.GetTypeSystem();
codegen::type::Type type_to_cast_left = left_type;
codegen::type::Type type_to_cast_right = right_type;
const codegen::type::TypeSystem::Comparison *result;
if (codegen::type::TypeSystem::CanImplicitlyCastTo(left_type,
right_type) ||
codegen::type::TypeSystem::CanImplicitlyCastTo(right_type,
left_type)) {
// If the types are implicitly cast-able to one or the other, the
// comparison shouldn't fail
EXPECT_NO_THROW({
result = type_system.GetComparison(left_type, type_to_cast_left,
right_type, type_to_cast_right);
});
EXPECT_NE(nullptr, result);
} else {
// The types are **NOT** implicitly cast-able, this should fail
EXPECT_THROW({
result = type_system.GetComparison(left_type, type_to_cast_left,
right_type, type_to_cast_right);
}, Exception);
}
}
}
}
// TODO: This test only does math ops. We need a generic way to test binary ops.
TEST_F(TypeIntegrityTest, MathOpWithImplicitCastTest) {
const auto binary_ops = {OperatorId::Add, OperatorId::Sub, OperatorId::Mul,
OperatorId::Div, OperatorId::Mod};
const std::vector<codegen::type::Type> types_to_test = {
codegen::type::Boolean::Instance(),
codegen::type::TinyInt::Instance(),
codegen::type::SmallInt::Instance(),
codegen::type::Integer::Instance(),
codegen::type::BigInt::Instance(),
codegen::type::Decimal::Instance(),
codegen::type::Date::Instance(),
codegen::type::Timestamp::Instance()};
const auto IsNumber = [](const codegen::type::Type &type) {
switch (type.type_id) {
case peloton::type::TypeId::TINYINT:
case peloton::type::TypeId::SMALLINT:
case peloton::type::TypeId::INTEGER:
case peloton::type::TypeId::BIGINT:
case peloton::type::TypeId::DECIMAL:
return true;
default:
return false;
}
};
for (auto left_type : types_to_test) {
for (auto right_type : types_to_test) {
for (auto bin_op : binary_ops) {
const auto &type_system = left_type.GetTypeSystem();
codegen::type::Type type_to_cast_left = left_type;
codegen::type::Type type_to_cast_right = right_type;
const codegen::type::TypeSystem::BinaryOperator *result;
if (IsNumber(left_type) && IsNumber(right_type)) {
// If the types are implicitly cast-able to one or the other, the
// comparison shouldn't fail
EXPECT_NO_THROW({
result = type_system.GetBinaryOperator(
bin_op, left_type, type_to_cast_left, right_type,
type_to_cast_right);
});
EXPECT_NE(nullptr, result);
} else {
// The types are **NOT** implicitly cast-able, this should fail
EXPECT_THROW({
result = type_system.GetBinaryOperator(
bin_op, left_type, type_to_cast_left, right_type,
type_to_cast_right);
}, Exception);
}
}
}
}
}
} // namespace test
} // namespace peloton
|
/*
* Medical Image Registration ToolKit (MIRTK)
*
* Copyright 2013-2016 Imperial College London
* Copyright 2013-2016 Andreas Schuh
*
* 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 "mirtk/PointSetIO.h"
#include "mirtk/Path.h"
#include "mirtk/Stream.h"
#include "mirtk/Vtk.h"
#include "vtkPoints.h"
#include "vtkPointData.h"
#include "vtkDataArray.h"
#include "vtkCellArray.h"
#include "vtkIdTypeArray.h"
#include "vtkIdList.h"
#include "vtkInformation.h"
#include "vtkUnsignedShortArray.h"
#include "vtkFloatArray.h"
#include "vtkUnstructuredGrid.h"
#include "vtkStructuredGrid.h"
#include "vtkGenericDataObjectReader.h"
#include "vtkDataSetWriter.h"
#include "vtkPolyDataReader.h"
#include "vtkPolyDataWriter.h"
#include "vtkXMLGenericDataObjectReader.h"
#include "vtkXMLDataSetWriter.h"
#include "vtkXMLPolyDataReader.h"
#include "vtkXMLPolyDataWriter.h"
#include "vtkOBJReader.h"
#include "vtkPLYReader.h"
#include "vtkSTLReader.h"
#include "vtkPLYWriter.h"
#include "vtkSTLWriter.h"
#include "brainsuite/dfsurface.h"
#if MIRTK_IO_WITH_GIFTI
#include "mirtk/NiftiImageInfo.h"
#include "gifti/gifti_io.h"
#endif
namespace mirtk {
// =============================================================================
// File name extension
// =============================================================================
// -----------------------------------------------------------------------------
const char *DefaultExtension(vtkDataSet *dataset)
{
if (vtkPolyData ::SafeDownCast(dataset)) return ".vtp";
else if (vtkUnstructuredGrid::SafeDownCast(dataset)) return ".vtu";
else if (vtkStructuredGrid ::SafeDownCast(dataset)) return ".vts";
return ".vtk";
}
// =============================================================================
// Generic I/O functions
// =============================================================================
// -----------------------------------------------------------------------------
vtkSmartPointer<vtkPointSet> ReadPointSet(const char *fname, int *ftype, bool exit_on_failure)
{
vtkSmartPointer<vtkPointSet> pointset;
const string ext = Extension(fname);
if (ext == ".vtp" || ext == ".stl" || ext == ".ply" || ext == ".obj" || ext == ".dfs" || ext == ".off" || ext == ".gii") {
pointset = ReadPolyData(fname);
} else if (ext.length() == 4 && ext.substr(0, 3) == ".vt" && ext != ".vtk") {
vtkSmartPointer<vtkXMLGenericDataObjectReader> reader;
reader = vtkSmartPointer<vtkXMLGenericDataObjectReader>::New();
reader->SetFileName(fname);
reader->Update();
pointset = vtkPointSet::SafeDownCast(reader->GetOutput());
} else {
vtkSmartPointer<vtkGenericDataObjectReader> reader;
reader = vtkSmartPointer<vtkGenericDataObjectReader>::New();
reader->SetFileName(fname);
reader->Update();
if (ftype) *ftype = reader->GetFileType();
pointset = vtkPointSet::SafeDownCast(reader->GetOutput());
}
if (exit_on_failure && (!pointset || pointset->GetNumberOfPoints() == 0)) {
cerr << "File " << fname << " either contains no points or could not be read" << endl;
exit(1);
}
return pointset;
}
// -----------------------------------------------------------------------------
bool WritePointSet(const char *fname, vtkPointSet *pointset, bool compress, bool ascii)
{
vtkPolyData *polydata = vtkPolyData::SafeDownCast(pointset);
if (polydata) return WritePolyData(fname, polydata, compress, ascii);
const string ext = Extension(fname);
int success = 0;
if (ext.length() == 4 && ext.substr(0, 3) == ".vt" && ext != ".vtk") {
vtkSmartPointer<vtkXMLDataSetWriter> writer;
writer = vtkSmartPointer<vtkXMLDataSetWriter>::New();
SetVTKInput(writer, pointset);
writer->SetFileName(fname);
if (compress) writer->SetCompressorTypeToZLib();
else writer->SetCompressorTypeToNone();
success = writer->Write();
} else {
vtkSmartPointer<vtkDataSetWriter> writer;
writer = vtkSmartPointer<vtkDataSetWriter>::New();
SetVTKInput(writer, pointset);
writer->SetFileName(fname);
if (ascii) writer->SetFileTypeToASCII();
else writer->SetFileTypeToBinary();
success = writer->Write();
}
return (success == 1);
}
// -----------------------------------------------------------------------------
vtkSmartPointer<vtkPolyData> ReadPolyData(const char *fname, int *ftype, bool exit_on_failure)
{
vtkSmartPointer<vtkPolyData> polydata;
const string ext = Extension(fname);
if (ext == ".vtp") {
vtkSmartPointer<vtkXMLPolyDataReader> reader;
reader = vtkSmartPointer<vtkXMLPolyDataReader>::New();
reader->SetFileName(fname);
reader->Update();
polydata = reader->GetOutput();
} else if (ext == ".stl") {
vtkSmartPointer<vtkSTLReader> reader;
reader = vtkSmartPointer<vtkSTLReader>::New();
reader->SetFileName(fname);
reader->Update();
polydata = reader->GetOutput();
} else if (ext == ".ply") {
vtkSmartPointer<vtkPLYReader> reader;
reader = vtkSmartPointer<vtkPLYReader>::New();
reader->SetFileName(fname);
reader->Update();
polydata = reader->GetOutput();
} else if (ext == ".obj") {
vtkSmartPointer<vtkOBJReader> reader;
reader = vtkSmartPointer<vtkOBJReader>::New();
reader->SetFileName(fname);
reader->Update();
polydata = reader->GetOutput();
} else if (ext == ".dfs") {
polydata = ReadDFS(fname);
} else if (ext == ".off") {
polydata = ReadOFF(fname);
} else if (ext == ".gii") {
#if MIRTK_IO_WITH_GIFTI
polydata = ReadGIFTI(fname, nullptr, exit_on_failure);
#else
if (exit_on_failure) {
cerr << "Error: File '" << fname << "' cannot be read because MIRTK I/O library was built without GIFTI support!" << endl;
exit(1);
}
#endif
} else {
vtkSmartPointer<vtkPolyDataReader> reader;
reader = vtkSmartPointer<vtkPolyDataReader>::New();
reader->SetFileName(fname);
reader->Update();
if (ftype) *ftype = reader->GetFileType();
polydata = reader->GetOutput();
}
if (exit_on_failure && polydata->GetNumberOfPoints() == 0) {
cerr << "Error: File '" << fname << "' either contains no points or could not be read!" << endl;
exit(1);
}
return polydata;
}
// -----------------------------------------------------------------------------
bool WritePolyData(const char *fname, vtkPolyData *polydata, bool compress, bool ascii)
{
const string ext = Extension(fname);
int success = 0;
if (ext == ".vtp") {
vtkSmartPointer<vtkXMLPolyDataWriter> writer;
writer = vtkSmartPointer<vtkXMLPolyDataWriter>::New();
SetVTKInput(writer, polydata);
writer->SetFileName(fname);
if (compress) writer->SetCompressorTypeToZLib();
else writer->SetCompressorTypeToNone();
success = writer->Write();
} else if (ext == ".stl") {
vtkSmartPointer<vtkSTLWriter> writer;
writer = vtkSmartPointer<vtkSTLWriter>::New();
SetVTKInput(writer, polydata);
if (ascii) writer->SetFileTypeToASCII();
else writer->SetFileTypeToBinary();
writer->SetFileName(fname);
success = writer->Write();
} else if (ext == ".ply") {
vtkSmartPointer<vtkPLYWriter> writer;
writer = vtkSmartPointer<vtkPLYWriter>::New();
SetVTKInput(writer, polydata);
if (ascii) writer->SetFileTypeToASCII();
else writer->SetFileTypeToBinary();
writer->SetFileName(fname);
success = writer->Write();
} else if (ext == ".node") {
success = WriteTetGenNode(fname, polydata);
} else if (ext == ".poly") {
success = WriteTetGenPoly(fname, polydata);
} else if (ext == ".smesh") {
success = WriteTetGenSMesh(fname, polydata);
} else if (ext == ".dfs") {
success = WriteDFS(fname, polydata);
} else if (ext == ".off") {
success = WriteOFF(fname, polydata);
} else if (ext == ".gii") {
#if MIRTK_IO_WITH_GIFTI
success = WriteGIFTI(fname, polydata, compress, ascii);
#else
cerr << "Error: Cannot write surface to GIFTI file because MIRTK I/O library was built without GIFTI support!" << endl;
#endif
} else {
vtkSmartPointer<vtkPolyDataWriter> writer;
writer = vtkSmartPointer<vtkPolyDataWriter>::New();
SetVTKInput(writer, polydata);
writer->SetFileName(fname);
if (ascii) writer->SetFileTypeToASCII();
else writer->SetFileTypeToBinary();
success = writer->Write();
}
return (success == 1);
}
// =============================================================================
// BrainSuite I/O functions
// =============================================================================
// -----------------------------------------------------------------------------
vtkSmartPointer<vtkPolyData> ReadDFS(const char *fname)
{
vtkSmartPointer<vtkPolyData> polydata = vtkSmartPointer<vtkPolyData>::New();
// Read .dfs file
SILT::DFSurface surface;
if (!surface.readDFS(fname)) return polydata;
const vtkIdType npoints = static_cast<vtkIdType>(surface.vertices .size());
const vtkIdType ncells = static_cast<vtkIdType>(surface.triangles.size());
// Copy vertex coordinates
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
points->SetNumberOfPoints(npoints);
double p[3];
for (vtkIdType i = 0; i < npoints; ++i) {
p[0] = static_cast<double>(surface.vertices[i].x);
p[1] = static_cast<double>(surface.vertices[i].y);
p[2] = static_cast<double>(surface.vertices[i].z);
points->SetPoint(i, p);
}
polydata->SetPoints(points);
// Copy triangle face list
vtkIdType pts[3];
vtkSmartPointer<vtkCellArray> cells = vtkSmartPointer<vtkCellArray>::New();
cells->Allocate(cells->EstimateSize(ncells, 3));
for (vtkIdType i = 0; i < ncells; ++i) {
pts[0] = static_cast<vtkIdType>(surface.triangles[i].a);
pts[1] = static_cast<vtkIdType>(surface.triangles[i].b);
pts[2] = static_cast<vtkIdType>(surface.triangles[i].c);
cells->InsertNextCell(3, pts);
}
polydata->SetPolys(cells);
// Copy vertex normals
if (!surface.vertexNormals.empty()) {
double n[3];
vtkSmartPointer<vtkFloatArray> normals = vtkSmartPointer<vtkFloatArray>::New();
normals->SetName("Normals");
normals->SetNumberOfComponents(3);
normals->SetNumberOfTuples(npoints);
for (vtkIdType i = 0; i < npoints; ++i) {
n[0] = static_cast<double>(surface.vertexNormals[i].x);
n[1] = static_cast<double>(surface.vertexNormals[i].y);
n[2] = static_cast<double>(surface.vertexNormals[i].z);
normals->SetTuple(i, n);
}
polydata->GetPointData()->SetNormals(normals);
}
// Copy vertex colors
if (!surface.vertexColors.empty()) {
double rgb[3];
vtkSmartPointer<vtkFloatArray> colors = vtkSmartPointer<vtkFloatArray>::New();
colors->SetName("Colors");
colors->SetNumberOfComponents(3);
colors->SetNumberOfTuples(npoints);
for (vtkIdType i = 0; i < npoints; ++i) {
rgb[0] = static_cast<double>(surface.vertexColors[i].x);
rgb[1] = static_cast<double>(surface.vertexColors[i].y);
rgb[2] = static_cast<double>(surface.vertexColors[i].z);
colors->SetTuple(i, rgb);
}
polydata->GetPointData()->AddArray(colors);
}
// Copy vertex UV coordinates
if (!surface.vertexUV.empty()) {
double uv[3] = {.0};
vtkSmartPointer<vtkFloatArray> coords = vtkSmartPointer<vtkFloatArray>::New();
coords->SetName("UV");
coords->SetNumberOfComponents(3);
coords->SetNumberOfTuples(npoints);
for (vtkIdType i = 0; i < npoints; ++i) {
uv[0] = static_cast<double>(surface.vertexUV[i].u);
uv[1] = static_cast<double>(surface.vertexUV[i].v);
coords->SetTuple(i, uv);
}
polydata->GetPointData()->SetTCoords(coords);
}
// Copy vertex labels
if (!surface.vertexLabels.empty()) {
vtkSmartPointer<vtkUnsignedShortArray> labels = vtkSmartPointer<vtkUnsignedShortArray>::New();
labels->SetName("Labels");
labels->SetNumberOfComponents(1);
labels->SetNumberOfTuples(npoints);
for (vtkIdType i = 0; i < npoints; ++i) {
labels->SetValue(i, surface.vertexLabels[i]);
}
polydata->GetPointData()->AddArray(labels);
}
// Copy vertex attributes
if (!surface.vertexAttributes.empty()) {
vtkSmartPointer<vtkFloatArray> scalars = vtkSmartPointer<vtkFloatArray>::New();
scalars->SetName("Attributes");
scalars->SetNumberOfComponents(1);
scalars->SetNumberOfTuples(npoints);
for (vtkIdType i = 0; i < npoints; ++i) {
scalars->SetValue(i, surface.vertexAttributes[i]);
}
polydata->GetPointData()->SetScalars(scalars);
}
return polydata;
}
// -----------------------------------------------------------------------------
bool WriteDFS(const char *fname, vtkPolyData *polydata)
{
SILT::DFSurface surface;
// Copy vertex coordinates
double p[3];
surface.vertices.resize(polydata->GetNumberOfPoints());
for (vtkIdType i = 0; i < polydata->GetNumberOfPoints(); ++i) {
polydata->GetPoint(i, p);
surface.vertices[i].x = static_cast<float>(p[0]);
surface.vertices[i].y = static_cast<float>(p[1]);
surface.vertices[i].z = static_cast<float>(p[2]);
}
// Copy triangular faces
vtkIdType npts, *pts;
surface.triangles.resize(polydata->GetNumberOfCells());
for (vtkIdType i = 0; i < polydata->GetNumberOfCells(); ++i) {
polydata->GetCellPoints(i, npts, pts);
if (npts != 3) return false;
surface.triangles[i].a = static_cast<int>(pts[0]);
surface.triangles[i].b = static_cast<int>(pts[1]);
surface.triangles[i].c = static_cast<int>(pts[2]);
}
// Copy vertex normals
vtkDataArray *normals = polydata->GetPointData()->GetNormals();
if (!normals) normals = polydata->GetPointData()->GetArray("Normals");
if (normals) {
double n[3];
surface.vertexNormals.resize(polydata->GetNumberOfPoints());
for (vtkIdType i = 0; i < polydata->GetNumberOfPoints(); ++i) {
normals->GetTuple(i, n);
surface.vertexNormals[i].x = static_cast<float>(n[0]);
surface.vertexNormals[i].y = static_cast<float>(n[1]);
surface.vertexNormals[i].z = static_cast<float>(n[2]);
}
}
// Copy vertex colors
vtkDataArray *colors = polydata->GetPointData()->GetArray("Colors");
if (colors) {
double rgb[3];
surface.vertexColors.resize(polydata->GetNumberOfPoints());
for (vtkIdType i = 0; i < polydata->GetNumberOfPoints(); ++i) {
colors->GetTuple(i, rgb);
surface.vertexColors[i].x = static_cast<float>(rgb[0]);
surface.vertexColors[i].y = static_cast<float>(rgb[1]);
surface.vertexColors[i].z = static_cast<float>(rgb[2]);
}
}
// Copy vertex UV coordinates
vtkDataArray *coords = polydata->GetPointData()->GetTCoords();
if (!coords) coords = polydata->GetPointData()->GetArray("UV");
if (coords && (coords->GetNumberOfComponents() == 2 || coords->GetNumberOfComponents() == 3)) {
surface.vertexUV.resize(polydata->GetNumberOfPoints());
for (vtkIdType i = 0; i < polydata->GetNumberOfPoints(); ++i) {
surface.vertexUV[i].u = static_cast<float>(coords->GetComponent(i, 0));
surface.vertexUV[i].v = static_cast<float>(coords->GetComponent(i, 1));
}
}
// Copy vertex labels
vtkDataArray *labels = polydata->GetPointData()->GetArray("Labels");
if (labels && labels->GetNumberOfComponents() == 1) {
surface.vertexLabels.resize(polydata->GetNumberOfPoints());
for (vtkIdType i = 0; i < polydata->GetNumberOfPoints(); ++i) {
surface.vertexLabels[i] = static_cast<unsigned short>(labels->GetComponent(i, 0));
}
}
// Copy vertex attributes
vtkDataArray *scalars = polydata->GetPointData()->GetScalars();
if (!scalars) scalars = polydata->GetPointData()->GetArray("Attributes");
if (scalars && scalars->GetNumberOfComponents() == 1) {
surface.vertexAttributes.resize(polydata->GetNumberOfPoints());
for (vtkIdType i = 0; i < polydata->GetNumberOfPoints(); ++i) {
surface.vertexAttributes[i] = static_cast<float>(scalars->GetComponent(i, 0));
}
}
// Write .dfs file
return surface.writeDFS(fname);
}
// =============================================================================
// Object File Format I/O functions
// =============================================================================
// -----------------------------------------------------------------------------
vtkSmartPointer<vtkPolyData> ReadOFF(const char *fname)
{
vtkSmartPointer<vtkPolyData> polydata = vtkSmartPointer<vtkPolyData>::New();
ifstream ifs(fname);
if (!ifs) return polydata;
string keyword;
ifs >> keyword;
if (keyword != "OFF" && keyword != "off") return polydata;
int numVertices = -1, numFaces = -1, numEdges = -1;
ifs >> numVertices >> numFaces >> numEdges;
if (ifs.fail()) return polydata;
if (numVertices < 0) numVertices = 0;
if (numFaces < 0) numFaces = 0;
vtkSmartPointer<vtkPoints> points;
points = vtkSmartPointer<vtkPoints>::New();
points->SetNumberOfPoints(numVertices);
double p[3];
for (int i = 0; i < numVertices; ++i) {
ifs >> p[0] >> p[1] >> p[2];
if (ifs.fail()) break;
points->SetPoint(i, p);
}
if (ifs.fail()) return polydata;
vtkSmartPointer<vtkCellArray> verts, lines, polys;
vtkSmartPointer<vtkIdList> cell = vtkSmartPointer<vtkIdList>::New();
verts = vtkSmartPointer<vtkCellArray>::New();
lines = vtkSmartPointer<vtkCellArray>::New();
polys = vtkSmartPointer<vtkCellArray>::New();
for (int i = 0, ptId, n; i < numFaces; ++i) {
ifs >> n;
if (ifs.fail()) break;
if (n > 0) {
cell->Reset();
for (int j = 0; j < n; ++j) {
ifs >> ptId;
cell->InsertNextId(ptId);
}
if (n == 1) verts->InsertNextCell(cell);
else if (n == 2) lines->InsertNextCell(cell);
else polys->InsertNextCell(cell);
if (!ifs.good()) break;
}
}
if (ifs.fail()) return polydata;
verts->Squeeze();
lines->Squeeze();
polys->Squeeze();
polydata->SetPoints(points);
if (verts->GetNumberOfCells() > 0) polydata->SetVerts(verts);
if (lines->GetNumberOfCells() > 0) polydata->SetLines(lines);
if (polys->GetNumberOfCells() > 0) polydata->SetPolys(polys);
return polydata;
}
// -----------------------------------------------------------------------------
bool WriteOFF(const char *fname, vtkPolyData *polydata)
{
ofstream ofs(fname);
ofs.precision(12);
ofs << "OFF\n";
ofs << polydata->GetNumberOfPoints() << " ";
ofs << polydata->GetNumberOfCells() << " 0\n";
double p[3];
for (vtkIdType ptId = 0; ptId < polydata->GetNumberOfPoints(); ++ptId) {
polydata->GetPoint(ptId, p);
ofs << p[0] << " " << p[1] << " " << p[2] << "\n";
}
vtkIdType numPts, *ptIds;
polydata->BuildCells();
for (vtkIdType cellId = 0; cellId < polydata->GetNumberOfCells(); ++cellId) {
polydata->GetCellPoints(cellId, numPts, ptIds);
ofs << numPts;
for (vtkIdType i = 0; i < numPts; ++i) {
ofs << " " << ptIds[i];
}
ofs << "\n";
}
return !ofs.fail();
}
// =============================================================================
// TetGen I/O functions
// =============================================================================
// -----------------------------------------------------------------------------
/// Write point set to TetGen .node output stream
///
/// @param[in, out] os Output stream.
/// @param[in] pointset Point set.
///
/// @return Whether point set was written successfully to the given output stream.
bool WriteTetGenNode(ostream &os, vtkPointSet *pointset)
{
vtkPointData *pd = pointset->GetPointData();
vtkDataArray *ar;
int nattributes = 0;
for (int i = 0; i < pd->GetNumberOfArrays(); ++i) {
nattributes += pd->GetArray(i)->GetNumberOfComponents();
}
os << pointset->GetNumberOfPoints() << " 3 " << nattributes << " 0\n";
double p[3];
streamsize precision = os.precision();
for (vtkIdType ptId = 0; ptId < pointset->GetNumberOfPoints(); ++ptId) {
os << (ptId + 1) << " ";
os.precision(8); // default TetGen tolerance is 1e-8
pointset->GetPoint(ptId, p);
os << " " << p[0] << " " << p[1] << " " << p[2];
os.precision(5);
for (int i = 0; i < pd->GetNumberOfArrays(); ++i) {
ar = pd->GetArray(i);
for (int j = 0; j < ar->GetNumberOfComponents(); ++j) {
os << " " << ar->GetComponent(ptId, j);
}
}
os << "\n";
}
os.precision(precision);
return !os.fail();
}
// -----------------------------------------------------------------------------
bool WriteTetGenNode(const char *fname, vtkPointSet *pointset)
{
ofstream os(fname);
if (!os.is_open()) return false;
return WriteTetGenNode(os, pointset);
}
// -----------------------------------------------------------------------------
bool WriteTetGenPoly(const char *fname, vtkPolyData *polydata, const PointSet *holes)
{
ofstream os(fname);
if (!os.is_open()) return false;
os << "# part 1: nodes\n";
WriteTetGenNode(os, polydata);
vtkIdType npts, *pts;
vtkCellArray *verts = polydata->GetVerts();
vtkCellArray *lines = polydata->GetLines();
vtkCellArray *polys = polydata->GetPolys();
vtkCellArray *strips = polydata->GetStrips();
int nfacets = 0;
if (verts ->GetNumberOfCells() > 0) nfacets += 1;
if (lines ->GetNumberOfCells() > 0) nfacets += 1;
if (polys ->GetNumberOfCells() > 0) nfacets += 1;
if (strips->GetNumberOfCells() > 0) nfacets += 1;
os << "\n# part 2: facets\n";
os << nfacets << " 0\n";
if (verts->GetNumberOfCells() > 0) {
os << "# verts\n";
os << verts->GetNumberOfCells() << "\n";
verts->InitTraversal();
while (verts->GetNextCell(npts, pts)) {
os << npts << " ";
for (vtkIdType i = 0; i < npts; ++i) os << " " << (pts[i] + 1);
os << "\n";
}
}
if (lines->GetNumberOfCells() > 0) {
os << "# lines\n";
os << lines->GetNumberOfCells() << "\n";
lines->InitTraversal();
while (lines->GetNextCell(npts, pts)) {
os << npts << " ";
for (vtkIdType i = 0; i < npts; ++i) os << " " << (pts[i] + 1);
os << "\n";
}
}
if (polys->GetNumberOfCells() > 0) {
os << "# polys\n";
os << polys->GetNumberOfCells() << "\n";
polys->InitTraversal();
while (polys->GetNextCell(npts, pts)) {
os << npts << " ";
for (vtkIdType i = 0; i < npts; ++i) os << " " << (pts[i] + 1);
os << "\n";
}
}
if (strips->GetNumberOfCells() > 0) {
os << "# strips\n";
os << strips->GetNumberOfCells() << "\n";
strips->InitTraversal();
while (strips->GetNextCell(npts, pts)) {
os << npts << " ";
for (vtkIdType i = 0; i < npts; ++i) os << " " << (pts[i] + 1);
os << "\n";
}
}
os << "\n# part 3: hole list\n";
if (holes) {
os << holes->Size() << "\n";
for (int i = 0; i < holes->Size(); ++i) {
const Point &p = holes->GetPoint(i);
os << (i+1) << " " << p._x << " " << p._y << " " << p._z << "\n";
}
} else {
os << "0\n";
}
os << "\n# part 4: region list\n";
os << "0\n";
return !os.fail();
}
// -----------------------------------------------------------------------------
bool WriteTetGenSMesh(const char *fname, vtkPolyData *polydata, const PointSet *holes)
{
ofstream os(fname);
if (!os.is_open()) return false;
os << "# part 1: nodes\n";
WriteTetGenNode(os, polydata);
vtkIdType npts, *pts;
vtkCellArray *verts = polydata->GetVerts();
vtkCellArray *lines = polydata->GetLines();
vtkCellArray *polys = polydata->GetPolys();
vtkCellArray *strips = polydata->GetStrips();
int nfacets = 0;
if (verts ->GetNumberOfCells() > 0) nfacets += verts ->GetNumberOfCells();
if (lines ->GetNumberOfCells() > 0) nfacets += lines ->GetNumberOfCells();
if (polys ->GetNumberOfCells() > 0) nfacets += polys ->GetNumberOfCells();
if (strips->GetNumberOfCells() > 0) nfacets += strips->GetNumberOfCells();
os << "\n# part 2: facets\n";
os << nfacets << " 0\n";
if (verts->GetNumberOfCells() > 0) {
verts->InitTraversal();
while (verts->GetNextCell(npts, pts)) {
os << npts << " ";
for (vtkIdType i = 0; i < npts; ++i) os << " " << (pts[i] + 1);
os << "\n";
}
}
if (lines->GetNumberOfCells() > 0) {
lines->InitTraversal();
while (lines->GetNextCell(npts, pts)) {
os << npts << " ";
for (vtkIdType i = 0; i < npts; ++i) os << " " << (pts[i] + 1);
os << "\n";
}
}
if (polys->GetNumberOfCells() > 0) {
polys->InitTraversal();
while (polys->GetNextCell(npts, pts)) {
os << npts << " ";
for (vtkIdType i = 0; i < npts; ++i) os << " " << (pts[i] + 1);
os << "\n";
}
}
if (strips->GetNumberOfCells() > 0) {
strips->InitTraversal();
while (strips->GetNextCell(npts, pts)) {
os << npts;
for (vtkIdType i = 0; i < npts; ++i) os << " " << (pts[i] + 1);
os << "\n";
}
}
os << "\n# part 3: hole list\n";
if (holes) {
os << holes->Size() << "\n";
for (int i = 0; i < holes->Size(); ++i) {
const Point &p = holes->GetPoint(i);
os << (i+1) << " " << p._x << " " << p._y << " " << p._z << "\n";
}
} else {
os << "0\n";
}
os << "\n# part 4: region list\n";
os << "0\n";
return !os.fail();
}
// =============================================================================
// GIFTI I/O functions
// =============================================================================
#if MIRTK_IO_WITH_GIFTI
// -----------------------------------------------------------------------------
/// Get VTK data type enumeration value corresponding to given GIFTI datatype
static int GIFTIDataTypeToVTK(int datatype)
{
switch (datatype) {
case NIFTI_TYPE_INT8: return VTK_CHAR;
case NIFTI_TYPE_INT16: return VTK_SHORT;
case NIFTI_TYPE_INT32: return VTK_INT;
case NIFTI_TYPE_INT64: return VTK_LONG_LONG;
case NIFTI_TYPE_UINT8: return VTK_UNSIGNED_CHAR;
case NIFTI_TYPE_UINT16: return VTK_UNSIGNED_SHORT;
case NIFTI_TYPE_UINT32: return VTK_UNSIGNED_INT;
case NIFTI_TYPE_UINT64: return VTK_UNSIGNED_LONG_LONG;
case NIFTI_TYPE_FLOAT32: return VTK_FLOAT;
case NIFTI_TYPE_FLOAT64: return VTK_DOUBLE;
default: return VTK_VOID;
}
}
// -----------------------------------------------------------------------------
/// Copy GIFTI data array of data type matching the template argument to vtkDataArray
template <class T>
void CopyGIFTIDataArrayWithDataType(vtkDataArray *dst, const giiDataArray *src,
vtkIdTypeArray *indices = nullptr)
{
const int m = src->dims[0];
const int n = static_cast<int>(src->nvals / static_cast<long long>(m));
const T *v = reinterpret_cast<const T *>(src->data);
if (indices) {
vtkIdType index;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j) {
dst->SetComponent(i, j, .0);
}
if (src->ind_ord == GIFTI_IND_ORD_COL_MAJOR) {
for (int j = 0; j < n; ++j)
for (int i = 0; i < m; ++i, ++v) {
index = indices->GetComponent(i, 0);
dst->SetComponent(index, j, static_cast<double>(*v));
}
} else {
for (int i = 0; i < m; ++i) {
index = indices->GetComponent(i, 0);
for (int j = 0; j < n; ++j) {
dst->SetComponent(index, j, static_cast<double>(*v));
}
}
}
} else {
if (src->ind_ord == GIFTI_IND_ORD_COL_MAJOR) {
for (int j = 0; j < n; ++j)
for (int i = 0; i < m; ++i, ++v) {
dst->SetComponent(i, j, static_cast<double>(*v));
}
} else {
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j) {
dst->SetComponent(i, j, static_cast<double>(*v));
}
}
}
}
// -----------------------------------------------------------------------------
/// Copy GIFTI data array to vtkDataArray
static void CopyGIFTIDataArray(vtkDataArray *dst, const giiDataArray *src,
vtkIdTypeArray *indices = nullptr)
{
switch (src->datatype) {
case NIFTI_TYPE_INT8: CopyGIFTIDataArrayWithDataType<int8_t >(dst, src, indices); break;
case NIFTI_TYPE_INT16: CopyGIFTIDataArrayWithDataType<int16_t >(dst, src, indices); break;
case NIFTI_TYPE_INT32: CopyGIFTIDataArrayWithDataType<int32_t >(dst, src, indices); break;
case NIFTI_TYPE_INT64: CopyGIFTIDataArrayWithDataType<int64_t >(dst, src, indices); break;
case NIFTI_TYPE_UINT8: CopyGIFTIDataArrayWithDataType<uint8_t >(dst, src, indices); break;
case NIFTI_TYPE_UINT16: CopyGIFTIDataArrayWithDataType<uint16_t>(dst, src, indices); break;
case NIFTI_TYPE_UINT32: CopyGIFTIDataArrayWithDataType<uint32_t>(dst, src, indices); break;
case NIFTI_TYPE_UINT64: CopyGIFTIDataArrayWithDataType<uint64_t>(dst, src, indices); break;
case NIFTI_TYPE_FLOAT32: CopyGIFTIDataArrayWithDataType<float >(dst, src, indices); break;
case NIFTI_TYPE_FLOAT64: CopyGIFTIDataArrayWithDataType<double >(dst, src, indices); break;
default:
cerr << "GIFTI data array has unknown/invalid data type: " << src->datatype << endl;
exit(1);
}
}
// -----------------------------------------------------------------------------
// vtkInformation keys of standard GIFTI meta data entries
vtkInformationKeyMacro(GiftiMetaData, DATE, String);
vtkInformationKeyMacro(GiftiMetaData, USER_NAME, String);
vtkInformationKeyMacro(GiftiMetaData, SUBJECT_ID, String);
vtkInformationKeyMacro(GiftiMetaData, SURFACE_ID, String);
vtkInformationKeyMacro(GiftiMetaData, UNIQUE_ID, String);
vtkInformationKeyMacro(GiftiMetaData, NAME, String);
vtkInformationKeyMacro(GiftiMetaData, DESCRIPTION, String);
vtkInformationKeyMacro(GiftiMetaData, TIME_STEP, Double);
vtkInformationKeyMacro(GiftiMetaData, ANATOMICAL_STRUCTURE_PRIMARY, String);
vtkInformationKeyMacro(GiftiMetaData, ANATOMICAL_STRUCTURE_SECONDARY, String);
vtkInformationKeyMacro(GiftiMetaData, GEOMETRIC_TYPE, String);
vtkInformationKeyMacro(GiftiMetaData, TOPOLOGICAL_TYPE, String);
vtkInformationKeyMacro(GiftiMetaData, INTENT_CODE, Integer);
vtkInformationKeyMacro(GiftiMetaData, INTENT_P1, Double);
vtkInformationKeyMacro(GiftiMetaData, INTENT_P2, Double);
vtkInformationKeyMacro(GiftiMetaData, INTENT_P3, Double);
// -----------------------------------------------------------------------------
/// Copy standard GIFTI meta data to vtkInformation
static void CopyGIFTIMetaData(vtkInformation *info, const giiMetaData &meta)
{
for (int i = 0; i < meta.length; ++i) {
if (strcmp(meta.name[i], "Date") == 0) {
info->Set(GiftiMetaData::DATE(), meta.value[i]);
} else if (strcmp(meta.name[i], "UserName") == 0) {
info->Set(GiftiMetaData::USER_NAME(), meta.value[i]);
} else if (strcmp(meta.name[i], "SubjectID") == 0) {
info->Set(GiftiMetaData::SUBJECT_ID(), meta.value[i]);
} else if (strcmp(meta.name[i], "SurfaceID") == 0) {
info->Set(GiftiMetaData::SURFACE_ID(), meta.value[i]);
} else if (strcmp(meta.name[i], "UniqueID") == 0) {
info->Set(GiftiMetaData::UNIQUE_ID(), meta.value[i]);
} else if (strcmp(meta.name[i], "Name") == 0) {
info->Set(GiftiMetaData::NAME(), meta.value[i]);
} else if (strcmp(meta.name[i], "Description") == 0) {
info->Set(GiftiMetaData::DESCRIPTION(), meta.value[i]);
} else if (strcmp(meta.name[i], "TimeStep") == 0) {
double tr;
if (FromString(meta.value[i], tr)) {
info->Set(GiftiMetaData::TIME_STEP(), tr);
}
} else if (strcmp(meta.name[i], "AnatomicalStructurePrimary") == 0) {
info->Set(GiftiMetaData::ANATOMICAL_STRUCTURE_PRIMARY(), meta.value[i]);
} else if (strcmp(meta.name[i], "AnatomicalStructureSecondary") == 0) {
info->Set(GiftiMetaData::ANATOMICAL_STRUCTURE_SECONDARY(), meta.value[i]);
} else if (strcmp(meta.name[i], "GeometricType") == 0) {
info->Set(GiftiMetaData::GEOMETRIC_TYPE(), meta.value[i]);
} else if (strcmp(meta.name[i], "TopologicalType") == 0) {
info->Set(GiftiMetaData::TOPOLOGICAL_TYPE(), meta.value[i]);
} else if (strcmp(meta.name[i], "Intent") == 0 ||
strcmp(meta.name[i], "Intent_code") == 0 ||
strcmp(meta.name[i], "IntentCode") == 0) {
int intent_code;
if (FromString(meta.value[i], intent_code)) {
info->Set(GiftiMetaData::INTENT_CODE(), intent_code);
}
} else if (strcmp(meta.name[i], "IntentP1") == 0 ||
strcmp(meta.name[i], "Intent_p1") == 0 ||
strcmp(meta.name[i], "intent_p1") == 0) {
double intent_p1;
if (FromString(meta.value[i], intent_p1)) {
info->Set(GiftiMetaData::INTENT_P1(), intent_p1);
}
} else if (strcmp(meta.name[i], "IntentP2") == 0 ||
strcmp(meta.name[i], "Intent_p2") == 0 ||
strcmp(meta.name[i], "intent_p2") == 0) {
double intent_p2;
if (FromString(meta.value[i], intent_p2)) {
info->Set(GiftiMetaData::INTENT_P2(), intent_p2);
}
} else if (strcmp(meta.name[i], "IntentP3") == 0 ||
strcmp(meta.name[i], "Intent_p3") == 0 ||
strcmp(meta.name[i], "intent_p3") == 0) {
double intent_p3;
if (FromString(meta.value[i], intent_p3)) {
info->Set(GiftiMetaData::INTENT_P3(), intent_p3);
}
}
}
}
// -----------------------------------------------------------------------------
/// Copy GIFTI point set to vtkPoints
static vtkSmartPointer<vtkPoints>
GIFTICoordinatesToVTK(const gifti_image *gim, vtkInformation *info = nullptr, bool errmsg = false)
{
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
for (int i = 0; i < gim->numDA; ++i) {
giiDataArray *array = gim->darray[i];
if (array->intent == NIFTI_INTENT_POINTSET) {
if (array->datatype != NIFTI_TYPE_FLOAT32) {
if (errmsg) {
cerr << "Error: GIFTI coordinates array must have datatype NIFTI_TYPE_FLOAT32!" << endl;
}
break;
}
if (array->num_dim != 2) {
if (errmsg) {
cerr << "Error: GIFTI coordinates array must have 2 dimensions!" << endl;
}
break;
}
if (array->dims[1] != 3) {
if (errmsg) {
cerr << "Error: Second dimension of GIFTI coordinates array must have size 3!" << endl;
}
break;
}
const int n = array->dims[0];
points->SetNumberOfPoints(n);
const float *x = reinterpret_cast<float *>(array->data);
if (array->ind_ord == GIFTI_IND_ORD_COL_MAJOR) {
const float *y = x + n, *z = y + n;
for (int j = 0; j < n; ++j, ++x, ++y, ++z) {
points->SetPoint(j, static_cast<double>(*x), static_cast<double>(*y), static_cast<double>(*z));
}
} else {
const float *y = x + 1, *z = x + 2;
for (int j = 0; j < n; ++j, x += 3, y += 3, z += 3) {
points->SetPoint(j, static_cast<double>(*x), static_cast<double>(*y), static_cast<double>(*z));
}
}
if (info) CopyGIFTIMetaData(info, array->meta);
break;
}
}
return points;
}
// -----------------------------------------------------------------------------
/// Copy GIFTI topology information to vtkCellArray
static vtkSmartPointer<vtkCellArray>
GIFTITopologyToVTK(const gifti_image *gim, vtkInformation *info = nullptr, bool errmsg = false)
{
vtkSmartPointer<vtkCellArray> triangles;
for (int i = 0; i < gim->numDA; ++i) {
giiDataArray *array = gim->darray[i];
if (array->intent == NIFTI_INTENT_TRIANGLE) {
if (array->datatype != NIFTI_TYPE_INT32) {
if (errmsg) {
cerr << "Error: GIFTI topology array must have datatype NIFTI_TYPE_INT32!" << endl;
}
break;
}
if (array->num_dim != 2) {
if (errmsg) {
cerr << "Error: GIFTI topology array must have 2 dimensions!" << endl;
}
break;
}
if (array->dims[1] != 3) {
if (errmsg) {
cerr << "Error: Second dimension of GIFTI topology array must have size 3!" << endl;
}
break;
}
vtkIdType pts[3];
const int n = array->dims[0];
triangles = vtkSmartPointer<vtkCellArray>::New();
triangles->Allocate(3 * n);
const int *a = reinterpret_cast<int *>(array->data);
if (array->ind_ord == GIFTI_IND_ORD_COL_MAJOR) {
const int *b = a + n, *c = b + n;
for (int j = 0; j < n; ++j, ++a, ++b, ++c) {
pts[0] = static_cast<vtkIdType>(*a);
pts[1] = static_cast<vtkIdType>(*b);
pts[2] = static_cast<vtkIdType>(*c);
triangles->InsertNextCell(3, pts);
}
} else {
const int *b = a + 1, *c = a + 2;
for (int j = 0; j < n; ++j, a += 3, b += 3, c += 3) {
pts[0] = static_cast<vtkIdType>(*a);
pts[1] = static_cast<vtkIdType>(*b);
pts[2] = static_cast<vtkIdType>(*c);
triangles->InsertNextCell(3, pts);
}
}
if (info) CopyGIFTIMetaData(info, array->meta);
break;
}
}
return triangles;
}
// -----------------------------------------------------------------------------
/// Convert GIFTI node indices array to vtkDataArray
static vtkSmartPointer<vtkIdTypeArray>
GIFTINodeIndicesToVTK(const gifti_image *gim, bool errmsg = false)
{
vtkSmartPointer<vtkIdTypeArray> indices;
for (int i = 0; i < gim->numDA; ++i) {
giiDataArray *array = gim->darray[i];
if (array->intent == NIFTI_INTENT_NODE_INDEX) {
if (array->num_dim != 1) {
if (errmsg) {
cerr << "Error: GIFTI node indices array must have 1 dimension!" << endl;
}
break;
}
if (array->dims[0] <= 0) {
if (errmsg) {
cerr << "Error: GIFTI node indices array must contain at least one index!" << endl;
}
break;
}
indices = vtkSmartPointer<vtkIdTypeArray>::New();
indices->SetNumberOfComponents(1);
indices->SetNumberOfTuples(array->dims[0]);
CopyGIFTIDataArray(indices, array);
}
}
return indices;
}
// -----------------------------------------------------------------------------
/// Convert GIFTI data arrays to vtkDataArray instances of a vtkPointData
static vtkSmartPointer<vtkPointData>
GIFTIPointDataToVTK(const gifti_image *gim, vtkIdType npoints = 0, vtkIdTypeArray *indices = nullptr, bool errmsg = false)
{
vtkIdType nindices = 0;
if (indices) {
nindices = indices->GetNumberOfTuples();
if (npoints == 0) {
cerr << "GIFTIPointDataToVTK: Number of points cannot be zero when reading sparse point data arrays!" << endl;
exit(1);
}
if (nindices > npoints) {
cerr << "GIFTIPointDataToVTK: Number of points cannot be less then number of node indices!" << endl;
exit(1);
}
}
bool ok = true;
vtkSmartPointer<vtkPointData> pd = vtkSmartPointer<vtkPointData>::New();
for (int i = 0; i < gim->numDA; ++i) {
giiDataArray *array = gim->darray[i];
if (array->intent != NIFTI_INTENT_POINTSET &&
array->intent != NIFTI_INTENT_TRIANGLE &&
array->intent != NIFTI_INTENT_NODE_INDEX &&
array->num_dim > 0 && array->dims[0] > 0 && array->nvals > 0) {
const int ncomp = static_cast<int>(array->nvals / static_cast<long long>(array->dims[0]));
vtkSmartPointer<vtkDataArray> data;
data = NewVTKDataArray(GIFTIDataTypeToVTK(array->datatype));
data->SetNumberOfComponents(ncomp);
if (npoints) {
if (( indices && static_cast<vtkIdType>(array->dims[0]) != nindices) ||
(!indices && static_cast<vtkIdType>(array->dims[0]) != npoints)) {
if (errmsg) {
cerr << "Error: GIFTI array size does not match point set or node indices array size!" << endl;
}
ok = false;
break;
}
data->SetNumberOfTuples(npoints);
} else {
data->SetNumberOfTuples(array->dims[0]);
}
CopyGIFTIDataArray(data, array, indices);
vtkInformation * const info = data->GetInformation();
CopyGIFTIMetaData(info, array->meta);
if (info->Has(GiftiMetaData::NAME())) {
data->SetName(info->Get(GiftiMetaData::NAME()));
} else {
data->SetName(ToString(array->intent).c_str());
}
const int idx = pd->AddArray(data);
if (array->intent == NIFTI_INTENT_SHAPE && !pd->GetScalars()) {
pd->SetActiveAttribute(idx, vtkDataSetAttributes::SCALARS);
}
if (array->intent == NIFTI_INTENT_VECTOR && ncomp == 3 && !pd->GetVectors()) {
pd->SetActiveAttribute(idx, vtkDataSetAttributes::VECTORS);
}
}
}
if (!ok) pd->Initialize();
return pd;
}
// -----------------------------------------------------------------------------
vtkSmartPointer<vtkPoints> ReadGIFTICoordinates(const char *fname, vtkInformation *info, bool errmsg)
{
gifti_image *gim = gifti_read_image(fname, 1);
if (gim == nullptr) {
if (errmsg) {
cerr << "Error: Could not read GIFTI file: " << fname << endl;
}
return vtkSmartPointer<vtkPoints>::New();
}
return GIFTICoordinatesToVTK(gim, info, errmsg);
}
// -----------------------------------------------------------------------------
vtkSmartPointer<vtkCellArray> ReadGIFTITopology(const char *fname, vtkInformation *info, bool errmsg)
{
gifti_image *gim = gifti_read_image(fname, 1);
if (gim == nullptr) {
if (errmsg) {
cerr << "Error: Could not read GIFTI file: " << fname << endl;
}
return nullptr;
}
return GIFTITopologyToVTK(gim, info, errmsg);
}
// -----------------------------------------------------------------------------
vtkSmartPointer<vtkPointData> ReadGIFTIPointData(const char *fname, bool errmsg)
{
gifti_image *gim = gifti_read_image(fname, 1);
if (gim == nullptr) {
if (errmsg) {
cerr << "Error: Could not read GIFTI file: " << fname << endl;
}
return nullptr;
}
return GIFTIPointDataToVTK(gim, 0, nullptr, errmsg);
}
// -----------------------------------------------------------------------------
vtkSmartPointer<vtkPolyData> ReadGIFTI(const char *fname, vtkPolyData *surface, bool errmsg)
{
vtkSmartPointer<vtkPolyData> polydata = vtkSmartPointer<vtkPolyData>::New();
// Read GIFTI
const int read_data = 1;
gifti_image *gim = gifti_read_image(fname, read_data);
if (gim == nullptr) return polydata;
// Convert geometry and topology arrays including their meta data
vtkSmartPointer<vtkInformation> geom_info = vtkSmartPointer<vtkInformation>::New();
vtkSmartPointer<vtkInformation> topo_info = vtkSmartPointer<vtkInformation>::New();
vtkSmartPointer<vtkPoints> points = GIFTICoordinatesToVTK(gim, geom_info, errmsg);
vtkSmartPointer<vtkCellArray> polys = GIFTITopologyToVTK (gim, topo_info, errmsg);
// Polygonal dataset requires a point set
if (points->GetNumberOfPoints() == 0) {
if (surface && surface->GetNumberOfPoints() > 0) {
points = surface->GetPoints();
} else {
if (errmsg) {
cerr << "Error: Cannot read GIFTI point data without input point set (e.g., from .coords.gii or .surf.gii file)!" << endl;
}
return polydata;
}
}
// Get node indices array
vtkSmartPointer<vtkIdTypeArray> indices = GIFTINodeIndicesToVTK(gim, errmsg);
// Convert possibly sparse point data arrays
vtkSmartPointer<vtkPointData> pd;
pd = GIFTIPointDataToVTK(gim, points->GetNumberOfPoints(), indices, errmsg);
// Copy file meta data to vtkPolyData information
vtkInformation * const info = polydata->GetInformation();
CopyGIFTIMetaData(info, gim->meta);
// Free gifti_image instance
gifti_free_image(gim);
gim = nullptr;
// Verify consistency of resulting polygonal dataset
bool ok = (points->GetNumberOfPoints() > 0);
if (pd) {
for (int i = 0; i < pd->GetNumberOfArrays(); ++i) {
vtkDataArray *data = pd->GetArray(i);
if (data->GetNumberOfTuples() != points->GetNumberOfPoints()) {
cerr << "Error: First dimension of GIFTI array '" << pd->GetArray(i)->GetName()
<< "' (index " << i << ") has mismatching size!" << endl;
cerr << " - Number of points = " << points->GetNumberOfPoints() << endl;
cerr << " - Number of tuples = " << data ->GetNumberOfTuples() << endl;
ok = false;
}
}
}
// Finalize polygonal dataset
if (ok) {
// Set geometry, topology, and point data
polydata->SetPoints(points);
polydata->SetPolys(polys);
polydata->GetPointData()->ShallowCopy(pd);
// Copy meta data of geometry and topology data arrays to vtkPolyData information
if (geom_info->Has(GiftiMetaData::SUBJECT_ID())) {
info->CopyEntry(geom_info, GiftiMetaData::SUBJECT_ID());
}
if (geom_info->Has(GiftiMetaData::SURFACE_ID())) {
info->CopyEntry(geom_info, GiftiMetaData::SURFACE_ID());
}
if (geom_info->Has(GiftiMetaData::UNIQUE_ID())) {
info->CopyEntry(geom_info, GiftiMetaData::UNIQUE_ID());
}
if (geom_info->Has(GiftiMetaData::DESCRIPTION())) {
info->CopyEntry(geom_info, GiftiMetaData::DESCRIPTION());
}
if (geom_info->Has(GiftiMetaData::ANATOMICAL_STRUCTURE_PRIMARY())) {
info->CopyEntry(geom_info, GiftiMetaData::ANATOMICAL_STRUCTURE_PRIMARY());
}
if (geom_info->Has(GiftiMetaData::ANATOMICAL_STRUCTURE_SECONDARY())) {
info->CopyEntry(geom_info, GiftiMetaData::ANATOMICAL_STRUCTURE_SECONDARY());
}
if (geom_info->Has(GiftiMetaData::GEOMETRIC_TYPE())) {
info->CopyEntry(geom_info, GiftiMetaData::GEOMETRIC_TYPE());
}
if (topo_info->Has(GiftiMetaData::TOPOLOGICAL_TYPE())) {
info->CopyEntry(geom_info, GiftiMetaData::TOPOLOGICAL_TYPE());
}
} else {
info->Clear();
}
return polydata;
}
// -----------------------------------------------------------------------------
bool WriteGIFTI(const char *fname, vtkPolyData *polydata, bool compress, bool ascii)
{
return false;
}
#endif // MIRTK_IO_WITH_GIFTI
} // namespace mirtk
enh: Check consistency of read GIFTI data arrays [IO]
/*
* Medical Image Registration ToolKit (MIRTK)
*
* Copyright 2013-2016 Imperial College London
* Copyright 2013-2016 Andreas Schuh
*
* 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 "mirtk/PointSetIO.h"
#include "mirtk/Path.h"
#include "mirtk/Stream.h"
#include "mirtk/Vtk.h"
#include "vtkPoints.h"
#include "vtkPointData.h"
#include "vtkDataArray.h"
#include "vtkCellArray.h"
#include "vtkIdTypeArray.h"
#include "vtkIdList.h"
#include "vtkInformation.h"
#include "vtkUnsignedShortArray.h"
#include "vtkFloatArray.h"
#include "vtkUnstructuredGrid.h"
#include "vtkStructuredGrid.h"
#include "vtkGenericDataObjectReader.h"
#include "vtkDataSetWriter.h"
#include "vtkPolyDataReader.h"
#include "vtkPolyDataWriter.h"
#include "vtkXMLGenericDataObjectReader.h"
#include "vtkXMLDataSetWriter.h"
#include "vtkXMLPolyDataReader.h"
#include "vtkXMLPolyDataWriter.h"
#include "vtkOBJReader.h"
#include "vtkPLYReader.h"
#include "vtkSTLReader.h"
#include "vtkPLYWriter.h"
#include "vtkSTLWriter.h"
#include "brainsuite/dfsurface.h"
#if MIRTK_IO_WITH_GIFTI
#include "mirtk/NiftiImageInfo.h"
#include "gifti/gifti_io.h"
#endif
namespace mirtk {
// =============================================================================
// File name extension
// =============================================================================
// -----------------------------------------------------------------------------
const char *DefaultExtension(vtkDataSet *dataset)
{
if (vtkPolyData ::SafeDownCast(dataset)) return ".vtp";
else if (vtkUnstructuredGrid::SafeDownCast(dataset)) return ".vtu";
else if (vtkStructuredGrid ::SafeDownCast(dataset)) return ".vts";
return ".vtk";
}
// =============================================================================
// Generic I/O functions
// =============================================================================
// -----------------------------------------------------------------------------
vtkSmartPointer<vtkPointSet> ReadPointSet(const char *fname, int *ftype, bool exit_on_failure)
{
vtkSmartPointer<vtkPointSet> pointset;
const string ext = Extension(fname);
if (ext == ".vtp" || ext == ".stl" || ext == ".ply" || ext == ".obj" || ext == ".dfs" || ext == ".off" || ext == ".gii") {
pointset = ReadPolyData(fname);
} else if (ext.length() == 4 && ext.substr(0, 3) == ".vt" && ext != ".vtk") {
vtkSmartPointer<vtkXMLGenericDataObjectReader> reader;
reader = vtkSmartPointer<vtkXMLGenericDataObjectReader>::New();
reader->SetFileName(fname);
reader->Update();
pointset = vtkPointSet::SafeDownCast(reader->GetOutput());
} else {
vtkSmartPointer<vtkGenericDataObjectReader> reader;
reader = vtkSmartPointer<vtkGenericDataObjectReader>::New();
reader->SetFileName(fname);
reader->Update();
if (ftype) *ftype = reader->GetFileType();
pointset = vtkPointSet::SafeDownCast(reader->GetOutput());
}
if (exit_on_failure && (!pointset || pointset->GetNumberOfPoints() == 0)) {
cerr << "File " << fname << " either contains no points or could not be read" << endl;
exit(1);
}
return pointset;
}
// -----------------------------------------------------------------------------
bool WritePointSet(const char *fname, vtkPointSet *pointset, bool compress, bool ascii)
{
vtkPolyData *polydata = vtkPolyData::SafeDownCast(pointset);
if (polydata) return WritePolyData(fname, polydata, compress, ascii);
const string ext = Extension(fname);
int success = 0;
if (ext.length() == 4 && ext.substr(0, 3) == ".vt" && ext != ".vtk") {
vtkSmartPointer<vtkXMLDataSetWriter> writer;
writer = vtkSmartPointer<vtkXMLDataSetWriter>::New();
SetVTKInput(writer, pointset);
writer->SetFileName(fname);
if (compress) writer->SetCompressorTypeToZLib();
else writer->SetCompressorTypeToNone();
success = writer->Write();
} else {
vtkSmartPointer<vtkDataSetWriter> writer;
writer = vtkSmartPointer<vtkDataSetWriter>::New();
SetVTKInput(writer, pointset);
writer->SetFileName(fname);
if (ascii) writer->SetFileTypeToASCII();
else writer->SetFileTypeToBinary();
success = writer->Write();
}
return (success == 1);
}
// -----------------------------------------------------------------------------
vtkSmartPointer<vtkPolyData> ReadPolyData(const char *fname, int *ftype, bool exit_on_failure)
{
vtkSmartPointer<vtkPolyData> polydata;
const string ext = Extension(fname);
if (ext == ".vtp") {
vtkSmartPointer<vtkXMLPolyDataReader> reader;
reader = vtkSmartPointer<vtkXMLPolyDataReader>::New();
reader->SetFileName(fname);
reader->Update();
polydata = reader->GetOutput();
} else if (ext == ".stl") {
vtkSmartPointer<vtkSTLReader> reader;
reader = vtkSmartPointer<vtkSTLReader>::New();
reader->SetFileName(fname);
reader->Update();
polydata = reader->GetOutput();
} else if (ext == ".ply") {
vtkSmartPointer<vtkPLYReader> reader;
reader = vtkSmartPointer<vtkPLYReader>::New();
reader->SetFileName(fname);
reader->Update();
polydata = reader->GetOutput();
} else if (ext == ".obj") {
vtkSmartPointer<vtkOBJReader> reader;
reader = vtkSmartPointer<vtkOBJReader>::New();
reader->SetFileName(fname);
reader->Update();
polydata = reader->GetOutput();
} else if (ext == ".dfs") {
polydata = ReadDFS(fname);
} else if (ext == ".off") {
polydata = ReadOFF(fname);
} else if (ext == ".gii") {
#if MIRTK_IO_WITH_GIFTI
polydata = ReadGIFTI(fname, nullptr, exit_on_failure);
#else
if (exit_on_failure) {
cerr << "Error: File '" << fname << "' cannot be read because MIRTK I/O library was built without GIFTI support!" << endl;
exit(1);
}
#endif
} else {
vtkSmartPointer<vtkPolyDataReader> reader;
reader = vtkSmartPointer<vtkPolyDataReader>::New();
reader->SetFileName(fname);
reader->Update();
if (ftype) *ftype = reader->GetFileType();
polydata = reader->GetOutput();
}
if (exit_on_failure && polydata->GetNumberOfPoints() == 0) {
cerr << "Error: File '" << fname << "' either contains no points or could not be read!" << endl;
exit(1);
}
return polydata;
}
// -----------------------------------------------------------------------------
bool WritePolyData(const char *fname, vtkPolyData *polydata, bool compress, bool ascii)
{
const string ext = Extension(fname);
int success = 0;
if (ext == ".vtp") {
vtkSmartPointer<vtkXMLPolyDataWriter> writer;
writer = vtkSmartPointer<vtkXMLPolyDataWriter>::New();
SetVTKInput(writer, polydata);
writer->SetFileName(fname);
if (compress) writer->SetCompressorTypeToZLib();
else writer->SetCompressorTypeToNone();
success = writer->Write();
} else if (ext == ".stl") {
vtkSmartPointer<vtkSTLWriter> writer;
writer = vtkSmartPointer<vtkSTLWriter>::New();
SetVTKInput(writer, polydata);
if (ascii) writer->SetFileTypeToASCII();
else writer->SetFileTypeToBinary();
writer->SetFileName(fname);
success = writer->Write();
} else if (ext == ".ply") {
vtkSmartPointer<vtkPLYWriter> writer;
writer = vtkSmartPointer<vtkPLYWriter>::New();
SetVTKInput(writer, polydata);
if (ascii) writer->SetFileTypeToASCII();
else writer->SetFileTypeToBinary();
writer->SetFileName(fname);
success = writer->Write();
} else if (ext == ".node") {
success = WriteTetGenNode(fname, polydata);
} else if (ext == ".poly") {
success = WriteTetGenPoly(fname, polydata);
} else if (ext == ".smesh") {
success = WriteTetGenSMesh(fname, polydata);
} else if (ext == ".dfs") {
success = WriteDFS(fname, polydata);
} else if (ext == ".off") {
success = WriteOFF(fname, polydata);
} else if (ext == ".gii") {
#if MIRTK_IO_WITH_GIFTI
success = WriteGIFTI(fname, polydata, compress, ascii);
#else
cerr << "Error: Cannot write surface to GIFTI file because MIRTK I/O library was built without GIFTI support!" << endl;
#endif
} else {
vtkSmartPointer<vtkPolyDataWriter> writer;
writer = vtkSmartPointer<vtkPolyDataWriter>::New();
SetVTKInput(writer, polydata);
writer->SetFileName(fname);
if (ascii) writer->SetFileTypeToASCII();
else writer->SetFileTypeToBinary();
success = writer->Write();
}
return (success == 1);
}
// =============================================================================
// BrainSuite I/O functions
// =============================================================================
// -----------------------------------------------------------------------------
vtkSmartPointer<vtkPolyData> ReadDFS(const char *fname)
{
vtkSmartPointer<vtkPolyData> polydata = vtkSmartPointer<vtkPolyData>::New();
// Read .dfs file
SILT::DFSurface surface;
if (!surface.readDFS(fname)) return polydata;
const vtkIdType npoints = static_cast<vtkIdType>(surface.vertices .size());
const vtkIdType ncells = static_cast<vtkIdType>(surface.triangles.size());
// Copy vertex coordinates
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
points->SetNumberOfPoints(npoints);
double p[3];
for (vtkIdType i = 0; i < npoints; ++i) {
p[0] = static_cast<double>(surface.vertices[i].x);
p[1] = static_cast<double>(surface.vertices[i].y);
p[2] = static_cast<double>(surface.vertices[i].z);
points->SetPoint(i, p);
}
polydata->SetPoints(points);
// Copy triangle face list
vtkIdType pts[3];
vtkSmartPointer<vtkCellArray> cells = vtkSmartPointer<vtkCellArray>::New();
cells->Allocate(cells->EstimateSize(ncells, 3));
for (vtkIdType i = 0; i < ncells; ++i) {
pts[0] = static_cast<vtkIdType>(surface.triangles[i].a);
pts[1] = static_cast<vtkIdType>(surface.triangles[i].b);
pts[2] = static_cast<vtkIdType>(surface.triangles[i].c);
cells->InsertNextCell(3, pts);
}
polydata->SetPolys(cells);
// Copy vertex normals
if (!surface.vertexNormals.empty()) {
double n[3];
vtkSmartPointer<vtkFloatArray> normals = vtkSmartPointer<vtkFloatArray>::New();
normals->SetName("Normals");
normals->SetNumberOfComponents(3);
normals->SetNumberOfTuples(npoints);
for (vtkIdType i = 0; i < npoints; ++i) {
n[0] = static_cast<double>(surface.vertexNormals[i].x);
n[1] = static_cast<double>(surface.vertexNormals[i].y);
n[2] = static_cast<double>(surface.vertexNormals[i].z);
normals->SetTuple(i, n);
}
polydata->GetPointData()->SetNormals(normals);
}
// Copy vertex colors
if (!surface.vertexColors.empty()) {
double rgb[3];
vtkSmartPointer<vtkFloatArray> colors = vtkSmartPointer<vtkFloatArray>::New();
colors->SetName("Colors");
colors->SetNumberOfComponents(3);
colors->SetNumberOfTuples(npoints);
for (vtkIdType i = 0; i < npoints; ++i) {
rgb[0] = static_cast<double>(surface.vertexColors[i].x);
rgb[1] = static_cast<double>(surface.vertexColors[i].y);
rgb[2] = static_cast<double>(surface.vertexColors[i].z);
colors->SetTuple(i, rgb);
}
polydata->GetPointData()->AddArray(colors);
}
// Copy vertex UV coordinates
if (!surface.vertexUV.empty()) {
double uv[3] = {.0};
vtkSmartPointer<vtkFloatArray> coords = vtkSmartPointer<vtkFloatArray>::New();
coords->SetName("UV");
coords->SetNumberOfComponents(3);
coords->SetNumberOfTuples(npoints);
for (vtkIdType i = 0; i < npoints; ++i) {
uv[0] = static_cast<double>(surface.vertexUV[i].u);
uv[1] = static_cast<double>(surface.vertexUV[i].v);
coords->SetTuple(i, uv);
}
polydata->GetPointData()->SetTCoords(coords);
}
// Copy vertex labels
if (!surface.vertexLabels.empty()) {
vtkSmartPointer<vtkUnsignedShortArray> labels = vtkSmartPointer<vtkUnsignedShortArray>::New();
labels->SetName("Labels");
labels->SetNumberOfComponents(1);
labels->SetNumberOfTuples(npoints);
for (vtkIdType i = 0; i < npoints; ++i) {
labels->SetValue(i, surface.vertexLabels[i]);
}
polydata->GetPointData()->AddArray(labels);
}
// Copy vertex attributes
if (!surface.vertexAttributes.empty()) {
vtkSmartPointer<vtkFloatArray> scalars = vtkSmartPointer<vtkFloatArray>::New();
scalars->SetName("Attributes");
scalars->SetNumberOfComponents(1);
scalars->SetNumberOfTuples(npoints);
for (vtkIdType i = 0; i < npoints; ++i) {
scalars->SetValue(i, surface.vertexAttributes[i]);
}
polydata->GetPointData()->SetScalars(scalars);
}
return polydata;
}
// -----------------------------------------------------------------------------
bool WriteDFS(const char *fname, vtkPolyData *polydata)
{
SILT::DFSurface surface;
// Copy vertex coordinates
double p[3];
surface.vertices.resize(polydata->GetNumberOfPoints());
for (vtkIdType i = 0; i < polydata->GetNumberOfPoints(); ++i) {
polydata->GetPoint(i, p);
surface.vertices[i].x = static_cast<float>(p[0]);
surface.vertices[i].y = static_cast<float>(p[1]);
surface.vertices[i].z = static_cast<float>(p[2]);
}
// Copy triangular faces
vtkIdType npts, *pts;
surface.triangles.resize(polydata->GetNumberOfCells());
for (vtkIdType i = 0; i < polydata->GetNumberOfCells(); ++i) {
polydata->GetCellPoints(i, npts, pts);
if (npts != 3) return false;
surface.triangles[i].a = static_cast<int>(pts[0]);
surface.triangles[i].b = static_cast<int>(pts[1]);
surface.triangles[i].c = static_cast<int>(pts[2]);
}
// Copy vertex normals
vtkDataArray *normals = polydata->GetPointData()->GetNormals();
if (!normals) normals = polydata->GetPointData()->GetArray("Normals");
if (normals) {
double n[3];
surface.vertexNormals.resize(polydata->GetNumberOfPoints());
for (vtkIdType i = 0; i < polydata->GetNumberOfPoints(); ++i) {
normals->GetTuple(i, n);
surface.vertexNormals[i].x = static_cast<float>(n[0]);
surface.vertexNormals[i].y = static_cast<float>(n[1]);
surface.vertexNormals[i].z = static_cast<float>(n[2]);
}
}
// Copy vertex colors
vtkDataArray *colors = polydata->GetPointData()->GetArray("Colors");
if (colors) {
double rgb[3];
surface.vertexColors.resize(polydata->GetNumberOfPoints());
for (vtkIdType i = 0; i < polydata->GetNumberOfPoints(); ++i) {
colors->GetTuple(i, rgb);
surface.vertexColors[i].x = static_cast<float>(rgb[0]);
surface.vertexColors[i].y = static_cast<float>(rgb[1]);
surface.vertexColors[i].z = static_cast<float>(rgb[2]);
}
}
// Copy vertex UV coordinates
vtkDataArray *coords = polydata->GetPointData()->GetTCoords();
if (!coords) coords = polydata->GetPointData()->GetArray("UV");
if (coords && (coords->GetNumberOfComponents() == 2 || coords->GetNumberOfComponents() == 3)) {
surface.vertexUV.resize(polydata->GetNumberOfPoints());
for (vtkIdType i = 0; i < polydata->GetNumberOfPoints(); ++i) {
surface.vertexUV[i].u = static_cast<float>(coords->GetComponent(i, 0));
surface.vertexUV[i].v = static_cast<float>(coords->GetComponent(i, 1));
}
}
// Copy vertex labels
vtkDataArray *labels = polydata->GetPointData()->GetArray("Labels");
if (labels && labels->GetNumberOfComponents() == 1) {
surface.vertexLabels.resize(polydata->GetNumberOfPoints());
for (vtkIdType i = 0; i < polydata->GetNumberOfPoints(); ++i) {
surface.vertexLabels[i] = static_cast<unsigned short>(labels->GetComponent(i, 0));
}
}
// Copy vertex attributes
vtkDataArray *scalars = polydata->GetPointData()->GetScalars();
if (!scalars) scalars = polydata->GetPointData()->GetArray("Attributes");
if (scalars && scalars->GetNumberOfComponents() == 1) {
surface.vertexAttributes.resize(polydata->GetNumberOfPoints());
for (vtkIdType i = 0; i < polydata->GetNumberOfPoints(); ++i) {
surface.vertexAttributes[i] = static_cast<float>(scalars->GetComponent(i, 0));
}
}
// Write .dfs file
return surface.writeDFS(fname);
}
// =============================================================================
// Object File Format I/O functions
// =============================================================================
// -----------------------------------------------------------------------------
vtkSmartPointer<vtkPolyData> ReadOFF(const char *fname)
{
vtkSmartPointer<vtkPolyData> polydata = vtkSmartPointer<vtkPolyData>::New();
ifstream ifs(fname);
if (!ifs) return polydata;
string keyword;
ifs >> keyword;
if (keyword != "OFF" && keyword != "off") return polydata;
int numVertices = -1, numFaces = -1, numEdges = -1;
ifs >> numVertices >> numFaces >> numEdges;
if (ifs.fail()) return polydata;
if (numVertices < 0) numVertices = 0;
if (numFaces < 0) numFaces = 0;
vtkSmartPointer<vtkPoints> points;
points = vtkSmartPointer<vtkPoints>::New();
points->SetNumberOfPoints(numVertices);
double p[3];
for (int i = 0; i < numVertices; ++i) {
ifs >> p[0] >> p[1] >> p[2];
if (ifs.fail()) break;
points->SetPoint(i, p);
}
if (ifs.fail()) return polydata;
vtkSmartPointer<vtkCellArray> verts, lines, polys;
vtkSmartPointer<vtkIdList> cell = vtkSmartPointer<vtkIdList>::New();
verts = vtkSmartPointer<vtkCellArray>::New();
lines = vtkSmartPointer<vtkCellArray>::New();
polys = vtkSmartPointer<vtkCellArray>::New();
for (int i = 0, ptId, n; i < numFaces; ++i) {
ifs >> n;
if (ifs.fail()) break;
if (n > 0) {
cell->Reset();
for (int j = 0; j < n; ++j) {
ifs >> ptId;
cell->InsertNextId(ptId);
}
if (n == 1) verts->InsertNextCell(cell);
else if (n == 2) lines->InsertNextCell(cell);
else polys->InsertNextCell(cell);
if (!ifs.good()) break;
}
}
if (ifs.fail()) return polydata;
verts->Squeeze();
lines->Squeeze();
polys->Squeeze();
polydata->SetPoints(points);
if (verts->GetNumberOfCells() > 0) polydata->SetVerts(verts);
if (lines->GetNumberOfCells() > 0) polydata->SetLines(lines);
if (polys->GetNumberOfCells() > 0) polydata->SetPolys(polys);
return polydata;
}
// -----------------------------------------------------------------------------
bool WriteOFF(const char *fname, vtkPolyData *polydata)
{
ofstream ofs(fname);
ofs.precision(12);
ofs << "OFF\n";
ofs << polydata->GetNumberOfPoints() << " ";
ofs << polydata->GetNumberOfCells() << " 0\n";
double p[3];
for (vtkIdType ptId = 0; ptId < polydata->GetNumberOfPoints(); ++ptId) {
polydata->GetPoint(ptId, p);
ofs << p[0] << " " << p[1] << " " << p[2] << "\n";
}
vtkIdType numPts, *ptIds;
polydata->BuildCells();
for (vtkIdType cellId = 0; cellId < polydata->GetNumberOfCells(); ++cellId) {
polydata->GetCellPoints(cellId, numPts, ptIds);
ofs << numPts;
for (vtkIdType i = 0; i < numPts; ++i) {
ofs << " " << ptIds[i];
}
ofs << "\n";
}
return !ofs.fail();
}
// =============================================================================
// TetGen I/O functions
// =============================================================================
// -----------------------------------------------------------------------------
/// Write point set to TetGen .node output stream
///
/// @param[in, out] os Output stream.
/// @param[in] pointset Point set.
///
/// @return Whether point set was written successfully to the given output stream.
bool WriteTetGenNode(ostream &os, vtkPointSet *pointset)
{
vtkPointData *pd = pointset->GetPointData();
vtkDataArray *ar;
int nattributes = 0;
for (int i = 0; i < pd->GetNumberOfArrays(); ++i) {
nattributes += pd->GetArray(i)->GetNumberOfComponents();
}
os << pointset->GetNumberOfPoints() << " 3 " << nattributes << " 0\n";
double p[3];
streamsize precision = os.precision();
for (vtkIdType ptId = 0; ptId < pointset->GetNumberOfPoints(); ++ptId) {
os << (ptId + 1) << " ";
os.precision(8); // default TetGen tolerance is 1e-8
pointset->GetPoint(ptId, p);
os << " " << p[0] << " " << p[1] << " " << p[2];
os.precision(5);
for (int i = 0; i < pd->GetNumberOfArrays(); ++i) {
ar = pd->GetArray(i);
for (int j = 0; j < ar->GetNumberOfComponents(); ++j) {
os << " " << ar->GetComponent(ptId, j);
}
}
os << "\n";
}
os.precision(precision);
return !os.fail();
}
// -----------------------------------------------------------------------------
bool WriteTetGenNode(const char *fname, vtkPointSet *pointset)
{
ofstream os(fname);
if (!os.is_open()) return false;
return WriteTetGenNode(os, pointset);
}
// -----------------------------------------------------------------------------
bool WriteTetGenPoly(const char *fname, vtkPolyData *polydata, const PointSet *holes)
{
ofstream os(fname);
if (!os.is_open()) return false;
os << "# part 1: nodes\n";
WriteTetGenNode(os, polydata);
vtkIdType npts, *pts;
vtkCellArray *verts = polydata->GetVerts();
vtkCellArray *lines = polydata->GetLines();
vtkCellArray *polys = polydata->GetPolys();
vtkCellArray *strips = polydata->GetStrips();
int nfacets = 0;
if (verts ->GetNumberOfCells() > 0) nfacets += 1;
if (lines ->GetNumberOfCells() > 0) nfacets += 1;
if (polys ->GetNumberOfCells() > 0) nfacets += 1;
if (strips->GetNumberOfCells() > 0) nfacets += 1;
os << "\n# part 2: facets\n";
os << nfacets << " 0\n";
if (verts->GetNumberOfCells() > 0) {
os << "# verts\n";
os << verts->GetNumberOfCells() << "\n";
verts->InitTraversal();
while (verts->GetNextCell(npts, pts)) {
os << npts << " ";
for (vtkIdType i = 0; i < npts; ++i) os << " " << (pts[i] + 1);
os << "\n";
}
}
if (lines->GetNumberOfCells() > 0) {
os << "# lines\n";
os << lines->GetNumberOfCells() << "\n";
lines->InitTraversal();
while (lines->GetNextCell(npts, pts)) {
os << npts << " ";
for (vtkIdType i = 0; i < npts; ++i) os << " " << (pts[i] + 1);
os << "\n";
}
}
if (polys->GetNumberOfCells() > 0) {
os << "# polys\n";
os << polys->GetNumberOfCells() << "\n";
polys->InitTraversal();
while (polys->GetNextCell(npts, pts)) {
os << npts << " ";
for (vtkIdType i = 0; i < npts; ++i) os << " " << (pts[i] + 1);
os << "\n";
}
}
if (strips->GetNumberOfCells() > 0) {
os << "# strips\n";
os << strips->GetNumberOfCells() << "\n";
strips->InitTraversal();
while (strips->GetNextCell(npts, pts)) {
os << npts << " ";
for (vtkIdType i = 0; i < npts; ++i) os << " " << (pts[i] + 1);
os << "\n";
}
}
os << "\n# part 3: hole list\n";
if (holes) {
os << holes->Size() << "\n";
for (int i = 0; i < holes->Size(); ++i) {
const Point &p = holes->GetPoint(i);
os << (i+1) << " " << p._x << " " << p._y << " " << p._z << "\n";
}
} else {
os << "0\n";
}
os << "\n# part 4: region list\n";
os << "0\n";
return !os.fail();
}
// -----------------------------------------------------------------------------
bool WriteTetGenSMesh(const char *fname, vtkPolyData *polydata, const PointSet *holes)
{
ofstream os(fname);
if (!os.is_open()) return false;
os << "# part 1: nodes\n";
WriteTetGenNode(os, polydata);
vtkIdType npts, *pts;
vtkCellArray *verts = polydata->GetVerts();
vtkCellArray *lines = polydata->GetLines();
vtkCellArray *polys = polydata->GetPolys();
vtkCellArray *strips = polydata->GetStrips();
int nfacets = 0;
if (verts ->GetNumberOfCells() > 0) nfacets += verts ->GetNumberOfCells();
if (lines ->GetNumberOfCells() > 0) nfacets += lines ->GetNumberOfCells();
if (polys ->GetNumberOfCells() > 0) nfacets += polys ->GetNumberOfCells();
if (strips->GetNumberOfCells() > 0) nfacets += strips->GetNumberOfCells();
os << "\n# part 2: facets\n";
os << nfacets << " 0\n";
if (verts->GetNumberOfCells() > 0) {
verts->InitTraversal();
while (verts->GetNextCell(npts, pts)) {
os << npts << " ";
for (vtkIdType i = 0; i < npts; ++i) os << " " << (pts[i] + 1);
os << "\n";
}
}
if (lines->GetNumberOfCells() > 0) {
lines->InitTraversal();
while (lines->GetNextCell(npts, pts)) {
os << npts << " ";
for (vtkIdType i = 0; i < npts; ++i) os << " " << (pts[i] + 1);
os << "\n";
}
}
if (polys->GetNumberOfCells() > 0) {
polys->InitTraversal();
while (polys->GetNextCell(npts, pts)) {
os << npts << " ";
for (vtkIdType i = 0; i < npts; ++i) os << " " << (pts[i] + 1);
os << "\n";
}
}
if (strips->GetNumberOfCells() > 0) {
strips->InitTraversal();
while (strips->GetNextCell(npts, pts)) {
os << npts;
for (vtkIdType i = 0; i < npts; ++i) os << " " << (pts[i] + 1);
os << "\n";
}
}
os << "\n# part 3: hole list\n";
if (holes) {
os << holes->Size() << "\n";
for (int i = 0; i < holes->Size(); ++i) {
const Point &p = holes->GetPoint(i);
os << (i+1) << " " << p._x << " " << p._y << " " << p._z << "\n";
}
} else {
os << "0\n";
}
os << "\n# part 4: region list\n";
os << "0\n";
return !os.fail();
}
// =============================================================================
// GIFTI I/O functions
// =============================================================================
#if MIRTK_IO_WITH_GIFTI
// -----------------------------------------------------------------------------
/// Get VTK data type enumeration value corresponding to given GIFTI datatype
static int GIFTIDataTypeToVTK(int datatype)
{
switch (datatype) {
case NIFTI_TYPE_INT8: return VTK_CHAR;
case NIFTI_TYPE_INT16: return VTK_SHORT;
case NIFTI_TYPE_INT32: return VTK_INT;
case NIFTI_TYPE_INT64: return VTK_LONG_LONG;
case NIFTI_TYPE_UINT8: return VTK_UNSIGNED_CHAR;
case NIFTI_TYPE_UINT16: return VTK_UNSIGNED_SHORT;
case NIFTI_TYPE_UINT32: return VTK_UNSIGNED_INT;
case NIFTI_TYPE_UINT64: return VTK_UNSIGNED_LONG_LONG;
case NIFTI_TYPE_FLOAT32: return VTK_FLOAT;
case NIFTI_TYPE_FLOAT64: return VTK_DOUBLE;
default: return VTK_VOID;
}
}
// -----------------------------------------------------------------------------
/// Copy GIFTI data array of data type matching the template argument to vtkDataArray
template <class T>
void CopyGIFTIDataArrayWithDataType(vtkDataArray *dst, const giiDataArray *src,
vtkIdTypeArray *indices = nullptr)
{
const int m = src->dims[0];
const int n = static_cast<int>(src->nvals / static_cast<long long>(m));
const T *v = reinterpret_cast<const T *>(src->data);
if (indices) {
vtkIdType index;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j) {
dst->SetComponent(i, j, .0);
}
if (src->ind_ord == GIFTI_IND_ORD_COL_MAJOR) {
for (int j = 0; j < n; ++j)
for (int i = 0; i < m; ++i, ++v) {
index = indices->GetComponent(i, 0);
dst->SetComponent(index, j, static_cast<double>(*v));
}
} else {
for (int i = 0; i < m; ++i) {
index = indices->GetComponent(i, 0);
for (int j = 0; j < n; ++j) {
dst->SetComponent(index, j, static_cast<double>(*v));
}
}
}
} else {
if (src->ind_ord == GIFTI_IND_ORD_COL_MAJOR) {
for (int j = 0; j < n; ++j)
for (int i = 0; i < m; ++i, ++v) {
dst->SetComponent(i, j, static_cast<double>(*v));
}
} else {
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j) {
dst->SetComponent(i, j, static_cast<double>(*v));
}
}
}
}
// -----------------------------------------------------------------------------
/// Copy GIFTI data array to vtkDataArray
static void CopyGIFTIDataArray(vtkDataArray *dst, const giiDataArray *src,
vtkIdTypeArray *indices = nullptr)
{
switch (src->datatype) {
case NIFTI_TYPE_INT8: CopyGIFTIDataArrayWithDataType<int8_t >(dst, src, indices); break;
case NIFTI_TYPE_INT16: CopyGIFTIDataArrayWithDataType<int16_t >(dst, src, indices); break;
case NIFTI_TYPE_INT32: CopyGIFTIDataArrayWithDataType<int32_t >(dst, src, indices); break;
case NIFTI_TYPE_INT64: CopyGIFTIDataArrayWithDataType<int64_t >(dst, src, indices); break;
case NIFTI_TYPE_UINT8: CopyGIFTIDataArrayWithDataType<uint8_t >(dst, src, indices); break;
case NIFTI_TYPE_UINT16: CopyGIFTIDataArrayWithDataType<uint16_t>(dst, src, indices); break;
case NIFTI_TYPE_UINT32: CopyGIFTIDataArrayWithDataType<uint32_t>(dst, src, indices); break;
case NIFTI_TYPE_UINT64: CopyGIFTIDataArrayWithDataType<uint64_t>(dst, src, indices); break;
case NIFTI_TYPE_FLOAT32: CopyGIFTIDataArrayWithDataType<float >(dst, src, indices); break;
case NIFTI_TYPE_FLOAT64: CopyGIFTIDataArrayWithDataType<double >(dst, src, indices); break;
default:
cerr << "GIFTI data array has unknown/invalid data type: " << src->datatype << endl;
exit(1);
}
}
// -----------------------------------------------------------------------------
// vtkInformation keys of standard GIFTI meta data entries
vtkInformationKeyMacro(GiftiMetaData, DATE, String);
vtkInformationKeyMacro(GiftiMetaData, USER_NAME, String);
vtkInformationKeyMacro(GiftiMetaData, SUBJECT_ID, String);
vtkInformationKeyMacro(GiftiMetaData, SURFACE_ID, String);
vtkInformationKeyMacro(GiftiMetaData, UNIQUE_ID, String);
vtkInformationKeyMacro(GiftiMetaData, NAME, String);
vtkInformationKeyMacro(GiftiMetaData, DESCRIPTION, String);
vtkInformationKeyMacro(GiftiMetaData, TIME_STEP, Double);
vtkInformationKeyMacro(GiftiMetaData, ANATOMICAL_STRUCTURE_PRIMARY, String);
vtkInformationKeyMacro(GiftiMetaData, ANATOMICAL_STRUCTURE_SECONDARY, String);
vtkInformationKeyMacro(GiftiMetaData, GEOMETRIC_TYPE, String);
vtkInformationKeyMacro(GiftiMetaData, TOPOLOGICAL_TYPE, String);
vtkInformationKeyMacro(GiftiMetaData, INTENT_CODE, Integer);
vtkInformationKeyMacro(GiftiMetaData, INTENT_P1, Double);
vtkInformationKeyMacro(GiftiMetaData, INTENT_P2, Double);
vtkInformationKeyMacro(GiftiMetaData, INTENT_P3, Double);
// -----------------------------------------------------------------------------
/// Copy standard GIFTI meta data to vtkInformation
static void CopyGIFTIMetaData(vtkInformation *info, const giiMetaData &meta)
{
for (int i = 0; i < meta.length; ++i) {
if (strcmp(meta.name[i], "Date") == 0) {
info->Set(GiftiMetaData::DATE(), meta.value[i]);
} else if (strcmp(meta.name[i], "UserName") == 0) {
info->Set(GiftiMetaData::USER_NAME(), meta.value[i]);
} else if (strcmp(meta.name[i], "SubjectID") == 0) {
info->Set(GiftiMetaData::SUBJECT_ID(), meta.value[i]);
} else if (strcmp(meta.name[i], "SurfaceID") == 0) {
info->Set(GiftiMetaData::SURFACE_ID(), meta.value[i]);
} else if (strcmp(meta.name[i], "UniqueID") == 0) {
info->Set(GiftiMetaData::UNIQUE_ID(), meta.value[i]);
} else if (strcmp(meta.name[i], "Name") == 0) {
info->Set(GiftiMetaData::NAME(), meta.value[i]);
} else if (strcmp(meta.name[i], "Description") == 0) {
info->Set(GiftiMetaData::DESCRIPTION(), meta.value[i]);
} else if (strcmp(meta.name[i], "TimeStep") == 0) {
double tr;
if (FromString(meta.value[i], tr)) {
info->Set(GiftiMetaData::TIME_STEP(), tr);
}
} else if (strcmp(meta.name[i], "AnatomicalStructurePrimary") == 0) {
info->Set(GiftiMetaData::ANATOMICAL_STRUCTURE_PRIMARY(), meta.value[i]);
} else if (strcmp(meta.name[i], "AnatomicalStructureSecondary") == 0) {
info->Set(GiftiMetaData::ANATOMICAL_STRUCTURE_SECONDARY(), meta.value[i]);
} else if (strcmp(meta.name[i], "GeometricType") == 0) {
info->Set(GiftiMetaData::GEOMETRIC_TYPE(), meta.value[i]);
} else if (strcmp(meta.name[i], "TopologicalType") == 0) {
info->Set(GiftiMetaData::TOPOLOGICAL_TYPE(), meta.value[i]);
} else if (strcmp(meta.name[i], "Intent") == 0 ||
strcmp(meta.name[i], "Intent_code") == 0 ||
strcmp(meta.name[i], "IntentCode") == 0) {
int intent_code;
if (FromString(meta.value[i], intent_code)) {
info->Set(GiftiMetaData::INTENT_CODE(), intent_code);
}
} else if (strcmp(meta.name[i], "IntentP1") == 0 ||
strcmp(meta.name[i], "Intent_p1") == 0 ||
strcmp(meta.name[i], "intent_p1") == 0) {
double intent_p1;
if (FromString(meta.value[i], intent_p1)) {
info->Set(GiftiMetaData::INTENT_P1(), intent_p1);
}
} else if (strcmp(meta.name[i], "IntentP2") == 0 ||
strcmp(meta.name[i], "Intent_p2") == 0 ||
strcmp(meta.name[i], "intent_p2") == 0) {
double intent_p2;
if (FromString(meta.value[i], intent_p2)) {
info->Set(GiftiMetaData::INTENT_P2(), intent_p2);
}
} else if (strcmp(meta.name[i], "IntentP3") == 0 ||
strcmp(meta.name[i], "Intent_p3") == 0 ||
strcmp(meta.name[i], "intent_p3") == 0) {
double intent_p3;
if (FromString(meta.value[i], intent_p3)) {
info->Set(GiftiMetaData::INTENT_P3(), intent_p3);
}
}
}
}
// -----------------------------------------------------------------------------
/// Copy GIFTI point set to vtkPoints
static vtkSmartPointer<vtkPoints>
GIFTICoordinatesToVTK(const gifti_image *gim, vtkInformation *info = nullptr, bool errmsg = false)
{
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
for (int i = 0; i < gim->numDA; ++i) {
giiDataArray *array = gim->darray[i];
if (array->intent == NIFTI_INTENT_POINTSET) {
if (array->datatype != NIFTI_TYPE_FLOAT32) {
if (errmsg) {
cerr << "Error: GIFTI coordinates array must have datatype NIFTI_TYPE_FLOAT32!" << endl;
}
break;
}
if (array->num_dim != 2) {
if (errmsg) {
cerr << "Error: GIFTI coordinates array must have 2 dimensions!" << endl;
}
break;
}
if (array->dims[1] != 3) {
if (errmsg) {
cerr << "Error: Second dimension of GIFTI coordinates array must have size 3!" << endl;
}
break;
}
const int n = array->dims[0];
points->SetNumberOfPoints(n);
const float *x = reinterpret_cast<float *>(array->data);
if (array->ind_ord == GIFTI_IND_ORD_COL_MAJOR) {
const float *y = x + n, *z = y + n;
for (int j = 0; j < n; ++j, ++x, ++y, ++z) {
points->SetPoint(j, static_cast<double>(*x), static_cast<double>(*y), static_cast<double>(*z));
}
} else {
const float *y = x + 1, *z = x + 2;
for (int j = 0; j < n; ++j, x += 3, y += 3, z += 3) {
points->SetPoint(j, static_cast<double>(*x), static_cast<double>(*y), static_cast<double>(*z));
}
}
if (info) CopyGIFTIMetaData(info, array->meta);
break;
}
}
return points;
}
// -----------------------------------------------------------------------------
/// Copy GIFTI topology information to vtkCellArray
static vtkSmartPointer<vtkCellArray>
GIFTITopologyToVTK(const gifti_image *gim, vtkInformation *info = nullptr, bool errmsg = false)
{
vtkSmartPointer<vtkCellArray> triangles;
for (int i = 0; i < gim->numDA; ++i) {
giiDataArray *array = gim->darray[i];
if (array->intent == NIFTI_INTENT_TRIANGLE) {
if (array->datatype != NIFTI_TYPE_INT32) {
if (errmsg) {
cerr << "Error: GIFTI topology array must have datatype NIFTI_TYPE_INT32!" << endl;
}
break;
}
if (array->num_dim != 2) {
if (errmsg) {
cerr << "Error: GIFTI topology array must have 2 dimensions!" << endl;
}
break;
}
if (array->dims[1] != 3) {
if (errmsg) {
cerr << "Error: Second dimension of GIFTI topology array must have size 3!" << endl;
}
break;
}
vtkIdType pts[3];
const int n = array->dims[0];
triangles = vtkSmartPointer<vtkCellArray>::New();
triangles->Allocate(3 * n);
const int *a = reinterpret_cast<int *>(array->data);
if (array->ind_ord == GIFTI_IND_ORD_COL_MAJOR) {
const int *b = a + n, *c = b + n;
for (int j = 0; j < n; ++j, ++a, ++b, ++c) {
pts[0] = static_cast<vtkIdType>(*a);
pts[1] = static_cast<vtkIdType>(*b);
pts[2] = static_cast<vtkIdType>(*c);
triangles->InsertNextCell(3, pts);
}
} else {
const int *b = a + 1, *c = a + 2;
for (int j = 0; j < n; ++j, a += 3, b += 3, c += 3) {
pts[0] = static_cast<vtkIdType>(*a);
pts[1] = static_cast<vtkIdType>(*b);
pts[2] = static_cast<vtkIdType>(*c);
triangles->InsertNextCell(3, pts);
}
}
if (info) CopyGIFTIMetaData(info, array->meta);
break;
}
}
return triangles;
}
// -----------------------------------------------------------------------------
/// Convert GIFTI node indices array to vtkDataArray
static vtkSmartPointer<vtkIdTypeArray>
GIFTINodeIndicesToVTK(const gifti_image *gim, bool errmsg = false)
{
vtkSmartPointer<vtkIdTypeArray> indices;
for (int i = 0; i < gim->numDA; ++i) {
giiDataArray *array = gim->darray[i];
if (array->intent == NIFTI_INTENT_NODE_INDEX) {
if (array->num_dim != 1) {
if (errmsg) {
cerr << "Error: GIFTI node indices array must have 1 dimension!" << endl;
}
break;
}
if (array->dims[0] <= 0) {
if (errmsg) {
cerr << "Error: GIFTI node indices array must contain at least one index!" << endl;
}
break;
}
indices = vtkSmartPointer<vtkIdTypeArray>::New();
indices->SetNumberOfComponents(1);
indices->SetNumberOfTuples(array->dims[0]);
CopyGIFTIDataArray(indices, array);
}
}
return indices;
}
// -----------------------------------------------------------------------------
/// Convert GIFTI data arrays to vtkDataArray instances of a vtkPointData
static vtkSmartPointer<vtkPointData>
GIFTIPointDataToVTK(const gifti_image *gim, vtkIdType npoints = 0, vtkIdTypeArray *indices = nullptr, bool errmsg = false)
{
vtkIdType nindices = 0;
if (indices) {
nindices = indices->GetNumberOfTuples();
if (npoints == 0) {
cerr << "GIFTIPointDataToVTK: Number of points cannot be zero when reading sparse point data arrays!" << endl;
exit(1);
}
if (nindices > npoints) {
cerr << "GIFTIPointDataToVTK: Number of points cannot be less then number of node indices!" << endl;
exit(1);
}
}
bool ok = true;
vtkSmartPointer<vtkPointData> pd = vtkSmartPointer<vtkPointData>::New();
for (int i = 0; i < gim->numDA; ++i) {
giiDataArray *array = gim->darray[i];
if (array->intent != NIFTI_INTENT_POINTSET &&
array->intent != NIFTI_INTENT_TRIANGLE &&
array->intent != NIFTI_INTENT_NODE_INDEX &&
array->num_dim > 0 && array->dims[0] > 0 && array->nvals > 0) {
const int ncomp = static_cast<int>(array->nvals / static_cast<long long>(array->dims[0]));
vtkSmartPointer<vtkDataArray> data;
data = NewVTKDataArray(GIFTIDataTypeToVTK(array->datatype));
data->SetNumberOfComponents(ncomp);
if (npoints) {
if (( indices && static_cast<vtkIdType>(array->dims[0]) != nindices) ||
(!indices && static_cast<vtkIdType>(array->dims[0]) != npoints)) {
if (errmsg) {
cerr << "Error: GIFTI array size does not match point set or node indices array size!" << endl;
}
ok = false;
break;
}
data->SetNumberOfTuples(npoints);
} else {
data->SetNumberOfTuples(array->dims[0]);
}
CopyGIFTIDataArray(data, array, indices);
vtkInformation * const info = data->GetInformation();
CopyGIFTIMetaData(info, array->meta);
if (info->Has(GiftiMetaData::NAME())) {
data->SetName(info->Get(GiftiMetaData::NAME()));
} else {
data->SetName(ToString(array->intent).c_str());
}
const int idx = pd->AddArray(data);
if (array->intent == NIFTI_INTENT_SHAPE && !pd->GetScalars()) {
pd->SetActiveAttribute(idx, vtkDataSetAttributes::SCALARS);
}
if (array->intent == NIFTI_INTENT_VECTOR && ncomp == 3 && !pd->GetVectors()) {
pd->SetActiveAttribute(idx, vtkDataSetAttributes::VECTORS);
}
}
}
if (!ok) pd->Initialize();
return pd;
}
// -----------------------------------------------------------------------------
vtkSmartPointer<vtkPoints> ReadGIFTICoordinates(const char *fname, vtkInformation *info, bool errmsg)
{
gifti_image *gim = gifti_read_image(fname, 1);
if (gim == nullptr) {
if (errmsg) {
cerr << "Error: Could not read GIFTI file: " << fname << endl;
}
return vtkSmartPointer<vtkPoints>::New();
}
return GIFTICoordinatesToVTK(gim, info, errmsg);
}
// -----------------------------------------------------------------------------
vtkSmartPointer<vtkCellArray> ReadGIFTITopology(const char *fname, vtkInformation *info, bool errmsg)
{
gifti_image *gim = gifti_read_image(fname, 1);
if (gim == nullptr) {
if (errmsg) {
cerr << "Error: Could not read GIFTI file: " << fname << endl;
}
return nullptr;
}
return GIFTITopologyToVTK(gim, info, errmsg);
}
// -----------------------------------------------------------------------------
vtkSmartPointer<vtkPointData> ReadGIFTIPointData(const char *fname, bool errmsg)
{
gifti_image *gim = gifti_read_image(fname, 1);
if (gim == nullptr) {
if (errmsg) {
cerr << "Error: Could not read GIFTI file: " << fname << endl;
}
return nullptr;
}
return GIFTIPointDataToVTK(gim, 0, nullptr, errmsg);
}
// -----------------------------------------------------------------------------
vtkSmartPointer<vtkPolyData> ReadGIFTI(const char *fname, vtkPolyData *surface, bool errmsg)
{
vtkSmartPointer<vtkPolyData> polydata = vtkSmartPointer<vtkPolyData>::New();
// Read GIFTI
const int read_data = 1;
gifti_image *gim = gifti_read_image(fname, read_data);
if (gim == nullptr) return polydata;
// Convert geometry and topology arrays including their meta data
vtkSmartPointer<vtkInformation> geom_info = vtkSmartPointer<vtkInformation>::New();
vtkSmartPointer<vtkInformation> topo_info = vtkSmartPointer<vtkInformation>::New();
vtkSmartPointer<vtkPoints> points = GIFTICoordinatesToVTK(gim, geom_info, errmsg);
vtkSmartPointer<vtkCellArray> polys = GIFTITopologyToVTK (gim, topo_info, errmsg);
// Polygonal dataset requires a point set
if (points->GetNumberOfPoints() == 0) {
if (surface && surface->GetNumberOfPoints() > 0) {
points = surface->GetPoints();
} else {
if (errmsg) {
cerr << "Error: Cannot read GIFTI point data without input point set (e.g., from .coords.gii or .surf.gii file)!" << endl;
}
return polydata;
}
}
const vtkIdType npoints = points->GetNumberOfPoints();
// Check topology information
polys->InitTraversal();
vtkIdType npts, *pts;
while (polys->GetNextCell(npts, pts) != 0) {
if (npts != 3 || pts[0] >= npoints || pts[1] >= npoints || pts[2] >= npoints) {
if (errmsg) {
cerr << "Error: GIFTI topology array has invalid point index!" << endl;
}
return polydata;
}
}
// Get node indices array
vtkSmartPointer<vtkIdTypeArray> indices = GIFTINodeIndicesToVTK(gim, errmsg);
if (indices) {
for (vtkIdType i = 0; i < indices->GetNumberOfTuples(); ++i) {
const vtkIdType index = indices->GetComponent(i, 0);
if (index >= npoints) {
if (errmsg) {
cerr << "Error: Index of GIFTI node indices array element is out of range!" << endl;
cerr << " - Number of points = " << npoints << endl;
cerr << " - Node index = " << index << endl;
}
return polydata;
}
}
}
// Convert possibly sparse point data arrays
vtkSmartPointer<vtkPointData> pd = GIFTIPointDataToVTK(gim, npoints, indices, errmsg);
// Copy file meta data to vtkPolyData information
vtkInformation * const info = polydata->GetInformation();
CopyGIFTIMetaData(info, gim->meta);
// Free gifti_image instance
gifti_free_image(gim);
gim = nullptr;
// Check number of tuples of point data arrays
bool ok = true;
if (pd) {
for (int i = 0; i < pd->GetNumberOfArrays(); ++i) {
vtkDataArray *array = pd->GetArray(i);
if (array->GetNumberOfTuples() != npoints) {
cerr << "Error: GIFTI array '" << array->GetName()
<< "' at index " << i << " has mismatching size!" << endl;
cerr << " - Number of points = " << npoints << endl;
cerr << " - Number of tuples = " << array->GetNumberOfTuples() << endl;
ok = false;
}
}
}
// Finalize polygonal dataset
if (ok) {
// Set geometry, topology, and point data
polydata->SetPoints(points);
polydata->SetPolys(polys);
polydata->GetPointData()->ShallowCopy(pd);
// Copy meta data of geometry and topology data arrays to vtkPolyData information
if (geom_info->Has(GiftiMetaData::SUBJECT_ID())) {
info->CopyEntry(geom_info, GiftiMetaData::SUBJECT_ID());
}
if (geom_info->Has(GiftiMetaData::SURFACE_ID())) {
info->CopyEntry(geom_info, GiftiMetaData::SURFACE_ID());
}
if (geom_info->Has(GiftiMetaData::UNIQUE_ID())) {
info->CopyEntry(geom_info, GiftiMetaData::UNIQUE_ID());
}
if (geom_info->Has(GiftiMetaData::DESCRIPTION())) {
info->CopyEntry(geom_info, GiftiMetaData::DESCRIPTION());
}
if (geom_info->Has(GiftiMetaData::ANATOMICAL_STRUCTURE_PRIMARY())) {
info->CopyEntry(geom_info, GiftiMetaData::ANATOMICAL_STRUCTURE_PRIMARY());
}
if (geom_info->Has(GiftiMetaData::ANATOMICAL_STRUCTURE_SECONDARY())) {
info->CopyEntry(geom_info, GiftiMetaData::ANATOMICAL_STRUCTURE_SECONDARY());
}
if (geom_info->Has(GiftiMetaData::GEOMETRIC_TYPE())) {
info->CopyEntry(geom_info, GiftiMetaData::GEOMETRIC_TYPE());
}
if (topo_info->Has(GiftiMetaData::TOPOLOGICAL_TYPE())) {
info->CopyEntry(geom_info, GiftiMetaData::TOPOLOGICAL_TYPE());
}
} else {
info->Clear();
}
return polydata;
}
// -----------------------------------------------------------------------------
bool WriteGIFTI(const char *fname, vtkPolyData *polydata, bool compress, bool ascii)
{
return false;
}
#endif // MIRTK_IO_WITH_GIFTI
} // namespace mirtk
|
/*
* Copyright 2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrift/lib/cpp/concurrency/ThreadManager.h>
#include <assert.h>
#include <memory>
#include <queue>
#include <set>
#include <atomic>
#if defined(DEBUG)
#include <iostream>
#endif //defined(DEBUG)
#include <folly/Conv.h>
#include <folly/Logging.h>
#include <folly/MPMCQueue.h>
#include <folly/Memory.h>
#include <folly/io/async/Request.h>
#include <thrift/lib/cpp/concurrency/Exception.h>
#include <thrift/lib/cpp/concurrency/Monitor.h>
#include <thrift/lib/cpp/concurrency/PosixThreadFactory.h>
#include <thrift/lib/cpp/concurrency/Thread.h>
#include <wangle/concurrent/Codel.h>
#include <thrift/lib/cpp/concurrency/ThreadManager-impl.h>
namespace apache { namespace thrift { namespace concurrency {
using std::shared_ptr;
using std::make_shared;
using std::dynamic_pointer_cast;
using std::unique_ptr;
using folly::RequestContext;
/**
* ThreadManager class
*
* This class manages a pool of threads. It uses a ThreadFactory to create
* threads. It never actually creates or destroys worker threads, rather
* it maintains statistics on number of idle threads, number of active threads,
* task backlog, and average wait and service times.
*
* @version $Id:$
*/
template <typename SemType>
template <typename SemTypeT>
class ThreadManager::ImplT<SemType>::Worker : public Runnable {
public:
Worker(ThreadManager::ImplT<SemTypeT>* manager) :
manager_(manager) {}
~Worker() override {}
/**
* Worker entry point
*
* As long as worker thread is running, pull tasks off the task queue and
* execute.
*/
void run() override {
// Inform our manager that we are starting
manager_->workerStarted(this);
while (true) {
// Wait for a task to run
auto task = manager_->waitOnTask();
// A nullptr task means that this thread is supposed to exit
if (!task) {
manager_->workerExiting(this);
return;
}
// Getting the current time is moderately expensive,
// so only get the time if we actually need it.
SystemClockTimePoint startTime;
if (task->canExpire() || task->statsEnabled()) {
startTime = SystemClock::now();
// Codel auto-expire time algorithm
auto delay = std::chrono::duration_cast<std::chrono::milliseconds>(
startTime - task->getQueueBeginTime());
if (manager_->codel_.overloaded(delay)) {
if (manager_->codelCallback_) {
manager_->codelCallback_(task->getRunnable());
}
if (manager_->codelEnabled_) {
FB_LOG_EVERY_MS(WARNING, 10000) << "Queueing delay timeout";
manager_->onTaskExpired(*task);
continue;
}
}
if (manager_->observer_) {
// Hold lock to ensure that observer_ does not get deleted
folly::RWSpinLock::ReadHolder g(manager_->observerLock_);
if (manager_->observer_) {
manager_->observer_->preRun(task->getContext().get());
}
}
}
// Check if the task is expired
if (task->canExpire() &&
task->getExpireTime() <= startTime) {
manager_->onTaskExpired(*task);
continue;
}
try {
task->run();
} catch(const std::exception& ex) {
T_ERROR("ThreadManager: worker task threw unhandled "
"%s exception: %s", typeid(ex).name(), ex.what());
} catch(...) {
T_ERROR("ThreadManager: worker task threw unhandled "
"non-exception object");
}
if (task->statsEnabled()) {
auto endTime = SystemClock::now();
manager_->reportTaskStats(*task,
startTime,
endTime);
}
}
}
private:
ThreadManager::ImplT<SemType>* manager_;
};
template <typename SemType>
void ThreadManager::ImplT<SemType>::addWorker(size_t value) {
for (size_t ix = 0; ix < value; ix++) {
auto worker = make_shared<Worker<SemType>>(this);
auto thread = threadFactory_->newThread(worker,
ThreadFactory::ATTACHED);
{
// We need to increment idle count
Guard g(mutex_);
if (state_ != STARTED) {
throw IllegalStateException("ThreadManager::addWorker(): "
"ThreadManager not running");
}
idleCount_++;
}
try {
thread->start();
} catch (...) {
// If thread is started unsuccessfully, we need to decrement the
// count we incremented above
Guard g(mutex_);
idleCount_--;
throw;
}
Guard g(mutex_);
workerCount_++;
intendedWorkerCount_++;
}
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::workerStarted(Worker<SemType>* worker) {
InitCallback initCallback;
{
Guard g(mutex_);
assert(idleCount_ > 0);
--idleCount_;
++totalTaskCount_;
shared_ptr<Thread> thread = worker->thread();
idMap_.insert(std::make_pair(thread->getId(), thread));
initCallback = initCallback_;
if (!namePrefix_.empty()) {
thread->setName(folly::to<std::string>(namePrefix_, "-",
++namePrefixCounter_));
}
}
if (initCallback) {
initCallback();
}
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::workerExiting(Worker<SemType>* worker) {
Guard g(mutex_);
shared_ptr<Thread> thread = worker->thread();
size_t numErased = idMap_.erase(thread->getId());
DCHECK_EQ(numErased, 1);
--workerCount_;
--totalTaskCount_;
deadWorkers_.push_back(thread);
deadWorkerMonitor_.notify();
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::start() {
Guard g(mutex_);
if (state_ == ThreadManager::STOPPED) {
return;
}
if (state_ == ThreadManager::UNINITIALIZED) {
if (threadFactory_ == nullptr) {
throw InvalidArgumentException();
}
state_ = ThreadManager::STARTED;
monitor_.notifyAll();
}
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::stopImpl(bool joinArg) {
Guard g(mutex_);
if (state_ == ThreadManager::UNINITIALIZED) {
// The thread manager was never started. Just ignore the stop() call.
// This will happen if the ThreadManager is destroyed without ever being
// started.
} else if (state_ == ThreadManager::STARTED) {
if (joinArg) {
state_ = ThreadManager::JOINING;
removeWorkerImpl(intendedWorkerCount_, true);
assert(tasks_.isEmpty());
} else {
state_ = ThreadManager::STOPPING;
removeWorkerImpl(intendedWorkerCount_);
// Empty the task queue, in case we stopped without running
// all of the tasks.
totalTaskCount_ -= tasks_.size();
std::unique_ptr<Task> task;
while (tasks_.read(task)) { }
}
state_ = ThreadManager::STOPPED;
monitor_.notifyAll();
g.release();
} else {
// Another stopImpl() call is already in progress.
// Just wait for the state to change to STOPPED
while (state_ != ThreadManager::STOPPED) {
monitor_.wait();
}
}
assert(workerCount_ == 0);
assert(intendedWorkerCount_ == 0);
assert(idleCount_ == 0);
assert(totalTaskCount_ == 0);
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::removeWorker(size_t value) {
Guard g(mutex_);
removeWorkerImpl(value);
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::removeWorkerImpl(size_t value, bool afterTasks) {
assert(mutex_.isLocked());
if (value > intendedWorkerCount_) {
throw InvalidArgumentException();
}
intendedWorkerCount_ -= value;
if (afterTasks) {
// Insert nullptr tasks onto the tasks queue to ask workers to exit
// after all current tasks are completed
size_t bad = 0;
for (size_t n = 0; n < value; ++n) {
if (!tasks_.write(nullptr)) {
T_ERROR("ThreadManager: Can't remove worker. Increase maxQueueLen?");
bad++;
continue;
}
++totalTaskCount_;
}
monitor_.notifyAll();
for (size_t n = 0; n < value; ++n) {
waitSem_.post();
}
intendedWorkerCount_ += bad;
value -= bad;
} else {
// Ask threads to exit ASAP
workersToStop_ += value;
monitor_.notifyAll();
for (size_t n = 0; n < value; ++n) {
waitSem_.post();
}
}
// Wait for the specified number of threads to exit
for (size_t n = 0; n < value; ++n) {
while (deadWorkers_.empty()) {
deadWorkerMonitor_.wait();
}
shared_ptr<Thread> thread = deadWorkers_.front();
deadWorkers_.pop_front();
thread->join();
}
}
template <typename SemType>
bool ThreadManager::ImplT<SemType>::canSleep() {
assert(mutex_.isLocked());
const Thread::id_t id = threadFactory_->getCurrentThreadId();
return idMap_.find(id) == idMap_.end();
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::add(shared_ptr<Runnable> value,
int64_t timeout,
int64_t expiration,
bool /*cancellable*/,
bool numa) {
if (numa) {
VLOG_EVERY_N(1, 100) << "ThreadManager::add called with numa == true, but "
<< "not a NumaThreadManager";
}
if (state_ != ThreadManager::STARTED) {
throw IllegalStateException("ThreadManager::Impl::add ThreadManager "
"not started");
}
if (pendingTaskCountMax_ > 0
&& tasks_.size() >= folly::to<ssize_t>(pendingTaskCountMax_)) {
Guard g(mutex_, timeout);
if (!g) {
throw TimedOutException();
}
if (canSleep() && timeout >= 0) {
while (pendingTaskCountMax_ > 0
&& tasks_.size() >= folly::to<ssize_t>(pendingTaskCountMax_)) {
// This is thread safe because the mutex is shared between monitors.
maxMonitor_.wait(timeout);
}
} else {
throw TooManyPendingTasksException();
}
}
auto task = folly::make_unique<Task>(std::move(value),
std::chrono::milliseconds{expiration});
if (!tasks_.write(std::move(task))) {
T_ERROR("ThreadManager: Failed to enqueue item. Increase maxQueueLen?");
throw TooManyPendingTasksException();
}
++totalTaskCount_;
if (idleCount_ > 0) {
// If an idle thread is available notify it, otherwise all worker threads
// are running and will get around to this task in time.
waitSem_.post();
}
}
template <typename SemType>
bool ThreadManager::ImplT<SemType>::tryAdd(shared_ptr<Runnable> value) {
if (state_ != ThreadManager::STARTED) {
return false;
}
if (pendingTaskCountMax_ > 0 &&
tasks_.size() >= folly::to<ssize_t>(pendingTaskCountMax_)) {
return false;
}
auto task = folly::make_unique<Task>(std::move(value),
std::chrono::milliseconds{0});
if (!tasks_.write(std::move(task))) {
return false;
}
++totalTaskCount_;
if (idleCount_ > 0) {
// If an idle thread is available notify it, otherwise all worker threads
// are running and will get around to this task in time.
waitSem_.post();
}
return true;
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::remove(shared_ptr<Runnable> /*task*/) {
Synchronized s(monitor_);
if (state_ != ThreadManager::STARTED) {
throw IllegalStateException("ThreadManager::Impl::remove ThreadManager not "
"started");
}
throw IllegalStateException("ThreadManager::Impl::remove() not implemented");
}
template <typename SemType>
std::shared_ptr<Runnable> ThreadManager::ImplT<SemType>::removeNextPending() {
Guard g(mutex_);
if (state_ != ThreadManager::STARTED) {
throw IllegalStateException("ThreadManager::Impl::removeNextPending "
"ThreadManager not started");
}
std::unique_ptr<Task> task;
if (tasks_.read(task)) {
std::shared_ptr<Runnable> r = task->getRunnable();
--totalTaskCount_;
maybeNotifyMaxMonitor(false);
return r;
} else {
return std::shared_ptr<Runnable>();
}
}
template <typename SemType>
bool ThreadManager::ImplT<SemType>::shouldStop() {
// in normal cases, only do a read (prevents cache line bounces)
if (workersToStop_ <= 0) {
return false;
}
// modify only if needed
if (workersToStop_-- > 0) {
return true;
} else {
workersToStop_++;
return false;
}
}
template <typename SemType>
std::unique_ptr<ThreadManager::Task>
ThreadManager::ImplT<SemType>::waitOnTask() {
if (shouldStop()) {
return nullptr;
}
std::unique_ptr<Task> task;
// Fast path - if tasks are ready, get one
if (tasks_.read(task)) {
--totalTaskCount_;
maybeNotifyMaxMonitor(true);
return task;
}
// Otherwise, no tasks on the horizon, so go sleep
Guard g(mutex_);
if (shouldStop()) {
// check again because it might have changed by the time we got the mutex
return nullptr;
}
++idleCount_;
--totalTaskCount_;
g.release();
while (!tasks_.read(task)) {
waitSem_.wait();
if (shouldStop()) {
Guard f(mutex_);
--idleCount_;
++totalTaskCount_;
return nullptr;
}
}
--idleCount_;
// totalTaskCount_ doesn't change:
// the decrement of idleCount_ and the dequeueing of a task cancel each other
maybeNotifyMaxMonitor(true);
return task;
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::maybeNotifyMaxMonitor(bool shouldLock) {
if (pendingTaskCountMax_ != 0
&& tasks_.size() < folly::to<ssize_t>(pendingTaskCountMax_)) {
if (shouldLock) {
Guard g(mutex_);
maxMonitor_.notify();
} else {
assert(mutex_.isLocked());
maxMonitor_.notify();
}
}
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::onTaskExpired(const Task& task) {
ExpireCallback expireCallback;
{
Guard g(mutex_);
expiredCount_++;
expireCallback = expireCallback_;
}
if (expireCallback) {
// Expired callback should _not_ be called holding mutex_
expireCallback(task.getRunnable());
}
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::setExpireCallback(ExpireCallback expireCallback) {
expireCallback_ = expireCallback;
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::setCodelCallback(ExpireCallback expireCallback) {
codelCallback_ = expireCallback;
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::getStats(int64_t& waitTimeUs, int64_t& runTimeUs,
int64_t maxItems) {
folly::MSLGuard g(statsLock_);
if (numTasks_) {
if (numTasks_ >= maxItems) {
waitingTimeUs_ /= numTasks_;
executingTimeUs_ /= numTasks_;
numTasks_ = 1;
}
waitTimeUs = waitingTimeUs_ / numTasks_;
runTimeUs = executingTimeUs_ / numTasks_;
} else {
waitTimeUs = 0;
runTimeUs = 0;
}
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::reportTaskStats(
const Task& task,
const SystemClockTimePoint& workBegin,
const SystemClockTimePoint& workEnd) {
auto queueBegin = task.getQueueBeginTime();
int64_t waitTimeUs = std::chrono::duration_cast<std::chrono::microseconds>(
workBegin - queueBegin).count();
int64_t runTimeUs = std::chrono::duration_cast<std::chrono::microseconds>(
workEnd - workBegin).count();
if (enableTaskStats_) {
folly::MSLGuard g(statsLock_);
waitingTimeUs_ += waitTimeUs;
executingTimeUs_ += runTimeUs;
++numTasks_;
}
// Optimistic check lock free
if (ThreadManager::ImplT<SemType>::observer_) {
// Hold lock to ensure that observer_ does not get deleted.
folly::RWSpinLock::ReadHolder g(ThreadManager::ImplT<SemType>::observerLock_);
if (ThreadManager::ImplT<SemType>::observer_) {
// Note: We are assuming the namePrefix_ does not change after the thread is
// started.
// TODO: enforce this.
ThreadManager::ImplT<SemType>::observer_->postRun(
task.getContext().get(),
{namePrefix_, queueBegin, workBegin, workEnd});
}
}
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::enableCodel(bool enabled) {
codelEnabled_ = enabled || FLAGS_codel_enabled;
}
template <typename SemType>
Codel* ThreadManager::ImplT<SemType>::getCodel() {
return &codel_;
}
template <typename SemType>
class SimpleThreadManager : public ThreadManager::ImplT<SemType> {
public:
explicit SimpleThreadManager(size_t workerCount = 4,
size_t pendingTaskCountMax = 0,
bool enableTaskStats = false,
size_t maxQueueLen = 0) :
ThreadManager::Impl(pendingTaskCountMax, enableTaskStats, maxQueueLen)
, workerCount_(workerCount) {
}
void start() override {
if (this->state() == this->STARTED) {
return;
}
ThreadManager::ImplT<SemType>::start();
this->addWorker(workerCount_);
}
private:
const size_t workerCount_;
};
template <typename SemType>
shared_ptr<ThreadManager> ThreadManager::newSimpleThreadManager(
size_t count,
size_t pendingTaskCountMax,
bool enableTaskStats,
size_t maxQueueLen) {
return make_shared<SimpleThreadManager<SemType>>(count, pendingTaskCountMax,
enableTaskStats, maxQueueLen);
}
template <typename SemType>
class PriorityThreadManager::PriorityImplT : public PriorityThreadManager {
public:
PriorityImplT(const std::array<std::pair<shared_ptr<ThreadFactory>, size_t>,
N_PRIORITIES>& factories,
bool enableTaskStats = false,
size_t maxQueueLen = 0) {
for (int i = 0; i < N_PRIORITIES; i++) {
unique_ptr<ThreadManager> m(
new ThreadManager::ImplT<SemType>(0, enableTaskStats, maxQueueLen));
m->threadFactory(factories[i].first);
managers_[i] = std::move(m);
counts_[i] = factories[i].second;
}
}
void start() override {
Guard g(mutex_);
for (int i = 0; i < N_PRIORITIES; i++) {
if (managers_[i]->state() == STARTED) {
continue;
}
managers_[i]->start();
managers_[i]->addWorker(counts_[i]);
}
}
void stop() override {
Guard g(mutex_);
for (auto& m : managers_) {
m->stop();
}
}
void join() override {
Guard g(mutex_);
for (auto& m : managers_) {
m->join();
}
}
std::string getNamePrefix() const override {
return managers_[0]->getNamePrefix();
}
void setNamePrefix(const std::string& name) override {
for (int i = 0; i < N_PRIORITIES; i++) {
managers_[i]->setNamePrefix(folly::to<std::string>(name, "-pri", i));
}
}
void addWorker(size_t value) override {
addWorker(NORMAL, value);
}
void removeWorker(size_t value) override {
removeWorker(NORMAL, value);
}
void addWorker(PRIORITY priority, size_t value) override {
managers_[priority]->addWorker(value);
}
void removeWorker(PRIORITY priority, size_t value) override {
managers_[priority]->removeWorker(value);
}
STATE state() const override {
size_t started = 0;
Guard g(mutex_);
for (auto& m : managers_) {
STATE cur_state = m->state();
switch (cur_state) {
case UNINITIALIZED:
case STARTING:
case JOINING:
case STOPPING:
return cur_state;
case STARTED:
started++;
break;
case STOPPED:
break;
}
}
if (started == 0) {
return STOPPED;
}
return STARTED;
}
std::shared_ptr<ThreadFactory> threadFactory() const override {
throw IllegalStateException("Not implemented");
return std::shared_ptr<ThreadFactory>();
}
void threadFactory(std::shared_ptr<ThreadFactory> value) override {
Guard g(mutex_);
for (auto& m : managers_) {
m->threadFactory(value);
}
}
void add(std::shared_ptr<Runnable> task,
int64_t timeout = 0,
int64_t expiration = 0,
bool cancellable = false,
bool numa = false) override {
PriorityRunnable* p = dynamic_cast<PriorityRunnable*>(task.get());
PRIORITY prio = p ? p->getPriority() : NORMAL;
add(prio, std::move(task), timeout, expiration, cancellable, numa);
}
void add(PRIORITY priority,
std::shared_ptr<Runnable> task,
int64_t timeout = 0,
int64_t expiration = 0,
bool cancellable = false,
bool numa = false) override {
managers_[priority]->add(
std::move(task), timeout, expiration, cancellable, numa);
}
bool tryAdd(std::shared_ptr<Runnable> task) override {
PriorityRunnable* p = dynamic_cast<PriorityRunnable*>(task.get());
PRIORITY prio = p ? p->getPriority() : NORMAL;
return tryAdd(prio, std::move(task));
}
bool tryAdd(PRIORITY priority, std::shared_ptr<Runnable> task) override {
return managers_[priority]->tryAdd(std::move(task));
}
/**
* Implements folly::Executor::add()
*/
void add(folly::Func f) override {
add(FunctionRunner::create(std::move(f)));
}
/**
* Implements folly::Executor::addWithPriority()
* Maps executor priority task to respective PriorityThreadManager threads:
* >= 3 pri tasks to 'HIGH_IMPORTANT' threads,
* 2 pri tasks to 'HIGH' threads,
* 1 pri tasks to 'IMPORTANT' threads,
* 0 pri tasks to 'NORMAL' threads,
* <= -1 pri tasks to 'BEST_EFFORT' threads,
*/
void addWithPriority(folly::Func f, int8_t priority) override {
PRIORITY prio = PRIORITY::NORMAL;
if (priority >= 3) {
prio = PRIORITY::HIGH_IMPORTANT;
} else if (priority == 2) {
prio = PRIORITY::HIGH;
} else if (priority == 1) {
prio = PRIORITY::IMPORTANT;
} else if (priority == 0) {
prio = PRIORITY::NORMAL;
} else if (priority <= -1) {
prio = PRIORITY::BEST_EFFORT;
}
add(prio, FunctionRunner::create(std::move(f)));
}
template <typename T>
size_t sum(T method) const {
size_t count = 0;
for (const auto& m : managers_) {
count += ((*m).*method)();
}
return count;
}
size_t idleWorkerCount() const override {
return sum(&ThreadManager::idleWorkerCount);
}
size_t workerCount() const override {
return sum(&ThreadManager::workerCount);
}
size_t pendingTaskCount() const override {
return sum(&ThreadManager::pendingTaskCount);
}
size_t totalTaskCount() const override {
return sum(&ThreadManager::totalTaskCount);
}
size_t pendingTaskCountMax() const override {
throw IllegalStateException("Not implemented");
return 0;
}
size_t expiredTaskCount() override {
return sum(&ThreadManager::expiredTaskCount);
}
void remove(std::shared_ptr<Runnable> /*task*/) override {
throw IllegalStateException("Not implemented");
}
std::shared_ptr<Runnable> removeNextPending() override {
throw IllegalStateException("Not implemented");
return std::shared_ptr<Runnable>();
}
void setExpireCallback(ExpireCallback expireCallback) override {
for (const auto& m : managers_) {
m->setExpireCallback(expireCallback);
}
}
void setCodelCallback(ExpireCallback expireCallback) override {
for (const auto& m : managers_) {
m->setCodelCallback(expireCallback);
}
}
void setThreadInitCallback(InitCallback /*initCallback*/) override {
throw IllegalStateException("Not implemented");
}
void enableCodel(bool enabled) override {
for (const auto& m : managers_) {
m->enableCodel(enabled);
}
}
Codel* getCodel() override {
return getCodel(NORMAL);
}
Codel* getCodel(PRIORITY priority) override {
return managers_[priority]->getCodel();
}
private:
unique_ptr<ThreadManager> managers_[N_PRIORITIES];
size_t counts_[N_PRIORITIES];
Mutex mutex_;
};
static inline shared_ptr<ThreadFactory> Factory(PosixThreadFactory::PRIORITY prio) {
return make_shared<PosixThreadFactory>(PosixThreadFactory::OTHER, prio);
}
static const size_t NORMAL_PRIORITY_MINIMUM_THREADS = 1;
template <typename SemType>
shared_ptr<PriorityThreadManager>
PriorityThreadManager::newPriorityThreadManager(
const std::array<std::pair<shared_ptr<ThreadFactory>, size_t>,
N_PRIORITIES>& factories,
bool enableTaskStats,
size_t maxQueueLen) {
auto copy = factories;
if (copy[PRIORITY::NORMAL].second < NORMAL_PRIORITY_MINIMUM_THREADS) {
LOG(INFO) << "Creating minimum threads of NORMAL priority: "
<< NORMAL_PRIORITY_MINIMUM_THREADS;
copy[PRIORITY::NORMAL].second = NORMAL_PRIORITY_MINIMUM_THREADS;
}
return std::make_shared<PriorityThreadManager::PriorityImplT<SemType>>(
copy, enableTaskStats, maxQueueLen);
}
template <typename SemType>
shared_ptr<PriorityThreadManager>
PriorityThreadManager::newPriorityThreadManager(
const std::array<size_t, N_PRIORITIES>& counts,
bool enableTaskStats,
size_t maxQueueLen) {
static_assert(N_PRIORITIES == 5, "Implementation is out-of-date");
// Note that priorities for HIGH and IMPORTANT are the same, the difference
// is in the number of threads.
const std::array<std::pair<shared_ptr<ThreadFactory>, size_t>, N_PRIORITIES>
factories{{
{Factory(PosixThreadFactory::HIGHER), counts[PRIORITY::HIGH_IMPORTANT]},
{Factory(PosixThreadFactory::HIGH), counts[PRIORITY::HIGH]},
{Factory(PosixThreadFactory::HIGH), counts[PRIORITY::IMPORTANT]},
{Factory(PosixThreadFactory::NORMAL), counts[PRIORITY::NORMAL]},
{Factory(PosixThreadFactory::LOW), counts[PRIORITY::BEST_EFFORT]},
}};
return newPriorityThreadManager<SemType>(
factories, enableTaskStats, maxQueueLen);
}
template <typename SemType>
shared_ptr<PriorityThreadManager>
PriorityThreadManager::newPriorityThreadManager(
size_t normalThreadsCount,
bool enableTaskStats,
size_t maxQueueLen) {
return newPriorityThreadManager<SemType>({{2, 2, 2, normalThreadsCount, 2}},
enableTaskStats,
maxQueueLen);
}
}}} // apache::thrift::concurrency
Use glog instead of T_ERROR logging for ThreadManager
Summary:We've been seeing a large spikes of
ERROR: ThreadManager: Failed to enqueue item. Increase maxQueueLen?
in our service logs recently. These are not picked up by logview, so
they're quite hard to spot in the first place. Also, it's quite hard
to debug exactly which ThreadManager instance is experiencing these
spikes as there's no equivalent of -log_backtrace_at. As the newer
thrift code is already using glog and even ThreadManager uses it in
some place, it's probably a good idea to replace the T_ERROR logging.
Differential Revision: D3202864
fb-gh-sync-id: 258a85c525b80e91da3c21dad4311a9eb8622108
fbshipit-source-id: 258a85c525b80e91da3c21dad4311a9eb8622108
/*
* Copyright 2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrift/lib/cpp/concurrency/ThreadManager.h>
#include <assert.h>
#include <memory>
#include <queue>
#include <set>
#include <atomic>
#if defined(DEBUG)
#include <iostream>
#endif //defined(DEBUG)
#include <folly/Conv.h>
#include <folly/Logging.h>
#include <folly/MPMCQueue.h>
#include <folly/Memory.h>
#include <folly/io/async/Request.h>
#include <folly/String.h>
#include <thrift/lib/cpp/concurrency/Exception.h>
#include <thrift/lib/cpp/concurrency/Monitor.h>
#include <thrift/lib/cpp/concurrency/PosixThreadFactory.h>
#include <thrift/lib/cpp/concurrency/Thread.h>
#include <wangle/concurrent/Codel.h>
#include <thrift/lib/cpp/concurrency/ThreadManager-impl.h>
namespace apache { namespace thrift { namespace concurrency {
using std::shared_ptr;
using std::make_shared;
using std::dynamic_pointer_cast;
using std::unique_ptr;
using folly::RequestContext;
/**
* ThreadManager class
*
* This class manages a pool of threads. It uses a ThreadFactory to create
* threads. It never actually creates or destroys worker threads, rather
* it maintains statistics on number of idle threads, number of active threads,
* task backlog, and average wait and service times.
*
* @version $Id:$
*/
template <typename SemType>
template <typename SemTypeT>
class ThreadManager::ImplT<SemType>::Worker : public Runnable {
public:
Worker(ThreadManager::ImplT<SemTypeT>* manager) :
manager_(manager) {}
~Worker() override {}
/**
* Worker entry point
*
* As long as worker thread is running, pull tasks off the task queue and
* execute.
*/
void run() override {
// Inform our manager that we are starting
manager_->workerStarted(this);
while (true) {
// Wait for a task to run
auto task = manager_->waitOnTask();
// A nullptr task means that this thread is supposed to exit
if (!task) {
manager_->workerExiting(this);
return;
}
// Getting the current time is moderately expensive,
// so only get the time if we actually need it.
SystemClockTimePoint startTime;
if (task->canExpire() || task->statsEnabled()) {
startTime = SystemClock::now();
// Codel auto-expire time algorithm
auto delay = std::chrono::duration_cast<std::chrono::milliseconds>(
startTime - task->getQueueBeginTime());
if (manager_->codel_.overloaded(delay)) {
if (manager_->codelCallback_) {
manager_->codelCallback_(task->getRunnable());
}
if (manager_->codelEnabled_) {
FB_LOG_EVERY_MS(WARNING, 10000) << "Queueing delay timeout";
manager_->onTaskExpired(*task);
continue;
}
}
if (manager_->observer_) {
// Hold lock to ensure that observer_ does not get deleted
folly::RWSpinLock::ReadHolder g(manager_->observerLock_);
if (manager_->observer_) {
manager_->observer_->preRun(task->getContext().get());
}
}
}
// Check if the task is expired
if (task->canExpire() &&
task->getExpireTime() <= startTime) {
manager_->onTaskExpired(*task);
continue;
}
try {
task->run();
} catch (const std::exception& ex) {
LOG(ERROR) << "worker task threw unhandled " << folly::exceptionStr(ex);
} catch (...) {
LOG(ERROR) << "worker task threw unhandled non-exception object";
}
if (task->statsEnabled()) {
auto endTime = SystemClock::now();
manager_->reportTaskStats(*task,
startTime,
endTime);
}
}
}
private:
ThreadManager::ImplT<SemType>* manager_;
};
template <typename SemType>
void ThreadManager::ImplT<SemType>::addWorker(size_t value) {
for (size_t ix = 0; ix < value; ix++) {
auto worker = make_shared<Worker<SemType>>(this);
auto thread = threadFactory_->newThread(worker,
ThreadFactory::ATTACHED);
{
// We need to increment idle count
Guard g(mutex_);
if (state_ != STARTED) {
throw IllegalStateException("ThreadManager::addWorker(): "
"ThreadManager not running");
}
idleCount_++;
}
try {
thread->start();
} catch (...) {
// If thread is started unsuccessfully, we need to decrement the
// count we incremented above
Guard g(mutex_);
idleCount_--;
throw;
}
Guard g(mutex_);
workerCount_++;
intendedWorkerCount_++;
}
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::workerStarted(Worker<SemType>* worker) {
InitCallback initCallback;
{
Guard g(mutex_);
assert(idleCount_ > 0);
--idleCount_;
++totalTaskCount_;
shared_ptr<Thread> thread = worker->thread();
idMap_.insert(std::make_pair(thread->getId(), thread));
initCallback = initCallback_;
if (!namePrefix_.empty()) {
thread->setName(folly::to<std::string>(namePrefix_, "-",
++namePrefixCounter_));
}
}
if (initCallback) {
initCallback();
}
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::workerExiting(Worker<SemType>* worker) {
Guard g(mutex_);
shared_ptr<Thread> thread = worker->thread();
size_t numErased = idMap_.erase(thread->getId());
DCHECK_EQ(numErased, 1);
--workerCount_;
--totalTaskCount_;
deadWorkers_.push_back(thread);
deadWorkerMonitor_.notify();
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::start() {
Guard g(mutex_);
if (state_ == ThreadManager::STOPPED) {
return;
}
if (state_ == ThreadManager::UNINITIALIZED) {
if (threadFactory_ == nullptr) {
throw InvalidArgumentException();
}
state_ = ThreadManager::STARTED;
monitor_.notifyAll();
}
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::stopImpl(bool joinArg) {
Guard g(mutex_);
if (state_ == ThreadManager::UNINITIALIZED) {
// The thread manager was never started. Just ignore the stop() call.
// This will happen if the ThreadManager is destroyed without ever being
// started.
} else if (state_ == ThreadManager::STARTED) {
if (joinArg) {
state_ = ThreadManager::JOINING;
removeWorkerImpl(intendedWorkerCount_, true);
assert(tasks_.isEmpty());
} else {
state_ = ThreadManager::STOPPING;
removeWorkerImpl(intendedWorkerCount_);
// Empty the task queue, in case we stopped without running
// all of the tasks.
totalTaskCount_ -= tasks_.size();
std::unique_ptr<Task> task;
while (tasks_.read(task)) { }
}
state_ = ThreadManager::STOPPED;
monitor_.notifyAll();
g.release();
} else {
// Another stopImpl() call is already in progress.
// Just wait for the state to change to STOPPED
while (state_ != ThreadManager::STOPPED) {
monitor_.wait();
}
}
assert(workerCount_ == 0);
assert(intendedWorkerCount_ == 0);
assert(idleCount_ == 0);
assert(totalTaskCount_ == 0);
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::removeWorker(size_t value) {
Guard g(mutex_);
removeWorkerImpl(value);
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::removeWorkerImpl(size_t value, bool afterTasks) {
assert(mutex_.isLocked());
if (value > intendedWorkerCount_) {
throw InvalidArgumentException();
}
intendedWorkerCount_ -= value;
if (afterTasks) {
// Insert nullptr tasks onto the tasks queue to ask workers to exit
// after all current tasks are completed
size_t bad = 0;
for (size_t n = 0; n < value; ++n) {
if (!tasks_.write(nullptr)) {
LOG(ERROR) << "Can't remove worker. Increase maxQueueLen?";
bad++;
continue;
}
++totalTaskCount_;
}
monitor_.notifyAll();
for (size_t n = 0; n < value; ++n) {
waitSem_.post();
}
intendedWorkerCount_ += bad;
value -= bad;
} else {
// Ask threads to exit ASAP
workersToStop_ += value;
monitor_.notifyAll();
for (size_t n = 0; n < value; ++n) {
waitSem_.post();
}
}
// Wait for the specified number of threads to exit
for (size_t n = 0; n < value; ++n) {
while (deadWorkers_.empty()) {
deadWorkerMonitor_.wait();
}
shared_ptr<Thread> thread = deadWorkers_.front();
deadWorkers_.pop_front();
thread->join();
}
}
template <typename SemType>
bool ThreadManager::ImplT<SemType>::canSleep() {
assert(mutex_.isLocked());
const Thread::id_t id = threadFactory_->getCurrentThreadId();
return idMap_.find(id) == idMap_.end();
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::add(shared_ptr<Runnable> value,
int64_t timeout,
int64_t expiration,
bool /*cancellable*/,
bool numa) {
if (numa) {
VLOG_EVERY_N(1, 100) << "ThreadManager::add called with numa == true, but "
<< "not a NumaThreadManager";
}
if (state_ != ThreadManager::STARTED) {
throw IllegalStateException("ThreadManager::Impl::add ThreadManager "
"not started");
}
if (pendingTaskCountMax_ > 0
&& tasks_.size() >= folly::to<ssize_t>(pendingTaskCountMax_)) {
Guard g(mutex_, timeout);
if (!g) {
throw TimedOutException();
}
if (canSleep() && timeout >= 0) {
while (pendingTaskCountMax_ > 0
&& tasks_.size() >= folly::to<ssize_t>(pendingTaskCountMax_)) {
// This is thread safe because the mutex is shared between monitors.
maxMonitor_.wait(timeout);
}
} else {
throw TooManyPendingTasksException();
}
}
auto task = folly::make_unique<Task>(std::move(value),
std::chrono::milliseconds{expiration});
if (!tasks_.write(std::move(task))) {
LOG(ERROR) << "Failed to enqueue item. Increase maxQueueLen?";
throw TooManyPendingTasksException();
}
++totalTaskCount_;
if (idleCount_ > 0) {
// If an idle thread is available notify it, otherwise all worker threads
// are running and will get around to this task in time.
waitSem_.post();
}
}
template <typename SemType>
bool ThreadManager::ImplT<SemType>::tryAdd(shared_ptr<Runnable> value) {
if (state_ != ThreadManager::STARTED) {
return false;
}
if (pendingTaskCountMax_ > 0 &&
tasks_.size() >= folly::to<ssize_t>(pendingTaskCountMax_)) {
return false;
}
auto task = folly::make_unique<Task>(std::move(value),
std::chrono::milliseconds{0});
if (!tasks_.write(std::move(task))) {
return false;
}
++totalTaskCount_;
if (idleCount_ > 0) {
// If an idle thread is available notify it, otherwise all worker threads
// are running and will get around to this task in time.
waitSem_.post();
}
return true;
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::remove(shared_ptr<Runnable> /*task*/) {
Synchronized s(monitor_);
if (state_ != ThreadManager::STARTED) {
throw IllegalStateException("ThreadManager::Impl::remove ThreadManager not "
"started");
}
throw IllegalStateException("ThreadManager::Impl::remove() not implemented");
}
template <typename SemType>
std::shared_ptr<Runnable> ThreadManager::ImplT<SemType>::removeNextPending() {
Guard g(mutex_);
if (state_ != ThreadManager::STARTED) {
throw IllegalStateException("ThreadManager::Impl::removeNextPending "
"ThreadManager not started");
}
std::unique_ptr<Task> task;
if (tasks_.read(task)) {
std::shared_ptr<Runnable> r = task->getRunnable();
--totalTaskCount_;
maybeNotifyMaxMonitor(false);
return r;
} else {
return std::shared_ptr<Runnable>();
}
}
template <typename SemType>
bool ThreadManager::ImplT<SemType>::shouldStop() {
// in normal cases, only do a read (prevents cache line bounces)
if (workersToStop_ <= 0) {
return false;
}
// modify only if needed
if (workersToStop_-- > 0) {
return true;
} else {
workersToStop_++;
return false;
}
}
template <typename SemType>
std::unique_ptr<ThreadManager::Task>
ThreadManager::ImplT<SemType>::waitOnTask() {
if (shouldStop()) {
return nullptr;
}
std::unique_ptr<Task> task;
// Fast path - if tasks are ready, get one
if (tasks_.read(task)) {
--totalTaskCount_;
maybeNotifyMaxMonitor(true);
return task;
}
// Otherwise, no tasks on the horizon, so go sleep
Guard g(mutex_);
if (shouldStop()) {
// check again because it might have changed by the time we got the mutex
return nullptr;
}
++idleCount_;
--totalTaskCount_;
g.release();
while (!tasks_.read(task)) {
waitSem_.wait();
if (shouldStop()) {
Guard f(mutex_);
--idleCount_;
++totalTaskCount_;
return nullptr;
}
}
--idleCount_;
// totalTaskCount_ doesn't change:
// the decrement of idleCount_ and the dequeueing of a task cancel each other
maybeNotifyMaxMonitor(true);
return task;
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::maybeNotifyMaxMonitor(bool shouldLock) {
if (pendingTaskCountMax_ != 0
&& tasks_.size() < folly::to<ssize_t>(pendingTaskCountMax_)) {
if (shouldLock) {
Guard g(mutex_);
maxMonitor_.notify();
} else {
assert(mutex_.isLocked());
maxMonitor_.notify();
}
}
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::onTaskExpired(const Task& task) {
ExpireCallback expireCallback;
{
Guard g(mutex_);
expiredCount_++;
expireCallback = expireCallback_;
}
if (expireCallback) {
// Expired callback should _not_ be called holding mutex_
expireCallback(task.getRunnable());
}
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::setExpireCallback(ExpireCallback expireCallback) {
expireCallback_ = expireCallback;
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::setCodelCallback(ExpireCallback expireCallback) {
codelCallback_ = expireCallback;
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::getStats(int64_t& waitTimeUs, int64_t& runTimeUs,
int64_t maxItems) {
folly::MSLGuard g(statsLock_);
if (numTasks_) {
if (numTasks_ >= maxItems) {
waitingTimeUs_ /= numTasks_;
executingTimeUs_ /= numTasks_;
numTasks_ = 1;
}
waitTimeUs = waitingTimeUs_ / numTasks_;
runTimeUs = executingTimeUs_ / numTasks_;
} else {
waitTimeUs = 0;
runTimeUs = 0;
}
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::reportTaskStats(
const Task& task,
const SystemClockTimePoint& workBegin,
const SystemClockTimePoint& workEnd) {
auto queueBegin = task.getQueueBeginTime();
int64_t waitTimeUs = std::chrono::duration_cast<std::chrono::microseconds>(
workBegin - queueBegin).count();
int64_t runTimeUs = std::chrono::duration_cast<std::chrono::microseconds>(
workEnd - workBegin).count();
if (enableTaskStats_) {
folly::MSLGuard g(statsLock_);
waitingTimeUs_ += waitTimeUs;
executingTimeUs_ += runTimeUs;
++numTasks_;
}
// Optimistic check lock free
if (ThreadManager::ImplT<SemType>::observer_) {
// Hold lock to ensure that observer_ does not get deleted.
folly::RWSpinLock::ReadHolder g(ThreadManager::ImplT<SemType>::observerLock_);
if (ThreadManager::ImplT<SemType>::observer_) {
// Note: We are assuming the namePrefix_ does not change after the thread is
// started.
// TODO: enforce this.
ThreadManager::ImplT<SemType>::observer_->postRun(
task.getContext().get(),
{namePrefix_, queueBegin, workBegin, workEnd});
}
}
}
template <typename SemType>
void ThreadManager::ImplT<SemType>::enableCodel(bool enabled) {
codelEnabled_ = enabled || FLAGS_codel_enabled;
}
template <typename SemType>
Codel* ThreadManager::ImplT<SemType>::getCodel() {
return &codel_;
}
template <typename SemType>
class SimpleThreadManager : public ThreadManager::ImplT<SemType> {
public:
explicit SimpleThreadManager(size_t workerCount = 4,
size_t pendingTaskCountMax = 0,
bool enableTaskStats = false,
size_t maxQueueLen = 0) :
ThreadManager::Impl(pendingTaskCountMax, enableTaskStats, maxQueueLen)
, workerCount_(workerCount) {
}
void start() override {
if (this->state() == this->STARTED) {
return;
}
ThreadManager::ImplT<SemType>::start();
this->addWorker(workerCount_);
}
private:
const size_t workerCount_;
};
template <typename SemType>
shared_ptr<ThreadManager> ThreadManager::newSimpleThreadManager(
size_t count,
size_t pendingTaskCountMax,
bool enableTaskStats,
size_t maxQueueLen) {
return make_shared<SimpleThreadManager<SemType>>(count, pendingTaskCountMax,
enableTaskStats, maxQueueLen);
}
template <typename SemType>
class PriorityThreadManager::PriorityImplT : public PriorityThreadManager {
public:
PriorityImplT(const std::array<std::pair<shared_ptr<ThreadFactory>, size_t>,
N_PRIORITIES>& factories,
bool enableTaskStats = false,
size_t maxQueueLen = 0) {
for (int i = 0; i < N_PRIORITIES; i++) {
unique_ptr<ThreadManager> m(
new ThreadManager::ImplT<SemType>(0, enableTaskStats, maxQueueLen));
m->threadFactory(factories[i].first);
managers_[i] = std::move(m);
counts_[i] = factories[i].second;
}
}
void start() override {
Guard g(mutex_);
for (int i = 0; i < N_PRIORITIES; i++) {
if (managers_[i]->state() == STARTED) {
continue;
}
managers_[i]->start();
managers_[i]->addWorker(counts_[i]);
}
}
void stop() override {
Guard g(mutex_);
for (auto& m : managers_) {
m->stop();
}
}
void join() override {
Guard g(mutex_);
for (auto& m : managers_) {
m->join();
}
}
std::string getNamePrefix() const override {
return managers_[0]->getNamePrefix();
}
void setNamePrefix(const std::string& name) override {
for (int i = 0; i < N_PRIORITIES; i++) {
managers_[i]->setNamePrefix(folly::to<std::string>(name, "-pri", i));
}
}
void addWorker(size_t value) override {
addWorker(NORMAL, value);
}
void removeWorker(size_t value) override {
removeWorker(NORMAL, value);
}
void addWorker(PRIORITY priority, size_t value) override {
managers_[priority]->addWorker(value);
}
void removeWorker(PRIORITY priority, size_t value) override {
managers_[priority]->removeWorker(value);
}
STATE state() const override {
size_t started = 0;
Guard g(mutex_);
for (auto& m : managers_) {
STATE cur_state = m->state();
switch (cur_state) {
case UNINITIALIZED:
case STARTING:
case JOINING:
case STOPPING:
return cur_state;
case STARTED:
started++;
break;
case STOPPED:
break;
}
}
if (started == 0) {
return STOPPED;
}
return STARTED;
}
std::shared_ptr<ThreadFactory> threadFactory() const override {
throw IllegalStateException("Not implemented");
return std::shared_ptr<ThreadFactory>();
}
void threadFactory(std::shared_ptr<ThreadFactory> value) override {
Guard g(mutex_);
for (auto& m : managers_) {
m->threadFactory(value);
}
}
void add(std::shared_ptr<Runnable> task,
int64_t timeout = 0,
int64_t expiration = 0,
bool cancellable = false,
bool numa = false) override {
PriorityRunnable* p = dynamic_cast<PriorityRunnable*>(task.get());
PRIORITY prio = p ? p->getPriority() : NORMAL;
add(prio, std::move(task), timeout, expiration, cancellable, numa);
}
void add(PRIORITY priority,
std::shared_ptr<Runnable> task,
int64_t timeout = 0,
int64_t expiration = 0,
bool cancellable = false,
bool numa = false) override {
managers_[priority]->add(
std::move(task), timeout, expiration, cancellable, numa);
}
bool tryAdd(std::shared_ptr<Runnable> task) override {
PriorityRunnable* p = dynamic_cast<PriorityRunnable*>(task.get());
PRIORITY prio = p ? p->getPriority() : NORMAL;
return tryAdd(prio, std::move(task));
}
bool tryAdd(PRIORITY priority, std::shared_ptr<Runnable> task) override {
return managers_[priority]->tryAdd(std::move(task));
}
/**
* Implements folly::Executor::add()
*/
void add(folly::Func f) override {
add(FunctionRunner::create(std::move(f)));
}
/**
* Implements folly::Executor::addWithPriority()
* Maps executor priority task to respective PriorityThreadManager threads:
* >= 3 pri tasks to 'HIGH_IMPORTANT' threads,
* 2 pri tasks to 'HIGH' threads,
* 1 pri tasks to 'IMPORTANT' threads,
* 0 pri tasks to 'NORMAL' threads,
* <= -1 pri tasks to 'BEST_EFFORT' threads,
*/
void addWithPriority(folly::Func f, int8_t priority) override {
PRIORITY prio = PRIORITY::NORMAL;
if (priority >= 3) {
prio = PRIORITY::HIGH_IMPORTANT;
} else if (priority == 2) {
prio = PRIORITY::HIGH;
} else if (priority == 1) {
prio = PRIORITY::IMPORTANT;
} else if (priority == 0) {
prio = PRIORITY::NORMAL;
} else if (priority <= -1) {
prio = PRIORITY::BEST_EFFORT;
}
add(prio, FunctionRunner::create(std::move(f)));
}
template <typename T>
size_t sum(T method) const {
size_t count = 0;
for (const auto& m : managers_) {
count += ((*m).*method)();
}
return count;
}
size_t idleWorkerCount() const override {
return sum(&ThreadManager::idleWorkerCount);
}
size_t workerCount() const override {
return sum(&ThreadManager::workerCount);
}
size_t pendingTaskCount() const override {
return sum(&ThreadManager::pendingTaskCount);
}
size_t totalTaskCount() const override {
return sum(&ThreadManager::totalTaskCount);
}
size_t pendingTaskCountMax() const override {
throw IllegalStateException("Not implemented");
return 0;
}
size_t expiredTaskCount() override {
return sum(&ThreadManager::expiredTaskCount);
}
void remove(std::shared_ptr<Runnable> /*task*/) override {
throw IllegalStateException("Not implemented");
}
std::shared_ptr<Runnable> removeNextPending() override {
throw IllegalStateException("Not implemented");
return std::shared_ptr<Runnable>();
}
void setExpireCallback(ExpireCallback expireCallback) override {
for (const auto& m : managers_) {
m->setExpireCallback(expireCallback);
}
}
void setCodelCallback(ExpireCallback expireCallback) override {
for (const auto& m : managers_) {
m->setCodelCallback(expireCallback);
}
}
void setThreadInitCallback(InitCallback /*initCallback*/) override {
throw IllegalStateException("Not implemented");
}
void enableCodel(bool enabled) override {
for (const auto& m : managers_) {
m->enableCodel(enabled);
}
}
Codel* getCodel() override {
return getCodel(NORMAL);
}
Codel* getCodel(PRIORITY priority) override {
return managers_[priority]->getCodel();
}
private:
unique_ptr<ThreadManager> managers_[N_PRIORITIES];
size_t counts_[N_PRIORITIES];
Mutex mutex_;
};
static inline shared_ptr<ThreadFactory> Factory(PosixThreadFactory::PRIORITY prio) {
return make_shared<PosixThreadFactory>(PosixThreadFactory::OTHER, prio);
}
static const size_t NORMAL_PRIORITY_MINIMUM_THREADS = 1;
template <typename SemType>
shared_ptr<PriorityThreadManager>
PriorityThreadManager::newPriorityThreadManager(
const std::array<std::pair<shared_ptr<ThreadFactory>, size_t>,
N_PRIORITIES>& factories,
bool enableTaskStats,
size_t maxQueueLen) {
auto copy = factories;
if (copy[PRIORITY::NORMAL].second < NORMAL_PRIORITY_MINIMUM_THREADS) {
LOG(INFO) << "Creating minimum threads of NORMAL priority: "
<< NORMAL_PRIORITY_MINIMUM_THREADS;
copy[PRIORITY::NORMAL].second = NORMAL_PRIORITY_MINIMUM_THREADS;
}
return std::make_shared<PriorityThreadManager::PriorityImplT<SemType>>(
copy, enableTaskStats, maxQueueLen);
}
template <typename SemType>
shared_ptr<PriorityThreadManager>
PriorityThreadManager::newPriorityThreadManager(
const std::array<size_t, N_PRIORITIES>& counts,
bool enableTaskStats,
size_t maxQueueLen) {
static_assert(N_PRIORITIES == 5, "Implementation is out-of-date");
// Note that priorities for HIGH and IMPORTANT are the same, the difference
// is in the number of threads.
const std::array<std::pair<shared_ptr<ThreadFactory>, size_t>, N_PRIORITIES>
factories{{
{Factory(PosixThreadFactory::HIGHER), counts[PRIORITY::HIGH_IMPORTANT]},
{Factory(PosixThreadFactory::HIGH), counts[PRIORITY::HIGH]},
{Factory(PosixThreadFactory::HIGH), counts[PRIORITY::IMPORTANT]},
{Factory(PosixThreadFactory::NORMAL), counts[PRIORITY::NORMAL]},
{Factory(PosixThreadFactory::LOW), counts[PRIORITY::BEST_EFFORT]},
}};
return newPriorityThreadManager<SemType>(
factories, enableTaskStats, maxQueueLen);
}
template <typename SemType>
shared_ptr<PriorityThreadManager>
PriorityThreadManager::newPriorityThreadManager(
size_t normalThreadsCount,
bool enableTaskStats,
size_t maxQueueLen) {
return newPriorityThreadManager<SemType>({{2, 2, 2, normalThreadsCount, 2}},
enableTaskStats,
maxQueueLen);
}
}}} // apache::thrift::concurrency
|
/*
* Copyright (C) 2017-present ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "schema_fwd.hh"
#include "query-request.hh"
#include "mutation_fragment.hh"
#include "partition_version.hh"
#include "tracing/tracing.hh"
#include "row_cache.hh"
namespace cache {
/*
* Represent a flat reader to the underlying source.
* This reader automatically makes sure that it's up to date with all cache updates
*/
class autoupdating_underlying_reader final {
row_cache& _cache;
read_context& _read_context;
flat_mutation_reader_opt _reader;
utils::phased_barrier::phase_type _reader_creation_phase = 0;
dht::partition_range _range = { };
std::optional<dht::decorated_key> _last_key;
std::optional<dht::decorated_key> _new_last_key;
future<> close_reader() noexcept {
return _reader ? _reader->close() : make_ready_future<>();
}
public:
autoupdating_underlying_reader(row_cache& cache, read_context& context)
: _cache(cache)
, _read_context(context)
{ }
future<mutation_fragment_opt> move_to_next_partition(db::timeout_clock::time_point timeout) {
_last_key = std::move(_new_last_key);
auto start = population_range_start();
auto phase = _cache.phase_of(start);
auto refresh_reader = make_ready_future<>();
if (!_reader || _reader_creation_phase != phase) {
if (_last_key) {
auto cmp = dht::ring_position_comparator(*_cache._schema);
auto&& new_range = _range.split_after(*_last_key, cmp);
if (!new_range) {
return close_reader().then([] {
return make_ready_future<mutation_fragment_opt>();
});
}
_range = std::move(*new_range);
_last_key = {};
}
if (_reader) {
++_cache._tracker._stats.underlying_recreations;
}
auto old_reader = std::move(*_reader);
refresh_reader = futurize_invoke([this, phase] () {
_reader = _cache.create_underlying_reader(_read_context, _cache.snapshot_for_phase(phase), _range);
_reader_creation_phase = phase;
}).finally([rd = std::move(old_reader)] () mutable {
return rd.close();
});
}
return refresh_reader.then([this, timeout] {
return _reader->next_partition().then([this, timeout] {
if (_reader->is_end_of_stream() && _reader->is_buffer_empty()) {
return make_ready_future<mutation_fragment_opt>();
}
return (*_reader)(timeout).then([this] (auto&& mfopt) {
if (mfopt) {
assert(mfopt->is_partition_start());
_new_last_key = mfopt->as_partition_start().key();
}
return std::move(mfopt);
});
});
});
}
future<> fast_forward_to(dht::partition_range&& range, db::timeout_clock::time_point timeout) {
auto snapshot_and_phase = _cache.snapshot_of(dht::ring_position_view::for_range_start(_range));
return fast_forward_to(std::move(range), snapshot_and_phase.snapshot, snapshot_and_phase.phase, timeout);
}
future<> fast_forward_to(dht::partition_range&& range, mutation_source& snapshot, row_cache::phase_type phase, db::timeout_clock::time_point timeout) {
_range = std::move(range);
_last_key = { };
_new_last_key = { };
if (_reader) {
if (_reader_creation_phase == phase) {
++_cache._tracker._stats.underlying_partition_skips;
return _reader->fast_forward_to(_range, timeout);
} else {
++_cache._tracker._stats.underlying_recreations;
}
}
return close_reader().then([this, snapshot, phase] () mutable {
// FIXME: indentation
_reader = _cache.create_underlying_reader(_read_context, snapshot, _range);
_reader_creation_phase = phase;
});
}
future<> close() noexcept {
return close_reader();
}
utils::phased_barrier::phase_type creation_phase() const {
return _reader_creation_phase;
}
const dht::partition_range& range() const {
return _range;
}
flat_mutation_reader& underlying() { return *_reader; }
dht::ring_position_view population_range_start() const {
return _last_key ? dht::ring_position_view::for_after_key(*_last_key)
: dht::ring_position_view::for_range_start(_range);
}
};
class read_context final : public enable_lw_shared_from_this<read_context> {
row_cache& _cache;
schema_ptr _schema;
reader_permit _permit;
const dht::partition_range& _range;
const query::partition_slice& _slice;
const io_priority_class& _pc;
tracing::trace_state_ptr _trace_state;
mutation_reader::forwarding _fwd_mr;
bool _range_query;
// When reader enters a partition, it must be set up for reading that
// partition from the underlying mutation source (_underlying) in one of two ways:
//
// 1) either _underlying is already in that partition
//
// 2) _underlying is before the partition, then _underlying_snapshot and _key
// are set so that _underlying_flat can be fast forwarded to the right partition.
//
autoupdating_underlying_reader _underlying;
uint64_t _underlying_created = 0;
mutation_source_opt _underlying_snapshot;
dht::partition_range _sm_range;
std::optional<dht::decorated_key> _key;
bool _partition_exists;
row_cache::phase_type _phase;
public:
read_context(row_cache& cache,
schema_ptr schema,
reader_permit permit,
const dht::partition_range& range,
const query::partition_slice& slice,
const io_priority_class& pc,
tracing::trace_state_ptr trace_state,
mutation_reader::forwarding fwd_mr)
: _cache(cache)
, _schema(std::move(schema))
, _permit(std::move(permit))
, _range(range)
, _slice(slice)
, _pc(pc)
, _trace_state(std::move(trace_state))
, _fwd_mr(fwd_mr)
, _range_query(!query::is_single_partition(range))
, _underlying(_cache, *this)
{
++_cache._tracker._stats.reads;
if (!_range_query) {
_key = range.start()->value().as_decorated_key();
}
}
~read_context() {
++_cache._tracker._stats.reads_done;
if (_underlying_created) {
_cache._stats.reads_with_misses.mark();
++_cache._tracker._stats.reads_with_misses;
} else {
_cache._stats.reads_with_no_misses.mark();
}
}
read_context(const read_context&) = delete;
row_cache& cache() { return _cache; }
const schema_ptr& schema() const { return _schema; }
reader_permit permit() const { return _permit; }
const dht::partition_range& range() const { return _range; }
const query::partition_slice& slice() const { return _slice; }
const io_priority_class& pc() const { return _pc; }
tracing::trace_state_ptr trace_state() const { return _trace_state; }
mutation_reader::forwarding fwd_mr() const { return _fwd_mr; }
bool is_range_query() const { return _range_query; }
autoupdating_underlying_reader& underlying() { return _underlying; }
row_cache::phase_type phase() const { return _phase; }
const dht::decorated_key& key() const { return *_key; }
bool partition_exists() const { return _partition_exists; }
void on_underlying_created() { ++_underlying_created; }
bool digest_requested() const { return _slice.options.contains<query::partition_slice::option::with_digest>(); }
public:
future<> ensure_underlying(db::timeout_clock::time_point timeout) {
if (_underlying_snapshot) {
return create_underlying(timeout).then([this, timeout] {
return _underlying.underlying()(timeout).then([this] (mutation_fragment_opt&& mfopt) {
_partition_exists = bool(mfopt);
});
});
}
// We know that partition exists because all the callers of
// enter_partition(const dht::decorated_key&, row_cache::phase_type)
// check that and there's no other way of setting _underlying_snapshot
// to empty. Except for calling create_underlying.
_partition_exists = true;
return make_ready_future<>();
}
public:
future<> create_underlying(db::timeout_clock::time_point timeout);
void enter_partition(const dht::decorated_key& dk, mutation_source& snapshot, row_cache::phase_type phase) {
_phase = phase;
_underlying_snapshot = snapshot;
_key = dk;
}
// Precondition: each caller needs to make sure that partition with |dk| key
// exists in underlying before calling this function.
void enter_partition(const dht::decorated_key& dk, row_cache::phase_type phase) {
_phase = phase;
_underlying_snapshot = {};
_key = dk;
}
future<> close() noexcept {
return _underlying.close();
}
};
}
row_cache: autoupdating_underlying_reader: fast_forward_to: fixup indentation
Signed-off-by: Benny Halevy <23c997c90eb8537635e9392d48e7af1bf1b2ca22@scylladb.com>
Message-Id: <20210613104232.634621-2-23c997c90eb8537635e9392d48e7af1bf1b2ca22@scylladb.com>
/*
* Copyright (C) 2017-present ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "schema_fwd.hh"
#include "query-request.hh"
#include "mutation_fragment.hh"
#include "partition_version.hh"
#include "tracing/tracing.hh"
#include "row_cache.hh"
namespace cache {
/*
* Represent a flat reader to the underlying source.
* This reader automatically makes sure that it's up to date with all cache updates
*/
class autoupdating_underlying_reader final {
row_cache& _cache;
read_context& _read_context;
flat_mutation_reader_opt _reader;
utils::phased_barrier::phase_type _reader_creation_phase = 0;
dht::partition_range _range = { };
std::optional<dht::decorated_key> _last_key;
std::optional<dht::decorated_key> _new_last_key;
future<> close_reader() noexcept {
return _reader ? _reader->close() : make_ready_future<>();
}
public:
autoupdating_underlying_reader(row_cache& cache, read_context& context)
: _cache(cache)
, _read_context(context)
{ }
future<mutation_fragment_opt> move_to_next_partition(db::timeout_clock::time_point timeout) {
_last_key = std::move(_new_last_key);
auto start = population_range_start();
auto phase = _cache.phase_of(start);
auto refresh_reader = make_ready_future<>();
if (!_reader || _reader_creation_phase != phase) {
if (_last_key) {
auto cmp = dht::ring_position_comparator(*_cache._schema);
auto&& new_range = _range.split_after(*_last_key, cmp);
if (!new_range) {
return close_reader().then([] {
return make_ready_future<mutation_fragment_opt>();
});
}
_range = std::move(*new_range);
_last_key = {};
}
if (_reader) {
++_cache._tracker._stats.underlying_recreations;
}
auto old_reader = std::move(*_reader);
refresh_reader = futurize_invoke([this, phase] () {
_reader = _cache.create_underlying_reader(_read_context, _cache.snapshot_for_phase(phase), _range);
_reader_creation_phase = phase;
}).finally([rd = std::move(old_reader)] () mutable {
return rd.close();
});
}
return refresh_reader.then([this, timeout] {
return _reader->next_partition().then([this, timeout] {
if (_reader->is_end_of_stream() && _reader->is_buffer_empty()) {
return make_ready_future<mutation_fragment_opt>();
}
return (*_reader)(timeout).then([this] (auto&& mfopt) {
if (mfopt) {
assert(mfopt->is_partition_start());
_new_last_key = mfopt->as_partition_start().key();
}
return std::move(mfopt);
});
});
});
}
future<> fast_forward_to(dht::partition_range&& range, db::timeout_clock::time_point timeout) {
auto snapshot_and_phase = _cache.snapshot_of(dht::ring_position_view::for_range_start(_range));
return fast_forward_to(std::move(range), snapshot_and_phase.snapshot, snapshot_and_phase.phase, timeout);
}
future<> fast_forward_to(dht::partition_range&& range, mutation_source& snapshot, row_cache::phase_type phase, db::timeout_clock::time_point timeout) {
_range = std::move(range);
_last_key = { };
_new_last_key = { };
if (_reader) {
if (_reader_creation_phase == phase) {
++_cache._tracker._stats.underlying_partition_skips;
return _reader->fast_forward_to(_range, timeout);
} else {
++_cache._tracker._stats.underlying_recreations;
}
}
return close_reader().then([this, snapshot, phase] () mutable {
_reader = _cache.create_underlying_reader(_read_context, snapshot, _range);
_reader_creation_phase = phase;
});
}
future<> close() noexcept {
return close_reader();
}
utils::phased_barrier::phase_type creation_phase() const {
return _reader_creation_phase;
}
const dht::partition_range& range() const {
return _range;
}
flat_mutation_reader& underlying() { return *_reader; }
dht::ring_position_view population_range_start() const {
return _last_key ? dht::ring_position_view::for_after_key(*_last_key)
: dht::ring_position_view::for_range_start(_range);
}
};
class read_context final : public enable_lw_shared_from_this<read_context> {
row_cache& _cache;
schema_ptr _schema;
reader_permit _permit;
const dht::partition_range& _range;
const query::partition_slice& _slice;
const io_priority_class& _pc;
tracing::trace_state_ptr _trace_state;
mutation_reader::forwarding _fwd_mr;
bool _range_query;
// When reader enters a partition, it must be set up for reading that
// partition from the underlying mutation source (_underlying) in one of two ways:
//
// 1) either _underlying is already in that partition
//
// 2) _underlying is before the partition, then _underlying_snapshot and _key
// are set so that _underlying_flat can be fast forwarded to the right partition.
//
autoupdating_underlying_reader _underlying;
uint64_t _underlying_created = 0;
mutation_source_opt _underlying_snapshot;
dht::partition_range _sm_range;
std::optional<dht::decorated_key> _key;
bool _partition_exists;
row_cache::phase_type _phase;
public:
read_context(row_cache& cache,
schema_ptr schema,
reader_permit permit,
const dht::partition_range& range,
const query::partition_slice& slice,
const io_priority_class& pc,
tracing::trace_state_ptr trace_state,
mutation_reader::forwarding fwd_mr)
: _cache(cache)
, _schema(std::move(schema))
, _permit(std::move(permit))
, _range(range)
, _slice(slice)
, _pc(pc)
, _trace_state(std::move(trace_state))
, _fwd_mr(fwd_mr)
, _range_query(!query::is_single_partition(range))
, _underlying(_cache, *this)
{
++_cache._tracker._stats.reads;
if (!_range_query) {
_key = range.start()->value().as_decorated_key();
}
}
~read_context() {
++_cache._tracker._stats.reads_done;
if (_underlying_created) {
_cache._stats.reads_with_misses.mark();
++_cache._tracker._stats.reads_with_misses;
} else {
_cache._stats.reads_with_no_misses.mark();
}
}
read_context(const read_context&) = delete;
row_cache& cache() { return _cache; }
const schema_ptr& schema() const { return _schema; }
reader_permit permit() const { return _permit; }
const dht::partition_range& range() const { return _range; }
const query::partition_slice& slice() const { return _slice; }
const io_priority_class& pc() const { return _pc; }
tracing::trace_state_ptr trace_state() const { return _trace_state; }
mutation_reader::forwarding fwd_mr() const { return _fwd_mr; }
bool is_range_query() const { return _range_query; }
autoupdating_underlying_reader& underlying() { return _underlying; }
row_cache::phase_type phase() const { return _phase; }
const dht::decorated_key& key() const { return *_key; }
bool partition_exists() const { return _partition_exists; }
void on_underlying_created() { ++_underlying_created; }
bool digest_requested() const { return _slice.options.contains<query::partition_slice::option::with_digest>(); }
public:
future<> ensure_underlying(db::timeout_clock::time_point timeout) {
if (_underlying_snapshot) {
return create_underlying(timeout).then([this, timeout] {
return _underlying.underlying()(timeout).then([this] (mutation_fragment_opt&& mfopt) {
_partition_exists = bool(mfopt);
});
});
}
// We know that partition exists because all the callers of
// enter_partition(const dht::decorated_key&, row_cache::phase_type)
// check that and there's no other way of setting _underlying_snapshot
// to empty. Except for calling create_underlying.
_partition_exists = true;
return make_ready_future<>();
}
public:
future<> create_underlying(db::timeout_clock::time_point timeout);
void enter_partition(const dht::decorated_key& dk, mutation_source& snapshot, row_cache::phase_type phase) {
_phase = phase;
_underlying_snapshot = snapshot;
_key = dk;
}
// Precondition: each caller needs to make sure that partition with |dk| key
// exists in underlying before calling this function.
void enter_partition(const dht::decorated_key& dk, row_cache::phase_type phase) {
_phase = phase;
_underlying_snapshot = {};
_key = dk;
}
future<> close() noexcept {
return _underlying.close();
}
};
}
|
#include "renderer_robot_plan.hpp"
#include "RobotPlanListener.hpp"
#include "plan_execution_gui_utils.hpp"
#include "plan_approval_gui_utils.hpp"
#define RENDERER_NAME "Robot Plan Display"
#define PARAM_SELECTION "Enable Selection"
#define PARAM_WIRE "Show BBoxs For Meshes"
#define PARAM_HIDE "Hide Plan"
#define PARAM_USE_COLORMAP "Use Colormap"
#define PARAM_PLAN_PART "Part of Plan"
#define PARAM_SHOW_DURING_CONTROL "During Control"
#define DRAW_PERSIST_SEC 4
#define PARAM_START_PLAN "Start Planning"
#define PARAM_SEND_COMMITTED_PLAN "Send Plan"
#define PARAM_NEW_VICON_PLAN "Get Vicon Plan"
#define PARAM_ADJUST_ENDSTATE "Adjust end keyframe"
#define PARAM_SHOW_FULLPLAN "Show Full Plan"
#define PARAM_SHOW_KEYFRAMES "Show Keyframes"
#define PARAM_SSE_KP_LEFT "Kp_L"
#define PARAM_SSE_KD_LEFT "Kd_L"
#define PARAM_SSE_KP_RIGHT "Kp_R"
#define PARAM_SSE_KD_RIGHT "Kd_R"
#define PARAM_KP_DEFAULT 5
#define PARAM_KD_DEFAULT 1
using namespace std;
using namespace boost;
using namespace renderer_robot_plan;
using namespace renderer_robot_plan_gui_utils;
static void
_renderer_free (BotRenderer *super)
{
RendererRobotPlan *self = (RendererRobotPlan*) super->user;
free(self);
}
//=================================
// Convert number to jet colour coordinates
// In: number between 0-->1
// Out: rgb jet colours 0->1
// http://metastine.com/2011/01/implementing-a-continuous-jet-colormap-function-in-glsl/
static inline void jet_rgb(float value,float rgb[]){
float fourValue = (float) 4 * value;
rgb[0] = std::min(fourValue - 1.5, -fourValue + 4.5);
rgb[1] = std::min(fourValue - 0.5, -fourValue + 3.5);
rgb[2] = std::min(fourValue + 0.5, -fourValue + 2.5);
for (int i=0;i<3;i++){
if (rgb[i] <0) {
rgb[i] =0;
}else if (rgb[i] >1){
rgb[i] =1;
}
}
}
static void
draw_state(BotViewer *viewer, BotRenderer *super, uint i, float rgb[]){
float c[3] = {0.3,0.3,0.6}; // light blue
float alpha = 0.4;
RendererRobotPlan *self = (RendererRobotPlan*) super->user;
if((self->use_colormap)&&(self->displayed_plan_index==-1)&&(!self->robotPlanListener->_is_manip_plan)) {
// Each model Jet: blue to red
float j = (float)i/ (self->robotPlanListener->_gl_robot_list.size() -1);
jet_rgb(j,c);
}else{
c[0] = rgb[0]; c[1] = rgb[1]; c[2] = rgb[2];
}
glColor4f(c[0],c[1],c[2], alpha);
self->robotPlanListener->_gl_robot_list[i]->show_bbox(self->visualize_bbox);
self->robotPlanListener->_gl_robot_list[i]->enable_link_selection(self->selection_enabled);
//if((*self->selection)!=" ")
self->robotPlanListener->_gl_robot_list[i]->highlight_link((*self->selection));
self->robotPlanListener->_gl_robot_list[i]->draw_body (c,alpha);
}
static void
draw_keyframe(BotViewer *viewer, BotRenderer *super, uint i){
float c_blue[3] = {0.3,0.3,0.6}; // light blue
float alpha = 0.7;
RendererRobotPlan *self = (RendererRobotPlan*) super->user;
float c[3];
if((self->use_colormap)) {
// Each model Jet: blue to red
float j = (float)i/ (self->robotPlanListener->_gl_robot_keyframe_list.size() -1);
jet_rgb(j,c);
}
else{
c[0] = c_blue[0];c[1] = c_blue[1];c[2] = c_blue[2];
}
if(self->robotPlanListener->_gl_left_hand->is_bodypose_adjustment_enabled())
alpha = 0.2;
glColor4f(c[0],c[1],c[2], alpha);
//self->robotPlanListener->_gl_robot_keyframe_list[i]->enable_link_selection(self->selection_enabled);
std::string selected_keyframe_name = " ";
//if(self->selected_keyframe_index!=-1)
if((*self->selection) != " ")
selected_keyframe_name = self->robotPlanListener->_gl_robot_keyframe_list[self->selected_keyframe_index]->_unique_name;
self->robotPlanListener->_gl_robot_keyframe_list[i]->highlight_body(selected_keyframe_name);
self->robotPlanListener->_gl_robot_keyframe_list[i]->draw_body(c,alpha);
if ((self->robotPlanListener->is_in_motion(i))&&(self->robotPlanListener->_gl_left_hand->is_bodypose_adjustment_enabled()))
{
alpha = 0.9;
self->robotPlanListener->_gl_left_hand->draw_body(c_blue,alpha);
self->robotPlanListener->_gl_right_hand->draw_body(c_blue,alpha);
self->robotPlanListener->_gl_left_foot->draw_body(c_blue,alpha);
self->robotPlanListener->_gl_right_foot->draw_body(c_blue,alpha);
}
}
static void
_renderer_draw (BotViewer *viewer, BotRenderer *super)
{
RendererRobotPlan *self = (RendererRobotPlan*) super->user;
// if hide is enabled - then dont draw the plan:
if (bot_gtk_param_widget_get_bool(self->pw, PARAM_HIDE)) {
return;
}
glEnable(GL_DEPTH_TEST);
//-draw
//glPointSize(5.0f);
//glBegin(GL_POINTS);
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_BLEND);
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
if((self->selection_enabled)&&(self->clicked)){
glLineWidth (3.0);
glPushMatrix();
glBegin(GL_LINES);
glVertex3f(self->ray_start[0], self->ray_start[1],self->ray_start[2]); // object coord
glVertex3f(self->ray_end[0], self->ray_end[1],self->ray_end[2]);
glEnd();
glPopMatrix();
}
int plan_size = self->robotPlanListener->_gl_robot_list.size();
if (plan_size ==0){ // nothing to renderer
// on receipt of a apprved footstep plan, the current plan is purged in waiting for a new walking plan.
// if any plan execution/approval dock's exist, they will be destroyed.
if(self->plan_execution_dock!=NULL){
gtk_widget_destroy(self->plan_execution_dock);
self->plan_execution_dock= NULL;
}
if(self->multiapprove_plan_execution_dock!=NULL)
{
gtk_widget_destroy(self->multiapprove_plan_execution_dock);
self->multiapprove_plan_execution_dock= NULL;
}
if(self->plan_approval_dock!=NULL){
gtk_widget_destroy(self->plan_approval_dock);
self->plan_approval_dock= NULL;
}
return;
}
// Show keyframes
if((self->show_keyframes)&&(self->robotPlanListener->_is_manip_plan)&&(self->robotPlanListener->_gl_robot_keyframe_list.size()>0))
{
for(uint i = 1; i < self->robotPlanListener->_gl_robot_keyframe_list.size(); i++)
{
draw_keyframe(viewer,super,i);
}
}
if (self->show_fullplan){
int max_num_states = 20;
int inc =1;
int totol_states = self->robotPlanListener->_gl_robot_list.size();
if ( totol_states > max_num_states) {
inc = ceil( totol_states/max_num_states);
inc = min(max(inc,1),max_num_states);
}
//std::cout << "totol_states is " << totol_states << "\n";
//std::cout << "inc is " << inc << "\n";
float c[3] = {0.3,0.3,0.6}; // light blue (holder)
for(uint i = 0; i < totol_states; i=i+inc){//_gl_robot_list.size(); i++){
draw_state(viewer,super,i,c);
}
self->displayed_plan_index = -1;
}else{
double plan_part = bot_gtk_param_widget_get_double(self->pw, PARAM_PLAN_PART);
uint w_plan = (uint) round(plan_part* (plan_size -1));
//printf(" Show around %f of %d %d\n", plan_part, plan_size, w_plan);
self->displayed_plan_index = w_plan;
float c[3] = {0.3,0.3,0.6}; // light blue
draw_state(viewer,super,w_plan,c);
}
if(bot_gtk_param_widget_get_bool(self->pw, PARAM_SHOW_DURING_CONTROL) ){
if(self->robotPlanListener->_controller_status == drc::controller_status_t::WALKING){ // walking
int rx_plan_size = self->robotPlanListener->_received_plan.num_states;
int64_t last_plan_utime = self->robotPlanListener->_received_plan.plan[rx_plan_size-1].utime;
double current_plan_part = ((double) self->robotPlanListener->_controller_utime / last_plan_utime);
//printf ("controller time: %lld \n", self->robotPlanListener->_controller_utime);
//std::cout << self->robotPlanListener->_received_plan.num_states << " is rxd plan size\n";
//std::cout << plan_size << " is plan size\n";
//std::cout << last_plan_utime << " is last_plan_utime\n";
//std::cout << current_plan_part << " is current_plan_part\n";
if((current_plan_part >0.0 )&&(current_plan_part <1.0)){
double plan_part = bot_gtk_param_widget_get_double(self->pw, PARAM_PLAN_PART);
uint w_plan = (uint) round(current_plan_part* (plan_size -1));
//printf(" Show around %f of %d %d\n", plan_part, plan_size, w_plan);
self->displayed_plan_index = w_plan;
float c[3] = {0.6,0.3,0.3}; // light red
draw_state(viewer,super,w_plan,c);
}
}
}
if(self->robotPlanListener->is_multi_approval_plan())
{
if((self->multiapprove_plan_execution_dock==NULL)&&(!self->robotPlanListener->_is_manip_map))
spawn_plan_execution_dock(self);
}
else
{
if((self->plan_execution_dock==NULL)&&(!self->robotPlanListener->_is_manip_map))
spawn_plan_execution_dock(self);
}
if((self->plan_approval_dock==NULL)&&(self->robotPlanListener->_is_manip_map))
spawn_plan_approval_dock (self);
}
// temporary method: will be replaced later
static void publish_eegoal_to_start_planning(boost::shared_ptr<lcm::LCM> &_lcm, std::string channel)
{
drc::ee_goal_t goalmsg;
goalmsg.robot_name = "atlas";
goalmsg.root_name = "pelvis";
goalmsg.ee_name = "ee_plan_start";
double x,y,z,w;
// desired ee position in world frame
KDL::Frame T_body_ee;
T_body_ee = KDL::Frame::Identity();; // send them in world frame for now.
goalmsg.ee_goal_pos.translation.x = T_body_ee.p[0];
goalmsg.ee_goal_pos.translation.y = T_body_ee.p[1];
goalmsg.ee_goal_pos.translation.z = T_body_ee.p[2];
goalmsg.ee_goal_pos.rotation.x = 0;
goalmsg.ee_goal_pos.rotation.y = 0;
goalmsg.ee_goal_pos.rotation.z = 0;
goalmsg.ee_goal_pos.rotation.w = 1;
goalmsg.ee_goal_twist.linear_velocity.x = 0.0;
goalmsg.ee_goal_twist.linear_velocity.y = 0.0;
goalmsg.ee_goal_twist.linear_velocity.z = 0.0;
goalmsg.ee_goal_twist.angular_velocity.x = 0.0;
goalmsg.ee_goal_twist.angular_velocity.y = 0.0;
goalmsg.ee_goal_twist.angular_velocity.z = 0.0;
goalmsg.num_chain_joints =0;
// No specified posture bias
goalmsg.use_posture_bias = false;
goalmsg.joint_posture_bias.resize(goalmsg.num_chain_joints);
goalmsg.chain_joint_names.resize(goalmsg.num_chain_joints);
for(int i = 0; i < goalmsg.num_chain_joints; i++){
goalmsg.joint_posture_bias[i]=0;
goalmsg.chain_joint_names[i]= " ";
}
// Publish the message
goalmsg.halt_ee_controller = false;
_lcm->publish(channel, &goalmsg);
}
static void publish_manip_gain(boost::shared_ptr<lcm::LCM> &_lcm, std::string channel,int64_t utime, double Kp, double Kd, int ee_type)
{
drc::ee_manip_gain_t msg;
msg.utime = utime;
msg.is_leg = false;
msg.ee_type=ee_type;
msg.Kp=Kp;
msg.Kd=Kd;
_lcm->publish(channel, &msg);
}
//========================= Event Handling ================
static double pick_query (BotViewer *viewer, BotEventHandler *ehandler, const double ray_start[3], const double ray_dir[3])
{
RendererRobotPlan *self = (RendererRobotPlan*) ehandler->user;
if((self->selection_enabled==0)||(bot_gtk_param_widget_get_bool(self->pw, PARAM_HIDE))){
return -1.0;
}
//fprintf(stderr, "RobotStateRenderer Pick Query Active\n");
Eigen::Vector3f from,to;
from << ray_start[0], ray_start[1], ray_start[2];
Eigen::Vector3f plane_normal,plane_pt;
plane_normal << 0,0,1;
if(ray_start[2]<0)
plane_pt << 0,0,10;
else
plane_pt << 0,0,-10;
double lambda1 = ray_dir[0] * plane_normal[0]+
ray_dir[1] * plane_normal[1] +
ray_dir[2] * plane_normal[2];
// check for degenerate case where ray is (more or less) parallel to plane
if (fabs (lambda1) < 1e-9) return -1.0;
double lambda2 = (plane_pt[0] - ray_start[0]) * plane_normal[0] +
(plane_pt[1] - ray_start[1]) * plane_normal[1] +
(plane_pt[2] - ray_start[2]) * plane_normal[2];
double t = lambda2 / lambda1;// =1;
to << ray_start[0]+t*ray_dir[0], ray_start[1]+t*ray_dir[1], ray_start[2]+t*ray_dir[2];
self->ray_start = from;
self->ray_end = to;
self->ray_hit_t = t;
self->ray_hit_drag = to;
self->ray_hit = to;
//
Eigen::Vector3f hit_pt;
collision::Collision_Object * intersected_object = NULL;
double shortest_distance = -1;
self->selected_plan_index= 0;
if(self->robotPlanListener->_is_manip_plan) {
shortest_distance = get_shortest_distance_between_keyframes_and_markers(self,from,to);
}
else {
shortest_distance = get_shortest_distance_from_a_plan_frame(self,from,to);
}
//std::cout << "RobotStateRenderer distance " << -1.0 << std::endl;
return shortest_distance;
}
static int mouse_press (BotViewer *viewer, BotEventHandler *ehandler, const double ray_start[3], const double ray_dir[3], const GdkEventButton *event)
{
RendererRobotPlan *self = (RendererRobotPlan*) ehandler->user;
if((ehandler->picking==0)||(self->selection_enabled==0)){
//fprintf(stderr, "Ehandler Not active\n");
(*self->selection) = " ";
return 0;
}
// fprintf(stderr, "RobotPlanRenderer Ehandler Activated\n");
self->clicked = 1;
//fprintf(stderr, "Mouse Press : %f,%f\n",ray_start[0], ray_start[1]);
collision::Collision_Object * intersected_object = NULL;
if((self->robotPlanListener->_is_manip_plan)&&(self->selected_keyframe_index!=-1)&&(self->robotPlanListener->_gl_robot_keyframe_list.size()>0))
{
// cout << "keyframe: " << self->selected_keyframe_index << " " << self->robotPlanListener->_gl_robot_keyframe_list.size()<< endl;
self->robotPlanListener->_gl_robot_keyframe_list[self->selected_keyframe_index]->_collision_detector->ray_test( self->ray_start, self->ray_end, intersected_object );
if( intersected_object != NULL ){
std::cout << "prev selection :" << (*self->selection) << std::endl;
std::cout << "intersected :" << intersected_object->id().c_str() << std::endl;
(*self->selection) = std::string(intersected_object->id().c_str());
std::string body_name = self->robotPlanListener->_gl_robot_keyframe_list[self->selected_keyframe_index]->_unique_name;
self->robotPlanListener->_gl_robot_keyframe_list[self->selected_keyframe_index]->highlight_body(body_name);
//self->robotPlanListener->_gl_robot_keyframe_list[self->selected_keyframe_index]->highlight_link((*self->selection));
}
}
else{
self->robotPlanListener->_gl_robot_list[self->selected_plan_index]->_collision_detector->ray_test( self->ray_start, self->ray_end, intersected_object );
if( intersected_object != NULL ){
std::cout << "prev selection :" << (*self->selection) << std::endl;
std::cout << "intersected :" << intersected_object->id().c_str() << std::endl;
(*self->selection) = std::string(intersected_object->id().c_str());
self->robotPlanListener->_gl_robot_list[self->selected_plan_index]->highlight_link((*self->selection));
}
}
if((self->robotPlanListener->_is_manip_plan)&&(((*self->selection) != " ") || ((*self->marker_selection) != " "))&&(event->button==1) &&(event->type==GDK_2BUTTON_PRESS))
{
if((*self->marker_selection) == " ")
cout << "DblClk: " << (*self->selection) << endl;
else
cout << "DblClk on Marker: " << (*self->marker_selection) << endl;
/* if((*self->marker_selection) == " ")// dbl clk on keyframe then toogle
{ */
bool toggle=true;
if (self->robotPlanListener->is_in_motion(self->selected_keyframe_index)){
toggle = !self->robotPlanListener->_gl_left_hand->is_bodypose_adjustment_enabled();
}
self->robotPlanListener->set_in_motion_hands_state(self->selected_keyframe_index);
self->robotPlanListener->_gl_left_hand->enable_bodypose_adjustment(toggle);
self->robotPlanListener->_gl_right_hand->enable_bodypose_adjustment(toggle);
self->robotPlanListener->set_in_motion_feet_state(self->selected_keyframe_index);
self->robotPlanListener->_gl_left_foot->enable_bodypose_adjustment(toggle);
self->robotPlanListener->_gl_right_foot->enable_bodypose_adjustment(toggle);
if(!toggle){
(*self->marker_selection) = " ";
}
//}
// On double click create/toggle local copies of right and left sticky hand duplicates and spawn them with markers
return 1;// consumed if pop up comes up.
}
else if(((*self->marker_selection) != " "))
{
self->dragging = 1;
KDL::Frame T_world_ee;
if(self->is_hand_in_motion){
if(self->is_left_in_motion) {
T_world_ee = self->robotPlanListener->_gl_left_hand->_T_world_body;
}
else {
T_world_ee = self->robotPlanListener->_gl_right_hand->_T_world_body;
}
}
else{
if(self->is_left_in_motion) {
T_world_ee = self->robotPlanListener->_gl_left_foot->_T_world_body;
}
else {
T_world_ee = self->robotPlanListener->_gl_right_foot->_T_world_body;
}
}
self->marker_offset_on_press << self->ray_hit[0]-T_world_ee.p[0],self->ray_hit[1]-T_world_ee.p[1],self->ray_hit[2]-T_world_ee.p[2];
std::cout << "RendererRobotPlan: Event is consumed" << std::endl;
return 1;// consumed
}
bot_viewer_request_redraw(self->viewer);
return 0;
}
static int
mouse_release (BotViewer *viewer, BotEventHandler *ehandler, const double ray_start[3],
const double ray_dir[3], const GdkEventButton *event)
{
RendererRobotPlan *self = (RendererRobotPlan*) ehandler->user;
self->clicked = 0;
if((ehandler->picking==0)||(self->selection_enabled==0)){
//fprintf(stderr, "Ehandler Not active\n");
return 0;
}
if (self->dragging) {
self->dragging = 0;
string channel = "MANIP_PLAN_CONSTRAINT";
Eigen::Vector3f diff=self->ray_hit_drag-self->ray_hit;
double movement = diff.norm();
if(((*self->marker_selection) != " ")&&(movement>=1e-3)){
//cout << "publishing manip_plan_constraint \n";
publish_traj_opt_constraint(self,channel,self->selected_keyframe_index);
}
}
if (ehandler->picking==1)
ehandler->picking=0; //release picking(IMPORTANT)
bot_viewer_request_redraw(self->viewer);
return 0;
}
static int mouse_motion (BotViewer *viewer, BotEventHandler *ehandler, const double ray_start[3], const double ray_dir[3], const GdkEventMotion *event)
{
RendererRobotPlan *self = (RendererRobotPlan*) ehandler->user;
if((!self->dragging)||(ehandler->picking==0)){
return 0;
}
if((*self->marker_selection) != " "){
double t = self->ray_hit_t;
self->ray_hit_drag << ray_start[0]+t*ray_dir[0], ray_start[1]+t*ray_dir[1], ray_start[2]+t*ray_dir[2];
adjust_keyframe_on_marker_motion(self);
// cout << (*self->marker_selection) << ": mouse drag\n";
}
bot_viewer_request_redraw(self->viewer);
return 1;
}
// ------------------------END Event Handling-------------------------------------------
static void onRobotUtime (const lcm_recv_buf_t * buf, const char *channel,
const drc_utime_t *msg, void *user){
RendererRobotPlan *self = (RendererRobotPlan*) user;
self->robot_utime = msg->utime;
}
static void on_param_widget_changed(BotGtkParamWidget *pw, const char *name, void *user)
{
RendererRobotPlan *self = (RendererRobotPlan*) user;
if (! strcmp(name, PARAM_SELECTION)) {
self->selection_enabled = bot_gtk_param_widget_get_bool(pw, PARAM_SELECTION);
} else if(! strcmp(name, PARAM_WIRE)) {
self->visualize_bbox = bot_gtk_param_widget_get_bool(pw, PARAM_WIRE);
} else if(! strcmp(name,PARAM_USE_COLORMAP)) {
self->use_colormap = bot_gtk_param_widget_get_bool(pw, PARAM_USE_COLORMAP);
} else if(! strcmp(name,PARAM_USE_COLORMAP)) {
self->use_colormap= bot_gtk_param_widget_get_bool(pw, PARAM_USE_COLORMAP);
} else if(! strcmp(name,PARAM_ADJUST_ENDSTATE)) {
self->adjust_endstate = bot_gtk_param_widget_get_bool(pw, PARAM_ADJUST_ENDSTATE);
} else if(! strcmp(name,PARAM_SHOW_FULLPLAN)) {
self->show_fullplan = bot_gtk_param_widget_get_bool(pw, PARAM_SHOW_FULLPLAN);
} else if(! strcmp(name,PARAM_SHOW_KEYFRAMES)) {
self->show_keyframes = bot_gtk_param_widget_get_bool(pw, PARAM_SHOW_KEYFRAMES);
}else if(!strcmp(name,PARAM_START_PLAN)){
publish_eegoal_to_start_planning(self->lcm,"EE_PLAN_START");
}else if(!strcmp(name,PARAM_SEND_COMMITTED_PLAN)){
self->lcm->publish("COMMITTED_ROBOT_PLAN", &(self->robotPlanListener->_received_plan) );
}
else if(!strcmp(name,PARAM_SSE_KP_LEFT)){
double kp = bot_gtk_param_widget_get_double(self->pw, PARAM_SSE_KP_LEFT);
double kd = bot_gtk_param_widget_get_double(self->pw, PARAM_SSE_KD_LEFT);
publish_manip_gain(self->lcm,"COMMITTED_MANIP_GAIN",self->robot_utime,kp,kd,0);
}else if(!strcmp(name,PARAM_SSE_KD_LEFT)){
double kp = bot_gtk_param_widget_get_double(self->pw, PARAM_SSE_KP_LEFT);
double kd = bot_gtk_param_widget_get_double(self->pw, PARAM_SSE_KD_LEFT);
publish_manip_gain(self->lcm,"COMMITTED_MANIP_GAIN",self->robot_utime,kp,kd,0);
}
else if(!strcmp(name,PARAM_SSE_KP_RIGHT)){
double kp = bot_gtk_param_widget_get_double(self->pw, PARAM_SSE_KP_RIGHT);
double kd = bot_gtk_param_widget_get_double(self->pw, PARAM_SSE_KD_RIGHT);
publish_manip_gain(self->lcm,"COMMITTED_MANIP_GAIN",self->robot_utime,kp,kd,1);
}else if(!strcmp(name,PARAM_SSE_KD_RIGHT)){
double kp = bot_gtk_param_widget_get_double(self->pw, PARAM_SSE_KP_RIGHT);
double kd = bot_gtk_param_widget_get_double(self->pw, PARAM_SSE_KD_RIGHT);
publish_manip_gain(self->lcm,"COMMITTED_MANIP_GAIN",self->robot_utime,kp,kd,1);
}
else if(! strcmp(name, PARAM_NEW_VICON_PLAN)) {
drc::plan_collect_t msg;
msg.utime = self->robot_utime;//bot_timestamp_now();
msg.type = self->vicon_type;
msg.n_plan_samples = self->vicon_n_plan_samples;
msg.sample_period = self->vicon_sample_period;
self->lcm->publish("VICON_GET_PLAN", &msg);
bot_viewer_set_status_bar_message(self->viewer, "Sent VICON_GET_PLAN [nsamples: %d, period %fsec] @ %lld",msg.n_plan_samples, msg.sample_period, msg.utime);
}
bot_viewer_request_redraw(self->viewer);
}
void
setup_renderer_robot_plan(BotViewer *viewer, int render_priority, lcm_t *lcm, int operation_mode)
{
RendererRobotPlan *self = (RendererRobotPlan*) calloc (1, sizeof (RendererRobotPlan));
self->lcm = boost::shared_ptr<lcm::LCM>(new lcm::LCM(lcm));
self->robotPlanListener = boost::shared_ptr<RobotPlanListener>(new RobotPlanListener(self->lcm,
viewer, operation_mode));
BotRenderer *renderer = &self->renderer;
renderer->draw = _renderer_draw;
renderer->destroy = _renderer_free;
renderer->widget = bot_gtk_param_widget_new();
renderer->name = (char *) RENDERER_NAME;
if (operation_mode ==1){
renderer->name =(char *) "Robot Plan Loopback";
}else if(operation_mode ==2){
renderer->name =(char *) "Robot Plan LB Compressed";
}
renderer->user = self;
renderer->enabled = 1;
self->viewer = viewer;
// default Vicon plan sample values:
self->vicon_n_plan_samples = 20;
self->vicon_sample_period = 0.5;
self->pw = BOT_GTK_PARAM_WIDGET(renderer->widget);
// C-style subscribe:
drc_utime_t_subscribe(self->lcm->getUnderlyingLCM(),"ROBOT_UTIME",onRobotUtime,self);
bot_gtk_param_widget_add_booleans(self->pw, BOT_GTK_PARAM_WIDGET_CHECKBOX, PARAM_SELECTION, 0, NULL);
bot_gtk_param_widget_add_booleans(self->pw, BOT_GTK_PARAM_WIDGET_CHECKBOX, PARAM_WIRE, 0, NULL);
bot_gtk_param_widget_add_buttons(self->pw, PARAM_NEW_VICON_PLAN, NULL);
bot_gtk_param_widget_add_buttons(self->pw, PARAM_START_PLAN, NULL);
bot_gtk_param_widget_add_buttons(self->pw, PARAM_SEND_COMMITTED_PLAN, NULL);
bot_gtk_param_widget_add_booleans(self->pw, BOT_GTK_PARAM_WIDGET_CHECKBOX, PARAM_HIDE, 0, NULL);
bot_gtk_param_widget_add_booleans(self->pw, BOT_GTK_PARAM_WIDGET_CHECKBOX, PARAM_USE_COLORMAP, 0, NULL);
self->adjust_endstate = false;
bot_gtk_param_widget_add_booleans(self->pw, BOT_GTK_PARAM_WIDGET_CHECKBOX, PARAM_ADJUST_ENDSTATE, 0, NULL);
bot_gtk_param_widget_add_booleans(self->pw, BOT_GTK_PARAM_WIDGET_CHECKBOX, PARAM_SHOW_FULLPLAN, 0, NULL);
bot_gtk_param_widget_add_booleans(self->pw, BOT_GTK_PARAM_WIDGET_CHECKBOX, PARAM_SHOW_KEYFRAMES, 1, NULL);
bot_gtk_param_widget_add_double (self->pw, PARAM_PLAN_PART,
BOT_GTK_PARAM_WIDGET_SLIDER, 0, 1, 0.005, 1);
bot_gtk_param_widget_add_booleans(self->pw, BOT_GTK_PARAM_WIDGET_CHECKBOX, PARAM_SHOW_DURING_CONTROL, 1, NULL);
bot_gtk_param_widget_add_separator (self->pw,"Steady-State Error Compensation");
bot_gtk_param_widget_add_double (self->pw, PARAM_SSE_KP_LEFT,
BOT_GTK_PARAM_WIDGET_SLIDER, 0, 100, 1, PARAM_KP_DEFAULT);
bot_gtk_param_widget_add_double (self->pw, PARAM_SSE_KD_LEFT,
BOT_GTK_PARAM_WIDGET_SLIDER, 0, 100, 1, PARAM_KD_DEFAULT);
bot_gtk_param_widget_add_double (self->pw, PARAM_SSE_KP_RIGHT,
BOT_GTK_PARAM_WIDGET_SLIDER, 0, 100, 1, PARAM_KP_DEFAULT);
bot_gtk_param_widget_add_double (self->pw, PARAM_SSE_KD_RIGHT,
BOT_GTK_PARAM_WIDGET_SLIDER, 0, 100, 1, PARAM_KD_DEFAULT);
g_signal_connect(G_OBJECT(self->pw), "changed", G_CALLBACK(on_param_widget_changed), self);
self->selection_enabled = 1;
bot_gtk_param_widget_set_bool(self->pw, PARAM_SELECTION,self->selection_enabled);
self->use_colormap = 1;
bot_gtk_param_widget_set_bool(self->pw, PARAM_USE_COLORMAP,self->use_colormap);
self->clicked = 0;
self->dragging = 0;
self->selection = new std::string(" ");
self->marker_selection = new std::string(" ");
self->is_left_in_motion = true;
self->is_hand_in_motion = true;
self->visualize_bbox = false;
self->multiapprove_plan_execution_dock= NULL;
self->plan_execution_dock= NULL;
self->plan_approval_dock= NULL;
int plan_size = self->robotPlanListener->_gl_robot_list.size();
self->show_fullplan = bot_gtk_param_widget_get_bool(self->pw, PARAM_SHOW_FULLPLAN);
self->show_keyframes = bot_gtk_param_widget_get_bool(self->pw, PARAM_SHOW_KEYFRAMES);
double plan_part = bot_gtk_param_widget_get_double(self->pw, PARAM_PLAN_PART);
if ((self->show_fullplan)||(plan_size==0)){
self->displayed_plan_index = -1;
}else{
uint w_plan = (uint) round(plan_part* (plan_size -1));
self->displayed_plan_index = w_plan;
}
//bot_viewer_add_renderer(viewer, &self->renderer, render_priority);
bot_viewer_add_renderer_on_side(viewer,&self->renderer, render_priority, 0);
BotEventHandler *ehandler = &self->ehandler;
ehandler->name = (char*) RENDERER_NAME;
if (operation_mode==1){
ehandler->name =(char *) "Robot Plan Loopback";
}else if(operation_mode==2){
ehandler->name =(char *) "Robot Plan LB Compressed";
}
ehandler->enabled = 1;
ehandler->pick_query = pick_query;
ehandler->hover_query = NULL;
ehandler->mouse_press = mouse_press;
ehandler->mouse_release = mouse_release;
ehandler->mouse_motion = mouse_motion;
ehandler->user = self;
bot_viewer_add_event_handler(viewer, &self->ehandler, render_priority);
}
more #define's in robot plan renderer
git-svn-id: 767549f2a3626ae39d79f5348867a3ebb5082aca@4313 c7283977-0100-402a-a91a-fa70b306dbfe
#include "renderer_robot_plan.hpp"
#include "RobotPlanListener.hpp"
#include "plan_execution_gui_utils.hpp"
#include "plan_approval_gui_utils.hpp"
#define PARAM_KP_DEFAULT 5
#define PARAM_KD_DEFAULT 1
#define PARAM_KP_MIN 0
#define PARAM_KD_MIN 0
#define PARAM_KP_MAX 100
#define PARAM_KD_MAX 100
#define PARAM_KP_INC 1
#define PARAM_KD_INC 1
#define RENDERER_NAME "Robot Plan Display"
#define PARAM_SELECTION "Enable Selection"
#define PARAM_WIRE "Show BBoxs For Meshes"
#define PARAM_HIDE "Hide Plan"
#define PARAM_USE_COLORMAP "Use Colormap"
#define PARAM_PLAN_PART "Part of Plan"
#define PARAM_SHOW_DURING_CONTROL "During Control"
#define DRAW_PERSIST_SEC 4
#define PARAM_START_PLAN "Start Planning"
#define PARAM_SEND_COMMITTED_PLAN "Send Plan"
#define PARAM_NEW_VICON_PLAN "Get Vicon Plan"
#define PARAM_ADJUST_ENDSTATE "Adjust end keyframe"
#define PARAM_SHOW_FULLPLAN "Show Full Plan"
#define PARAM_SHOW_KEYFRAMES "Show Keyframes"
#define PARAM_SSE_KP_LEFT "Kp_L"
#define PARAM_SSE_KD_LEFT "Kd_L"
#define PARAM_SSE_KP_RIGHT "Kp_R"
#define PARAM_SSE_KD_RIGHT "Kd_R"
using namespace std;
using namespace boost;
using namespace renderer_robot_plan;
using namespace renderer_robot_plan_gui_utils;
static void
_renderer_free (BotRenderer *super)
{
RendererRobotPlan *self = (RendererRobotPlan*) super->user;
free(self);
}
//=================================
// Convert number to jet colour coordinates
// In: number between 0-->1
// Out: rgb jet colours 0->1
// http://metastine.com/2011/01/implementing-a-continuous-jet-colormap-function-in-glsl/
static inline void jet_rgb(float value,float rgb[]){
float fourValue = (float) 4 * value;
rgb[0] = std::min(fourValue - 1.5, -fourValue + 4.5);
rgb[1] = std::min(fourValue - 0.5, -fourValue + 3.5);
rgb[2] = std::min(fourValue + 0.5, -fourValue + 2.5);
for (int i=0;i<3;i++){
if (rgb[i] <0) {
rgb[i] =0;
}else if (rgb[i] >1){
rgb[i] =1;
}
}
}
static void
draw_state(BotViewer *viewer, BotRenderer *super, uint i, float rgb[]){
float c[3] = {0.3,0.3,0.6}; // light blue
float alpha = 0.4;
RendererRobotPlan *self = (RendererRobotPlan*) super->user;
if((self->use_colormap)&&(self->displayed_plan_index==-1)&&(!self->robotPlanListener->_is_manip_plan)) {
// Each model Jet: blue to red
float j = (float)i/ (self->robotPlanListener->_gl_robot_list.size() -1);
jet_rgb(j,c);
}else{
c[0] = rgb[0]; c[1] = rgb[1]; c[2] = rgb[2];
}
glColor4f(c[0],c[1],c[2], alpha);
self->robotPlanListener->_gl_robot_list[i]->show_bbox(self->visualize_bbox);
self->robotPlanListener->_gl_robot_list[i]->enable_link_selection(self->selection_enabled);
//if((*self->selection)!=" ")
self->robotPlanListener->_gl_robot_list[i]->highlight_link((*self->selection));
self->robotPlanListener->_gl_robot_list[i]->draw_body (c,alpha);
}
static void
draw_keyframe(BotViewer *viewer, BotRenderer *super, uint i){
float c_blue[3] = {0.3,0.3,0.6}; // light blue
float alpha = 0.7;
RendererRobotPlan *self = (RendererRobotPlan*) super->user;
float c[3];
if((self->use_colormap)) {
// Each model Jet: blue to red
float j = (float)i/ (self->robotPlanListener->_gl_robot_keyframe_list.size() -1);
jet_rgb(j,c);
}
else{
c[0] = c_blue[0];c[1] = c_blue[1];c[2] = c_blue[2];
}
if(self->robotPlanListener->_gl_left_hand->is_bodypose_adjustment_enabled())
alpha = 0.2;
glColor4f(c[0],c[1],c[2], alpha);
//self->robotPlanListener->_gl_robot_keyframe_list[i]->enable_link_selection(self->selection_enabled);
std::string selected_keyframe_name = " ";
//if(self->selected_keyframe_index!=-1)
if((*self->selection) != " ")
selected_keyframe_name = self->robotPlanListener->_gl_robot_keyframe_list[self->selected_keyframe_index]->_unique_name;
self->robotPlanListener->_gl_robot_keyframe_list[i]->highlight_body(selected_keyframe_name);
self->robotPlanListener->_gl_robot_keyframe_list[i]->draw_body(c,alpha);
if ((self->robotPlanListener->is_in_motion(i))&&(self->robotPlanListener->_gl_left_hand->is_bodypose_adjustment_enabled()))
{
alpha = 0.9;
self->robotPlanListener->_gl_left_hand->draw_body(c_blue,alpha);
self->robotPlanListener->_gl_right_hand->draw_body(c_blue,alpha);
self->robotPlanListener->_gl_left_foot->draw_body(c_blue,alpha);
self->robotPlanListener->_gl_right_foot->draw_body(c_blue,alpha);
}
}
static void
_renderer_draw (BotViewer *viewer, BotRenderer *super)
{
RendererRobotPlan *self = (RendererRobotPlan*) super->user;
// if hide is enabled - then dont draw the plan:
if (bot_gtk_param_widget_get_bool(self->pw, PARAM_HIDE)) {
return;
}
glEnable(GL_DEPTH_TEST);
//-draw
//glPointSize(5.0f);
//glBegin(GL_POINTS);
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_BLEND);
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
if((self->selection_enabled)&&(self->clicked)){
glLineWidth (3.0);
glPushMatrix();
glBegin(GL_LINES);
glVertex3f(self->ray_start[0], self->ray_start[1],self->ray_start[2]); // object coord
glVertex3f(self->ray_end[0], self->ray_end[1],self->ray_end[2]);
glEnd();
glPopMatrix();
}
int plan_size = self->robotPlanListener->_gl_robot_list.size();
if (plan_size ==0){ // nothing to renderer
// on receipt of a apprved footstep plan, the current plan is purged in waiting for a new walking plan.
// if any plan execution/approval dock's exist, they will be destroyed.
if(self->plan_execution_dock!=NULL){
gtk_widget_destroy(self->plan_execution_dock);
self->plan_execution_dock= NULL;
}
if(self->multiapprove_plan_execution_dock!=NULL)
{
gtk_widget_destroy(self->multiapprove_plan_execution_dock);
self->multiapprove_plan_execution_dock= NULL;
}
if(self->plan_approval_dock!=NULL){
gtk_widget_destroy(self->plan_approval_dock);
self->plan_approval_dock= NULL;
}
return;
}
// Show keyframes
if((self->show_keyframes)&&(self->robotPlanListener->_is_manip_plan)&&(self->robotPlanListener->_gl_robot_keyframe_list.size()>0))
{
for(uint i = 1; i < self->robotPlanListener->_gl_robot_keyframe_list.size(); i++)
{
draw_keyframe(viewer,super,i);
}
}
if (self->show_fullplan){
int max_num_states = 20;
int inc =1;
int totol_states = self->robotPlanListener->_gl_robot_list.size();
if ( totol_states > max_num_states) {
inc = ceil( totol_states/max_num_states);
inc = min(max(inc,1),max_num_states);
}
//std::cout << "totol_states is " << totol_states << "\n";
//std::cout << "inc is " << inc << "\n";
float c[3] = {0.3,0.3,0.6}; // light blue (holder)
for(uint i = 0; i < totol_states; i=i+inc){//_gl_robot_list.size(); i++){
draw_state(viewer,super,i,c);
}
self->displayed_plan_index = -1;
}else{
double plan_part = bot_gtk_param_widget_get_double(self->pw, PARAM_PLAN_PART);
uint w_plan = (uint) round(plan_part* (plan_size -1));
//printf(" Show around %f of %d %d\n", plan_part, plan_size, w_plan);
self->displayed_plan_index = w_plan;
float c[3] = {0.3,0.3,0.6}; // light blue
draw_state(viewer,super,w_plan,c);
}
if(bot_gtk_param_widget_get_bool(self->pw, PARAM_SHOW_DURING_CONTROL) ){
if(self->robotPlanListener->_controller_status == drc::controller_status_t::WALKING){ // walking
int rx_plan_size = self->robotPlanListener->_received_plan.num_states;
int64_t last_plan_utime = self->robotPlanListener->_received_plan.plan[rx_plan_size-1].utime;
double current_plan_part = ((double) self->robotPlanListener->_controller_utime / last_plan_utime);
//printf ("controller time: %lld \n", self->robotPlanListener->_controller_utime);
//std::cout << self->robotPlanListener->_received_plan.num_states << " is rxd plan size\n";
//std::cout << plan_size << " is plan size\n";
//std::cout << last_plan_utime << " is last_plan_utime\n";
//std::cout << current_plan_part << " is current_plan_part\n";
if((current_plan_part >0.0 )&&(current_plan_part <1.0)){
double plan_part = bot_gtk_param_widget_get_double(self->pw, PARAM_PLAN_PART);
uint w_plan = (uint) round(current_plan_part* (plan_size -1));
//printf(" Show around %f of %d %d\n", plan_part, plan_size, w_plan);
self->displayed_plan_index = w_plan;
float c[3] = {0.6,0.3,0.3}; // light red
draw_state(viewer,super,w_plan,c);
}
}
}
if(self->robotPlanListener->is_multi_approval_plan())
{
if((self->multiapprove_plan_execution_dock==NULL)&&(!self->robotPlanListener->_is_manip_map))
spawn_plan_execution_dock(self);
}
else
{
if((self->plan_execution_dock==NULL)&&(!self->robotPlanListener->_is_manip_map))
spawn_plan_execution_dock(self);
}
if((self->plan_approval_dock==NULL)&&(self->robotPlanListener->_is_manip_map))
spawn_plan_approval_dock (self);
}
// temporary method: will be replaced later
static void publish_eegoal_to_start_planning(boost::shared_ptr<lcm::LCM> &_lcm, std::string channel)
{
drc::ee_goal_t goalmsg;
goalmsg.robot_name = "atlas";
goalmsg.root_name = "pelvis";
goalmsg.ee_name = "ee_plan_start";
double x,y,z,w;
// desired ee position in world frame
KDL::Frame T_body_ee;
T_body_ee = KDL::Frame::Identity();; // send them in world frame for now.
goalmsg.ee_goal_pos.translation.x = T_body_ee.p[0];
goalmsg.ee_goal_pos.translation.y = T_body_ee.p[1];
goalmsg.ee_goal_pos.translation.z = T_body_ee.p[2];
goalmsg.ee_goal_pos.rotation.x = 0;
goalmsg.ee_goal_pos.rotation.y = 0;
goalmsg.ee_goal_pos.rotation.z = 0;
goalmsg.ee_goal_pos.rotation.w = 1;
goalmsg.ee_goal_twist.linear_velocity.x = 0.0;
goalmsg.ee_goal_twist.linear_velocity.y = 0.0;
goalmsg.ee_goal_twist.linear_velocity.z = 0.0;
goalmsg.ee_goal_twist.angular_velocity.x = 0.0;
goalmsg.ee_goal_twist.angular_velocity.y = 0.0;
goalmsg.ee_goal_twist.angular_velocity.z = 0.0;
goalmsg.num_chain_joints =0;
// No specified posture bias
goalmsg.use_posture_bias = false;
goalmsg.joint_posture_bias.resize(goalmsg.num_chain_joints);
goalmsg.chain_joint_names.resize(goalmsg.num_chain_joints);
for(int i = 0; i < goalmsg.num_chain_joints; i++){
goalmsg.joint_posture_bias[i]=0;
goalmsg.chain_joint_names[i]= " ";
}
// Publish the message
goalmsg.halt_ee_controller = false;
_lcm->publish(channel, &goalmsg);
}
static void publish_manip_gain(boost::shared_ptr<lcm::LCM> &_lcm, std::string channel,int64_t utime, double Kp, double Kd, int ee_type)
{
drc::ee_manip_gain_t msg;
msg.utime = utime;
msg.is_leg = false;
msg.ee_type=ee_type;
msg.Kp=Kp;
msg.Kd=Kd;
_lcm->publish(channel, &msg);
}
//========================= Event Handling ================
static double pick_query (BotViewer *viewer, BotEventHandler *ehandler, const double ray_start[3], const double ray_dir[3])
{
RendererRobotPlan *self = (RendererRobotPlan*) ehandler->user;
if((self->selection_enabled==0)||(bot_gtk_param_widget_get_bool(self->pw, PARAM_HIDE))){
return -1.0;
}
//fprintf(stderr, "RobotStateRenderer Pick Query Active\n");
Eigen::Vector3f from,to;
from << ray_start[0], ray_start[1], ray_start[2];
Eigen::Vector3f plane_normal,plane_pt;
plane_normal << 0,0,1;
if(ray_start[2]<0)
plane_pt << 0,0,10;
else
plane_pt << 0,0,-10;
double lambda1 = ray_dir[0] * plane_normal[0]+
ray_dir[1] * plane_normal[1] +
ray_dir[2] * plane_normal[2];
// check for degenerate case where ray is (more or less) parallel to plane
if (fabs (lambda1) < 1e-9) return -1.0;
double lambda2 = (plane_pt[0] - ray_start[0]) * plane_normal[0] +
(plane_pt[1] - ray_start[1]) * plane_normal[1] +
(plane_pt[2] - ray_start[2]) * plane_normal[2];
double t = lambda2 / lambda1;// =1;
to << ray_start[0]+t*ray_dir[0], ray_start[1]+t*ray_dir[1], ray_start[2]+t*ray_dir[2];
self->ray_start = from;
self->ray_end = to;
self->ray_hit_t = t;
self->ray_hit_drag = to;
self->ray_hit = to;
//
Eigen::Vector3f hit_pt;
collision::Collision_Object * intersected_object = NULL;
double shortest_distance = -1;
self->selected_plan_index= 0;
if(self->robotPlanListener->_is_manip_plan) {
shortest_distance = get_shortest_distance_between_keyframes_and_markers(self,from,to);
}
else {
shortest_distance = get_shortest_distance_from_a_plan_frame(self,from,to);
}
//std::cout << "RobotStateRenderer distance " << -1.0 << std::endl;
return shortest_distance;
}
static int mouse_press (BotViewer *viewer, BotEventHandler *ehandler, const double ray_start[3], const double ray_dir[3], const GdkEventButton *event)
{
RendererRobotPlan *self = (RendererRobotPlan*) ehandler->user;
if((ehandler->picking==0)||(self->selection_enabled==0)){
//fprintf(stderr, "Ehandler Not active\n");
(*self->selection) = " ";
return 0;
}
// fprintf(stderr, "RobotPlanRenderer Ehandler Activated\n");
self->clicked = 1;
//fprintf(stderr, "Mouse Press : %f,%f\n",ray_start[0], ray_start[1]);
collision::Collision_Object * intersected_object = NULL;
if((self->robotPlanListener->_is_manip_plan)&&(self->selected_keyframe_index!=-1)&&(self->robotPlanListener->_gl_robot_keyframe_list.size()>0))
{
// cout << "keyframe: " << self->selected_keyframe_index << " " << self->robotPlanListener->_gl_robot_keyframe_list.size()<< endl;
self->robotPlanListener->_gl_robot_keyframe_list[self->selected_keyframe_index]->_collision_detector->ray_test( self->ray_start, self->ray_end, intersected_object );
if( intersected_object != NULL ){
std::cout << "prev selection :" << (*self->selection) << std::endl;
std::cout << "intersected :" << intersected_object->id().c_str() << std::endl;
(*self->selection) = std::string(intersected_object->id().c_str());
std::string body_name = self->robotPlanListener->_gl_robot_keyframe_list[self->selected_keyframe_index]->_unique_name;
self->robotPlanListener->_gl_robot_keyframe_list[self->selected_keyframe_index]->highlight_body(body_name);
//self->robotPlanListener->_gl_robot_keyframe_list[self->selected_keyframe_index]->highlight_link((*self->selection));
}
}
else{
self->robotPlanListener->_gl_robot_list[self->selected_plan_index]->_collision_detector->ray_test( self->ray_start, self->ray_end, intersected_object );
if( intersected_object != NULL ){
std::cout << "prev selection :" << (*self->selection) << std::endl;
std::cout << "intersected :" << intersected_object->id().c_str() << std::endl;
(*self->selection) = std::string(intersected_object->id().c_str());
self->robotPlanListener->_gl_robot_list[self->selected_plan_index]->highlight_link((*self->selection));
}
}
if((self->robotPlanListener->_is_manip_plan)&&(((*self->selection) != " ") || ((*self->marker_selection) != " "))&&(event->button==1) &&(event->type==GDK_2BUTTON_PRESS))
{
if((*self->marker_selection) == " ")
cout << "DblClk: " << (*self->selection) << endl;
else
cout << "DblClk on Marker: " << (*self->marker_selection) << endl;
/* if((*self->marker_selection) == " ")// dbl clk on keyframe then toogle
{ */
bool toggle=true;
if (self->robotPlanListener->is_in_motion(self->selected_keyframe_index)){
toggle = !self->robotPlanListener->_gl_left_hand->is_bodypose_adjustment_enabled();
}
self->robotPlanListener->set_in_motion_hands_state(self->selected_keyframe_index);
self->robotPlanListener->_gl_left_hand->enable_bodypose_adjustment(toggle);
self->robotPlanListener->_gl_right_hand->enable_bodypose_adjustment(toggle);
self->robotPlanListener->set_in_motion_feet_state(self->selected_keyframe_index);
self->robotPlanListener->_gl_left_foot->enable_bodypose_adjustment(toggle);
self->robotPlanListener->_gl_right_foot->enable_bodypose_adjustment(toggle);
if(!toggle){
(*self->marker_selection) = " ";
}
//}
// On double click create/toggle local copies of right and left sticky hand duplicates and spawn them with markers
return 1;// consumed if pop up comes up.
}
else if(((*self->marker_selection) != " "))
{
self->dragging = 1;
KDL::Frame T_world_ee;
if(self->is_hand_in_motion){
if(self->is_left_in_motion) {
T_world_ee = self->robotPlanListener->_gl_left_hand->_T_world_body;
}
else {
T_world_ee = self->robotPlanListener->_gl_right_hand->_T_world_body;
}
}
else{
if(self->is_left_in_motion) {
T_world_ee = self->robotPlanListener->_gl_left_foot->_T_world_body;
}
else {
T_world_ee = self->robotPlanListener->_gl_right_foot->_T_world_body;
}
}
self->marker_offset_on_press << self->ray_hit[0]-T_world_ee.p[0],self->ray_hit[1]-T_world_ee.p[1],self->ray_hit[2]-T_world_ee.p[2];
std::cout << "RendererRobotPlan: Event is consumed" << std::endl;
return 1;// consumed
}
bot_viewer_request_redraw(self->viewer);
return 0;
}
static int
mouse_release (BotViewer *viewer, BotEventHandler *ehandler, const double ray_start[3],
const double ray_dir[3], const GdkEventButton *event)
{
RendererRobotPlan *self = (RendererRobotPlan*) ehandler->user;
self->clicked = 0;
if((ehandler->picking==0)||(self->selection_enabled==0)){
//fprintf(stderr, "Ehandler Not active\n");
return 0;
}
if (self->dragging) {
self->dragging = 0;
string channel = "MANIP_PLAN_CONSTRAINT";
Eigen::Vector3f diff=self->ray_hit_drag-self->ray_hit;
double movement = diff.norm();
if(((*self->marker_selection) != " ")&&(movement>=1e-3)){
//cout << "publishing manip_plan_constraint \n";
publish_traj_opt_constraint(self,channel,self->selected_keyframe_index);
}
}
if (ehandler->picking==1)
ehandler->picking=0; //release picking(IMPORTANT)
bot_viewer_request_redraw(self->viewer);
return 0;
}
static int mouse_motion (BotViewer *viewer, BotEventHandler *ehandler, const double ray_start[3], const double ray_dir[3], const GdkEventMotion *event)
{
RendererRobotPlan *self = (RendererRobotPlan*) ehandler->user;
if((!self->dragging)||(ehandler->picking==0)){
return 0;
}
if((*self->marker_selection) != " "){
double t = self->ray_hit_t;
self->ray_hit_drag << ray_start[0]+t*ray_dir[0], ray_start[1]+t*ray_dir[1], ray_start[2]+t*ray_dir[2];
adjust_keyframe_on_marker_motion(self);
// cout << (*self->marker_selection) << ": mouse drag\n";
}
bot_viewer_request_redraw(self->viewer);
return 1;
}
// ------------------------END Event Handling-------------------------------------------
static void onRobotUtime (const lcm_recv_buf_t * buf, const char *channel,
const drc_utime_t *msg, void *user){
RendererRobotPlan *self = (RendererRobotPlan*) user;
self->robot_utime = msg->utime;
}
static void on_param_widget_changed(BotGtkParamWidget *pw, const char *name, void *user)
{
RendererRobotPlan *self = (RendererRobotPlan*) user;
if (! strcmp(name, PARAM_SELECTION)) {
self->selection_enabled = bot_gtk_param_widget_get_bool(pw, PARAM_SELECTION);
} else if(! strcmp(name, PARAM_WIRE)) {
self->visualize_bbox = bot_gtk_param_widget_get_bool(pw, PARAM_WIRE);
} else if(! strcmp(name,PARAM_USE_COLORMAP)) {
self->use_colormap = bot_gtk_param_widget_get_bool(pw, PARAM_USE_COLORMAP);
} else if(! strcmp(name,PARAM_USE_COLORMAP)) {
self->use_colormap= bot_gtk_param_widget_get_bool(pw, PARAM_USE_COLORMAP);
} else if(! strcmp(name,PARAM_ADJUST_ENDSTATE)) {
self->adjust_endstate = bot_gtk_param_widget_get_bool(pw, PARAM_ADJUST_ENDSTATE);
} else if(! strcmp(name,PARAM_SHOW_FULLPLAN)) {
self->show_fullplan = bot_gtk_param_widget_get_bool(pw, PARAM_SHOW_FULLPLAN);
} else if(! strcmp(name,PARAM_SHOW_KEYFRAMES)) {
self->show_keyframes = bot_gtk_param_widget_get_bool(pw, PARAM_SHOW_KEYFRAMES);
}else if(!strcmp(name,PARAM_START_PLAN)){
publish_eegoal_to_start_planning(self->lcm,"EE_PLAN_START");
}else if(!strcmp(name,PARAM_SEND_COMMITTED_PLAN)){
self->lcm->publish("COMMITTED_ROBOT_PLAN", &(self->robotPlanListener->_received_plan) );
}
else if(!strcmp(name,PARAM_SSE_KP_LEFT)){
double kp = bot_gtk_param_widget_get_double(self->pw, PARAM_SSE_KP_LEFT);
double kd = bot_gtk_param_widget_get_double(self->pw, PARAM_SSE_KD_LEFT);
publish_manip_gain(self->lcm,"COMMITTED_MANIP_GAIN",self->robot_utime,kp,kd,0);
}else if(!strcmp(name,PARAM_SSE_KD_LEFT)){
double kp = bot_gtk_param_widget_get_double(self->pw, PARAM_SSE_KP_LEFT);
double kd = bot_gtk_param_widget_get_double(self->pw, PARAM_SSE_KD_LEFT);
publish_manip_gain(self->lcm,"COMMITTED_MANIP_GAIN",self->robot_utime,kp,kd,0);
}
else if(!strcmp(name,PARAM_SSE_KP_RIGHT)){
double kp = bot_gtk_param_widget_get_double(self->pw, PARAM_SSE_KP_RIGHT);
double kd = bot_gtk_param_widget_get_double(self->pw, PARAM_SSE_KD_RIGHT);
publish_manip_gain(self->lcm,"COMMITTED_MANIP_GAIN",self->robot_utime,kp,kd,1);
}else if(!strcmp(name,PARAM_SSE_KD_RIGHT)){
double kp = bot_gtk_param_widget_get_double(self->pw, PARAM_SSE_KP_RIGHT);
double kd = bot_gtk_param_widget_get_double(self->pw, PARAM_SSE_KD_RIGHT);
publish_manip_gain(self->lcm,"COMMITTED_MANIP_GAIN",self->robot_utime,kp,kd,1);
}
else if(! strcmp(name, PARAM_NEW_VICON_PLAN)) {
drc::plan_collect_t msg;
msg.utime = self->robot_utime;//bot_timestamp_now();
msg.type = self->vicon_type;
msg.n_plan_samples = self->vicon_n_plan_samples;
msg.sample_period = self->vicon_sample_period;
self->lcm->publish("VICON_GET_PLAN", &msg);
bot_viewer_set_status_bar_message(self->viewer, "Sent VICON_GET_PLAN [nsamples: %d, period %fsec] @ %lld",msg.n_plan_samples, msg.sample_period, msg.utime);
}
bot_viewer_request_redraw(self->viewer);
}
void
setup_renderer_robot_plan(BotViewer *viewer, int render_priority, lcm_t *lcm, int operation_mode)
{
RendererRobotPlan *self = (RendererRobotPlan*) calloc (1, sizeof (RendererRobotPlan));
self->lcm = boost::shared_ptr<lcm::LCM>(new lcm::LCM(lcm));
self->robotPlanListener = boost::shared_ptr<RobotPlanListener>(new RobotPlanListener(self->lcm,
viewer, operation_mode));
BotRenderer *renderer = &self->renderer;
renderer->draw = _renderer_draw;
renderer->destroy = _renderer_free;
renderer->widget = bot_gtk_param_widget_new();
renderer->name = (char *) RENDERER_NAME;
if (operation_mode ==1){
renderer->name =(char *) "Robot Plan Loopback";
}else if(operation_mode ==2){
renderer->name =(char *) "Robot Plan LB Compressed";
}
renderer->user = self;
renderer->enabled = 1;
self->viewer = viewer;
// default Vicon plan sample values:
self->vicon_n_plan_samples = 20;
self->vicon_sample_period = 0.5;
self->pw = BOT_GTK_PARAM_WIDGET(renderer->widget);
// C-style subscribe:
drc_utime_t_subscribe(self->lcm->getUnderlyingLCM(),"ROBOT_UTIME",onRobotUtime,self);
bot_gtk_param_widget_add_booleans(self->pw, BOT_GTK_PARAM_WIDGET_CHECKBOX, PARAM_SELECTION, 0, NULL);
bot_gtk_param_widget_add_booleans(self->pw, BOT_GTK_PARAM_WIDGET_CHECKBOX, PARAM_WIRE, 0, NULL);
bot_gtk_param_widget_add_buttons(self->pw, PARAM_NEW_VICON_PLAN, NULL);
bot_gtk_param_widget_add_buttons(self->pw, PARAM_START_PLAN, NULL);
bot_gtk_param_widget_add_buttons(self->pw, PARAM_SEND_COMMITTED_PLAN, NULL);
bot_gtk_param_widget_add_booleans(self->pw, BOT_GTK_PARAM_WIDGET_CHECKBOX, PARAM_HIDE, 0, NULL);
bot_gtk_param_widget_add_booleans(self->pw, BOT_GTK_PARAM_WIDGET_CHECKBOX, PARAM_USE_COLORMAP, 0, NULL);
self->adjust_endstate = false;
bot_gtk_param_widget_add_booleans(self->pw, BOT_GTK_PARAM_WIDGET_CHECKBOX, PARAM_ADJUST_ENDSTATE, 0, NULL);
bot_gtk_param_widget_add_booleans(self->pw, BOT_GTK_PARAM_WIDGET_CHECKBOX, PARAM_SHOW_FULLPLAN, 0, NULL);
bot_gtk_param_widget_add_booleans(self->pw, BOT_GTK_PARAM_WIDGET_CHECKBOX, PARAM_SHOW_KEYFRAMES, 1, NULL);
bot_gtk_param_widget_add_double (self->pw, PARAM_PLAN_PART,
BOT_GTK_PARAM_WIDGET_SLIDER, 0, 1, 0.005, 1);
bot_gtk_param_widget_add_booleans(self->pw, BOT_GTK_PARAM_WIDGET_CHECKBOX, PARAM_SHOW_DURING_CONTROL, 1, NULL);
bot_gtk_param_widget_add_separator (self->pw,"Steady-State Error Compensation");
bot_gtk_param_widget_add_double (self->pw, PARAM_SSE_KP_LEFT,
BOT_GTK_PARAM_WIDGET_SLIDER, PARAM_KP_MIN, PARAM_KP_MAX, PARAM_KP_INC, PARAM_KP_DEFAULT);
bot_gtk_param_widget_add_double (self->pw, PARAM_SSE_KD_LEFT,
BOT_GTK_PARAM_WIDGET_SLIDER, PARAM_KP_MIN, PARAM_KD_MAX, PARAM_KD_INC, PARAM_KD_DEFAULT);
bot_gtk_param_widget_add_double (self->pw, PARAM_SSE_KP_RIGHT,
BOT_GTK_PARAM_WIDGET_SLIDER, PARAM_KP_MIN, PARAM_KP_MAX, PARAM_KP_INC, PARAM_KP_DEFAULT);
bot_gtk_param_widget_add_double (self->pw, PARAM_SSE_KD_RIGHT,
BOT_GTK_PARAM_WIDGET_SLIDER, PARAM_KP_MIN, PARAM_KD_MAX, PARAM_KD_INC, PARAM_KD_DEFAULT);
g_signal_connect(G_OBJECT(self->pw), "changed", G_CALLBACK(on_param_widget_changed), self);
self->selection_enabled = 1;
bot_gtk_param_widget_set_bool(self->pw, PARAM_SELECTION,self->selection_enabled);
self->use_colormap = 1;
bot_gtk_param_widget_set_bool(self->pw, PARAM_USE_COLORMAP,self->use_colormap);
self->clicked = 0;
self->dragging = 0;
self->selection = new std::string(" ");
self->marker_selection = new std::string(" ");
self->is_left_in_motion = true;
self->is_hand_in_motion = true;
self->visualize_bbox = false;
self->multiapprove_plan_execution_dock= NULL;
self->plan_execution_dock= NULL;
self->plan_approval_dock= NULL;
int plan_size = self->robotPlanListener->_gl_robot_list.size();
self->show_fullplan = bot_gtk_param_widget_get_bool(self->pw, PARAM_SHOW_FULLPLAN);
self->show_keyframes = bot_gtk_param_widget_get_bool(self->pw, PARAM_SHOW_KEYFRAMES);
double plan_part = bot_gtk_param_widget_get_double(self->pw, PARAM_PLAN_PART);
if ((self->show_fullplan)||(plan_size==0)){
self->displayed_plan_index = -1;
}else{
uint w_plan = (uint) round(plan_part* (plan_size -1));
self->displayed_plan_index = w_plan;
}
//bot_viewer_add_renderer(viewer, &self->renderer, render_priority);
bot_viewer_add_renderer_on_side(viewer,&self->renderer, render_priority, 0);
BotEventHandler *ehandler = &self->ehandler;
ehandler->name = (char*) RENDERER_NAME;
if (operation_mode==1){
ehandler->name =(char *) "Robot Plan Loopback";
}else if(operation_mode==2){
ehandler->name =(char *) "Robot Plan LB Compressed";
}
ehandler->enabled = 1;
ehandler->pick_query = pick_query;
ehandler->hover_query = NULL;
ehandler->mouse_press = mouse_press;
ehandler->mouse_release = mouse_release;
ehandler->mouse_motion = mouse_motion;
ehandler->user = self;
bot_viewer_add_event_handler(viewer, &self->ehandler, render_priority);
}
|
//===-- SwiftExpressionParser.cpp -------------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "SwiftExpressionParser.h"
#include "SwiftASTManipulator.h"
#include "SwiftREPLMaterializer.h"
#include "SwiftSILManipulator.h"
#include "SwiftUserExpression.h"
#include "Plugins/ExpressionParser/Swift/SwiftDiagnostic.h"
#include "Plugins/ExpressionParser/Swift/SwiftExpressionVariable.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ModuleList.h"
#include "lldb/Core/ModuleSpec.h"
#include "lldb/Core/ValueObject.h"
#include "lldb/Expression/DiagnosticManager.h"
#include "lldb/Expression/Expression.h"
#include "lldb/Expression/ExpressionSourceCode.h"
#include "lldb/Expression/IRExecutionUnit.h"
#include "lldb/Symbol/CompileUnit.h"
#include "lldb/Symbol/SymbolVendor.h"
#include "lldb/Symbol/Type.h"
#include "lldb/Symbol/VariableList.h"
#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/StackFrame.h"
#include "lldb/Target/SwiftLanguageRuntime.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/Stream.h"
#include "llvm-c/Analysis.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/Basic/Module.h"
#include "clang/Rewrite/Core/RewriteBuffer.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/DiagnosticConsumer.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/Module.h"
#include "swift/AST/ModuleLoader.h"
#include "swift/Demangling/Demangle.h"
#include "swift/Basic/PrimarySpecificPaths.h"
#include "swift/Basic/SourceManager.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/Frontend/Frontend.h"
#include "swift/Parse/LocalContext.h"
#include "swift/Parse/PersistentParserState.h"
#include "swift/SIL/SILDebuggerClient.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILModule.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/Serialization/SerializedModuleLoader.h"
#include "swift/Subsystems.h"
using namespace lldb_private;
SwiftExpressionParser::SwiftExpressionParser(
ExecutionContextScope *exe_scope, Expression &expr,
const EvaluateExpressionOptions &options)
: ExpressionParser(exe_scope, expr, options.GetGenerateDebugInfo()),
m_expr(expr), m_triple(), m_llvm_context(), m_module(),
m_execution_unit_sp(), m_swift_ast_context(NULL), m_sc(),
m_stack_frame_wp(), m_options(options) {
assert(expr.Language() == lldb::eLanguageTypeSwift);
// TODO This code is copied from ClangExpressionParser.cpp.
// Factor this out into common code.
lldb::TargetSP target_sp;
if (exe_scope) {
target_sp = exe_scope->CalculateTarget();
lldb::StackFrameSP stack_frame = exe_scope->CalculateStackFrame();
if (stack_frame) {
m_stack_frame_wp = stack_frame;
m_sc = stack_frame->GetSymbolContext(lldb::eSymbolContextEverything);
} else {
m_sc.target_sp = target_sp;
}
}
if (target_sp && target_sp->GetArchitecture().IsValid()) {
std::string triple = target_sp->GetArchitecture().GetTriple().str();
int dash_count = 0;
for (size_t i = 0; i < triple.size(); ++i) {
if (triple[i] == '-')
dash_count++;
if (dash_count == 3) {
triple.resize(i);
break;
}
}
m_triple = triple;
} else {
m_triple = llvm::sys::getDefaultTargetTriple();
}
if (target_sp) {
m_swift_ast_context = llvm::cast_or_null<SwiftASTContext>(
target_sp->GetScratchTypeSystemForLanguage(nullptr,
lldb::eLanguageTypeSwift));
}
}
static void DescribeFileUnit(Stream &s, swift::FileUnit *file_unit) {
s.PutCString("kind = ");
switch (file_unit->getKind()) {
default: { s.PutCString("<unknown>"); }
case swift::FileUnitKind::Source: {
s.PutCString("Source, ");
if (swift::SourceFile *source_file =
llvm::dyn_cast<swift::SourceFile>(file_unit)) {
s.Printf("filename = '%s', ", source_file->getFilename().str().c_str());
s.PutCString("source file kind = ");
switch (source_file->Kind) {
case swift::SourceFileKind::Library:
s.PutCString("Library");
case swift::SourceFileKind::Main:
s.PutCString("Main");
case swift::SourceFileKind::REPL:
s.PutCString("REPL");
case swift::SourceFileKind::SIL:
s.PutCString("SIL");
}
}
} break;
case swift::FileUnitKind::Builtin: {
s.PutCString("Builtin");
} break;
case swift::FileUnitKind::SerializedAST:
case swift::FileUnitKind::ClangModule: {
s.PutCString("SerializedAST, ");
swift::LoadedFile *loaded_file = llvm::cast<swift::LoadedFile>(file_unit);
s.Printf("filename = '%s'", loaded_file->getFilename().str().c_str());
} break;
};
}
// Gets the full module name from the module passed in.
static void GetNameFromModule(swift::ModuleDecl *module, std::string &result) {
result.clear();
if (module) {
const char *name = module->getName().get();
if (!name)
return;
result.append(name);
const clang::Module *clang_module = module->findUnderlyingClangModule();
// At present, there doesn't seem to be any way to get the full module path
// from the Swift side.
if (!clang_module)
return;
for (const clang::Module *cur_module = clang_module->Parent; cur_module;
cur_module = cur_module->Parent) {
if (!cur_module->Name.empty()) {
result.insert(0, 1, '.');
result.insert(0, cur_module->Name);
}
}
}
}
// Largely lifted from swift::performAutoImport, but serves our own nefarious
// purposes.
bool SwiftExpressionParser::PerformAutoImport(swift::SourceFile &source_file,
bool user_imports,
Status &error) {
Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
const std::vector<ConstString> *cu_modules = nullptr;
CompileUnit *compile_unit = m_sc.comp_unit;
if (compile_unit)
cu_modules = &compile_unit->GetImportedModules();
llvm::SmallVector<swift::ModuleDecl::ImportedModule, 2> imported_modules;
llvm::SmallVector<std::pair<swift::ModuleDecl::ImportedModule,
swift::SourceFile::ImportOptions>,
2>
additional_imports;
source_file.getImportedModules(imported_modules,
swift::ModuleDecl::ImportFilter::All);
std::set<ConstString> loaded_modules;
auto load_one_module = [this, log, &loaded_modules, &imported_modules,
&additional_imports,
&error](const ConstString &module_name) {
error.Clear();
if (loaded_modules.count(module_name))
return true;
if (log)
log->Printf("[PerformAutoImport] Importing module %s",
module_name.AsCString());
loaded_modules.insert(module_name);
swift::ModuleDecl *swift_module = nullptr;
lldb::StackFrameSP this_frame_sp(m_stack_frame_wp.lock());
if (module_name == ConstString(m_swift_ast_context->GetClangImporter()
->getImportedHeaderModule()
->getName()
.str()))
swift_module =
m_swift_ast_context->GetClangImporter()->getImportedHeaderModule();
else if (this_frame_sp) {
lldb::ProcessSP process_sp(this_frame_sp->CalculateProcess());
if (process_sp)
swift_module = m_swift_ast_context->FindAndLoadModule(
module_name, *process_sp.get(), error);
} else
swift_module = m_swift_ast_context->GetModule(module_name, error);
if (!swift_module || !error.Success() ||
m_swift_ast_context->HasFatalErrors()) {
if (log)
log->Printf("[PerformAutoImport] Couldnt import module %s: %s",
module_name.AsCString(), error.AsCString());
if (!swift_module || m_swift_ast_context->HasFatalErrors()) {
return false;
}
}
if (log) {
log->Printf("Importing %s with source files:", module_name.AsCString());
for (swift::FileUnit *file_unit : swift_module->getFiles()) {
StreamString ss;
DescribeFileUnit(ss, file_unit);
log->Printf(" %s", ss.GetData());
}
}
additional_imports.push_back(std::make_pair(
std::make_pair(swift::ModuleDecl::AccessPathTy(), swift_module),
swift::SourceFile::ImportOptions()));
imported_modules.push_back(
std::make_pair(swift::ModuleDecl::AccessPathTy(), swift_module));
return true;
};
if (!user_imports) {
if (!load_one_module(ConstString("Swift")))
return false;
if (cu_modules) {
for (const ConstString &module_name : *cu_modules) {
if (!load_one_module(module_name))
return false;
}
}
} else {
llvm::SmallVector<swift::ModuleDecl::ImportedModule, 2> parsed_imports;
source_file.getImportedModules(parsed_imports,
swift::ModuleDecl::ImportFilter::All);
SwiftPersistentExpressionState *persistent_expression_state =
llvm::cast<SwiftPersistentExpressionState>(
m_sc.target_sp->GetPersistentExpressionStateForLanguage(
lldb::eLanguageTypeSwift));
for (auto module_pair : parsed_imports) {
swift::ModuleDecl *module = module_pair.second;
if (module) {
std::string module_name;
GetNameFromModule(module, module_name);
if (!module_name.empty()) {
ConstString module_const_str(module_name);
if (log)
log->Printf("[PerformAutoImport] Performing auto import on found "
"module: %s.\n",
module_name.c_str());
if (!load_one_module(module_const_str))
return false;
if (1 /* How do we tell we are in REPL or playground mode? */) {
persistent_expression_state->AddHandLoadedModule(module_const_str);
}
}
}
}
// Finally get the hand-loaded modules from the
// SwiftPersistentExpressionState and load them into this context:
if (!persistent_expression_state->RunOverHandLoadedModules(load_one_module))
return false;
}
source_file.addImports(additional_imports);
return true;
}
class VariableMetadataPersistent
: public SwiftASTManipulatorBase::VariableMetadata {
public:
VariableMetadataPersistent(lldb::ExpressionVariableSP &persistent_variable_sp)
: m_persistent_variable_sp(persistent_variable_sp) {}
static constexpr unsigned Type() { return 'Pers'; }
virtual unsigned GetType() { return Type(); }
lldb::ExpressionVariableSP m_persistent_variable_sp;
};
class VariableMetadataVariable
: public SwiftASTManipulatorBase::VariableMetadata {
public:
VariableMetadataVariable(lldb::VariableSP &variable_sp)
: m_variable_sp(variable_sp) {}
static constexpr unsigned Type() { return 'Vari'; }
virtual unsigned GetType() { return Type(); }
lldb::VariableSP m_variable_sp;
};
static CompilerType ImportType(SwiftASTContext &target_context,
CompilerType source_type) {
SwiftASTContext *swift_ast_ctx =
llvm::dyn_cast_or_null<SwiftASTContext>(source_type.GetTypeSystem());
if (swift_ast_ctx == nullptr)
return CompilerType();
if (swift_ast_ctx == &target_context)
return source_type;
Status error, mangled_error;
CompilerType target_type;
// First try to get the type by using the mangled name,
// That will save the mangling step ImportType would have to do:
ConstString type_name = source_type.GetTypeName();
ConstString mangled_counterpart;
bool found_counterpart = type_name.GetMangledCounterpart(mangled_counterpart);
if (found_counterpart)
target_type = target_context.GetTypeFromMangledTypename(
mangled_counterpart.GetCString(), mangled_error);
if (!target_type.IsValid())
target_type = target_context.ImportType(source_type, error);
return target_type;
}
namespace {
class LLDBNameLookup : public swift::SILDebuggerClient {
public:
LLDBNameLookup(SwiftExpressionParser &parser, swift::SourceFile &source_file,
SwiftExpressionParser::SILVariableMap &variable_map,
SymbolContext &sc)
: SILDebuggerClient(source_file.getASTContext()), m_parser(parser),
m_log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)),
m_source_file(source_file), m_variable_map(variable_map), m_sc(sc) {
source_file.getParentModule()->setDebugClient(this);
if (m_sc.target_sp) {
m_persistent_vars = llvm::cast<SwiftPersistentExpressionState>(
m_sc.target_sp->GetPersistentExpressionStateForLanguage(
lldb::eLanguageTypeSwift));
}
}
virtual ~LLDBNameLookup() {}
virtual bool shouldGlobalize(swift::Identifier Name, swift::DeclKind Kind) {
if (m_parser.GetOptions().GetREPLEnabled())
return true;
else {
// Extensions have to be globalized, there's no way to mark them as local
// to the function, since their
// name is the name of the thing being extended...
if (Kind == swift::DeclKind::Extension)
return true;
// Operators need to be parsed at the global scope regardless of name.
if (Kind == swift::DeclKind::Func && Name.isOperator())
return true;
const char *name_cstr = Name.get();
if (name_cstr && name_cstr[0] == '$') {
if (m_log)
m_log->Printf("[LLDBNameLookup::shouldGlobalize] Returning true to "
"globalizing %s",
name_cstr);
return true;
}
}
return false;
}
virtual void didGlobalize(swift::Decl *decl) {
swift::ValueDecl *value_decl = swift::dyn_cast<swift::ValueDecl>(decl);
if (value_decl) {
// It seems weird to be asking this again, but some DeclKinds must be
// moved to
// the source-file level to be legal. But we don't want to register them
// with
// lldb unless they are of the kind lldb explicitly wants to globalize.
if (shouldGlobalize(value_decl->getBaseName().getIdentifier(),
value_decl->getKind()))
m_staged_decls.AddDecl(value_decl, false, ConstString());
}
}
virtual bool lookupOverrides(swift::DeclBaseName Name, swift::DeclContext *DC,
swift::SourceLoc Loc, bool IsTypeLookup,
ResultVector &RV) {
static unsigned counter = 0;
unsigned count = counter++;
if (m_log) {
m_log->Printf("[LLDBNameLookup::lookupOverrides(%u)] Searching for %s",
count, Name.getIdentifier().get());
}
return false;
}
virtual bool lookupAdditions(swift::DeclBaseName Name, swift::DeclContext *DC,
swift::SourceLoc Loc, bool IsTypeLookup,
ResultVector &RV) {
static unsigned counter = 0;
unsigned count = counter++;
StringRef NameStr = Name.getIdentifier().str();
if (m_log) {
m_log->Printf("[LLDBNameLookup::lookupAdditions (%u)] Searching for %s",
count, Name.getIdentifier().str().str().c_str());
}
ConstString name_const_str(NameStr);
std::vector<swift::ValueDecl *> results;
// First look up the matching Decl's we've made in this compile, then pass
// that list to the
// persistent decls, which will only add decls it has that are NOT
// equivalent to the decls
// we made locally.
m_staged_decls.FindMatchingDecls(name_const_str, results);
// Next look up persistent decls matching this name. Then, if we are in the
// plain expression parser, and we
// aren't looking at a debugger variable, filter out persistent results of
// the same kind as one found by the
// ordinary lookup mechanism in the parser . The problem
// we are addressing here is the case where the user has entered the REPL
// while in an ordinary debugging session
// to play around. While there, e.g., they define a class that happens to
// have the same name as one in the
// program, then in some other context "expr" will call the class they've
// defined, not the one in the program
// itself would use. Plain "expr" should behave as much like code in the
// program would, so we want to favor
// entities of the same DeclKind & name from the program over ones defined
// in the REPL. For function decls we
// check the interface type and full name so we don't remove overloads that
// don't exist in the current scope.
//
// Note also, we only do this for the persistent decls. Anything in the
// "staged" list has been defined in this
// expr setting and so is more local than local.
bool skip_results_with_matching_kind =
!(m_parser.GetOptions().GetREPLEnabled() ||
m_parser.GetOptions().GetPlaygroundTransformEnabled() ||
(!NameStr.empty() && NameStr.front() == '$'));
size_t num_external_results = RV.size();
if (skip_results_with_matching_kind && num_external_results > 0) {
std::vector<swift::ValueDecl *> persistent_results;
m_persistent_vars->GetSwiftPersistentDecls(name_const_str,
persistent_results);
size_t num_persistent_results = persistent_results.size();
for (size_t idx = 0; idx < num_persistent_results; idx++) {
swift::ValueDecl *value_decl = persistent_results[idx];
if (!value_decl)
continue;
swift::DeclName value_decl_name = value_decl->getFullName();
swift::DeclKind value_decl_kind = value_decl->getKind();
swift::CanType value_interface_type =
value_decl->getInterfaceType()->getCanonicalType();
bool is_function = swift::isa<swift::AbstractFunctionDecl>(value_decl);
bool skip_it = false;
for (size_t rv_idx = 0; rv_idx < num_external_results; rv_idx++) {
if (swift::ValueDecl *rv_decl = RV[rv_idx].getValueDecl()) {
if (value_decl_kind == rv_decl->getKind()) {
if (is_function) {
swift::DeclName rv_full_name = rv_decl->getFullName();
if (rv_full_name.matchesRef(value_decl_name)) {
// If the full names match, make sure the interface types
// match:
if (rv_decl->getInterfaceType()->getCanonicalType() ==
value_interface_type)
skip_it = true;
}
} else {
skip_it = true;
}
if (skip_it)
break;
}
}
}
if (!skip_it)
results.push_back(value_decl);
}
} else {
m_persistent_vars->GetSwiftPersistentDecls(name_const_str, results);
}
for (size_t idx = 0; idx < results.size(); idx++) {
swift::ValueDecl *value_decl = results[idx];
assert(&DC->getASTContext() ==
&value_decl->getASTContext()); // no import required
RV.push_back(swift::LookupResultEntry(value_decl));
}
return results.size() > 0;
}
virtual swift::SILValue emitLValueForVariable(swift::VarDecl *var,
swift::SILBuilder &builder) {
SwiftSILManipulator manipulator(builder);
swift::Identifier variable_name = var->getName();
ConstString variable_const_string(variable_name.get());
SwiftExpressionParser::SILVariableMap::iterator vi =
m_variable_map.find(variable_const_string.AsCString());
if (vi == m_variable_map.end())
return swift::SILValue();
return manipulator.emitLValueForVariable(var, vi->second);
}
SwiftPersistentExpressionState::SwiftDeclMap &GetStagedDecls() {
return m_staged_decls;
}
virtual swift::Identifier getPreferredPrivateDiscriminator() {
if (m_sc.comp_unit) {
if (lldb_private::Module *module = m_sc.module_sp.get()) {
if (lldb_private::SymbolVendor *symbol_vendor =
module->GetSymbolVendor()) {
std::string private_discriminator_string;
if (symbol_vendor->GetCompileOption("-private-discriminator",
private_discriminator_string,
m_sc.comp_unit)) {
return m_source_file.getASTContext().getIdentifier(
private_discriminator_string);
}
}
}
}
return swift::Identifier();
}
private:
SwiftExpressionParser &m_parser;
Log *m_log;
swift::SourceFile &m_source_file;
SwiftExpressionParser::SILVariableMap &m_variable_map;
SymbolContext m_sc;
SwiftPersistentExpressionState *m_persistent_vars = nullptr;
SwiftPersistentExpressionState::SwiftDeclMap
m_staged_decls; // We stage the decls we are globalize in this map.
// They will get copied over to the SwiftPersistentVariable
// store if the parse succeeds.
};
} // END Anonymous namespace
static void
AddRequiredAliases(Block *block, lldb::StackFrameSP &stack_frame_sp,
SwiftASTContext &swift_ast_context,
SwiftASTManipulator &manipulator,
const Expression::SwiftGenericInfo &generic_info) {
// First, emit the typealias for "$__lldb_context"
do {
if (!block)
break;
Function *function = block->CalculateSymbolContextFunction();
if (!function)
break;
constexpr bool can_create = true;
Block &function_block(function->GetBlock(can_create));
lldb::VariableListSP variable_list_sp(
function_block.GetBlockVariableList(true));
if (!variable_list_sp)
break;
lldb::VariableSP self_var_sp(
variable_list_sp->FindVariable(ConstString("self")));
if (!self_var_sp)
break;
CompilerType self_type;
if (stack_frame_sp) {
lldb::ValueObjectSP valobj_sp =
stack_frame_sp->GetValueObjectForFrameVariable(
self_var_sp, lldb::eNoDynamicValues);
if (valobj_sp)
self_type = valobj_sp->GetCompilerType();
}
if (!self_type.IsValid()) {
if (Type *type = self_var_sp->GetType()) {
self_type = type->GetForwardCompilerType();
}
}
if (!self_type.IsValid() ||
!llvm::isa<SwiftASTContext>(self_type.GetTypeSystem()))
break;
// Import before getting the unbound version, because the unbound version
// may not be in the mangled name map
CompilerType imported_self_type = ImportType(swift_ast_context, self_type);
if (!imported_self_type.IsValid())
break;
// This might be a referenced type, in which case we really want to extend
// the referent:
imported_self_type =
llvm::cast<SwiftASTContext>(imported_self_type.GetTypeSystem())
->GetReferentType(imported_self_type);
// If we are extending a generic class it's going to be a metatype, and we
// have to grab the instance type:
imported_self_type =
llvm::cast<SwiftASTContext>(imported_self_type.GetTypeSystem())
->GetInstanceType(imported_self_type.GetOpaqueQualType());
Flags imported_self_type_flags(imported_self_type.GetTypeInfo());
// If 'self' is the Self archetype, resolve it to the actual metatype it is
if (SwiftASTContext::IsSelfArchetypeType(imported_self_type)) {
SwiftLanguageRuntime *swift_runtime =
stack_frame_sp->GetThread()->GetProcess()->GetSwiftLanguageRuntime();
if (CompilerType concrete_self_type = swift_runtime->GetConcreteType(
stack_frame_sp.get(), ConstString("Self"))) {
if (SwiftASTContext *concrete_self_type_ast_ctx =
llvm::dyn_cast_or_null<SwiftASTContext>(
concrete_self_type.GetTypeSystem())) {
imported_self_type = concrete_self_type_ast_ctx->CreateMetatypeType(
concrete_self_type);
imported_self_type_flags.Reset(imported_self_type.GetTypeInfo());
imported_self_type =
ImportType(swift_ast_context, imported_self_type);
if (imported_self_type_flags.AllSet(lldb::eTypeIsSwift |
lldb::eTypeIsMetatype)) {
imported_self_type = imported_self_type.GetInstanceType();
}
}
}
}
// Get the instance type:
if (imported_self_type_flags.AllSet(lldb::eTypeIsSwift |
lldb::eTypeIsMetatype)) {
imported_self_type = imported_self_type.GetInstanceType();
imported_self_type_flags.Reset(imported_self_type.GetTypeInfo());
}
swift::Type object_type =
swift::Type((swift::TypeBase *)(imported_self_type.GetOpaqueQualType()))
->getWithoutSpecifierType();
if (object_type.getPointer() &&
(object_type.getPointer() != imported_self_type.GetOpaqueQualType()))
imported_self_type = CompilerType(imported_self_type.GetTypeSystem(),
object_type.getPointer());
// If the type of 'self' is a bound generic type, get the unbound version
bool is_generic = imported_self_type_flags.AllSet(lldb::eTypeIsSwift |
lldb::eTypeIsGeneric);
bool is_bound = imported_self_type_flags.AllSet(lldb::eTypeIsSwift |
lldb::eTypeIsBound);
if (is_generic) {
if (is_bound)
imported_self_type = imported_self_type.GetUnboundType();
}
// if 'self' is a weak storage type, it must be an optional. Look through
// it and unpack the argument of "optional".
if (swift::WeakStorageType *weak_storage_type =
((swift::TypeBase *)imported_self_type.GetOpaqueQualType())
->getAs<swift::WeakStorageType>()) {
swift::Type referent_type = weak_storage_type->getReferentType();
swift::BoundGenericEnumType *optional_type =
referent_type->getAs<swift::BoundGenericEnumType>();
if (!optional_type) {
break;
}
swift::Type first_arg_type = optional_type->getGenericArgs()[0];
swift::ClassType *self_class_type =
first_arg_type->getAs<swift::ClassType>();
if (!self_class_type) {
break;
}
imported_self_type =
CompilerType(imported_self_type.GetTypeSystem(), self_class_type);
}
imported_self_type_flags.Reset(imported_self_type.GetTypeInfo());
if (imported_self_type_flags.AllClear(lldb::eTypeIsArchetype)) {
swift::ValueDecl *type_alias_decl = nullptr;
type_alias_decl = manipulator.MakeGlobalTypealias(
swift_ast_context.GetASTContext()->getIdentifier("$__lldb_context"),
imported_self_type);
if (!type_alias_decl) {
Log *log(
lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
if (log)
log->Printf("SEP:AddRequiredAliases: Failed to make the "
"$__lldb_context typealias.");
}
} else {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
if (log)
log->Printf("SEP:AddRequiredAliases: Failed to resolve the self "
"archetype - could not make the $__lldb_context "
"typealias.");
}
} while (0);
// Emit the typedefs
for (const Expression::SwiftGenericInfo::Binding &binding :
generic_info.function_bindings) {
CompilerType bound_type = binding.type;
if (!llvm::isa<SwiftASTContext>(bound_type.GetTypeSystem()))
continue;
CompilerType imported_bound_type =
ImportType(swift_ast_context, bound_type);
if (!imported_bound_type.IsValid())
continue;
std::string alias_name("$__lldb_typeof_generic_");
alias_name.append(binding.name);
swift::ValueDecl *type_alias_decl = manipulator.MakeGlobalTypealias(
swift_ast_context.GetASTContext()->getIdentifier(alias_name),
imported_bound_type);
if (!type_alias_decl)
continue;
}
}
static void CountLocals(
SymbolContext &sc, lldb::StackFrameSP &stack_frame_sp,
SwiftASTContext &ast_context,
llvm::SmallVectorImpl<SwiftASTManipulator::VariableInfo> &local_variables) {
std::set<ConstString> counted_names; // avoids shadowing
if (!sc.block && !sc.function)
return;
Block *block = sc.block;
Block *top_block = block->GetContainingInlinedBlock();
if (!top_block)
top_block = &sc.function->GetBlock(true);
static ConstString s_self_name("self");
SwiftLanguageRuntime *language_runtime = nullptr;
ExecutionContextScope *scope = nullptr;
if (stack_frame_sp) {
language_runtime =
stack_frame_sp->GetThread()->GetProcess()->GetSwiftLanguageRuntime();
scope = stack_frame_sp.get();
}
// The module scoped variables are stored at the CompUnit level, so after we
// go through the current context,
// then we have to take one more pass through the variables in the CompUnit.
bool handling_globals = false;
while (true) {
VariableList variables;
if (!handling_globals) {
constexpr bool can_create = true;
constexpr bool get_parent_variables = false;
constexpr bool stop_if_block_is_inlined_function = true;
block->AppendVariables(can_create, get_parent_variables,
stop_if_block_is_inlined_function,
[](Variable *) { return true; }, &variables);
} else {
if (sc.comp_unit) {
lldb::VariableListSP globals_sp = sc.comp_unit->GetVariableList(true);
if (globals_sp)
variables.AddVariables(globals_sp.get());
}
}
for (size_t vi = 0, ve = variables.GetSize(); vi != ve; ++vi) {
lldb::VariableSP variable_sp(variables.GetVariableAtIndex(vi));
const ConstString &name(variable_sp->GetName());
const char *name_cstring = variable_sp->GetName().GetCString();
if (name.IsEmpty())
continue;
if (counted_names.count(name))
continue;
CompilerType var_type;
if (stack_frame_sp) {
lldb::ValueObjectSP valobj_sp =
stack_frame_sp->GetValueObjectForFrameVariable(
variable_sp, lldb::eNoDynamicValues);
if (!valobj_sp || valobj_sp->GetError().Fail()) {
// Ignore the variable if we couldn't find its corresponding value
// object.
// TODO if the expression tries to use an ignored variable, produce a
// sensible error.
continue;
} else {
var_type = valobj_sp->GetCompilerType();
}
if (var_type.IsValid() && !SwiftASTContext::IsFullyRealized(var_type)) {
lldb::ValueObjectSP dynamic_valobj_sp =
valobj_sp->GetDynamicValue(lldb::eDynamicDontRunTarget);
if (!dynamic_valobj_sp || dynamic_valobj_sp->GetError().Fail()) {
continue;
}
}
}
if (!var_type.IsValid()) {
Type *var_lldb_type = variable_sp->GetType();
if (var_lldb_type)
var_type = var_lldb_type->GetFullCompilerType();
}
if (!var_type.IsValid())
continue;
if (!llvm::isa<SwiftASTContext>(var_type.GetTypeSystem()))
continue;
Status error;
CompilerType target_type = ast_context.ImportType(var_type, error);
// If the import failed, give up
if (!target_type.IsValid())
continue;
// Make sure to resolve all archetypes in the variable type.
if (language_runtime && stack_frame_sp)
target_type = language_runtime->DoArchetypeBindingForType(
*stack_frame_sp, target_type);
// If we couldn't fully realize the type, then we aren't going to get very
// far making a local out of it,
// so discard it here.
Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TYPES |
LIBLLDB_LOG_EXPRESSIONS));
if (!SwiftASTContext::IsFullyRealized(target_type)) {
if (log) {
log->Printf("Discarding local %s because we couldn't fully realize "
"it, our best attempt was: %s.",
name_cstring,
target_type.GetTypeName().AsCString("<unknown>"));
}
continue;
}
SwiftASTManipulatorBase::VariableMetadataSP metadata_sp(
new VariableMetadataVariable(variable_sp));
const char *overridden_name = name_cstring;
if (name == s_self_name) {
overridden_name = ConstString("$__lldb_injected_self").AsCString();
if (log) {
swift::TypeBase *swift_type =
(swift::TypeBase *)target_type.GetOpaqueQualType();
if (swift_type) {
std::string s;
llvm::raw_string_ostream ss(s);
swift_type->dump(ss);
ss.flush();
log->Printf("Adding injected self: type (%p) context(%p) is: %s",
swift_type, ast_context.GetASTContext(), s.c_str());
}
}
}
SwiftASTManipulator::VariableInfo variable_info(
target_type,
ast_context.GetASTContext()->getIdentifier(overridden_name),
metadata_sp,
swift::VarDecl::Specifier::Var);
local_variables.push_back(variable_info);
counted_names.insert(name);
}
if (handling_globals) {
// Okay, now we're done...
break;
} else if (block == top_block) {
// Now add the containing module block, that's what holds the module
// globals:
handling_globals = true;
} else
block = block->GetParent();
}
}
static void ResolveSpecialNames(
SymbolContext &sc, SwiftASTContext &ast_context,
llvm::SmallVectorImpl<swift::Identifier> &special_names,
llvm::SmallVectorImpl<SwiftASTManipulator::VariableInfo> &local_variables) {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
if (!sc.target_sp)
return;
SwiftPersistentExpressionState *persistent_state =
llvm::cast<SwiftPersistentExpressionState>(
sc.target_sp->GetPersistentExpressionStateForLanguage(
lldb::eLanguageTypeSwift));
std::set<ConstString> resolved_names;
for (swift::Identifier &name : special_names) {
ConstString name_cs = ConstString(name.str());
if (resolved_names.count(name_cs))
continue;
resolved_names.insert(name_cs);
if (log)
log->Printf("Resolving special name %s", name_cs.AsCString());
lldb::ExpressionVariableSP expr_var_sp =
persistent_state->GetVariable(name_cs);
if (!expr_var_sp)
continue;
CompilerType var_type = expr_var_sp->GetCompilerType();
if (!var_type.IsValid())
continue;
if (!llvm::isa<SwiftASTContext>(var_type.GetTypeSystem()))
continue;
CompilerType target_type;
Status error;
target_type = ast_context.ImportType(var_type, error);
if (!target_type)
continue;
SwiftASTManipulatorBase::VariableMetadataSP metadata_sp(
new VariableMetadataPersistent(expr_var_sp));
auto specifier = llvm::cast<SwiftExpressionVariable>(expr_var_sp.get())
->GetIsModifiable()
? swift::VarDecl::Specifier::Var
: swift::VarDecl::Specifier::Let;
SwiftASTManipulator::VariableInfo variable_info(
target_type, ast_context.GetASTContext()->getIdentifier(name.str()),
metadata_sp, specifier);
local_variables.push_back(variable_info);
}
}
//----------------------------------------------------------------------
// Diagnostics are part of the ShintASTContext and we must enable and
// disable colorization manually in the ShintASTContext. We need to
// ensure that if we modify the setting that we restore it to what it
// was. This class helps us to do that without having to intrument all
// returns from a function, like in SwiftExpressionParser::Parse(...).
//----------------------------------------------------------------------
class SetColorize {
public:
SetColorize(SwiftASTContext *swift_ast, bool colorize)
: m_swift_ast(swift_ast),
m_saved_colorize(swift_ast->SetColorizeDiagnostics(colorize)) {}
~SetColorize() { m_swift_ast->SetColorizeDiagnostics(m_saved_colorize); }
protected:
SwiftASTContext *m_swift_ast;
const bool m_saved_colorize;
};
/// Returns the buffer_id for the expression's source code.
static std::pair<unsigned, std::string>
CreateMainFile(SwiftASTContext &swift_ast_context, StringRef filename,
StringRef text, const EvaluateExpressionOptions &options) {
const bool generate_debug_info = options.GetGenerateDebugInfo();
swift_ast_context.SetGenerateDebugInfo(generate_debug_info
? swift::IRGenDebugInfoKind::Normal
: swift::IRGenDebugInfoKind::None);
swift::IRGenOptions &ir_gen_options = swift_ast_context.GetIRGenOptions();
if (generate_debug_info) {
std::string temp_source_path;
if (ExpressionSourceCode::SaveExpressionTextToTempFile(text, options,
temp_source_path)) {
auto error_or_buffer_ap =
llvm::MemoryBuffer::getFile(temp_source_path.c_str());
if (error_or_buffer_ap.getError() == std::error_condition()) {
unsigned buffer_id =
swift_ast_context.GetSourceManager().addNewSourceBuffer(
std::move(error_or_buffer_ap.get()));
llvm::SmallString<256> source_dir(temp_source_path);
llvm::sys::path::remove_filename(source_dir);
ir_gen_options.DebugCompilationDir = source_dir.str();
return {buffer_id, temp_source_path};
}
}
}
std::unique_ptr<llvm::MemoryBuffer> expr_buffer(
llvm::MemoryBuffer::getMemBufferCopy(text, filename));
unsigned buffer_id = swift_ast_context.GetSourceManager().addNewSourceBuffer(
std::move(expr_buffer));
return {buffer_id, filename};
}
unsigned SwiftExpressionParser::Parse(DiagnosticManager &diagnostic_manager,
uint32_t first_line, uint32_t last_line,
uint32_t line_offset) {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
// In the case of playgrounds, we turn all rewriting functionality off.
const bool repl = m_options.GetREPLEnabled();
const bool playground = m_options.GetPlaygroundTransformEnabled();
if (!m_swift_ast_context) {
diagnostic_manager.PutString(
eDiagnosticSeverityError,
"No AST context to parse into. Please parse with a target.\n");
return 1;
}
// Lazily get the clang importer if we can to make sure it exists in case we
// need it
if (!m_swift_ast_context->GetClangImporter()) {
diagnostic_manager.PutString(
eDiagnosticSeverityError,
"Swift expressions require OS X 10.10 / iOS 8 SDKs or later.\n");
return 1;
}
if (m_swift_ast_context->HasFatalErrors()) {
diagnostic_manager.PutString(eDiagnosticSeverityError,
"The AST context is in a fatal error state.");
return 1;
}
swift::ASTContext *ast_context = m_swift_ast_context->GetASTContext();
if (!ast_context) {
diagnostic_manager.PutString(
eDiagnosticSeverityError,
"Couldn't initialize the AST context. Please check your settings.");
return 1;
}
if (m_swift_ast_context->HasFatalErrors()) {
diagnostic_manager.PutString(eDiagnosticSeverityError,
"The AST context is in a fatal error state.");
return 1;
}
// If we are using the playground, hand import the necessary modules.
// FIXME: We won't have to do this once the playground adds import statements
// for the things it needs itself.
if (playground) {
SwiftPersistentExpressionState *persistent_state =
llvm::cast<SwiftPersistentExpressionState>(
m_sc.target_sp->GetPersistentExpressionStateForLanguage(
lldb::eLanguageTypeSwift));
persistent_state->AddHandLoadedModule(ConstString("Swift"));
}
// TODO find a way to get contraint-solver output sent to a stream so we can
// log it
// m_swift_ast_context->GetLanguageOptions().DebugConstraintSolver = true;
m_swift_ast_context->ClearDiagnostics();
// Make a class that will set/restore the colorize setting in the
// SwiftASTContext for us
// SetColorize colorize(m_swift_ast_context,
// stream.GetFlags().Test(Stream::eANSIColor));
m_swift_ast_context->GetLanguageOptions().DebuggerSupport = true;
m_swift_ast_context->GetLanguageOptions().EnableDollarIdentifiers =
true; // No longer part of debugger support, set it separately.
m_swift_ast_context->GetLanguageOptions().EnableAccessControl =
(repl || playground);
m_swift_ast_context->GetLanguageOptions().EnableTargetOSChecking = false;
{
lldb::StackFrameSP this_frame_sp(m_stack_frame_wp.lock());
if (this_frame_sp) {
lldb::ProcessSP process_sp(this_frame_sp->CalculateProcess());
if (process_sp) {
Status error;
if (!process_sp->GetObjCLanguageRuntime()) {
m_swift_ast_context->GetLanguageOptions().EnableObjCInterop = false;
}
}
}
}
if (repl || playground) {
m_swift_ast_context->GetLanguageOptions().Playground = true;
m_swift_ast_context->GetIRGenOptions().Playground = true;
} else {
m_swift_ast_context->GetLanguageOptions().Playground = true;
m_swift_ast_context->GetIRGenOptions().Playground = false;
}
// For the expression parser and REPL we want to relax the requirement that
// you put "try" in
// front of every expression that might throw.
if (!playground) {
m_swift_ast_context->GetLanguageOptions().EnableThrowWithoutTry = true;
}
m_swift_ast_context->GetIRGenOptions().OptMode
= swift::OptimizationMode::NoOptimization;
m_swift_ast_context->GetIRGenOptions().Verify =
false; // normally we'd like to verify, but unfortunately the verifier's
// error mode is abort().
bool created_main_file = false;
unsigned buffer_id;
std::string main_filename;
std::tie(buffer_id, main_filename) =
CreateMainFile(*m_swift_ast_context, repl ? "<REPL>" : "<EXPR>",
m_expr.Text(), m_options);
char expr_name_buf[32];
snprintf(expr_name_buf, sizeof(expr_name_buf), "__lldb_expr_%u",
m_options.GetExpressionNumber());
swift::Identifier module_id(ast_context->getIdentifier(expr_name_buf));
swift::ModuleDecl *module = swift::ModuleDecl::create(module_id, *ast_context);
const swift::SourceFile::ImplicitModuleImportKind implicit_import_kind =
swift::SourceFile::ImplicitModuleImportKind::Stdlib;
m_swift_ast_context->GetCompilerInvocation().getFrontendOptions().ModuleName =
expr_name_buf;
m_swift_ast_context->GetCompilerInvocation().getIRGenOptions().ModuleName =
expr_name_buf;
swift::SourceFileKind source_file_kind = swift::SourceFileKind::Library;
if (playground || repl) {
source_file_kind = swift::SourceFileKind::Main;
}
swift::SourceFile *source_file = new (*ast_context) swift::SourceFile(
*module, source_file_kind, buffer_id, implicit_import_kind,
/*Keep tokens*/false);
module->addFile(*source_file);
bool done = false;
SILVariableMap variable_map;
LLDBNameLookup *external_lookup =
new LLDBNameLookup(*this, *source_file, variable_map, m_sc);
// FIXME: This call is here just so that the we keep the DebuggerClients alive
// as long as the Module we are not
// inserting them in.
m_swift_ast_context->AddDebuggerClient(external_lookup);
swift::PersistentParserState persistent_state;
while (!done) {
swift::parseIntoSourceFile(*source_file, buffer_id, &done, nullptr,
&persistent_state);
if (m_swift_ast_context->HasErrors()) {
m_swift_ast_context->PrintDiagnostics(diagnostic_manager, buffer_id,
first_line, last_line, line_offset);
return 1;
}
}
// This currently crashes with Assertion failed: (BufferID != -1), function
// findBufferContainingLoc, file
// llvm/tools/swift/include/swift/Basic/SourceManager.h, line 92.
// if (log)
// {
// std::string s;
// llvm::raw_string_ostream ss(s);
// source_file->dump(ss);
// ss.flush();
//
// log->Printf("Source file after parsing:");
// log->PutCString(s.c_str());
// }
if (!done) {
diagnostic_manager.PutString(
eDiagnosticSeverityError,
"Parse did not consume the whole expression.");
return 1;
}
std::unique_ptr<SwiftASTManipulator> code_manipulator;
if (!playground) {
code_manipulator.reset(new SwiftASTManipulator(*source_file, repl));
code_manipulator->RewriteResult();
}
Status auto_import_error;
if (!PerformAutoImport(*source_file, false, auto_import_error)) {
diagnostic_manager.Printf(eDiagnosticSeverityError, "in auto-import:\n%s",
auto_import_error.AsCString());
return 1;
}
// Swift Modules that rely on shared libraries (not frameworks) don't record
// the link information in the
// swiftmodule file, so we can't really make them work without outside
// information. However, in the REPL you can
// added -L & -l options to the initial compiler startup, and we should dlopen
// anything that's been stuffed
// on there and hope it will be useful later on.
if (repl) {
lldb::StackFrameSP this_frame_sp(m_stack_frame_wp.lock());
if (this_frame_sp) {
lldb::ProcessSP process_sp(this_frame_sp->CalculateProcess());
if (process_sp) {
Status error;
m_swift_ast_context->LoadExtraDylibs(*process_sp.get(), error);
}
}
}
if (!playground && !repl) {
lldb::StackFrameSP stack_frame_sp = m_stack_frame_wp.lock();
bool local_context_is_swift = true;
if (m_sc.block) {
Function *function = m_sc.block->CalculateSymbolContextFunction();
if (function && function->GetLanguage() != lldb::eLanguageTypeSwift)
local_context_is_swift = false;
}
llvm::SmallVector<SwiftASTManipulator::VariableInfo, 5> local_variables;
if (local_context_is_swift) {
AddRequiredAliases(m_sc.block, stack_frame_sp, *m_swift_ast_context,
*code_manipulator, m_expr.GetSwiftGenericInfo());
// Register all local variables so that lookups to them resolve
CountLocals(m_sc, stack_frame_sp, *m_swift_ast_context, local_variables);
}
// Register all magic variables
llvm::SmallVector<swift::Identifier, 2> special_names;
llvm::StringRef persistent_var_prefix;
if (!repl)
persistent_var_prefix = "$";
code_manipulator->FindSpecialNames(special_names, persistent_var_prefix);
ResolveSpecialNames(m_sc, *m_swift_ast_context, special_names,
local_variables);
code_manipulator->AddExternalVariables(local_variables);
// This currently crashes with Assertion failed: (BufferID != -1), function
// findBufferContainingLoc, file
// llvm/tools/swift/include/swift/Basic/SourceManager.h, line 92.
// if (log)
// {
// std::string s;
// llvm::raw_string_ostream ss(s);
// source_file->dump(ss);
// ss.flush();
//
// log->Printf("Source file after code manipulation:");
// log->PutCString(s.c_str());
// }
stack_frame_sp.reset();
}
swift::performNameBinding(*source_file);
if (m_swift_ast_context->HasErrors()) {
m_swift_ast_context->PrintDiagnostics(diagnostic_manager, buffer_id,
first_line, last_line, line_offset);
return 1;
}
// Do the auto-importing after Name Binding, that's when the Imports for the
// source file are figured out.
{
std::lock_guard<std::recursive_mutex> global_context_locker(
IRExecutionUnit::GetLLVMGlobalContextMutex());
Status auto_import_error;
if (!PerformAutoImport(*source_file, true, auto_import_error)) {
diagnostic_manager.Printf(eDiagnosticSeverityError, "in auto-import:\n%s",
auto_import_error.AsCString());
return 1;
}
}
swift::TopLevelContext top_level_context; // not persistent because we're
// building source files one at a
// time
swift::OptionSet<swift::TypeCheckingFlags> type_checking_options;
swift::performTypeChecking(*source_file, top_level_context,
type_checking_options);
if (m_swift_ast_context->HasErrors()) {
m_swift_ast_context->PrintDiagnostics(diagnostic_manager, buffer_id,
first_line, last_line, line_offset);
return 1;
}
if (log) {
std::string s;
llvm::raw_string_ostream ss(s);
source_file->dump(ss);
ss.flush();
log->Printf("Source file after type checking:");
log->PutCString(s.c_str());
}
if (repl) {
code_manipulator->MakeDeclarationsPublic();
}
Status error;
if (!playground) {
code_manipulator->FixupResultAfterTypeChecking(error);
if (!error.Success()) {
diagnostic_manager.PutString(eDiagnosticSeverityError,
error.AsCString());
return 1;
}
} else {
swift::performPlaygroundTransform(*source_file, true);
swift::typeCheckExternalDefinitions(*source_file);
}
// I think we now have to do the name binding and type checking again, but
// there should be only the result
// variable to bind up at this point.
if (log) {
std::string s;
llvm::raw_string_ostream ss(s);
source_file->dump(ss);
ss.flush();
log->Printf("Source file after FixupResult:");
log->PutCString(s.c_str());
}
if (m_sc.target_sp && !playground) {
if (!code_manipulator->CheckPatternBindings()) // Do this first, so we don't
// pollute the persistent
// variable namespace
{
m_swift_ast_context->PrintDiagnostics(diagnostic_manager, buffer_id,
first_line, last_line, line_offset);
return 1;
}
Status error;
SwiftASTContext *scratch_ast_context =
m_sc.target_sp->GetScratchSwiftASTContext(error);
if (scratch_ast_context) {
SwiftPersistentExpressionState *persistent_state =
llvm::dyn_cast<SwiftPersistentExpressionState>(
scratch_ast_context->GetPersistentExpressionState());
llvm::SmallVector<size_t, 1> declaration_indexes;
code_manipulator->FindVariableDeclarations(declaration_indexes, repl);
for (size_t declaration_index : declaration_indexes) {
SwiftASTManipulator::VariableInfo &variable_info =
code_manipulator->GetVariableInfo()[declaration_index];
CompilerType imported_type =
ImportType(*scratch_ast_context, variable_info.GetType());
if (imported_type) {
lldb::ExpressionVariableSP persistent_variable =
persistent_state->AddNewlyConstructedVariable(
new SwiftExpressionVariable(
m_sc.target_sp.get(),
ConstString(variable_info.GetName().str()), imported_type,
m_sc.target_sp->GetArchitecture().GetByteOrder(),
m_sc.target_sp->GetArchitecture().GetAddressByteSize()));
if (repl) {
persistent_variable->m_flags |= ExpressionVariable::EVKeepInTarget;
persistent_variable->m_flags |=
ExpressionVariable::EVIsProgramReference;
} else {
persistent_variable->m_flags |=
ExpressionVariable::EVNeedsAllocation;
persistent_variable->m_flags |= ExpressionVariable::EVKeepInTarget;
llvm::cast<SwiftExpressionVariable>(persistent_variable.get())
->m_swift_flags |= SwiftExpressionVariable::EVSNeedsInit;
}
swift::VarDecl *decl = variable_info.GetDecl();
if (decl) {
if (decl->isLet()) {
llvm::cast<SwiftExpressionVariable>(persistent_variable.get())
->SetIsModifiable(false);
}
if (decl->getStorageKind() ==
swift::VarDecl::StorageKindTy::Computed) {
llvm::cast<SwiftExpressionVariable>(persistent_variable.get())
->SetIsComputed(true);
}
}
variable_info.m_metadata.reset(
new VariableMetadataPersistent(persistent_variable));
persistent_state->RegisterSwiftPersistentDecl(decl);
}
}
if (repl) {
llvm::SmallVector<swift::ValueDecl *, 1> non_variables;
code_manipulator->FindNonVariableDeclarations(non_variables);
for (swift::ValueDecl *decl : non_variables) {
persistent_state->RegisterSwiftPersistentDecl(decl);
}
}
}
}
if (!playground && !repl) {
code_manipulator->FixCaptures();
// This currently crashes with Assertion failed: (BufferID != -1), function
// findBufferContainingLoc, file
// llvm/tools/swift/include/swift/Basic/SourceManager.h, line 92.
// if (log)
// {
// std::string s;
// llvm::raw_string_ostream ss(s);
// source_file->dump(ss);
// ss.flush();
//
// log->Printf("Source file after capture fixing:");
// log->PutCString(s.c_str());
// }
if (log) {
log->Printf("Variables:");
for (const SwiftASTManipulatorBase::VariableInfo &variable :
code_manipulator->GetVariableInfo()) {
StreamString ss;
variable.Print(ss);
log->Printf(" %s", ss.GetData());
}
}
}
Materializer *materializer = m_expr.GetMaterializer();
if (materializer && !playground) {
for (SwiftASTManipulatorBase::VariableInfo &variable :
code_manipulator->GetVariableInfo()) {
uint64_t offset = 0;
bool needs_init = false;
bool is_result =
variable
.MetadataIs<SwiftASTManipulatorBase::VariableMetadataResult>();
bool is_error =
variable.MetadataIs<SwiftASTManipulatorBase::VariableMetadataError>();
SwiftUserExpression *user_expression = static_cast<SwiftUserExpression *>(
&m_expr); // this is the only thing that has a materializer
if (is_result || is_error) {
needs_init = true;
Status error;
if (repl) {
if (swift::TypeBase *swift_type =
(swift::TypeBase *)variable.GetType().GetOpaqueQualType()) {
if (!swift_type->getCanonicalType()->isVoid()) {
if (is_result)
offset = llvm::cast<SwiftREPLMaterializer>(materializer)
->AddREPLResultVariable(
variable.GetType(), variable.GetDecl(),
&user_expression->GetResultDelegate(), error);
else
offset = llvm::cast<SwiftREPLMaterializer>(materializer)
->AddREPLResultVariable(
variable.GetType(), variable.GetDecl(),
&user_expression->GetErrorDelegate(), error);
}
}
} else {
CompilerType actual_type(variable.GetType());
if (Flags(actual_type.GetTypeInfo())
.AllSet(lldb::eTypeIsSwift | lldb::eTypeIsArchetype)) {
lldb::StackFrameSP stack_frame_sp = m_stack_frame_wp.lock();
if (stack_frame_sp && stack_frame_sp->GetThread() &&
stack_frame_sp->GetThread()->GetProcess()) {
SwiftLanguageRuntime *swift_runtime =
stack_frame_sp->GetThread()
->GetProcess()
->GetSwiftLanguageRuntime();
if (swift_runtime) {
actual_type = swift_runtime->GetConcreteType(
stack_frame_sp.get(), actual_type.GetTypeName());
if (actual_type.IsValid())
variable.SetType(actual_type);
else
actual_type = variable.GetType();
}
}
}
swift::Type actual_swift_type =
swift::Type((swift::TypeBase *)actual_type.GetOpaqueQualType());
swift::Type fixed_type = code_manipulator->FixupResultType(
actual_swift_type, user_expression->GetLanguageFlags());
if (!fixed_type.isNull()) {
actual_type = CompilerType(actual_type.GetTypeSystem(),
fixed_type.getPointer());
variable.SetType(actual_type);
}
if (is_result)
offset = materializer->AddResultVariable(
actual_type, false, true, &user_expression->GetResultDelegate(),
error);
else
offset = materializer->AddResultVariable(
actual_type, false, true, &user_expression->GetErrorDelegate(),
error);
}
if (!error.Success()) {
diagnostic_manager.Printf(eDiagnosticSeverityError,
"couldn't add %s variable to struct: %s.\n",
is_result ? "result" : "error",
error.AsCString());
return 1;
}
if (log)
log->Printf("Added %s variable to struct at offset %llu",
is_result ? "result" : "error",
(unsigned long long)offset);
} else if (variable.MetadataIs<VariableMetadataVariable>()) {
Status error;
VariableMetadataVariable *variable_metadata =
static_cast<VariableMetadataVariable *>(variable.m_metadata.get());
offset =
materializer->AddVariable(variable_metadata->m_variable_sp, error);
if (!error.Success()) {
diagnostic_manager.Printf(eDiagnosticSeverityError,
"couldn't add variable to struct: %s.\n",
error.AsCString());
return 1;
}
if (log)
log->Printf("Added variable %s to struct at offset %llu",
variable_metadata->m_variable_sp->GetName().AsCString(),
(unsigned long long)offset);
} else if (variable.MetadataIs<VariableMetadataPersistent>()) {
VariableMetadataPersistent *variable_metadata =
static_cast<VariableMetadataPersistent *>(
variable.m_metadata.get());
needs_init = llvm::cast<SwiftExpressionVariable>(
variable_metadata->m_persistent_variable_sp.get())
->m_swift_flags &
SwiftExpressionVariable::EVSNeedsInit;
Status error;
offset = materializer->AddPersistentVariable(
variable_metadata->m_persistent_variable_sp,
&user_expression->GetPersistentVariableDelegate(), error);
if (!error.Success()) {
diagnostic_manager.Printf(eDiagnosticSeverityError,
"couldn't add variable to struct: %s.\n",
error.AsCString());
return 1;
}
if (log)
log->Printf("Added persistent variable %s with flags 0x%llx to "
"struct at offset %llu",
variable_metadata->m_persistent_variable_sp->GetName()
.AsCString(),
(unsigned long long)
variable_metadata->m_persistent_variable_sp->m_flags,
(unsigned long long)offset);
}
variable_map[ConstString(variable.GetName().get()).GetCString()] =
SILVariableInfo(variable.GetType(), offset, needs_init);
}
}
std::unique_ptr<swift::SILModule> sil_module(swift::performSILGeneration(
*source_file, m_swift_ast_context->GetSILOptions()));
if (log) {
std::string s;
llvm::raw_string_ostream ss(s);
const bool verbose = false;
sil_module->print(ss, verbose, module);
ss.flush();
log->Printf("SIL module before linking:");
log->PutCString(s.c_str());
}
swift::performSILLinking(sil_module.get());
if (m_swift_ast_context->HasErrors()) {
m_swift_ast_context->PrintDiagnostics(diagnostic_manager, buffer_id,
first_line, last_line, line_offset);
return 1;
}
if (log) {
std::string s;
llvm::raw_string_ostream ss(s);
const bool verbose = false;
sil_module->print(ss, verbose, module);
ss.flush();
log->Printf("Generated SIL module:");
log->PutCString(s.c_str());
}
runSILDiagnosticPasses(*sil_module);
if (log) {
std::string s;
llvm::raw_string_ostream ss(s);
const bool verbose = false;
sil_module->print(ss, verbose, module);
ss.flush();
log->Printf("SIL module after diagnostic passes:");
log->PutCString(s.c_str());
}
if (m_swift_ast_context->HasErrors()) {
m_swift_ast_context->PrintDiagnostics(diagnostic_manager, buffer_id,
first_line, last_line, line_offset);
return 1;
}
{
std::lock_guard<std::recursive_mutex> global_context_locker(
IRExecutionUnit::GetLLVMGlobalContextMutex());
m_module = swift::performIRGeneration(
m_swift_ast_context->GetIRGenOptions(), module, std::move(sil_module),
"lldb_module", swift::PrimarySpecificPaths("", main_filename),
SwiftASTContext::GetGlobalLLVMContext(), llvm::ArrayRef<std::string>());
}
if (m_swift_ast_context->HasErrors()) {
m_swift_ast_context->PrintDiagnostics(diagnostic_manager, buffer_id,
first_line, last_line, line_offset);
return 1;
}
if (!m_module) {
diagnostic_manager.PutString(
eDiagnosticSeverityError,
"Couldn't IRGen expression, no additional error");
return 1;
}
if (log) {
std::string s;
llvm::raw_string_ostream ss(s);
m_module->print(ss, NULL);
ss.flush();
log->Printf("Generated IR module:");
log->PutCString(s.c_str());
}
{
std::lock_guard<std::recursive_mutex> global_context_locker(
IRExecutionUnit::GetLLVMGlobalContextMutex());
LLVMVerifyModule((LLVMOpaqueModule *)m_module.get(), LLVMReturnStatusAction,
nullptr);
}
bool fail = m_swift_ast_context->HasErrors();
if (!fail) {
// The Parse succeeded! Now put this module into the context's list of
// loaded modules,
// and copy the Decls that were globalized as part of the parse from the
// staging area in the
// external lookup object into the SwiftPersistentExpressionState.
ast_context->LoadedModules.insert(std::make_pair(module_id, module));
if (m_swift_ast_context)
m_swift_ast_context->CacheModule(module);
if (m_sc.target_sp) {
SwiftPersistentExpressionState *persistent_state =
llvm::cast<SwiftPersistentExpressionState>(
m_sc.target_sp->GetPersistentExpressionStateForLanguage(
lldb::eLanguageTypeSwift));
persistent_state->CopyInSwiftPersistentDecls(
external_lookup->GetStagedDecls());
}
}
return fail ? 1 : 0;
}
static bool FindFunctionInModule(ConstString &mangled_name,
llvm::Module *module, const char *orig_name,
bool exact) {
swift::Demangle::Context demangle_ctx;
for (llvm::Module::iterator fi = module->getFunctionList().begin(),
fe = module->getFunctionList().end();
fi != fe; ++fi) {
if (exact) {
if (!fi->getName().str().compare(orig_name)) {
mangled_name.SetCString(fi->getName().str().c_str());
return true;
}
} else {
if (fi->getName().str().find(orig_name) != std::string::npos) {
mangled_name.SetCString(fi->getName().str().c_str());
return true;
}
// The new demangling is cannier about compression, so the name may
// not be in the mangled name plain. Let's demangle it and see if we
// can find it in the demangled nodes.
demangle_ctx.clear();
swift::Demangle::NodePointer node_ptr = demangle_ctx.demangleSymbolAsNode(fi->getName());
if (node_ptr)
{
if (node_ptr->getKind() != swift::Demangle::Node::Kind::Global)
continue;
if (node_ptr->getNumChildren() != 1)
continue;
node_ptr = node_ptr->getFirstChild();
if (node_ptr->getKind() != swift::Demangle::Node::Kind::Function)
continue;
size_t num_children = node_ptr->getNumChildren();
for (size_t i = 0; i < num_children; i++)
{
swift::Demangle::NodePointer child_ptr = node_ptr->getChild(i);
if (child_ptr->getKind() == swift::Demangle::Node::Kind::Identifier) {
if (!child_ptr->hasText())
continue;
if(child_ptr->getText().contains(orig_name))
{
mangled_name.SetCString(fi->getName().str().c_str());
return true;
}
}
}
}
}
}
return false;
}
Status SwiftExpressionParser::PrepareForExecution(
lldb::addr_t &func_addr, lldb::addr_t &func_end,
lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx,
bool &can_interpret, ExecutionPolicy execution_policy) {
Status err;
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
if (!m_module) {
err.SetErrorString("Can't prepare a NULL module for execution");
return err;
}
const char *orig_name = nullptr;
bool exact = false;
if (m_options.GetPlaygroundTransformEnabled() || m_options.GetREPLEnabled()) {
orig_name = "main";
exact = true;
} else {
orig_name = "$__lldb_expr";
}
ConstString function_name;
if (!FindFunctionInModule(function_name, m_module.get(), orig_name, exact)) {
err.SetErrorToGenericError();
err.SetErrorStringWithFormat("Couldn't find %s() in the module", orig_name);
return err;
} else {
if (log)
log->Printf("Found function %s for %s", function_name.AsCString(),
"$__lldb_expr");
}
// Retrieve an appropriate symbol context.
SymbolContext sc;
if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) {
sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything);
} else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) {
sc.target_sp = target_sp;
}
std::vector<std::string> features;
std::unique_ptr<llvm::LLVMContext> llvm_context_up;
m_execution_unit_sp.reset(
new IRExecutionUnit(llvm_context_up,
m_module, // handed off here
function_name, exe_ctx.GetTargetSP(), sc, features));
// TODO figure out some way to work ClangExpressionDeclMap into this or do the
// equivalent
// for Swift
m_execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
execution_unit_sp = m_execution_unit_sp;
m_execution_unit_sp.reset();
return err;
}
bool SwiftExpressionParser::RewriteExpression(
DiagnosticManager &diagnostic_manager) {
// There isn't a Swift equivalent to clang::Rewriter, so we'll just use
// that...
if (!m_swift_ast_context)
return false;
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
swift::SourceManager &source_manager =
m_swift_ast_context->GetSourceManager();
const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics();
size_t num_diags = diagnostics.size();
if (num_diags == 0)
return false;
clang::RewriteBuffer rewrite_buf;
llvm::StringRef text_ref(m_expr.Text());
rewrite_buf.Initialize(text_ref);
for (const Diagnostic *diag : diagnostic_manager.Diagnostics()) {
const SwiftDiagnostic *diagnostic = llvm::dyn_cast<SwiftDiagnostic>(diag);
if (!(diagnostic && diagnostic->HasFixIts()))
continue;
const SwiftDiagnostic::FixItList &fixits = diagnostic->FixIts();
std::vector<swift::CharSourceRange> source_ranges;
for (const swift::DiagnosticInfo::FixIt &fixit : fixits) {
const swift::CharSourceRange &range = fixit.getRange();
swift::SourceLoc start_loc = range.getStart();
if (!start_loc.isValid()) {
// getLocOffsetInBuffer will assert if you pass it an invalid location,
// so we have to check that first.
if (log)
log->Printf(
"SwiftExpressionParser::RewriteExpression: ignoring fixit since "
"it contains an invalid source location: %s.",
range.str().str().c_str());
return false;
}
// ReplaceText can't handle replacing the same source range more than
// once, so we have to check that
// before we proceed:
if (std::find(source_ranges.begin(), source_ranges.end(), range) !=
source_ranges.end()) {
if (log)
log->Printf(
"SwiftExpressionParser::RewriteExpression: ignoring fix-it since "
"source range appears twice: %s.\n",
range.str().str().c_str());
return false;
} else
source_ranges.push_back(range);
// ReplaceText will either assert or crash if the start_loc isn't inside
// the buffer it is said to
// reside in. That shouldn't happen, but it doesn't hurt to check before
// we call ReplaceText.
auto *Buffer = source_manager.getLLVMSourceMgr().getMemoryBuffer(
diagnostic->GetBufferID());
if (!(start_loc.getOpaquePointerValue() >= Buffer->getBuffer().begin() &&
start_loc.getOpaquePointerValue() <= Buffer->getBuffer().end())) {
if (log)
log->Printf(
"SwiftExpressionParser::RewriteExpression: ignoring fixit since "
"it contains a source location not in the specified buffer: %s.",
range.str().str().c_str());
}
unsigned offset = source_manager.getLocOffsetInBuffer(
range.getStart(), diagnostic->GetBufferID());
rewrite_buf.ReplaceText(offset, range.getByteLength(), fixit.getText());
}
}
std::string fixed_expression;
llvm::raw_string_ostream out_stream(fixed_expression);
rewrite_buf.write(out_stream);
out_stream.flush();
diagnostic_manager.SetFixedExpression(fixed_expression);
return true;
}
SwiftExpressionParser: Factor out variable materialization (NFC)
//===-- SwiftExpressionParser.cpp -------------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "SwiftExpressionParser.h"
#include "SwiftASTManipulator.h"
#include "SwiftREPLMaterializer.h"
#include "SwiftSILManipulator.h"
#include "SwiftUserExpression.h"
#include "Plugins/ExpressionParser/Swift/SwiftDiagnostic.h"
#include "Plugins/ExpressionParser/Swift/SwiftExpressionVariable.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ModuleList.h"
#include "lldb/Core/ModuleSpec.h"
#include "lldb/Core/ValueObject.h"
#include "lldb/Expression/DiagnosticManager.h"
#include "lldb/Expression/Expression.h"
#include "lldb/Expression/ExpressionSourceCode.h"
#include "lldb/Expression/IRExecutionUnit.h"
#include "lldb/Symbol/CompileUnit.h"
#include "lldb/Symbol/SymbolVendor.h"
#include "lldb/Symbol/Type.h"
#include "lldb/Symbol/VariableList.h"
#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/StackFrame.h"
#include "lldb/Target/SwiftLanguageRuntime.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/Stream.h"
#include "llvm-c/Analysis.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/Basic/Module.h"
#include "clang/Rewrite/Core/RewriteBuffer.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/DiagnosticConsumer.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/Module.h"
#include "swift/AST/ModuleLoader.h"
#include "swift/Demangling/Demangle.h"
#include "swift/Basic/PrimarySpecificPaths.h"
#include "swift/Basic/SourceManager.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/Frontend/Frontend.h"
#include "swift/Parse/LocalContext.h"
#include "swift/Parse/PersistentParserState.h"
#include "swift/SIL/SILDebuggerClient.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILModule.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/Serialization/SerializedModuleLoader.h"
#include "swift/Subsystems.h"
using namespace lldb_private;
SwiftExpressionParser::SwiftExpressionParser(
ExecutionContextScope *exe_scope, Expression &expr,
const EvaluateExpressionOptions &options)
: ExpressionParser(exe_scope, expr, options.GetGenerateDebugInfo()),
m_expr(expr), m_triple(), m_llvm_context(), m_module(),
m_execution_unit_sp(), m_swift_ast_context(NULL), m_sc(),
m_stack_frame_wp(), m_options(options) {
assert(expr.Language() == lldb::eLanguageTypeSwift);
// TODO This code is copied from ClangExpressionParser.cpp.
// Factor this out into common code.
lldb::TargetSP target_sp;
if (exe_scope) {
target_sp = exe_scope->CalculateTarget();
lldb::StackFrameSP stack_frame = exe_scope->CalculateStackFrame();
if (stack_frame) {
m_stack_frame_wp = stack_frame;
m_sc = stack_frame->GetSymbolContext(lldb::eSymbolContextEverything);
} else {
m_sc.target_sp = target_sp;
}
}
if (target_sp && target_sp->GetArchitecture().IsValid()) {
std::string triple = target_sp->GetArchitecture().GetTriple().str();
int dash_count = 0;
for (size_t i = 0; i < triple.size(); ++i) {
if (triple[i] == '-')
dash_count++;
if (dash_count == 3) {
triple.resize(i);
break;
}
}
m_triple = triple;
} else {
m_triple = llvm::sys::getDefaultTargetTriple();
}
if (target_sp) {
m_swift_ast_context = llvm::cast_or_null<SwiftASTContext>(
target_sp->GetScratchTypeSystemForLanguage(nullptr,
lldb::eLanguageTypeSwift));
}
}
static void DescribeFileUnit(Stream &s, swift::FileUnit *file_unit) {
s.PutCString("kind = ");
switch (file_unit->getKind()) {
default: { s.PutCString("<unknown>"); }
case swift::FileUnitKind::Source: {
s.PutCString("Source, ");
if (swift::SourceFile *source_file =
llvm::dyn_cast<swift::SourceFile>(file_unit)) {
s.Printf("filename = '%s', ", source_file->getFilename().str().c_str());
s.PutCString("source file kind = ");
switch (source_file->Kind) {
case swift::SourceFileKind::Library:
s.PutCString("Library");
case swift::SourceFileKind::Main:
s.PutCString("Main");
case swift::SourceFileKind::REPL:
s.PutCString("REPL");
case swift::SourceFileKind::SIL:
s.PutCString("SIL");
}
}
} break;
case swift::FileUnitKind::Builtin: {
s.PutCString("Builtin");
} break;
case swift::FileUnitKind::SerializedAST:
case swift::FileUnitKind::ClangModule: {
s.PutCString("SerializedAST, ");
swift::LoadedFile *loaded_file = llvm::cast<swift::LoadedFile>(file_unit);
s.Printf("filename = '%s'", loaded_file->getFilename().str().c_str());
} break;
};
}
// Gets the full module name from the module passed in.
static void GetNameFromModule(swift::ModuleDecl *module, std::string &result) {
result.clear();
if (module) {
const char *name = module->getName().get();
if (!name)
return;
result.append(name);
const clang::Module *clang_module = module->findUnderlyingClangModule();
// At present, there doesn't seem to be any way to get the full module path
// from the Swift side.
if (!clang_module)
return;
for (const clang::Module *cur_module = clang_module->Parent; cur_module;
cur_module = cur_module->Parent) {
if (!cur_module->Name.empty()) {
result.insert(0, 1, '.');
result.insert(0, cur_module->Name);
}
}
}
}
// Largely lifted from swift::performAutoImport, but serves our own nefarious
// purposes.
bool SwiftExpressionParser::PerformAutoImport(swift::SourceFile &source_file,
bool user_imports,
Status &error) {
Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
const std::vector<ConstString> *cu_modules = nullptr;
CompileUnit *compile_unit = m_sc.comp_unit;
if (compile_unit)
cu_modules = &compile_unit->GetImportedModules();
llvm::SmallVector<swift::ModuleDecl::ImportedModule, 2> imported_modules;
llvm::SmallVector<std::pair<swift::ModuleDecl::ImportedModule,
swift::SourceFile::ImportOptions>,
2>
additional_imports;
source_file.getImportedModules(imported_modules,
swift::ModuleDecl::ImportFilter::All);
std::set<ConstString> loaded_modules;
auto load_one_module = [this, log, &loaded_modules, &imported_modules,
&additional_imports,
&error](const ConstString &module_name) {
error.Clear();
if (loaded_modules.count(module_name))
return true;
if (log)
log->Printf("[PerformAutoImport] Importing module %s",
module_name.AsCString());
loaded_modules.insert(module_name);
swift::ModuleDecl *swift_module = nullptr;
lldb::StackFrameSP this_frame_sp(m_stack_frame_wp.lock());
if (module_name == ConstString(m_swift_ast_context->GetClangImporter()
->getImportedHeaderModule()
->getName()
.str()))
swift_module =
m_swift_ast_context->GetClangImporter()->getImportedHeaderModule();
else if (this_frame_sp) {
lldb::ProcessSP process_sp(this_frame_sp->CalculateProcess());
if (process_sp)
swift_module = m_swift_ast_context->FindAndLoadModule(
module_name, *process_sp.get(), error);
} else
swift_module = m_swift_ast_context->GetModule(module_name, error);
if (!swift_module || !error.Success() ||
m_swift_ast_context->HasFatalErrors()) {
if (log)
log->Printf("[PerformAutoImport] Couldnt import module %s: %s",
module_name.AsCString(), error.AsCString());
if (!swift_module || m_swift_ast_context->HasFatalErrors()) {
return false;
}
}
if (log) {
log->Printf("Importing %s with source files:", module_name.AsCString());
for (swift::FileUnit *file_unit : swift_module->getFiles()) {
StreamString ss;
DescribeFileUnit(ss, file_unit);
log->Printf(" %s", ss.GetData());
}
}
additional_imports.push_back(std::make_pair(
std::make_pair(swift::ModuleDecl::AccessPathTy(), swift_module),
swift::SourceFile::ImportOptions()));
imported_modules.push_back(
std::make_pair(swift::ModuleDecl::AccessPathTy(), swift_module));
return true;
};
if (!user_imports) {
if (!load_one_module(ConstString("Swift")))
return false;
if (cu_modules) {
for (const ConstString &module_name : *cu_modules) {
if (!load_one_module(module_name))
return false;
}
}
} else {
llvm::SmallVector<swift::ModuleDecl::ImportedModule, 2> parsed_imports;
source_file.getImportedModules(parsed_imports,
swift::ModuleDecl::ImportFilter::All);
SwiftPersistentExpressionState *persistent_expression_state =
llvm::cast<SwiftPersistentExpressionState>(
m_sc.target_sp->GetPersistentExpressionStateForLanguage(
lldb::eLanguageTypeSwift));
for (auto module_pair : parsed_imports) {
swift::ModuleDecl *module = module_pair.second;
if (module) {
std::string module_name;
GetNameFromModule(module, module_name);
if (!module_name.empty()) {
ConstString module_const_str(module_name);
if (log)
log->Printf("[PerformAutoImport] Performing auto import on found "
"module: %s.\n",
module_name.c_str());
if (!load_one_module(module_const_str))
return false;
if (1 /* How do we tell we are in REPL or playground mode? */) {
persistent_expression_state->AddHandLoadedModule(module_const_str);
}
}
}
}
// Finally get the hand-loaded modules from the
// SwiftPersistentExpressionState and load them into this context:
if (!persistent_expression_state->RunOverHandLoadedModules(load_one_module))
return false;
}
source_file.addImports(additional_imports);
return true;
}
class VariableMetadataPersistent
: public SwiftASTManipulatorBase::VariableMetadata {
public:
VariableMetadataPersistent(lldb::ExpressionVariableSP &persistent_variable_sp)
: m_persistent_variable_sp(persistent_variable_sp) {}
static constexpr unsigned Type() { return 'Pers'; }
virtual unsigned GetType() { return Type(); }
lldb::ExpressionVariableSP m_persistent_variable_sp;
};
class VariableMetadataVariable
: public SwiftASTManipulatorBase::VariableMetadata {
public:
VariableMetadataVariable(lldb::VariableSP &variable_sp)
: m_variable_sp(variable_sp) {}
static constexpr unsigned Type() { return 'Vari'; }
virtual unsigned GetType() { return Type(); }
lldb::VariableSP m_variable_sp;
};
static CompilerType ImportType(SwiftASTContext &target_context,
CompilerType source_type) {
SwiftASTContext *swift_ast_ctx =
llvm::dyn_cast_or_null<SwiftASTContext>(source_type.GetTypeSystem());
if (swift_ast_ctx == nullptr)
return CompilerType();
if (swift_ast_ctx == &target_context)
return source_type;
Status error, mangled_error;
CompilerType target_type;
// First try to get the type by using the mangled name,
// That will save the mangling step ImportType would have to do:
ConstString type_name = source_type.GetTypeName();
ConstString mangled_counterpart;
bool found_counterpart = type_name.GetMangledCounterpart(mangled_counterpart);
if (found_counterpart)
target_type = target_context.GetTypeFromMangledTypename(
mangled_counterpart.GetCString(), mangled_error);
if (!target_type.IsValid())
target_type = target_context.ImportType(source_type, error);
return target_type;
}
namespace {
class LLDBNameLookup : public swift::SILDebuggerClient {
public:
LLDBNameLookup(SwiftExpressionParser &parser, swift::SourceFile &source_file,
SwiftExpressionParser::SILVariableMap &variable_map,
SymbolContext &sc)
: SILDebuggerClient(source_file.getASTContext()), m_parser(parser),
m_log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)),
m_source_file(source_file), m_variable_map(variable_map), m_sc(sc) {
source_file.getParentModule()->setDebugClient(this);
if (m_sc.target_sp) {
m_persistent_vars = llvm::cast<SwiftPersistentExpressionState>(
m_sc.target_sp->GetPersistentExpressionStateForLanguage(
lldb::eLanguageTypeSwift));
}
}
virtual ~LLDBNameLookup() {}
virtual bool shouldGlobalize(swift::Identifier Name, swift::DeclKind Kind) {
if (m_parser.GetOptions().GetREPLEnabled())
return true;
else {
// Extensions have to be globalized, there's no way to mark them as local
// to the function, since their
// name is the name of the thing being extended...
if (Kind == swift::DeclKind::Extension)
return true;
// Operators need to be parsed at the global scope regardless of name.
if (Kind == swift::DeclKind::Func && Name.isOperator())
return true;
const char *name_cstr = Name.get();
if (name_cstr && name_cstr[0] == '$') {
if (m_log)
m_log->Printf("[LLDBNameLookup::shouldGlobalize] Returning true to "
"globalizing %s",
name_cstr);
return true;
}
}
return false;
}
virtual void didGlobalize(swift::Decl *decl) {
swift::ValueDecl *value_decl = swift::dyn_cast<swift::ValueDecl>(decl);
if (value_decl) {
// It seems weird to be asking this again, but some DeclKinds must be
// moved to
// the source-file level to be legal. But we don't want to register them
// with
// lldb unless they are of the kind lldb explicitly wants to globalize.
if (shouldGlobalize(value_decl->getBaseName().getIdentifier(),
value_decl->getKind()))
m_staged_decls.AddDecl(value_decl, false, ConstString());
}
}
virtual bool lookupOverrides(swift::DeclBaseName Name, swift::DeclContext *DC,
swift::SourceLoc Loc, bool IsTypeLookup,
ResultVector &RV) {
static unsigned counter = 0;
unsigned count = counter++;
if (m_log) {
m_log->Printf("[LLDBNameLookup::lookupOverrides(%u)] Searching for %s",
count, Name.getIdentifier().get());
}
return false;
}
virtual bool lookupAdditions(swift::DeclBaseName Name, swift::DeclContext *DC,
swift::SourceLoc Loc, bool IsTypeLookup,
ResultVector &RV) {
static unsigned counter = 0;
unsigned count = counter++;
StringRef NameStr = Name.getIdentifier().str();
if (m_log) {
m_log->Printf("[LLDBNameLookup::lookupAdditions (%u)] Searching for %s",
count, Name.getIdentifier().str().str().c_str());
}
ConstString name_const_str(NameStr);
std::vector<swift::ValueDecl *> results;
// First look up the matching Decl's we've made in this compile, then pass
// that list to the
// persistent decls, which will only add decls it has that are NOT
// equivalent to the decls
// we made locally.
m_staged_decls.FindMatchingDecls(name_const_str, results);
// Next look up persistent decls matching this name. Then, if we are in the
// plain expression parser, and we
// aren't looking at a debugger variable, filter out persistent results of
// the same kind as one found by the
// ordinary lookup mechanism in the parser . The problem
// we are addressing here is the case where the user has entered the REPL
// while in an ordinary debugging session
// to play around. While there, e.g., they define a class that happens to
// have the same name as one in the
// program, then in some other context "expr" will call the class they've
// defined, not the one in the program
// itself would use. Plain "expr" should behave as much like code in the
// program would, so we want to favor
// entities of the same DeclKind & name from the program over ones defined
// in the REPL. For function decls we
// check the interface type and full name so we don't remove overloads that
// don't exist in the current scope.
//
// Note also, we only do this for the persistent decls. Anything in the
// "staged" list has been defined in this
// expr setting and so is more local than local.
bool skip_results_with_matching_kind =
!(m_parser.GetOptions().GetREPLEnabled() ||
m_parser.GetOptions().GetPlaygroundTransformEnabled() ||
(!NameStr.empty() && NameStr.front() == '$'));
size_t num_external_results = RV.size();
if (skip_results_with_matching_kind && num_external_results > 0) {
std::vector<swift::ValueDecl *> persistent_results;
m_persistent_vars->GetSwiftPersistentDecls(name_const_str,
persistent_results);
size_t num_persistent_results = persistent_results.size();
for (size_t idx = 0; idx < num_persistent_results; idx++) {
swift::ValueDecl *value_decl = persistent_results[idx];
if (!value_decl)
continue;
swift::DeclName value_decl_name = value_decl->getFullName();
swift::DeclKind value_decl_kind = value_decl->getKind();
swift::CanType value_interface_type =
value_decl->getInterfaceType()->getCanonicalType();
bool is_function = swift::isa<swift::AbstractFunctionDecl>(value_decl);
bool skip_it = false;
for (size_t rv_idx = 0; rv_idx < num_external_results; rv_idx++) {
if (swift::ValueDecl *rv_decl = RV[rv_idx].getValueDecl()) {
if (value_decl_kind == rv_decl->getKind()) {
if (is_function) {
swift::DeclName rv_full_name = rv_decl->getFullName();
if (rv_full_name.matchesRef(value_decl_name)) {
// If the full names match, make sure the interface types
// match:
if (rv_decl->getInterfaceType()->getCanonicalType() ==
value_interface_type)
skip_it = true;
}
} else {
skip_it = true;
}
if (skip_it)
break;
}
}
}
if (!skip_it)
results.push_back(value_decl);
}
} else {
m_persistent_vars->GetSwiftPersistentDecls(name_const_str, results);
}
for (size_t idx = 0; idx < results.size(); idx++) {
swift::ValueDecl *value_decl = results[idx];
assert(&DC->getASTContext() ==
&value_decl->getASTContext()); // no import required
RV.push_back(swift::LookupResultEntry(value_decl));
}
return results.size() > 0;
}
virtual swift::SILValue emitLValueForVariable(swift::VarDecl *var,
swift::SILBuilder &builder) {
SwiftSILManipulator manipulator(builder);
swift::Identifier variable_name = var->getName();
ConstString variable_const_string(variable_name.get());
SwiftExpressionParser::SILVariableMap::iterator vi =
m_variable_map.find(variable_const_string.AsCString());
if (vi == m_variable_map.end())
return swift::SILValue();
return manipulator.emitLValueForVariable(var, vi->second);
}
SwiftPersistentExpressionState::SwiftDeclMap &GetStagedDecls() {
return m_staged_decls;
}
virtual swift::Identifier getPreferredPrivateDiscriminator() {
if (m_sc.comp_unit) {
if (lldb_private::Module *module = m_sc.module_sp.get()) {
if (lldb_private::SymbolVendor *symbol_vendor =
module->GetSymbolVendor()) {
std::string private_discriminator_string;
if (symbol_vendor->GetCompileOption("-private-discriminator",
private_discriminator_string,
m_sc.comp_unit)) {
return m_source_file.getASTContext().getIdentifier(
private_discriminator_string);
}
}
}
}
return swift::Identifier();
}
private:
SwiftExpressionParser &m_parser;
Log *m_log;
swift::SourceFile &m_source_file;
SwiftExpressionParser::SILVariableMap &m_variable_map;
SymbolContext m_sc;
SwiftPersistentExpressionState *m_persistent_vars = nullptr;
SwiftPersistentExpressionState::SwiftDeclMap
m_staged_decls; // We stage the decls we are globalize in this map.
// They will get copied over to the SwiftPersistentVariable
// store if the parse succeeds.
};
} // END Anonymous namespace
static void
AddRequiredAliases(Block *block, lldb::StackFrameSP &stack_frame_sp,
SwiftASTContext &swift_ast_context,
SwiftASTManipulator &manipulator,
const Expression::SwiftGenericInfo &generic_info) {
// First, emit the typealias for "$__lldb_context"
do {
if (!block)
break;
Function *function = block->CalculateSymbolContextFunction();
if (!function)
break;
constexpr bool can_create = true;
Block &function_block(function->GetBlock(can_create));
lldb::VariableListSP variable_list_sp(
function_block.GetBlockVariableList(true));
if (!variable_list_sp)
break;
lldb::VariableSP self_var_sp(
variable_list_sp->FindVariable(ConstString("self")));
if (!self_var_sp)
break;
CompilerType self_type;
if (stack_frame_sp) {
lldb::ValueObjectSP valobj_sp =
stack_frame_sp->GetValueObjectForFrameVariable(
self_var_sp, lldb::eNoDynamicValues);
if (valobj_sp)
self_type = valobj_sp->GetCompilerType();
}
if (!self_type.IsValid()) {
if (Type *type = self_var_sp->GetType()) {
self_type = type->GetForwardCompilerType();
}
}
if (!self_type.IsValid() ||
!llvm::isa<SwiftASTContext>(self_type.GetTypeSystem()))
break;
// Import before getting the unbound version, because the unbound version
// may not be in the mangled name map
CompilerType imported_self_type = ImportType(swift_ast_context, self_type);
if (!imported_self_type.IsValid())
break;
// This might be a referenced type, in which case we really want to extend
// the referent:
imported_self_type =
llvm::cast<SwiftASTContext>(imported_self_type.GetTypeSystem())
->GetReferentType(imported_self_type);
// If we are extending a generic class it's going to be a metatype, and we
// have to grab the instance type:
imported_self_type =
llvm::cast<SwiftASTContext>(imported_self_type.GetTypeSystem())
->GetInstanceType(imported_self_type.GetOpaqueQualType());
Flags imported_self_type_flags(imported_self_type.GetTypeInfo());
// If 'self' is the Self archetype, resolve it to the actual metatype it is
if (SwiftASTContext::IsSelfArchetypeType(imported_self_type)) {
SwiftLanguageRuntime *swift_runtime =
stack_frame_sp->GetThread()->GetProcess()->GetSwiftLanguageRuntime();
if (CompilerType concrete_self_type = swift_runtime->GetConcreteType(
stack_frame_sp.get(), ConstString("Self"))) {
if (SwiftASTContext *concrete_self_type_ast_ctx =
llvm::dyn_cast_or_null<SwiftASTContext>(
concrete_self_type.GetTypeSystem())) {
imported_self_type = concrete_self_type_ast_ctx->CreateMetatypeType(
concrete_self_type);
imported_self_type_flags.Reset(imported_self_type.GetTypeInfo());
imported_self_type =
ImportType(swift_ast_context, imported_self_type);
if (imported_self_type_flags.AllSet(lldb::eTypeIsSwift |
lldb::eTypeIsMetatype)) {
imported_self_type = imported_self_type.GetInstanceType();
}
}
}
}
// Get the instance type:
if (imported_self_type_flags.AllSet(lldb::eTypeIsSwift |
lldb::eTypeIsMetatype)) {
imported_self_type = imported_self_type.GetInstanceType();
imported_self_type_flags.Reset(imported_self_type.GetTypeInfo());
}
swift::Type object_type =
swift::Type((swift::TypeBase *)(imported_self_type.GetOpaqueQualType()))
->getWithoutSpecifierType();
if (object_type.getPointer() &&
(object_type.getPointer() != imported_self_type.GetOpaqueQualType()))
imported_self_type = CompilerType(imported_self_type.GetTypeSystem(),
object_type.getPointer());
// If the type of 'self' is a bound generic type, get the unbound version
bool is_generic = imported_self_type_flags.AllSet(lldb::eTypeIsSwift |
lldb::eTypeIsGeneric);
bool is_bound = imported_self_type_flags.AllSet(lldb::eTypeIsSwift |
lldb::eTypeIsBound);
if (is_generic) {
if (is_bound)
imported_self_type = imported_self_type.GetUnboundType();
}
// if 'self' is a weak storage type, it must be an optional. Look through
// it and unpack the argument of "optional".
if (swift::WeakStorageType *weak_storage_type =
((swift::TypeBase *)imported_self_type.GetOpaqueQualType())
->getAs<swift::WeakStorageType>()) {
swift::Type referent_type = weak_storage_type->getReferentType();
swift::BoundGenericEnumType *optional_type =
referent_type->getAs<swift::BoundGenericEnumType>();
if (!optional_type) {
break;
}
swift::Type first_arg_type = optional_type->getGenericArgs()[0];
swift::ClassType *self_class_type =
first_arg_type->getAs<swift::ClassType>();
if (!self_class_type) {
break;
}
imported_self_type =
CompilerType(imported_self_type.GetTypeSystem(), self_class_type);
}
imported_self_type_flags.Reset(imported_self_type.GetTypeInfo());
if (imported_self_type_flags.AllClear(lldb::eTypeIsArchetype)) {
swift::ValueDecl *type_alias_decl = nullptr;
type_alias_decl = manipulator.MakeGlobalTypealias(
swift_ast_context.GetASTContext()->getIdentifier("$__lldb_context"),
imported_self_type);
if (!type_alias_decl) {
Log *log(
lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
if (log)
log->Printf("SEP:AddRequiredAliases: Failed to make the "
"$__lldb_context typealias.");
}
} else {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
if (log)
log->Printf("SEP:AddRequiredAliases: Failed to resolve the self "
"archetype - could not make the $__lldb_context "
"typealias.");
}
} while (0);
// Emit the typedefs
for (const Expression::SwiftGenericInfo::Binding &binding :
generic_info.function_bindings) {
CompilerType bound_type = binding.type;
if (!llvm::isa<SwiftASTContext>(bound_type.GetTypeSystem()))
continue;
CompilerType imported_bound_type =
ImportType(swift_ast_context, bound_type);
if (!imported_bound_type.IsValid())
continue;
std::string alias_name("$__lldb_typeof_generic_");
alias_name.append(binding.name);
swift::ValueDecl *type_alias_decl = manipulator.MakeGlobalTypealias(
swift_ast_context.GetASTContext()->getIdentifier(alias_name),
imported_bound_type);
if (!type_alias_decl)
continue;
}
}
static void CountLocals(
SymbolContext &sc, lldb::StackFrameSP &stack_frame_sp,
SwiftASTContext &ast_context,
llvm::SmallVectorImpl<SwiftASTManipulator::VariableInfo> &local_variables) {
std::set<ConstString> counted_names; // avoids shadowing
if (!sc.block && !sc.function)
return;
Block *block = sc.block;
Block *top_block = block->GetContainingInlinedBlock();
if (!top_block)
top_block = &sc.function->GetBlock(true);
static ConstString s_self_name("self");
SwiftLanguageRuntime *language_runtime = nullptr;
ExecutionContextScope *scope = nullptr;
if (stack_frame_sp) {
language_runtime =
stack_frame_sp->GetThread()->GetProcess()->GetSwiftLanguageRuntime();
scope = stack_frame_sp.get();
}
// The module scoped variables are stored at the CompUnit level, so after we
// go through the current context,
// then we have to take one more pass through the variables in the CompUnit.
bool handling_globals = false;
while (true) {
VariableList variables;
if (!handling_globals) {
constexpr bool can_create = true;
constexpr bool get_parent_variables = false;
constexpr bool stop_if_block_is_inlined_function = true;
block->AppendVariables(can_create, get_parent_variables,
stop_if_block_is_inlined_function,
[](Variable *) { return true; }, &variables);
} else {
if (sc.comp_unit) {
lldb::VariableListSP globals_sp = sc.comp_unit->GetVariableList(true);
if (globals_sp)
variables.AddVariables(globals_sp.get());
}
}
for (size_t vi = 0, ve = variables.GetSize(); vi != ve; ++vi) {
lldb::VariableSP variable_sp(variables.GetVariableAtIndex(vi));
const ConstString &name(variable_sp->GetName());
const char *name_cstring = variable_sp->GetName().GetCString();
if (name.IsEmpty())
continue;
if (counted_names.count(name))
continue;
CompilerType var_type;
if (stack_frame_sp) {
lldb::ValueObjectSP valobj_sp =
stack_frame_sp->GetValueObjectForFrameVariable(
variable_sp, lldb::eNoDynamicValues);
if (!valobj_sp || valobj_sp->GetError().Fail()) {
// Ignore the variable if we couldn't find its corresponding value
// object.
// TODO if the expression tries to use an ignored variable, produce a
// sensible error.
continue;
} else {
var_type = valobj_sp->GetCompilerType();
}
if (var_type.IsValid() && !SwiftASTContext::IsFullyRealized(var_type)) {
lldb::ValueObjectSP dynamic_valobj_sp =
valobj_sp->GetDynamicValue(lldb::eDynamicDontRunTarget);
if (!dynamic_valobj_sp || dynamic_valobj_sp->GetError().Fail()) {
continue;
}
}
}
if (!var_type.IsValid()) {
Type *var_lldb_type = variable_sp->GetType();
if (var_lldb_type)
var_type = var_lldb_type->GetFullCompilerType();
}
if (!var_type.IsValid())
continue;
if (!llvm::isa<SwiftASTContext>(var_type.GetTypeSystem()))
continue;
Status error;
CompilerType target_type = ast_context.ImportType(var_type, error);
// If the import failed, give up
if (!target_type.IsValid())
continue;
// Make sure to resolve all archetypes in the variable type.
if (language_runtime && stack_frame_sp)
target_type = language_runtime->DoArchetypeBindingForType(
*stack_frame_sp, target_type);
// If we couldn't fully realize the type, then we aren't going to get very
// far making a local out of it,
// so discard it here.
Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TYPES |
LIBLLDB_LOG_EXPRESSIONS));
if (!SwiftASTContext::IsFullyRealized(target_type)) {
if (log) {
log->Printf("Discarding local %s because we couldn't fully realize "
"it, our best attempt was: %s.",
name_cstring,
target_type.GetTypeName().AsCString("<unknown>"));
}
continue;
}
SwiftASTManipulatorBase::VariableMetadataSP metadata_sp(
new VariableMetadataVariable(variable_sp));
const char *overridden_name = name_cstring;
if (name == s_self_name) {
overridden_name = ConstString("$__lldb_injected_self").AsCString();
if (log) {
swift::TypeBase *swift_type =
(swift::TypeBase *)target_type.GetOpaqueQualType();
if (swift_type) {
std::string s;
llvm::raw_string_ostream ss(s);
swift_type->dump(ss);
ss.flush();
log->Printf("Adding injected self: type (%p) context(%p) is: %s",
swift_type, ast_context.GetASTContext(), s.c_str());
}
}
}
SwiftASTManipulator::VariableInfo variable_info(
target_type,
ast_context.GetASTContext()->getIdentifier(overridden_name),
metadata_sp,
swift::VarDecl::Specifier::Var);
local_variables.push_back(variable_info);
counted_names.insert(name);
}
if (handling_globals) {
// Okay, now we're done...
break;
} else if (block == top_block) {
// Now add the containing module block, that's what holds the module
// globals:
handling_globals = true;
} else
block = block->GetParent();
}
}
static void ResolveSpecialNames(
SymbolContext &sc, SwiftASTContext &ast_context,
llvm::SmallVectorImpl<swift::Identifier> &special_names,
llvm::SmallVectorImpl<SwiftASTManipulator::VariableInfo> &local_variables) {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
if (!sc.target_sp)
return;
SwiftPersistentExpressionState *persistent_state =
llvm::cast<SwiftPersistentExpressionState>(
sc.target_sp->GetPersistentExpressionStateForLanguage(
lldb::eLanguageTypeSwift));
std::set<ConstString> resolved_names;
for (swift::Identifier &name : special_names) {
ConstString name_cs = ConstString(name.str());
if (resolved_names.count(name_cs))
continue;
resolved_names.insert(name_cs);
if (log)
log->Printf("Resolving special name %s", name_cs.AsCString());
lldb::ExpressionVariableSP expr_var_sp =
persistent_state->GetVariable(name_cs);
if (!expr_var_sp)
continue;
CompilerType var_type = expr_var_sp->GetCompilerType();
if (!var_type.IsValid())
continue;
if (!llvm::isa<SwiftASTContext>(var_type.GetTypeSystem()))
continue;
CompilerType target_type;
Status error;
target_type = ast_context.ImportType(var_type, error);
if (!target_type)
continue;
SwiftASTManipulatorBase::VariableMetadataSP metadata_sp(
new VariableMetadataPersistent(expr_var_sp));
auto specifier = llvm::cast<SwiftExpressionVariable>(expr_var_sp.get())
->GetIsModifiable()
? swift::VarDecl::Specifier::Var
: swift::VarDecl::Specifier::Let;
SwiftASTManipulator::VariableInfo variable_info(
target_type, ast_context.GetASTContext()->getIdentifier(name.str()),
metadata_sp, specifier);
local_variables.push_back(variable_info);
}
}
//----------------------------------------------------------------------
// Diagnostics are part of the ShintASTContext and we must enable and
// disable colorization manually in the ShintASTContext. We need to
// ensure that if we modify the setting that we restore it to what it
// was. This class helps us to do that without having to intrument all
// returns from a function, like in SwiftExpressionParser::Parse(...).
//----------------------------------------------------------------------
class SetColorize {
public:
SetColorize(SwiftASTContext *swift_ast, bool colorize)
: m_swift_ast(swift_ast),
m_saved_colorize(swift_ast->SetColorizeDiagnostics(colorize)) {}
~SetColorize() { m_swift_ast->SetColorizeDiagnostics(m_saved_colorize); }
protected:
SwiftASTContext *m_swift_ast;
const bool m_saved_colorize;
};
/// Returns the buffer_id for the expression's source code.
static std::pair<unsigned, std::string>
CreateMainFile(SwiftASTContext &swift_ast_context, StringRef filename,
StringRef text, const EvaluateExpressionOptions &options) {
const bool generate_debug_info = options.GetGenerateDebugInfo();
swift_ast_context.SetGenerateDebugInfo(generate_debug_info
? swift::IRGenDebugInfoKind::Normal
: swift::IRGenDebugInfoKind::None);
swift::IRGenOptions &ir_gen_options = swift_ast_context.GetIRGenOptions();
if (generate_debug_info) {
std::string temp_source_path;
if (ExpressionSourceCode::SaveExpressionTextToTempFile(text, options,
temp_source_path)) {
auto error_or_buffer_ap =
llvm::MemoryBuffer::getFile(temp_source_path.c_str());
if (error_or_buffer_ap.getError() == std::error_condition()) {
unsigned buffer_id =
swift_ast_context.GetSourceManager().addNewSourceBuffer(
std::move(error_or_buffer_ap.get()));
llvm::SmallString<256> source_dir(temp_source_path);
llvm::sys::path::remove_filename(source_dir);
ir_gen_options.DebugCompilationDir = source_dir.str();
return {buffer_id, temp_source_path};
}
}
}
std::unique_ptr<llvm::MemoryBuffer> expr_buffer(
llvm::MemoryBuffer::getMemBufferCopy(text, filename));
unsigned buffer_id = swift_ast_context.GetSourceManager().addNewSourceBuffer(
std::move(expr_buffer));
return {buffer_id, filename};
}
/// Attempt to materialize one variable.
static llvm::Optional<SwiftExpressionParser::SILVariableInfo>
MaterializeVariable(SwiftASTManipulatorBase::VariableInfo &variable,
SwiftUserExpression &user_expression,
Materializer &materializer,
SwiftASTManipulator &manipulator,
lldb::StackFrameWP &stack_frame_wp,
DiagnosticManager &diagnostic_manager, Log *log,
bool repl) {
uint64_t offset = 0;
bool needs_init = false;
bool is_result =
variable.MetadataIs<SwiftASTManipulatorBase::VariableMetadataResult>();
bool is_error =
variable.MetadataIs<SwiftASTManipulatorBase::VariableMetadataError>();
if (is_result || is_error) {
needs_init = true;
Status error;
if (repl) {
if (swift::TypeBase *swift_type =
(swift::TypeBase *)variable.GetType().GetOpaqueQualType()) {
if (!swift_type->getCanonicalType()->isVoid()) {
auto &repl_mat = *llvm::cast<SwiftREPLMaterializer>(&materializer);
if (is_result)
offset = repl_mat.AddREPLResultVariable(
variable.GetType(), variable.GetDecl(),
&user_expression.GetResultDelegate(), error);
else
offset = repl_mat.AddREPLResultVariable(
variable.GetType(), variable.GetDecl(),
&user_expression.GetErrorDelegate(), error);
}
}
} else {
CompilerType actual_type(variable.GetType());
if (Flags(actual_type.GetTypeInfo())
.AllSet(lldb::eTypeIsSwift | lldb::eTypeIsArchetype)) {
lldb::StackFrameSP stack_frame_sp = stack_frame_wp.lock();
if (stack_frame_sp && stack_frame_sp->GetThread() &&
stack_frame_sp->GetThread()->GetProcess()) {
SwiftLanguageRuntime *swift_runtime = stack_frame_sp->GetThread()
->GetProcess()
->GetSwiftLanguageRuntime();
if (swift_runtime) {
actual_type = swift_runtime->GetConcreteType(
stack_frame_sp.get(), actual_type.GetTypeName());
if (actual_type.IsValid())
variable.SetType(actual_type);
else
actual_type = variable.GetType();
}
}
}
swift::Type actual_swift_type =
swift::Type((swift::TypeBase *)actual_type.GetOpaqueQualType());
swift::Type fixed_type = manipulator.FixupResultType(
actual_swift_type, user_expression.GetLanguageFlags());
if (!fixed_type.isNull()) {
actual_type =
CompilerType(actual_type.GetTypeSystem(), fixed_type.getPointer());
variable.SetType(actual_type);
}
if (is_result)
offset = materializer.AddResultVariable(
actual_type, false, true, &user_expression.GetResultDelegate(),
error);
else
offset = materializer.AddResultVariable(
actual_type, false, true, &user_expression.GetErrorDelegate(),
error);
}
if (!error.Success()) {
diagnostic_manager.Printf(
eDiagnosticSeverityError, "couldn't add %s variable to struct: %s.\n",
is_result ? "result" : "error", error.AsCString());
return llvm::None;
}
if (log)
log->Printf("Added %s variable to struct at offset %llu",
is_result ? "result" : "error", (unsigned long long)offset);
} else if (variable.MetadataIs<VariableMetadataVariable>()) {
Status error;
VariableMetadataVariable *variable_metadata =
static_cast<VariableMetadataVariable *>(variable.m_metadata.get());
offset = materializer.AddVariable(variable_metadata->m_variable_sp, error);
if (!error.Success()) {
diagnostic_manager.Printf(eDiagnosticSeverityError,
"couldn't add variable to struct: %s.\n",
error.AsCString());
return llvm::None;
}
if (log)
log->Printf("Added variable %s to struct at offset %llu",
variable_metadata->m_variable_sp->GetName().AsCString(),
(unsigned long long)offset);
} else if (variable.MetadataIs<VariableMetadataPersistent>()) {
VariableMetadataPersistent *variable_metadata =
static_cast<VariableMetadataPersistent *>(variable.m_metadata.get());
needs_init = llvm::cast<SwiftExpressionVariable>(
variable_metadata->m_persistent_variable_sp.get())
->m_swift_flags &
SwiftExpressionVariable::EVSNeedsInit;
Status error;
offset = materializer.AddPersistentVariable(
variable_metadata->m_persistent_variable_sp,
&user_expression.GetPersistentVariableDelegate(), error);
if (!error.Success()) {
diagnostic_manager.Printf(eDiagnosticSeverityError,
"couldn't add variable to struct: %s.\n",
error.AsCString());
return llvm::None;
}
if (log)
log->Printf(
"Added persistent variable %s with flags 0x%llx to "
"struct at offset %llu",
variable_metadata->m_persistent_variable_sp->GetName().AsCString(),
(unsigned long long)
variable_metadata->m_persistent_variable_sp->m_flags,
(unsigned long long)offset);
}
return SwiftExpressionParser::SILVariableInfo(variable.GetType(), offset,
needs_init);
}
unsigned SwiftExpressionParser::Parse(DiagnosticManager &diagnostic_manager,
uint32_t first_line, uint32_t last_line,
uint32_t line_offset) {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
// In the case of playgrounds, we turn all rewriting functionality off.
const bool repl = m_options.GetREPLEnabled();
const bool playground = m_options.GetPlaygroundTransformEnabled();
if (!m_swift_ast_context) {
diagnostic_manager.PutString(
eDiagnosticSeverityError,
"No AST context to parse into. Please parse with a target.\n");
return 1;
}
// Lazily get the clang importer if we can to make sure it exists in case we
// need it
if (!m_swift_ast_context->GetClangImporter()) {
diagnostic_manager.PutString(
eDiagnosticSeverityError,
"Swift expressions require OS X 10.10 / iOS 8 SDKs or later.\n");
return 1;
}
if (m_swift_ast_context->HasFatalErrors()) {
diagnostic_manager.PutString(eDiagnosticSeverityError,
"The AST context is in a fatal error state.");
return 1;
}
swift::ASTContext *ast_context = m_swift_ast_context->GetASTContext();
if (!ast_context) {
diagnostic_manager.PutString(
eDiagnosticSeverityError,
"Couldn't initialize the AST context. Please check your settings.");
return 1;
}
if (m_swift_ast_context->HasFatalErrors()) {
diagnostic_manager.PutString(eDiagnosticSeverityError,
"The AST context is in a fatal error state.");
return 1;
}
// If we are using the playground, hand import the necessary modules.
// FIXME: We won't have to do this once the playground adds import statements
// for the things it needs itself.
if (playground) {
SwiftPersistentExpressionState *persistent_state =
llvm::cast<SwiftPersistentExpressionState>(
m_sc.target_sp->GetPersistentExpressionStateForLanguage(
lldb::eLanguageTypeSwift));
persistent_state->AddHandLoadedModule(ConstString("Swift"));
}
// TODO find a way to get contraint-solver output sent to a stream so we can
// log it
// m_swift_ast_context->GetLanguageOptions().DebugConstraintSolver = true;
m_swift_ast_context->ClearDiagnostics();
// Make a class that will set/restore the colorize setting in the
// SwiftASTContext for us
// SetColorize colorize(m_swift_ast_context,
// stream.GetFlags().Test(Stream::eANSIColor));
m_swift_ast_context->GetLanguageOptions().DebuggerSupport = true;
m_swift_ast_context->GetLanguageOptions().EnableDollarIdentifiers =
true; // No longer part of debugger support, set it separately.
m_swift_ast_context->GetLanguageOptions().EnableAccessControl =
(repl || playground);
m_swift_ast_context->GetLanguageOptions().EnableTargetOSChecking = false;
{
lldb::StackFrameSP this_frame_sp(m_stack_frame_wp.lock());
if (this_frame_sp) {
lldb::ProcessSP process_sp(this_frame_sp->CalculateProcess());
if (process_sp) {
Status error;
if (!process_sp->GetObjCLanguageRuntime()) {
m_swift_ast_context->GetLanguageOptions().EnableObjCInterop = false;
}
}
}
}
if (repl || playground) {
m_swift_ast_context->GetLanguageOptions().Playground = true;
m_swift_ast_context->GetIRGenOptions().Playground = true;
} else {
m_swift_ast_context->GetLanguageOptions().Playground = true;
m_swift_ast_context->GetIRGenOptions().Playground = false;
}
// For the expression parser and REPL we want to relax the requirement that
// you put "try" in
// front of every expression that might throw.
if (!playground) {
m_swift_ast_context->GetLanguageOptions().EnableThrowWithoutTry = true;
}
m_swift_ast_context->GetIRGenOptions().OptMode
= swift::OptimizationMode::NoOptimization;
m_swift_ast_context->GetIRGenOptions().Verify =
false; // normally we'd like to verify, but unfortunately the verifier's
// error mode is abort().
unsigned buffer_id;
std::string main_filename;
std::tie(buffer_id, main_filename) =
CreateMainFile(*m_swift_ast_context, repl ? "<REPL>" : "<EXPR>",
m_expr.Text(), m_options);
char expr_name_buf[32];
snprintf(expr_name_buf, sizeof(expr_name_buf), "__lldb_expr_%u",
m_options.GetExpressionNumber());
swift::Identifier module_id(ast_context->getIdentifier(expr_name_buf));
swift::ModuleDecl *module = swift::ModuleDecl::create(module_id, *ast_context);
const swift::SourceFile::ImplicitModuleImportKind implicit_import_kind =
swift::SourceFile::ImplicitModuleImportKind::Stdlib;
m_swift_ast_context->GetCompilerInvocation().getFrontendOptions().ModuleName =
expr_name_buf;
m_swift_ast_context->GetCompilerInvocation().getIRGenOptions().ModuleName =
expr_name_buf;
swift::SourceFileKind source_file_kind = swift::SourceFileKind::Library;
if (playground || repl) {
source_file_kind = swift::SourceFileKind::Main;
}
swift::SourceFile *source_file = new (*ast_context) swift::SourceFile(
*module, source_file_kind, buffer_id, implicit_import_kind,
/*Keep tokens*/false);
module->addFile(*source_file);
bool done = false;
SILVariableMap variable_map;
LLDBNameLookup *external_lookup =
new LLDBNameLookup(*this, *source_file, variable_map, m_sc);
// FIXME: This call is here just so that the we keep the DebuggerClients alive
// as long as the Module we are not
// inserting them in.
m_swift_ast_context->AddDebuggerClient(external_lookup);
swift::PersistentParserState persistent_state;
while (!done) {
swift::parseIntoSourceFile(*source_file, buffer_id, &done, nullptr,
&persistent_state);
if (m_swift_ast_context->HasErrors()) {
m_swift_ast_context->PrintDiagnostics(diagnostic_manager, buffer_id,
first_line, last_line, line_offset);
return 1;
}
}
// This currently crashes with Assertion failed: (BufferID != -1), function
// findBufferContainingLoc, file
// llvm/tools/swift/include/swift/Basic/SourceManager.h, line 92.
// if (log)
// {
// std::string s;
// llvm::raw_string_ostream ss(s);
// source_file->dump(ss);
// ss.flush();
//
// log->Printf("Source file after parsing:");
// log->PutCString(s.c_str());
// }
if (!done) {
diagnostic_manager.PutString(
eDiagnosticSeverityError,
"Parse did not consume the whole expression.");
return 1;
}
std::unique_ptr<SwiftASTManipulator> code_manipulator;
if (!playground) {
code_manipulator.reset(new SwiftASTManipulator(*source_file, repl));
code_manipulator->RewriteResult();
}
Status auto_import_error;
if (!PerformAutoImport(*source_file, false, auto_import_error)) {
diagnostic_manager.Printf(eDiagnosticSeverityError, "in auto-import:\n%s",
auto_import_error.AsCString());
return 1;
}
// Swift Modules that rely on shared libraries (not frameworks) don't record
// the link information in the
// swiftmodule file, so we can't really make them work without outside
// information. However, in the REPL you can
// added -L & -l options to the initial compiler startup, and we should dlopen
// anything that's been stuffed
// on there and hope it will be useful later on.
if (repl) {
lldb::StackFrameSP this_frame_sp(m_stack_frame_wp.lock());
if (this_frame_sp) {
lldb::ProcessSP process_sp(this_frame_sp->CalculateProcess());
if (process_sp) {
Status error;
m_swift_ast_context->LoadExtraDylibs(*process_sp.get(), error);
}
}
}
if (!playground && !repl) {
lldb::StackFrameSP stack_frame_sp = m_stack_frame_wp.lock();
bool local_context_is_swift = true;
if (m_sc.block) {
Function *function = m_sc.block->CalculateSymbolContextFunction();
if (function && function->GetLanguage() != lldb::eLanguageTypeSwift)
local_context_is_swift = false;
}
llvm::SmallVector<SwiftASTManipulator::VariableInfo, 5> local_variables;
if (local_context_is_swift) {
AddRequiredAliases(m_sc.block, stack_frame_sp, *m_swift_ast_context,
*code_manipulator, m_expr.GetSwiftGenericInfo());
// Register all local variables so that lookups to them resolve
CountLocals(m_sc, stack_frame_sp, *m_swift_ast_context, local_variables);
}
// Register all magic variables
llvm::SmallVector<swift::Identifier, 2> special_names;
llvm::StringRef persistent_var_prefix;
if (!repl)
persistent_var_prefix = "$";
code_manipulator->FindSpecialNames(special_names, persistent_var_prefix);
ResolveSpecialNames(m_sc, *m_swift_ast_context, special_names,
local_variables);
code_manipulator->AddExternalVariables(local_variables);
// This currently crashes with Assertion failed: (BufferID != -1), function
// findBufferContainingLoc, file
// llvm/tools/swift/include/swift/Basic/SourceManager.h, line 92.
// if (log)
// {
// std::string s;
// llvm::raw_string_ostream ss(s);
// source_file->dump(ss);
// ss.flush();
//
// log->Printf("Source file after code manipulation:");
// log->PutCString(s.c_str());
// }
stack_frame_sp.reset();
}
swift::performNameBinding(*source_file);
if (m_swift_ast_context->HasErrors()) {
m_swift_ast_context->PrintDiagnostics(diagnostic_manager, buffer_id,
first_line, last_line, line_offset);
return 1;
}
// Do the auto-importing after Name Binding, that's when the Imports for the
// source file are figured out.
{
std::lock_guard<std::recursive_mutex> global_context_locker(
IRExecutionUnit::GetLLVMGlobalContextMutex());
Status auto_import_error;
if (!PerformAutoImport(*source_file, true, auto_import_error)) {
diagnostic_manager.Printf(eDiagnosticSeverityError, "in auto-import:\n%s",
auto_import_error.AsCString());
return 1;
}
}
swift::TopLevelContext top_level_context; // not persistent because we're
// building source files one at a
// time
swift::OptionSet<swift::TypeCheckingFlags> type_checking_options;
swift::performTypeChecking(*source_file, top_level_context,
type_checking_options);
if (m_swift_ast_context->HasErrors()) {
m_swift_ast_context->PrintDiagnostics(diagnostic_manager, buffer_id,
first_line, last_line, line_offset);
return 1;
}
if (log) {
std::string s;
llvm::raw_string_ostream ss(s);
source_file->dump(ss);
ss.flush();
log->Printf("Source file after type checking:");
log->PutCString(s.c_str());
}
if (repl) {
code_manipulator->MakeDeclarationsPublic();
}
Status error;
if (!playground) {
code_manipulator->FixupResultAfterTypeChecking(error);
if (!error.Success()) {
diagnostic_manager.PutString(eDiagnosticSeverityError,
error.AsCString());
return 1;
}
} else {
swift::performPlaygroundTransform(*source_file, true);
swift::typeCheckExternalDefinitions(*source_file);
}
// I think we now have to do the name binding and type checking again, but
// there should be only the result
// variable to bind up at this point.
if (log) {
std::string s;
llvm::raw_string_ostream ss(s);
source_file->dump(ss);
ss.flush();
log->Printf("Source file after FixupResult:");
log->PutCString(s.c_str());
}
if (m_sc.target_sp && !playground) {
if (!code_manipulator->CheckPatternBindings()) // Do this first, so we don't
// pollute the persistent
// variable namespace
{
m_swift_ast_context->PrintDiagnostics(diagnostic_manager, buffer_id,
first_line, last_line, line_offset);
return 1;
}
Status error;
SwiftASTContext *scratch_ast_context =
m_sc.target_sp->GetScratchSwiftASTContext(error);
if (scratch_ast_context) {
SwiftPersistentExpressionState *persistent_state =
llvm::dyn_cast<SwiftPersistentExpressionState>(
scratch_ast_context->GetPersistentExpressionState());
llvm::SmallVector<size_t, 1> declaration_indexes;
code_manipulator->FindVariableDeclarations(declaration_indexes, repl);
for (size_t declaration_index : declaration_indexes) {
SwiftASTManipulator::VariableInfo &variable_info =
code_manipulator->GetVariableInfo()[declaration_index];
CompilerType imported_type =
ImportType(*scratch_ast_context, variable_info.GetType());
if (imported_type) {
lldb::ExpressionVariableSP persistent_variable =
persistent_state->AddNewlyConstructedVariable(
new SwiftExpressionVariable(
m_sc.target_sp.get(),
ConstString(variable_info.GetName().str()), imported_type,
m_sc.target_sp->GetArchitecture().GetByteOrder(),
m_sc.target_sp->GetArchitecture().GetAddressByteSize()));
if (repl) {
persistent_variable->m_flags |= ExpressionVariable::EVKeepInTarget;
persistent_variable->m_flags |=
ExpressionVariable::EVIsProgramReference;
} else {
persistent_variable->m_flags |=
ExpressionVariable::EVNeedsAllocation;
persistent_variable->m_flags |= ExpressionVariable::EVKeepInTarget;
llvm::cast<SwiftExpressionVariable>(persistent_variable.get())
->m_swift_flags |= SwiftExpressionVariable::EVSNeedsInit;
}
swift::VarDecl *decl = variable_info.GetDecl();
if (decl) {
if (decl->isLet()) {
llvm::cast<SwiftExpressionVariable>(persistent_variable.get())
->SetIsModifiable(false);
}
if (decl->getStorageKind() ==
swift::VarDecl::StorageKindTy::Computed) {
llvm::cast<SwiftExpressionVariable>(persistent_variable.get())
->SetIsComputed(true);
}
}
variable_info.m_metadata.reset(
new VariableMetadataPersistent(persistent_variable));
persistent_state->RegisterSwiftPersistentDecl(decl);
}
}
if (repl) {
llvm::SmallVector<swift::ValueDecl *, 1> non_variables;
code_manipulator->FindNonVariableDeclarations(non_variables);
for (swift::ValueDecl *decl : non_variables) {
persistent_state->RegisterSwiftPersistentDecl(decl);
}
}
}
}
if (!playground && !repl) {
code_manipulator->FixCaptures();
// This currently crashes with Assertion failed: (BufferID != -1), function
// findBufferContainingLoc, file
// llvm/tools/swift/include/swift/Basic/SourceManager.h, line 92.
// if (log)
// {
// std::string s;
// llvm::raw_string_ostream ss(s);
// source_file->dump(ss);
// ss.flush();
//
// log->Printf("Source file after capture fixing:");
// log->PutCString(s.c_str());
// }
if (log) {
log->Printf("Variables:");
for (const SwiftASTManipulatorBase::VariableInfo &variable :
code_manipulator->GetVariableInfo()) {
StreamString ss;
variable.Print(ss);
log->Printf(" %s", ss.GetData());
}
}
}
if (!playground)
if (auto *materializer = m_expr.GetMaterializer())
for (auto &variable : code_manipulator->GetVariableInfo()) {
auto &swift_expr = *static_cast<SwiftUserExpression *>(&m_expr);
auto var_info = MaterializeVariable(variable, swift_expr, *materializer,
*code_manipulator, m_stack_frame_wp,
diagnostic_manager, log, repl);
if (!var_info)
return 1;
const char *name = ConstString(variable.GetName().get()).GetCString();
variable_map[name] = *var_info;
}
std::unique_ptr<swift::SILModule> sil_module(swift::performSILGeneration(
*source_file, m_swift_ast_context->GetSILOptions()));
if (log) {
std::string s;
llvm::raw_string_ostream ss(s);
const bool verbose = false;
sil_module->print(ss, verbose, module);
ss.flush();
log->Printf("SIL module before linking:");
log->PutCString(s.c_str());
}
swift::performSILLinking(sil_module.get());
if (m_swift_ast_context->HasErrors()) {
m_swift_ast_context->PrintDiagnostics(diagnostic_manager, buffer_id,
first_line, last_line, line_offset);
return 1;
}
if (log) {
std::string s;
llvm::raw_string_ostream ss(s);
const bool verbose = false;
sil_module->print(ss, verbose, module);
ss.flush();
log->Printf("Generated SIL module:");
log->PutCString(s.c_str());
}
runSILDiagnosticPasses(*sil_module);
if (log) {
std::string s;
llvm::raw_string_ostream ss(s);
const bool verbose = false;
sil_module->print(ss, verbose, module);
ss.flush();
log->Printf("SIL module after diagnostic passes:");
log->PutCString(s.c_str());
}
if (m_swift_ast_context->HasErrors()) {
m_swift_ast_context->PrintDiagnostics(diagnostic_manager, buffer_id,
first_line, last_line, line_offset);
return 1;
}
{
std::lock_guard<std::recursive_mutex> global_context_locker(
IRExecutionUnit::GetLLVMGlobalContextMutex());
m_module = swift::performIRGeneration(
m_swift_ast_context->GetIRGenOptions(), module, std::move(sil_module),
"lldb_module", swift::PrimarySpecificPaths("", main_filename),
SwiftASTContext::GetGlobalLLVMContext(), llvm::ArrayRef<std::string>());
}
if (m_swift_ast_context->HasErrors()) {
m_swift_ast_context->PrintDiagnostics(diagnostic_manager, buffer_id,
first_line, last_line, line_offset);
return 1;
}
if (!m_module) {
diagnostic_manager.PutString(
eDiagnosticSeverityError,
"Couldn't IRGen expression, no additional error");
return 1;
}
if (log) {
std::string s;
llvm::raw_string_ostream ss(s);
m_module->print(ss, NULL);
ss.flush();
log->Printf("Generated IR module:");
log->PutCString(s.c_str());
}
{
std::lock_guard<std::recursive_mutex> global_context_locker(
IRExecutionUnit::GetLLVMGlobalContextMutex());
LLVMVerifyModule((LLVMOpaqueModule *)m_module.get(), LLVMReturnStatusAction,
nullptr);
}
bool fail = m_swift_ast_context->HasErrors();
if (!fail) {
// The Parse succeeded! Now put this module into the context's list of
// loaded modules,
// and copy the Decls that were globalized as part of the parse from the
// staging area in the
// external lookup object into the SwiftPersistentExpressionState.
ast_context->LoadedModules.insert(std::make_pair(module_id, module));
if (m_swift_ast_context)
m_swift_ast_context->CacheModule(module);
if (m_sc.target_sp) {
SwiftPersistentExpressionState *persistent_state =
llvm::cast<SwiftPersistentExpressionState>(
m_sc.target_sp->GetPersistentExpressionStateForLanguage(
lldb::eLanguageTypeSwift));
persistent_state->CopyInSwiftPersistentDecls(
external_lookup->GetStagedDecls());
}
}
return fail ? 1 : 0;
}
static bool FindFunctionInModule(ConstString &mangled_name,
llvm::Module *module, const char *orig_name,
bool exact) {
swift::Demangle::Context demangle_ctx;
for (llvm::Module::iterator fi = module->getFunctionList().begin(),
fe = module->getFunctionList().end();
fi != fe; ++fi) {
if (exact) {
if (!fi->getName().str().compare(orig_name)) {
mangled_name.SetCString(fi->getName().str().c_str());
return true;
}
} else {
if (fi->getName().str().find(orig_name) != std::string::npos) {
mangled_name.SetCString(fi->getName().str().c_str());
return true;
}
// The new demangling is cannier about compression, so the name may
// not be in the mangled name plain. Let's demangle it and see if we
// can find it in the demangled nodes.
demangle_ctx.clear();
swift::Demangle::NodePointer node_ptr = demangle_ctx.demangleSymbolAsNode(fi->getName());
if (node_ptr)
{
if (node_ptr->getKind() != swift::Demangle::Node::Kind::Global)
continue;
if (node_ptr->getNumChildren() != 1)
continue;
node_ptr = node_ptr->getFirstChild();
if (node_ptr->getKind() != swift::Demangle::Node::Kind::Function)
continue;
size_t num_children = node_ptr->getNumChildren();
for (size_t i = 0; i < num_children; i++)
{
swift::Demangle::NodePointer child_ptr = node_ptr->getChild(i);
if (child_ptr->getKind() == swift::Demangle::Node::Kind::Identifier) {
if (!child_ptr->hasText())
continue;
if(child_ptr->getText().contains(orig_name))
{
mangled_name.SetCString(fi->getName().str().c_str());
return true;
}
}
}
}
}
}
return false;
}
Status SwiftExpressionParser::PrepareForExecution(
lldb::addr_t &func_addr, lldb::addr_t &func_end,
lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx,
bool &can_interpret, ExecutionPolicy execution_policy) {
Status err;
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
if (!m_module) {
err.SetErrorString("Can't prepare a NULL module for execution");
return err;
}
const char *orig_name = nullptr;
bool exact = false;
if (m_options.GetPlaygroundTransformEnabled() || m_options.GetREPLEnabled()) {
orig_name = "main";
exact = true;
} else {
orig_name = "$__lldb_expr";
}
ConstString function_name;
if (!FindFunctionInModule(function_name, m_module.get(), orig_name, exact)) {
err.SetErrorToGenericError();
err.SetErrorStringWithFormat("Couldn't find %s() in the module", orig_name);
return err;
} else {
if (log)
log->Printf("Found function %s for %s", function_name.AsCString(),
"$__lldb_expr");
}
// Retrieve an appropriate symbol context.
SymbolContext sc;
if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) {
sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything);
} else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) {
sc.target_sp = target_sp;
}
std::vector<std::string> features;
std::unique_ptr<llvm::LLVMContext> llvm_context_up;
m_execution_unit_sp.reset(
new IRExecutionUnit(llvm_context_up,
m_module, // handed off here
function_name, exe_ctx.GetTargetSP(), sc, features));
// TODO figure out some way to work ClangExpressionDeclMap into this or do the
// equivalent
// for Swift
m_execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
execution_unit_sp = m_execution_unit_sp;
m_execution_unit_sp.reset();
return err;
}
bool SwiftExpressionParser::RewriteExpression(
DiagnosticManager &diagnostic_manager) {
// There isn't a Swift equivalent to clang::Rewriter, so we'll just use
// that...
if (!m_swift_ast_context)
return false;
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
swift::SourceManager &source_manager =
m_swift_ast_context->GetSourceManager();
const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics();
size_t num_diags = diagnostics.size();
if (num_diags == 0)
return false;
clang::RewriteBuffer rewrite_buf;
llvm::StringRef text_ref(m_expr.Text());
rewrite_buf.Initialize(text_ref);
for (const Diagnostic *diag : diagnostic_manager.Diagnostics()) {
const SwiftDiagnostic *diagnostic = llvm::dyn_cast<SwiftDiagnostic>(diag);
if (!(diagnostic && diagnostic->HasFixIts()))
continue;
const SwiftDiagnostic::FixItList &fixits = diagnostic->FixIts();
std::vector<swift::CharSourceRange> source_ranges;
for (const swift::DiagnosticInfo::FixIt &fixit : fixits) {
const swift::CharSourceRange &range = fixit.getRange();
swift::SourceLoc start_loc = range.getStart();
if (!start_loc.isValid()) {
// getLocOffsetInBuffer will assert if you pass it an invalid location,
// so we have to check that first.
if (log)
log->Printf(
"SwiftExpressionParser::RewriteExpression: ignoring fixit since "
"it contains an invalid source location: %s.",
range.str().str().c_str());
return false;
}
// ReplaceText can't handle replacing the same source range more than
// once, so we have to check that
// before we proceed:
if (std::find(source_ranges.begin(), source_ranges.end(), range) !=
source_ranges.end()) {
if (log)
log->Printf(
"SwiftExpressionParser::RewriteExpression: ignoring fix-it since "
"source range appears twice: %s.\n",
range.str().str().c_str());
return false;
} else
source_ranges.push_back(range);
// ReplaceText will either assert or crash if the start_loc isn't inside
// the buffer it is said to
// reside in. That shouldn't happen, but it doesn't hurt to check before
// we call ReplaceText.
auto *Buffer = source_manager.getLLVMSourceMgr().getMemoryBuffer(
diagnostic->GetBufferID());
if (!(start_loc.getOpaquePointerValue() >= Buffer->getBuffer().begin() &&
start_loc.getOpaquePointerValue() <= Buffer->getBuffer().end())) {
if (log)
log->Printf(
"SwiftExpressionParser::RewriteExpression: ignoring fixit since "
"it contains a source location not in the specified buffer: %s.",
range.str().str().c_str());
}
unsigned offset = source_manager.getLocOffsetInBuffer(
range.getStart(), diagnostic->GetBufferID());
rewrite_buf.ReplaceText(offset, range.getByteLength(), fixit.getText());
}
}
std::string fixed_expression;
llvm::raw_string_ostream out_stream(fixed_expression);
rewrite_buf.write(out_stream);
out_stream.flush();
diagnostic_manager.SetFixedExpression(fixed_expression);
return true;
}
|
// tUtil.cpp
//
// Utility functions. These include hardware querying utilities like supported instruction sets, number or cores,
// hardware timer functions, and computer name/ip accessors.
//
// Copyright (c) 2004-2006, 2017, 2019 Tristan Grimmer.
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby
// granted, provided that the above copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
// AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
#ifdef PLATFORM_WIN
#include <Windows.h>
#include <intrin.h>
#endif
#include "Foundation/tStandard.h"
#include "System/tFile.h"
#include "System/tUtil.h"
#include "System/tPrint.h"
#ifdef PLATFORM_WIN
bool tSystem::tSupportsSSE()
{
int cpuInfo[4];
int infoType = 1;
__cpuid(cpuInfo, infoType);
int features = cpuInfo[3];
// SSE feature bit is 25.
if (features & (1 << 25))
return true;
else
return false;
}
bool tSystem::tSupportsSSE2()
{
int cpuInfo[4];
int infoType = 1;
__cpuid(cpuInfo, infoType);
int features = cpuInfo[3];
// SSE2 feature bit is 26.
if (features & (1 << 26))
return true;
else
return false;
}
#endif
tString tSystem::tGetCompName()
{
#ifdef PLATFORM_WIN
char name[128];
ulong nameSize = 128;
WinBool success = GetComputerName(name, &nameSize);
if (success)
return name;
#endif
return tString();
}
tString tSystem::tGetIPAddress()
{
// @todo Implement. Maybe use gethostname.
return tString();
}
#ifdef PLATFORM_WIN
int tSystem::tGetNumCores()
{
SYSTEM_INFO sysinfo;
tStd::tMemset(&sysinfo, 0, sizeof(sysinfo));
GetSystemInfo(&sysinfo);
if ((sysinfo.dwNumberOfProcessors == 0) || (sysinfo.dwNumberOfProcessors == -1))
return 1;
return sysinfo.dwNumberOfProcessors;
}
#endif
GetNumCores caches result for fast execution after the first time.
// tUtil.cpp
//
// Utility functions. These include hardware querying utilities like supported instruction sets, number or cores,
// hardware timer functions, and computer name/ip accessors.
//
// Copyright (c) 2004-2006, 2017, 2019 Tristan Grimmer.
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby
// granted, provided that the above copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
// AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
#ifdef PLATFORM_WIN
#include <Windows.h>
#include <intrin.h>
#endif
#include "Foundation/tStandard.h"
#include "System/tFile.h"
#include "System/tUtil.h"
#include "System/tPrint.h"
#ifdef PLATFORM_WIN
bool tSystem::tSupportsSSE()
{
int cpuInfo[4];
int infoType = 1;
__cpuid(cpuInfo, infoType);
int features = cpuInfo[3];
// SSE feature bit is 25.
if (features & (1 << 25))
return true;
else
return false;
}
bool tSystem::tSupportsSSE2()
{
int cpuInfo[4];
int infoType = 1;
__cpuid(cpuInfo, infoType);
int features = cpuInfo[3];
// SSE2 feature bit is 26.
if (features & (1 << 26))
return true;
else
return false;
}
#endif
tString tSystem::tGetCompName()
{
#ifdef PLATFORM_WIN
char name[128];
ulong nameSize = 128;
WinBool success = GetComputerName(name, &nameSize);
if (success)
return name;
#endif
return tString();
}
tString tSystem::tGetIPAddress()
{
// @todo Implement. Maybe use gethostname.
return tString();
}
#ifdef PLATFORM_WIN
int tSystem::tGetNumCores()
{
// Lets cache this value as it never changes.
static int numCores = 0;
if (numCores > 0)
return numCores;
SYSTEM_INFO sysinfo;
tStd::tMemset(&sysinfo, 0, sizeof(sysinfo));
GetSystemInfo(&sysinfo);
// dwNumberOfProcessors is unsigned, so can't say just > 0.
if ((sysinfo.dwNumberOfProcessors == 0) || (sysinfo.dwNumberOfProcessors == -1))
numCores = 1;
else
numCores = sysinfo.dwNumberOfProcessors;
return numCores;
}
#endif
|
/** @file
A brief file description
@section license License
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 "ts/ink_platform.h"
#include <strings.h>
#include <math.h>
#include "HttpTransact.h"
#include "HttpTransactHeaders.h"
#include "HttpSM.h"
#include "HttpCacheSM.h" //Added to get the scope of HttpCacheSM object - YTS Team, yamsat
#include "HttpDebugNames.h"
#include "time.h"
#include "ts/ParseRules.h"
#include "HTTP.h"
#include "HdrUtils.h"
#include "logging/Log.h"
#include "logging/LogUtils.h"
#include "Error.h"
#include "CacheControl.h"
#include "ControlMatcher.h"
#include "ReverseProxy.h"
#include "HttpBodyFactory.h"
#include "StatPages.h"
#include "../IPAllow.h"
#include "I_Machine.h"
static char range_type[] = "multipart/byteranges; boundary=RANGE_SEPARATOR";
#define RANGE_NUMBERS_LENGTH 60
#define TRANSACT_REMEMBER(_s, _e, _d) \
{ \
HttpSM *sm = (_s)->state_machine; \
sm->history[sm->history_pos % HISTORY_SIZE].file = __FILE__; \
sm->history[sm->history_pos % HISTORY_SIZE].line = __LINE__; \
sm->history[sm->history_pos % HISTORY_SIZE].event = _e; \
sm->history[sm->history_pos % HISTORY_SIZE].data = (void *)_d; \
sm->history_pos += 1; \
}
#define DebugTxn(tag, ...) DebugSpecific((s->state_machine->debug_on), tag, __VA_ARGS__)
extern HttpBodyFactory *body_factory;
inline static bool
is_localhost(const char *name, int len)
{
static const char local[] = "127.0.0.1";
return (len == (sizeof(local) - 1)) && (memcmp(name, local, len) == 0);
}
inline static void
simple_or_unavailable_server_retry(HttpTransact::State *s)
{
HTTP_RELEASE_ASSERT(!s->parent_result.parent_is_proxy());
// reponse is from a parent origin server.
HTTPStatus server_response = http_hdr_status_get(s->hdr_info.server_response.m_http);
DebugTxn("http_trans", "[simple_or_unavailabe_server_retry] server_response = %d, simple_retry_attempts: %d, numParents:%d ",
server_response, s->current.simple_retry_attempts, s->parent_params->numParents(&s->parent_result));
// simple retry is enabled, 0x1
if ((s->parent_result.retry_type() & PARENT_RETRY_SIMPLE) &&
s->current.simple_retry_attempts < s->parent_result.max_retries(PARENT_RETRY_SIMPLE) &&
server_response == HTTP_STATUS_NOT_FOUND) {
DebugTxn("parent_select", "RECEIVED A SIMPLE RETRY RESPONSE");
if (s->current.simple_retry_attempts < s->parent_params->numParents(&s->parent_result)) {
s->current.state = HttpTransact::PARENT_ORIGIN_RETRY;
s->current.retry_type = PARENT_RETRY_SIMPLE;
return;
} else {
DebugTxn("http_trans", "PARENT_RETRY_SIMPLE: retried all parents, send response to client.");
return;
}
}
// unavailable server retry is enabled 0x2
else if ((s->parent_result.retry_type() & PARENT_RETRY_UNAVAILABLE_SERVER) &&
s->current.unavailable_server_retry_attempts < s->parent_result.max_retries(PARENT_RETRY_UNAVAILABLE_SERVER) &&
s->parent_result.response_is_retryable(server_response)) {
DebugTxn("parent_select", "RECEIVED A PARENT_RETRY_UNAVAILABLE_SERVER RESPONSE");
if (s->current.unavailable_server_retry_attempts < s->parent_params->numParents(&s->parent_result)) {
s->current.state = HttpTransact::PARENT_ORIGIN_RETRY;
s->current.retry_type = PARENT_RETRY_UNAVAILABLE_SERVER;
return;
} else {
DebugTxn("http_trans", "PARENT_RETRY_UNAVAILABLE_SERVER: retried all parents, send error to client.");
return;
}
}
}
inline static bool
is_request_conditional(HTTPHdr *header)
{
uint64_t mask = (MIME_PRESENCE_IF_UNMODIFIED_SINCE | MIME_PRESENCE_IF_MODIFIED_SINCE | MIME_PRESENCE_IF_RANGE |
MIME_PRESENCE_IF_MATCH | MIME_PRESENCE_IF_NONE_MATCH);
return (header->presence(mask) &&
(header->method_get_wksidx() == HTTP_WKSIDX_GET || header->method_get_wksidx() == HTTP_WKSIDX_HEAD));
}
static inline bool
is_port_in_range(int port, HttpConfigPortRange *pr)
{
while (pr) {
if (pr->low == -1) {
return true;
} else if ((pr->low <= port) && (pr->high >= port)) {
return true;
}
pr = pr->next;
}
return false;
}
inline static void
update_cache_control_information_from_config(HttpTransact::State *s)
{
getCacheControl(&s->cache_control, &s->request_data, s->txn_conf);
s->cache_info.directives.does_config_permit_lookup &= (s->cache_control.never_cache == false);
s->cache_info.directives.does_config_permit_storing &= (s->cache_control.never_cache == false);
s->cache_info.directives.does_client_permit_storing =
HttpTransact::does_client_request_permit_storing(&s->cache_control, &s->hdr_info.client_request);
s->cache_info.directives.does_client_permit_lookup = HttpTransact::does_client_request_permit_cached_response(
s->txn_conf, &s->cache_control, &s->hdr_info.client_request, s->via_string);
s->cache_info.directives.does_client_permit_dns_storing =
HttpTransact::does_client_request_permit_dns_caching(&s->cache_control, &s->hdr_info.client_request);
if (s->client_info.http_version == HTTPVersion(0, 9)) {
s->cache_info.directives.does_client_permit_lookup = false;
s->cache_info.directives.does_client_permit_storing = false;
}
// Less than 0 means it wasn't overridden, so leave it alone.
if (s->cache_control.cache_responses_to_cookies >= 0) {
s->txn_conf->cache_responses_to_cookies = s->cache_control.cache_responses_to_cookies;
}
}
inline bool
HttpTransact::is_server_negative_cached(State *s)
{
if (s->host_db_info.app.http_data.last_failure != 0 &&
s->host_db_info.app.http_data.last_failure + s->txn_conf->down_server_timeout > s->client_request_time) {
return true;
} else {
// Make sure some nasty clock skew has not happened
// Use the server timeout to set an upperbound as to how far in the
// future we should tolerate bogus last failure times. This sets
// the upper bound to the time that we would ever consider a server
// down to 2*down_server_timeout
if (s->client_request_time + s->txn_conf->down_server_timeout < s->host_db_info.app.http_data.last_failure) {
s->host_db_info.app.http_data.last_failure = 0;
ink_assert(!"extreme clock skew");
return true;
}
return false;
}
}
inline static void
update_current_info(HttpTransact::CurrentInfo *into, HttpTransact::ConnectionAttributes *from, HttpTransact::LookingUp_t who,
int attempts)
{
into->request_to = who;
into->server = from;
into->attempts = attempts;
}
inline static void
update_dns_info(HttpTransact::DNSLookupInfo *dns, HttpTransact::CurrentInfo *from, int attempts, Arena * /* arena ATS_UNUSED */)
{
dns->looking_up = from->request_to;
dns->lookup_name = from->server->name;
dns->attempts = attempts;
}
inline static HTTPHdr *
find_appropriate_cached_resp(HttpTransact::State *s)
{
HTTPHdr *c_resp = NULL;
if (s->cache_info.object_store.valid()) {
c_resp = s->cache_info.object_store.response_get();
if (c_resp != NULL && c_resp->valid()) {
return c_resp;
}
}
ink_assert(s->cache_info.object_read != NULL);
return s->cache_info.object_read->response_get();
}
int response_cacheable_indicated_by_cc(HTTPHdr *response);
inline static bool
is_negative_caching_appropriate(HttpTransact::State *s)
{
if (!s->txn_conf->negative_caching_enabled || !s->hdr_info.server_response.valid()) {
return false;
}
switch (s->hdr_info.server_response.status_get()) {
case HTTP_STATUS_NO_CONTENT:
case HTTP_STATUS_USE_PROXY:
case HTTP_STATUS_BAD_REQUEST:
case HTTP_STATUS_FORBIDDEN:
case HTTP_STATUS_NOT_FOUND:
case HTTP_STATUS_METHOD_NOT_ALLOWED:
case HTTP_STATUS_REQUEST_URI_TOO_LONG:
case HTTP_STATUS_INTERNAL_SERVER_ERROR:
case HTTP_STATUS_NOT_IMPLEMENTED:
case HTTP_STATUS_BAD_GATEWAY:
case HTTP_STATUS_SERVICE_UNAVAILABLE:
case HTTP_STATUS_GATEWAY_TIMEOUT:
return true;
default:
break;
}
return false;
}
inline static HttpTransact::LookingUp_t
find_server_and_update_current_info(HttpTransact::State *s)
{
int host_len;
const char *host = s->hdr_info.client_request.host_get(&host_len);
if (is_localhost(host, host_len)) {
// Do not forward requests to local_host onto a parent.
// I just wanted to do this for cop heartbeats, someone else
// wanted it for all requests to local_host.
s->parent_result.result = PARENT_DIRECT;
} else if (s->method == HTTP_WKSIDX_CONNECT && s->http_config_param->disable_ssl_parenting) {
s->parent_params->findParent(&s->request_data, &s->parent_result);
if (!s->parent_result.is_some() || s->parent_result.is_api_result() || s->parent_result.parent_is_proxy()) {
DebugTxn("http_trans", "request not cacheable, so bypass parent");
s->parent_result.result = PARENT_DIRECT;
}
} else if (s->txn_conf->uncacheable_requests_bypass_parent && s->http_config_param->no_dns_forward_to_parent == 0 &&
!HttpTransact::is_request_cache_lookupable(s)) {
// request not lookupable and cacheable, so bypass parent if the parent is not an origin server.
// Note that the configuration of the proxy as well as the request
// itself affects the result of is_request_cache_lookupable();
// we are assuming both child and parent have similar configuration
// with respect to whether a request is cacheable or not.
// For example, the cache_urls_that_look_dynamic variable.
s->parent_params->findParent(&s->request_data, &s->parent_result);
if (!s->parent_result.is_some() || s->parent_result.is_api_result() || s->parent_result.parent_is_proxy()) {
DebugTxn("http_trans", "request not cacheable, so bypass parent");
s->parent_result.result = PARENT_DIRECT;
}
} else {
switch (s->parent_result.result) {
case PARENT_UNDEFINED:
s->parent_params->findParent(&s->request_data, &s->parent_result);
break;
case PARENT_SPECIFIED:
s->parent_params->nextParent(&s->request_data, &s->parent_result);
// Hack!
// We already have a parent that failed, if we are now told
// to go the origin server, we can only obey this if we
// dns'ed the origin server
if (s->parent_result.result == PARENT_DIRECT && s->http_config_param->no_dns_forward_to_parent != 0) {
ink_assert(!s->server_info.dst_addr.isValid());
s->parent_result.result = PARENT_FAIL;
}
break;
case PARENT_FAIL:
// Check to see if should bypass the parent and go direct
// We can only do this if
// 1) the config permitted us to dns the origin server
// 2) the config permits us
// 3) the parent was not set from API
if (s->http_config_param->no_dns_forward_to_parent == 0 && s->parent_result.bypass_ok() &&
s->parent_result.parent_is_proxy() && !s->parent_params->apiParentExists(&s->request_data)) {
s->parent_result.result = PARENT_DIRECT;
}
break;
default:
ink_assert(0);
// FALL THROUGH
case PARENT_DIRECT:
// // if we have already decided to go direct
// // dont bother calling nextParent.
// // do nothing here, guy.
break;
}
}
switch (s->parent_result.result) {
case PARENT_SPECIFIED:
s->parent_info.name = s->arena.str_store(s->parent_result.hostname, strlen(s->parent_result.hostname));
update_current_info(&s->current, &s->parent_info, HttpTransact::PARENT_PROXY, (s->current.attempts)++);
update_dns_info(&s->dns_info, &s->current, 0, &s->arena);
ink_assert(s->dns_info.looking_up == HttpTransact::PARENT_PROXY);
s->next_hop_scheme = URL_WKSIDX_HTTP;
return HttpTransact::PARENT_PROXY;
case PARENT_FAIL:
// No more parents - need to return an error message
s->current.request_to = HttpTransact::HOST_NONE;
return HttpTransact::HOST_NONE;
case PARENT_DIRECT:
/* fall through */
default:
update_current_info(&s->current, &s->server_info, HttpTransact::ORIGIN_SERVER, (s->current.attempts)++);
update_dns_info(&s->dns_info, &s->current, 0, &s->arena);
ink_assert(s->dns_info.looking_up == HttpTransact::ORIGIN_SERVER);
s->next_hop_scheme = s->scheme;
return HttpTransact::ORIGIN_SERVER;
}
}
inline static bool
do_cookies_prevent_caching(int cookies_conf, HTTPHdr *request, HTTPHdr *response, HTTPHdr *cached_request = NULL)
{
enum CookiesConfig {
COOKIES_CACHE_NONE = 0, // do not cache any responses to cookies
COOKIES_CACHE_ALL = 1, // cache for any content-type (ignore cookies)
COOKIES_CACHE_IMAGES = 2, // cache only for image types
COOKIES_CACHE_ALL_BUT_TEXT = 3, // cache for all but text content-types
COOKIES_CACHE_ALL_BUT_TEXT_EXT = 4 // cache for all but text content-types except with OS response
// without "Set-Cookie" or with "Cache-Control: public"
};
const char *content_type = NULL;
int str_len;
#ifdef DEBUG
ink_assert(request->type_get() == HTTP_TYPE_REQUEST);
ink_assert(response->type_get() == HTTP_TYPE_RESPONSE);
if (cached_request) {
ink_assert(cached_request->type_get() == HTTP_TYPE_REQUEST);
}
#endif
// Can cache all regardless of cookie header - just ignore all cookie headers
if ((CookiesConfig)cookies_conf == COOKIES_CACHE_ALL) {
return false;
}
// It is considered that Set-Cookie headers can be safely ignored
// for non text content types if Cache-Control private is not set.
// This enables a bigger hit rate, which currently outweighs the risk of
// breaking origin servers that truly intend to set a cookie with other
// objects such as images.
// At this time, it is believed that only advertisers do this, and that
// customers won't care about it.
// If the response does not have a Set-Cookie header and
// the response does not have a Cookie header and
// the object is not cached or the request does not have a Cookie header
// then cookies do not prevent caching.
if (!response->presence(MIME_PRESENCE_SET_COOKIE) && !request->presence(MIME_PRESENCE_COOKIE) &&
(cached_request == NULL || !cached_request->presence(MIME_PRESENCE_COOKIE))) {
return false;
}
// Do not cache if cookies option is COOKIES_CACHE_NONE
// and a Cookie is detected
if ((CookiesConfig)cookies_conf == COOKIES_CACHE_NONE) {
return true;
}
// All other options depend on the Content-Type
content_type = response->value_get(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, &str_len);
if ((CookiesConfig)cookies_conf == COOKIES_CACHE_IMAGES) {
if (content_type && str_len >= 5 && memcmp(content_type, "image", 5) == 0) {
// Images can be cached
return false;
}
return true; // do not cache if COOKIES_CACHE_IMAGES && content_type != "image"
}
// COOKIES_CACHE_ALL_BUT_TEXT || COOKIES_CACHE_ALL_BUT_TEXT_EXT
// Note: if the configuration is bad, we consider
// COOKIES_CACHE_ALL_BUT_TEXT to be the default
if (content_type && str_len >= 4 && memcmp(content_type, "text", 4) == 0) { // content type - "text"
// Text objects cannot be cached unless the option is
// COOKIES_CACHE_ALL_BUT_TEXT_EXT.
// Furthermore, if there is a Set-Cookie header, then
// Cache-Control must be set.
if ((CookiesConfig)cookies_conf == COOKIES_CACHE_ALL_BUT_TEXT_EXT &&
((!response->presence(MIME_PRESENCE_SET_COOKIE)) || response->is_cache_control_set(HTTP_VALUE_PUBLIC))) {
return false;
}
return true;
}
return false; // Non text objects can be cached
}
inline static bool
does_method_require_cache_copy_deletion(const HttpConfigParams *http_config_param, const int method)
{
return ((method != HTTP_WKSIDX_GET) &&
(method == HTTP_WKSIDX_DELETE || method == HTTP_WKSIDX_PURGE || method == HTTP_WKSIDX_PUT ||
(http_config_param->cache_post_method != 1 && method == HTTP_WKSIDX_POST)));
}
inline static bool
does_method_effect_cache(int method)
{
return ((method == HTTP_WKSIDX_GET || method == HTTP_WKSIDX_DELETE || method == HTTP_WKSIDX_PURGE || method == HTTP_WKSIDX_PUT ||
method == HTTP_WKSIDX_POST));
}
inline static HttpTransact::StateMachineAction_t
how_to_open_connection(HttpTransact::State *s)
{
ink_assert((s->pending_work == NULL) || (s->current.request_to == HttpTransact::PARENT_PROXY));
// Originally we returned which type of server to open
// Now, however, we may want to issue a cache
// operation first in order to lock the cache
// entry to prevent multiple origin server requests
// for the same document.
// The cache operation that we actually issue, of
// course, depends on the specified "cache_action".
// If there is no cache-action to be issued, just
// connect to the server.
switch (s->cache_info.action) {
case HttpTransact::CACHE_PREPARE_TO_DELETE:
case HttpTransact::CACHE_PREPARE_TO_UPDATE:
case HttpTransact::CACHE_PREPARE_TO_WRITE:
s->transact_return_point = HttpTransact::handle_cache_write_lock;
return HttpTransact::SM_ACTION_CACHE_ISSUE_WRITE;
default:
// This covers:
// CACHE_DO_UNDEFINED, CACHE_DO_NO_ACTION, CACHE_DO_DELETE,
// CACHE_DO_LOOKUP, CACHE_DO_REPLACE, CACHE_DO_SERVE,
// CACHE_DO_SERVE_AND_DELETE, CACHE_DO_SERVE_AND_UPDATE,
// CACHE_DO_UPDATE, CACHE_DO_WRITE, TOTAL_CACHE_ACTION_TYPES
break;
}
if (s->method == HTTP_WKSIDX_CONNECT && s->parent_result.result != PARENT_SPECIFIED) {
s->cdn_saved_next_action = HttpTransact::SM_ACTION_ORIGIN_SERVER_RAW_OPEN;
} else {
s->cdn_saved_next_action = HttpTransact::SM_ACTION_ORIGIN_SERVER_OPEN;
}
// In the following, if url_remap_mode == 2 (URL_REMAP_FOR_OS)
// then do remapping for requests to OS's.
// Whether there is CDN remapping or not, goto SM_ACTION_DNS_LOOKUP;
// after that, it'll goto ORIGIN_SERVER_(RAW_)OPEN as needed.
if ((url_remap_mode == HttpTransact::URL_REMAP_FOR_OS) && (s->current.request_to == HttpTransact::ORIGIN_SERVER) &&
!s->cdn_remap_complete) {
DebugTxn("cdn", "*** START CDN Remapping *** CDN mode = %d", url_remap_mode);
char *remap_redirect = NULL;
int host_len;
const char *host;
// We need to copy the client request into the server request. Why? BUGBUG
s->hdr_info.server_request.url_set(s->hdr_info.client_request.url_get());
// TODO yeah, not sure everything here is correct with redirects
// This probably doesn't work properly, since request_url_remap() is broken.
if (request_url_remap(s, &s->hdr_info.server_request, &remap_redirect)) {
ink_assert(!remap_redirect); // should not redirect in this code
HttpTransact::initialize_state_variables_for_origin_server(s, &s->hdr_info.server_request, true);
DebugTxn("cdn", "Converting proxy request to server request");
// Check whether a Host header field is missing from a 1.0 or 1.1 request.
if (/*outgoing_version != HTTPVersion(0,9) && */
!s->hdr_info.server_request.presence(MIME_PRESENCE_HOST)) {
URL *url = s->hdr_info.server_request.url_get();
host = url->host_get(&host_len);
// Add a ':port' to the HOST header if the request is not going
// to the default port.
int port = url->port_get();
if (port != url_canonicalize_port(URL_TYPE_HTTP, 0)) {
char *buf = (char *)alloca(host_len + 15);
memcpy(buf, host, host_len);
host_len += snprintf(buf + host_len, 15, ":%d", port);
s->hdr_info.server_request.value_set(MIME_FIELD_HOST, MIME_LEN_HOST, buf, host_len);
} else {
s->hdr_info.server_request.value_set(MIME_FIELD_HOST, MIME_LEN_HOST, host, host_len);
}
ats_free(remap_redirect); // This apparently shouldn't happen...
}
// Stripping out the host name from the URL
if (s->current.server == &s->server_info && s->next_hop_scheme == URL_WKSIDX_HTTP) {
DebugTxn("cdn", "Removing host name from URL");
HttpTransactHeaders::remove_host_name_from_url(&s->hdr_info.server_request);
}
} // the URL was remapped
if (is_debug_tag_set("cdn")) {
char *d_url = s->hdr_info.server_request.url_get()->string_get(NULL);
if (d_url) {
DebugTxn("cdn", "URL: %s", d_url);
}
char *d_hst = (char *)s->hdr_info.server_request.value_get(MIME_FIELD_HOST, MIME_LEN_HOST, &host_len);
if (d_hst) {
DebugTxn("cdn", "Host Hdr: %s", d_hst);
}
ats_free(d_url);
}
s->cdn_remap_complete = true; // It doesn't matter if there was an actual remap or not
s->transact_return_point = HttpTransact::OSDNSLookup;
ink_assert(s->next_action);
ink_assert(s->cdn_saved_next_action);
return HttpTransact::SM_ACTION_DNS_LOOKUP;
}
if (!s->already_downgraded) { // false unless downgraded previously (possibly due to HTTP 505)
(&s->hdr_info.server_request)->version_set(HTTPVersion(1, 1));
HttpTransactHeaders::convert_request(s->current.server->http_version, &s->hdr_info.server_request);
}
ink_assert(s->cdn_saved_next_action == HttpTransact::SM_ACTION_ORIGIN_SERVER_OPEN ||
s->cdn_saved_next_action == HttpTransact::SM_ACTION_ORIGIN_SERVER_RAW_OPEN);
return s->cdn_saved_next_action;
}
/*****************************************************************************
*****************************************************************************
**** ****
**** HttpTransact State Machine Handlers ****
**** ****
**** What follow from here on are the state machine handlers - the code ****
**** which is called from HttpSM::set_next_state to specify ****
**** what action the state machine needs to execute next. These ftns ****
**** take as input just the state and set the next_action variable. ****
*****************************************************************************
*****************************************************************************/
void
HttpTransact::BadRequest(State *s)
{
DebugTxn("http_trans", "[BadRequest]"
"parser marked request bad");
bootstrap_state_variables_from_request(s, &s->hdr_info.client_request);
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Invalid HTTP Request", "request#syntax_error", NULL);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
void
HttpTransact::HandleBlindTunnel(State *s)
{
bool inbound_transparent_p = s->state_machine->ua_session->get_netvc()->get_is_transparent();
URL u;
// IpEndpoint dest_addr;
// ip_text_buffer new_host;
DebugTxn("http_trans", "[HttpTransact::HandleBlindTunnel]");
// We've received a request on a port which we blind forward
// For logging purposes we create a fake request
s->hdr_info.client_request.create(HTTP_TYPE_REQUEST);
s->hdr_info.client_request.method_set(HTTP_METHOD_CONNECT, HTTP_LEN_CONNECT);
s->hdr_info.client_request.url_create(&u);
u.scheme_set(URL_SCHEME_TUNNEL, URL_LEN_TUNNEL);
s->hdr_info.client_request.url_set(&u);
// We set the version to 0.9 because once we know where we are going
// this blind ssl tunnel is indistinguishable from a "CONNECT 0.9"
// except for the need to suppression error messages
HTTPVersion ver(0, 9);
s->hdr_info.client_request.version_set(ver);
char new_host[INET6_ADDRSTRLEN];
ats_ip_ntop(s->state_machine->ua_session->get_netvc()->get_local_addr(), new_host, sizeof(new_host));
s->hdr_info.client_request.url_get()->host_set(new_host, strlen(new_host));
s->hdr_info.client_request.url_get()->port_set(s->state_machine->ua_session->get_netvc()->get_local_port());
// Initialize the state vars necessary to sending error responses
bootstrap_state_variables_from_request(s, &s->hdr_info.client_request);
if (is_debug_tag_set("http_trans")) {
int host_len;
const char *host = s->hdr_info.client_request.url_get()->host_get(&host_len);
DebugTxn("http_trans", "[HandleBlindTunnel] destination set to %.*s:%d", host_len, host,
s->hdr_info.client_request.url_get()->port_get());
}
// Now we need to run the url remapping engine to find the where
// this request really goes since we were sent was bound for
// machine we are running on
// Do request_url_remap only if url_remap_mode != URL_REMAP_FOR_OS.
bool url_remap_success = false;
char *remap_redirect = NULL;
if (s->transparent_passthrough) {
url_remap_success = true;
} else if (url_remap_mode == URL_REMAP_DEFAULT || url_remap_mode == URL_REMAP_ALL) {
// TODO: take a look at this
// This probably doesn't work properly, since request_url_remap() is broken.
url_remap_success = request_url_remap(s, &s->hdr_info.client_request, &remap_redirect);
}
// We must have mapping or we will self loop since the this
// request was addressed to us to begin with. Remap directs
// are something used in the normal reverse proxy and if we
// get them here they indicate a very bad misconfiguration!
if (!(inbound_transparent_p || url_remap_success) || remap_redirect != NULL) {
// The error message we send back will be suppressed so
// the only important thing in selecting the error is what
// status code it gets logged as
build_error_response(s, HTTP_STATUS_INTERNAL_SERVER_ERROR, "Port Forwarding Error", "default", NULL);
int host_len;
const char *host = s->hdr_info.client_request.url_get()->host_get(&host_len);
Log::error("Forwarded port error: request with destination %.*s:%d "
"does not have a mapping",
host_len, host, s->hdr_info.client_request.url_get()->port_get());
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
// Set the mode to tunnel so that we don't lookup the cache
s->current.mode = TUNNELLING_PROXY;
// Let the request work it's way through the code and
// we grab it again after the raw connection has been opened
HandleRequest(s);
}
bool
HttpTransact::perform_accept_encoding_filtering(State *s)
{
HttpUserAgent_RegxEntry *uae;
HTTPHdr *client_request;
MIMEField *accept_field;
MIMEField *usragent_field;
char tmp_ua_buf[1024], *c;
char const *u_agent = NULL;
int u_agent_len = 0;
bool retcode = false;
bool ua_match = false;
client_request = &s->hdr_info.client_request;
// Make sense to check Accept-Encoding if UserAgent is present (and matches)
if ((usragent_field = client_request->field_find(MIME_FIELD_USER_AGENT, MIME_LEN_USER_AGENT)) != 0 &&
(u_agent = usragent_field->value_get(&u_agent_len)) != 0 && u_agent_len > 0) {
if (u_agent_len >= (int)sizeof(tmp_ua_buf)) {
u_agent_len = (int)(sizeof(tmp_ua_buf) - 1);
}
memcpy(tmp_ua_buf, u_agent, u_agent_len);
tmp_ua_buf[u_agent_len] = '\0';
// TODO: Do we really want to do these hardcoded checks still?
// Check hardcoded case MSIE>6 & Mozilla>4
if ((c = strstr(tmp_ua_buf, "MSIE")) != NULL) {
if (c[5] >= '7' && c[5] <= '9') {
return false; // Don't change anything for IE > 6
}
ua_match = true;
} else if (!strncasecmp(tmp_ua_buf, "mozilla", 7)) {
if (tmp_ua_buf[8] >= '5' && tmp_ua_buf[8] <= '9') {
return false; // Don't change anything for Mozilla > 4
}
ua_match = true;
}
// Check custom filters
if (!ua_match && HttpConfig::user_agent_list) {
for (uae = HttpConfig::user_agent_list; uae && !ua_match; uae = uae->next) {
switch (uae->stype) {
case HttpUserAgent_RegxEntry::STRTYPE_SUBSTR_CASE: /* .substring, .string */
if (u_agent_len >= uae->user_agent_str_size && !memcmp(tmp_ua_buf, uae->user_agent_str, uae->user_agent_str_size)) {
ua_match = true;
}
break;
case HttpUserAgent_RegxEntry::STRTYPE_SUBSTR_NCASE: /* .substring_ncase, .string_ncase */
if (u_agent_len >= uae->user_agent_str_size && !strncasecmp(uae->user_agent_str, tmp_ua_buf, uae->user_agent_str_size)) {
ua_match = true;
}
break;
case HttpUserAgent_RegxEntry::STRTYPE_REGEXP: /* .regexp POSIX regular expression */
if (uae->regx_valid && !pcre_exec(uae->regx, NULL, tmp_ua_buf, u_agent_len, 0, 0, NULL, 0)) {
ua_match = true;
}
break;
default: /* unknown type in the structure - bad initialization - impossible bug! */
/* I can use ink_error() here since we should shutdown TS immediately */
ink_error("[HttpTransact::perform_accept_encoding_filtering] - get unknown User-Agent string type - bad initialization");
};
}
}
/* If we have correct User-Agent header ....
Just set Accept-Encoding: identity or .... do nothing because
"If no Accept-Encoding field is present in a request, the server MAY assume that the client
will accept any content coding. In this case, if "identity" is one of the available content-codings,
then the server SHOULD use the "identity" content-coding, unless it has additional information that
a different content-coding is meaningful to the client." */
if (ua_match) {
DebugTxn("http_trans", "HttpTransact::ModifyRequest, insert identity Accept-Encoding");
accept_field = client_request->field_find(MIME_FIELD_ACCEPT_ENCODING, MIME_LEN_ACCEPT_ENCODING);
if (!accept_field) {
accept_field = client_request->field_create(MIME_FIELD_ACCEPT_ENCODING, MIME_LEN_ACCEPT_ENCODING);
if (accept_field) {
client_request->field_attach(accept_field);
}
}
if (accept_field) {
client_request->field_value_set(accept_field, HTTP_VALUE_IDENTITY, HTTP_LEN_IDENTITY);
}
}
retcode = true;
} // end of 'user-agent'
return retcode;
}
void
HttpTransact::StartRemapRequest(State *s)
{
if (s->api_skip_all_remapping) {
Debug("http_trans", "API request to skip remapping");
s->hdr_info.client_request.set_url_target_from_host_field();
if (s->is_upgrade_request && s->post_remap_upgrade_return_point) {
TRANSACT_RETURN(SM_ACTION_POST_REMAP_SKIP, s->post_remap_upgrade_return_point);
}
TRANSACT_RETURN(SM_ACTION_POST_REMAP_SKIP, HttpTransact::HandleRequest);
}
DebugTxn("http_trans", "START HttpTransact::StartRemapRequest");
/**
* Check for URL remappings before checking request
* validity or initializing state variables since
* the remappings can insert or change the destination
* host, port and protocol.
**/
HTTPHdr *incoming_request = &s->hdr_info.client_request;
URL *url = incoming_request->url_get();
int host_len, path_len;
const char *host = url->host_get(&host_len);
const char *path = url->path_get(&path_len);
const int port = url->port_get();
const char syntxt[] = "synthetic.txt";
s->cop_test_page = is_localhost(host, host_len) && ((path_len == sizeof(syntxt) - 1) && (memcmp(path, syntxt, path_len) == 0)) &&
port == s->http_config_param->synthetic_port && s->method == HTTP_WKSIDX_GET &&
s->orig_scheme == URL_WKSIDX_HTTP && ats_ip4_addr_cast(&s->client_info.dst_addr.sa) == htonl(INADDR_LOOPBACK);
//////////////////////////////////////////////////////////////////
// FIX: this logic seems awfully convoluted and hard to follow; //
// seems like we could come up with a more elegant and //
// comprehensible design that generalized things //
//////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
// run the remap url-rewriting engine: //
// //
// * the variable <url_remap_success> is set true if //
// the url was rewritten //
// //
// * the variable <remap_redirect> is set to non-NULL if there //
// is a URL provided that the proxy is supposed to redirect //
// requesters of a particular URL to. //
/////////////////////////////////////////////////////////////////
if (is_debug_tag_set("http_chdr_describe") || is_debug_tag_set("http_trans")) {
DebugTxn("http_trans", "Before Remapping:");
obj_describe(s->hdr_info.client_request.m_http, 1);
}
if (url_remap_mode == URL_REMAP_DEFAULT || url_remap_mode == URL_REMAP_ALL) {
if (s->http_config_param->referer_filter_enabled) {
s->filter_mask = URL_REMAP_FILTER_REFERER;
if (s->http_config_param->referer_format_redirect) {
s->filter_mask |= URL_REMAP_FILTER_REDIRECT_FMT;
}
}
}
DebugTxn("http_trans", "END HttpTransact::StartRemapRequest");
TRANSACT_RETURN(SM_ACTION_API_PRE_REMAP, HttpTransact::PerformRemap);
}
void
HttpTransact::PerformRemap(State *s)
{
DebugTxn("http_trans", "Inside PerformRemap");
TRANSACT_RETURN(SM_ACTION_REMAP_REQUEST, HttpTransact::EndRemapRequest);
}
void
HttpTransact::EndRemapRequest(State *s)
{
DebugTxn("http_trans", "START HttpTransact::EndRemapRequest");
HTTPHdr *incoming_request = &s->hdr_info.client_request;
int method = incoming_request->method_get_wksidx();
int host_len;
const char *host = incoming_request->host_get(&host_len);
DebugTxn("http_trans", "EndRemapRequest host is %.*s", host_len, host);
////////////////////////////////////////////////////////////////
// if we got back a URL to redirect to, vector the user there //
////////////////////////////////////////////////////////////////
if (s->remap_redirect != NULL) {
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
if (s->http_return_code == HTTP_STATUS_MOVED_PERMANENTLY) {
build_error_response(s, HTTP_STATUS_MOVED_PERMANENTLY, "Redirect", "redirect#moved_permanently", NULL);
} else {
build_error_response(s, HTTP_STATUS_MOVED_TEMPORARILY, "Redirect", "redirect#moved_temporarily", NULL);
}
ats_free(s->remap_redirect);
s->reverse_proxy = false;
goto done;
}
/////////////////////////////////////////////////////
// Quick HTTP filtering (primary key: http method) //
/////////////////////////////////////////////////////
process_quick_http_filter(s, method);
/////////////////////////////////////////////////////////////////////////
// We must close this connection if client_connection_enabled == false //
/////////////////////////////////////////////////////////////////////////
if (!s->client_connection_enabled) {
build_error_response(s, HTTP_STATUS_FORBIDDEN, "Access Denied", "access#denied", NULL);
s->reverse_proxy = false;
goto done;
}
/////////////////////////////////////////////////////////////////
// Check if remap plugin set HTTP return code and return body //
/////////////////////////////////////////////////////////////////
if (s->http_return_code != HTTP_STATUS_NONE) {
build_error_response(s, s->http_return_code, NULL, NULL, s->internal_msg_buffer_size ? s->internal_msg_buffer : NULL);
s->reverse_proxy = false;
goto done;
}
///////////////////////////////////////////////////////////////
// if no mapping was found, handle the cases where: //
// //
// (1) reverse proxy is on, and no URL host (server request) //
// (2) no mappings are found, but mappings strictly required //
///////////////////////////////////////////////////////////////
if (!s->url_remap_success) {
/**
* It's better to test redirect rules just after url_remap failed
* Or those successfully remapped rules might be redirected
**/
if (handleIfRedirect(s)) {
DebugTxn("http_trans", "END HttpTransact::RemapRequest");
TRANSACT_RETURN(SM_ACTION_INTERNAL_CACHE_NOOP, NULL);
}
if (!s->http_config_param->url_remap_required && !incoming_request->is_target_in_url()) {
s->hdr_info.client_request.set_url_target_from_host_field();
}
/////////////////////////////////////////////////////////
// check for: (1) reverse proxy is on, and no URL host //
/////////////////////////////////////////////////////////
if (s->http_config_param->reverse_proxy_enabled && !s->client_info.is_transparent && !incoming_request->is_target_in_url()) {
/////////////////////////////////////////////////////////
// the url mapping failed, reverse proxy was enabled,
// and the request contains no host:
//
// * if there is an explanatory redirect, send there.
// * if there was no host, send "no host" error.
// * if there was a host, say "not found".
/////////////////////////////////////////////////////////
char *redirect_url = s->http_config_param->reverse_proxy_no_host_redirect;
int redirect_url_len = s->http_config_param->reverse_proxy_no_host_redirect_len;
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
if (redirect_url) { /* there is a redirect url */
build_error_response(s, HTTP_STATUS_MOVED_TEMPORARILY, "Redirect For Explanation", "request#no_host", NULL);
s->hdr_info.client_response.value_set(MIME_FIELD_LOCATION, MIME_LEN_LOCATION, redirect_url, redirect_url_len);
// socket when there is no host. Need to handle DNS failure elsewhere.
} else if (host == NULL) { /* no host */
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Host Header Required", "request#no_host", NULL);
s->squid_codes.log_code = SQUID_LOG_ERR_INVALID_URL;
} else {
build_error_response(s, HTTP_STATUS_NOT_FOUND, "Not Found on Accelerator", "urlrouting#no_mapping", NULL);
s->squid_codes.log_code = SQUID_LOG_ERR_INVALID_URL;
}
s->reverse_proxy = false;
goto done;
} else if (s->http_config_param->url_remap_required && !s->cop_test_page) {
///////////////////////////////////////////////////////
// the url mapping failed, but mappings are strictly //
// required (except for synthetic cop accesses), so //
// return an error message. //
///////////////////////////////////////////////////////
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_NOT_FOUND, "Not Found", "urlrouting#no_mapping", NULL);
s->squid_codes.log_code = SQUID_LOG_ERR_INVALID_URL;
s->reverse_proxy = false;
goto done;
}
} else {
if (s->http_config_param->reverse_proxy_enabled) {
s->req_flavor = REQ_FLAVOR_REVPROXY;
}
}
s->reverse_proxy = true;
s->server_info.is_transparent = s->state_machine->ua_session ? s->state_machine->ua_session->is_outbound_transparent() : false;
done:
// We now set the active-timeout again, since it might have been changed as part of the remap rules.
if (s->state_machine->ua_session) {
s->state_machine->ua_session->get_netvc()->set_active_timeout(HRTIME_SECONDS(s->txn_conf->transaction_active_timeout_in));
}
if (is_debug_tag_set("http_chdr_describe") || is_debug_tag_set("http_trans") || is_debug_tag_set("url_rewrite")) {
DebugTxn("http_trans", "After Remapping:");
obj_describe(s->hdr_info.client_request.m_http, 1);
}
/*
if s->reverse_proxy == false, we can assume remapping failed in some way
-however-
If an API setup a tunnel to fake the origin or proxy's response we will
continue to handle the request (as this was likely the plugin author's intent)
otherwise, 502/404 the request right now. /eric
*/
if (!s->reverse_proxy && s->state_machine->plugin_tunnel_type == HTTP_NO_PLUGIN_TUNNEL) {
DebugTxn("http_trans", "END HttpTransact::EndRemapRequest");
HTTP_INCREMENT_DYN_STAT(http_invalid_client_requests_stat);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
} else {
s->hdr_info.client_response.destroy(); // release the underlying memory.
s->hdr_info.client_response.clear(); // clear the pointers.
DebugTxn("http_trans", "END HttpTransact::EndRemapRequest");
if (s->is_upgrade_request && s->post_remap_upgrade_return_point) {
TRANSACT_RETURN(SM_ACTION_API_POST_REMAP, s->post_remap_upgrade_return_point);
}
TRANSACT_RETURN(SM_ACTION_API_POST_REMAP, HttpTransact::HandleRequest);
}
ink_assert(!"not reached");
}
bool
HttpTransact::handle_upgrade_request(State *s)
{
// Quickest way to determine that this is defintely not an upgrade.
/* RFC 6455 The method of the request MUST be GET, and the HTTP version MUST
be at least 1.1. */
if (!s->hdr_info.client_request.presence(MIME_PRESENCE_UPGRADE) ||
!s->hdr_info.client_request.presence(MIME_PRESENCE_CONNECTION) || s->method != HTTP_WKSIDX_GET ||
s->hdr_info.client_request.version_get() < HTTPVersion(1, 1)) {
return false;
}
MIMEField *upgrade_hdr = s->hdr_info.client_request.field_find(MIME_FIELD_UPGRADE, MIME_LEN_UPGRADE);
MIMEField *connection_hdr = s->hdr_info.client_request.field_find(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION);
StrList connection_hdr_vals;
const char *upgrade_hdr_val = NULL;
int upgrade_hdr_val_len = 0;
if (!upgrade_hdr || !connection_hdr || connection_hdr->value_get_comma_list(&connection_hdr_vals) == 0 ||
(upgrade_hdr_val = upgrade_hdr->value_get(&upgrade_hdr_val_len)) == NULL) {
DebugTxn("http_trans_upgrade", "Transaction wasn't a valid upgrade request, proceeding as a normal HTTP request.");
return false;
}
/*
* In order for this request to be treated as a normal upgrade request we must have a Connection: Upgrade header
* and a Upgrade: header, with a non-empty value, otherwise we just assume it's not an Upgrade Request, after
* we've verified that, we will try to match this upgrade to a known upgrade type such as Websockets.
*/
bool connection_contains_upgrade = false;
// Next, let's validate that the Connection header contains an Upgrade key
for (int i = 0; i < connection_hdr_vals.count; ++i) {
Str *val = connection_hdr_vals.get_idx(i);
if (ptr_len_casecmp(val->str, val->len, MIME_FIELD_UPGRADE, MIME_LEN_UPGRADE) == 0) {
connection_contains_upgrade = true;
break;
}
}
if (!connection_contains_upgrade) {
DebugTxn("http_trans_upgrade",
"Transaction wasn't a valid upgrade request, proceeding as a normal HTTP request, missing Connection upgrade header.");
return false;
}
// Mark this request as an upgrade request.
s->is_upgrade_request = true;
/*
RFC 6455
The request MUST contain an |Upgrade| header field whose value
MUST include the "websocket" keyword.
The request MUST contain a |Connection| header field whose value
MUST include the "Upgrade" token. // Checked Above
The request MUST include a header field with the name
|Sec-WebSocket-Key|.
The request MUST include a header field with the name
|Sec-WebSocket-Version|. The value of this header field MUST be
13.
*/
if (hdrtoken_tokenize(upgrade_hdr_val, upgrade_hdr_val_len, &s->upgrade_token_wks) >= 0) {
if (s->upgrade_token_wks == MIME_VALUE_WEBSOCKET) {
MIMEField *sec_websocket_key =
s->hdr_info.client_request.field_find(MIME_FIELD_SEC_WEBSOCKET_KEY, MIME_LEN_SEC_WEBSOCKET_KEY);
MIMEField *sec_websocket_ver =
s->hdr_info.client_request.field_find(MIME_FIELD_SEC_WEBSOCKET_VERSION, MIME_LEN_SEC_WEBSOCKET_VERSION);
if (sec_websocket_key && sec_websocket_ver && sec_websocket_ver->value_get_int() == 13) {
DebugTxn("http_trans_upgrade", "Transaction wants upgrade to websockets");
handle_websocket_upgrade_pre_remap(s);
return true;
} else {
DebugTxn("http_trans_upgrade", "Unable to upgrade connection to websockets, invalid headers (RFC 6455).");
}
}
// TODO accept h2c token to start HTTP/2 session after TS-3498 is fixed
} else {
DebugTxn("http_trans_upgrade", "Transaction requested upgrade for unknown protocol: %s", upgrade_hdr_val);
}
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Invalid Upgrade Request", "request#syntax_error", NULL);
// we want our modify_request method to just return while we fail out from here.
// this seems like the preferred option because the user wanted to do an upgrade but sent a bad protocol.
TRANSACT_RETURN_VAL(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL, true);
}
void
HttpTransact::handle_websocket_upgrade_pre_remap(State *s)
{
DebugTxn("http_trans_websocket_upgrade_pre_remap", "Prepping transaction before remap.");
/*
* We will use this opportunity to set everything up so that during the remap stage we can deal with
* ws:// and wss:// remap rules, and then we will take over again post remap.
*/
s->is_websocket = true;
s->post_remap_upgrade_return_point = HttpTransact::handle_websocket_upgrade_post_remap;
/* let's modify the url scheme to be wss or ws, so remapping will happen as expected */
URL *url = s->hdr_info.client_request.url_get();
if (url->scheme_get_wksidx() == URL_WKSIDX_HTTP) {
DebugTxn("http_trans_websocket_upgrade_pre_remap", "Changing scheme to WS for remapping.");
url->scheme_set(URL_SCHEME_WS, URL_LEN_WS);
} else if (url->scheme_get_wksidx() == URL_WKSIDX_HTTPS) {
DebugTxn("http_trans_websocket_upgrade_pre_remap", "Changing scheme to WSS for remapping.");
url->scheme_set(URL_SCHEME_WSS, URL_LEN_WSS);
} else {
DebugTxn("http_trans_websocket_upgrade_pre_remap", "Invalid scheme for websocket upgrade");
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Invalid Upgrade Request", "request#syntax_error", NULL);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
TRANSACT_RETURN(SM_ACTION_API_READ_REQUEST_HDR, HttpTransact::StartRemapRequest);
}
void
HttpTransact::handle_websocket_upgrade_post_remap(State *s)
{
DebugTxn("http_trans_websocket_upgrade_post_remap", "Remap is complete, start websocket upgrade");
TRANSACT_RETURN(SM_ACTION_API_POST_REMAP, HttpTransact::handle_websocket_connection);
}
void
HttpTransact::handle_websocket_connection(State *s)
{
DebugTxn("http_trans_websocket", "START handle_websocket_connection");
HandleRequest(s);
}
static bool
mimefield_value_equal(MIMEField *field, const char *value, const int value_len)
{
if (field != NULL) {
int field_value_len = 0;
const char *field_value = field->value_get(&field_value_len);
if (field_value != NULL) {
if (field_value_len == value_len) {
return !strncasecmp(field_value, value, value_len);
}
}
}
return false;
}
void
HttpTransact::ModifyRequest(State *s)
{
int scheme, hostname_len;
const char *hostname;
HTTPHdr &request = s->hdr_info.client_request;
DebugTxn("http_trans", "START HttpTransact::ModifyRequest");
// Initialize the state vars necessary to sending error responses
bootstrap_state_variables_from_request(s, &request);
////////////////////////////////////////////////
// If there is no scheme default to http //
////////////////////////////////////////////////
URL *url = request.url_get();
s->orig_scheme = (scheme = url->scheme_get_wksidx());
s->method = request.method_get_wksidx();
if (scheme < 0 && s->method != HTTP_WKSIDX_CONNECT) {
if (s->client_info.port_attribute == HttpProxyPort::TRANSPORT_SSL) {
url->scheme_set(URL_SCHEME_HTTPS, URL_LEN_HTTPS);
s->orig_scheme = URL_WKSIDX_HTTPS;
} else {
url->scheme_set(URL_SCHEME_HTTP, URL_LEN_HTTP);
s->orig_scheme = URL_WKSIDX_HTTP;
}
}
if (s->method == HTTP_WKSIDX_CONNECT && !request.is_port_in_header()) {
url->port_set(80);
}
// Ugly - this must come after the call to url->scheme_set or
// it can't get the scheme properly and the wrong data is cached.
// The solution should be to move the scheme detecting logic in to
// the header class, rather than doing it in a random bit of
// external code.
hostname = request.host_get(&hostname_len);
if (!request.is_target_in_url()) {
s->hdr_info.client_req_is_server_style = true;
}
// If the incoming request is proxy-style make sure the Host: header
// matches the incoming request URL. The exception is if we have
// Max-Forwards set to 0 in the request
int max_forwards = -1; // -1 is a valid value meaning that it didn't find the header
if (request.presence(MIME_PRESENCE_MAX_FORWARDS)) {
max_forwards = request.get_max_forwards();
}
if ((max_forwards != 0) && !s->hdr_info.client_req_is_server_style && s->method != HTTP_WKSIDX_CONNECT) {
MIMEField *host_field = request.field_find(MIME_FIELD_HOST, MIME_LEN_HOST);
int host_val_len = hostname_len;
const char **host_val = &hostname;
int port = url->port_get_raw();
char *buf = NULL;
// Form the host:port string if not a default port (e.g. 80)
if (port > 0) {
buf = (char *)alloca(host_val_len + 15);
memcpy(buf, hostname, host_val_len);
host_val_len += snprintf(buf + host_val_len, 15, ":%d", port);
host_val = (const char **)(&buf);
}
if (mimefield_value_equal(host_field, *host_val, host_val_len) == false) {
if (!host_field) { // Assure we have a Host field, before setting it
host_field = request.field_create(MIME_FIELD_HOST, MIME_LEN_HOST);
request.field_attach(host_field);
}
request.field_value_set(host_field, *host_val, host_val_len);
request.mark_target_dirty();
}
}
if (s->txn_conf->normalize_ae_gzip) {
// if enabled, force Accept-Encoding header to gzip or no header
MIMEField *ae_field = s->hdr_info.client_request.field_find(MIME_FIELD_ACCEPT_ENCODING, MIME_LEN_ACCEPT_ENCODING);
if (ae_field) {
if (HttpTransactCache::match_gzip(ae_field) == GZIP) {
s->hdr_info.client_request.field_value_set(ae_field, "gzip", 4);
DebugTxn("http_trans", "[ModifyRequest] normalized Accept-Encoding to gzip");
} else {
s->hdr_info.client_request.field_delete(ae_field);
DebugTxn("http_trans", "[ModifyRequest] removed non-gzip Accept-Encoding");
}
}
}
/////////////////////////////////////////////////////////
// Modify Accept-Encoding for several specific User-Agent
/////////////////////////////////////////////////////////
if (s->txn_conf->accept_encoding_filter_enabled) {
perform_accept_encoding_filtering(s);
}
DebugTxn("http_trans", "END HttpTransact::ModifyRequest");
DebugTxn("http_trans", "Checking if transaction wants to upgrade");
if (handle_upgrade_request(s)) {
// everything should be handled by the upgrade handler.
DebugTxn("http_trans", "Transaction will be upgraded by the appropriate upgrade handler.");
return;
}
TRANSACT_RETURN(SM_ACTION_API_READ_REQUEST_HDR, HttpTransact::StartRemapRequest);
}
// This function is supposed to figure out if this transaction is
// susceptible to a redirection as specified by remap.config
bool
HttpTransact::handleIfRedirect(State *s)
{
int answer;
URL redirect_url;
answer = request_url_remap_redirect(&s->hdr_info.client_request, &redirect_url);
if ((answer == PERMANENT_REDIRECT) || (answer == TEMPORARY_REDIRECT)) {
int remap_redirect_len;
s->remap_redirect = redirect_url.string_get(&s->arena, &remap_redirect_len);
redirect_url.destroy();
if (answer == TEMPORARY_REDIRECT) {
if ((s->client_info).http_version.m_version == HTTP_VERSION(1, 1)) {
build_error_response(s, HTTP_STATUS_TEMPORARY_REDIRECT, "Redirect", "redirect#moved_temporarily", NULL);
} else {
build_error_response(s, HTTP_STATUS_MOVED_TEMPORARILY, "Redirect", "redirect#moved_temporarily", NULL);
}
} else {
build_error_response(s, HTTP_STATUS_MOVED_PERMANENTLY, "Redirect", "redirect#moved_permanently", NULL);
}
s->arena.str_free(s->remap_redirect);
s->remap_redirect = NULL;
return true;
}
return false;
}
void
HttpTransact::HandleRequest(State *s)
{
DebugTxn("http_trans", "START HttpTransact::HandleRequest");
ink_assert(!s->hdr_info.server_request.valid());
HTTP_INCREMENT_DYN_STAT(http_incoming_requests_stat);
if (s->client_info.port_attribute == HttpProxyPort::TRANSPORT_SSL) {
HTTP_INCREMENT_DYN_STAT(https_incoming_requests_stat);
}
///////////////////////////////////////////////
// if request is bad, return error response //
///////////////////////////////////////////////
if (!(is_request_valid(s, &s->hdr_info.client_request))) {
HTTP_INCREMENT_DYN_STAT(http_invalid_client_requests_stat);
DebugTxn("http_seq", "[HttpTransact::HandleRequest] request invalid.");
s->next_action = SM_ACTION_SEND_ERROR_CACHE_NOOP;
// s->next_action = HttpTransact::PROXY_INTERNAL_CACHE_NOOP;
return;
}
DebugTxn("http_seq", "[HttpTransact::HandleRequest] request valid.");
if (is_debug_tag_set("http_chdr_describe")) {
obj_describe(s->hdr_info.client_request.m_http, 1);
}
// at this point we are guaranteed that the request is good and acceptable.
// initialize some state variables from the request (client version,
// client keep-alive, cache action, etc.
initialize_state_variables_from_request(s, &s->hdr_info.client_request);
// The following chunk of code will limit the maximum number of websocket connections (TS-3659)
if (s->is_upgrade_request && s->is_websocket && s->http_config_param->max_websocket_connections >= 0) {
int64_t val = 0;
HTTP_READ_DYN_SUM(http_websocket_current_active_client_connections_stat, val);
if (val >= s->http_config_param->max_websocket_connections) {
s->is_websocket = false; // unset to avoid screwing up stats.
DebugTxn("http_trans", "Rejecting websocket connection because the limit has been exceeded");
bootstrap_state_variables_from_request(s, &s->hdr_info.client_request);
build_error_response(s, HTTP_STATUS_SERVICE_UNAVAILABLE, "WebSocket Connection Limit Exceeded", NULL, NULL);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
}
// The following code is configurable to allow a user to control the max post size (TS-3631)
if (s->http_config_param->max_post_size > 0 && s->hdr_info.request_content_length > 0 &&
s->hdr_info.request_content_length > s->http_config_param->max_post_size) {
DebugTxn("http_trans", "Max post size %" PRId64 " Client tried to post a body that was too large.",
s->http_config_param->max_post_size);
HTTP_INCREMENT_DYN_STAT(http_post_body_too_large);
bootstrap_state_variables_from_request(s, &s->hdr_info.client_request);
build_error_response(s, HTTP_STATUS_REQUEST_ENTITY_TOO_LARGE, "Request Entity Too Large", "request#entity_too_large", NULL);
s->squid_codes.log_code = SQUID_LOG_ERR_POST_ENTITY_TOO_LARGE;
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
// The following chunk of code allows you to disallow post w/ expect 100-continue (TS-3459)
if (s->hdr_info.request_content_length && s->http_config_param->disallow_post_100_continue) {
MIMEField *expect = s->hdr_info.client_request.field_find(MIME_FIELD_EXPECT, MIME_LEN_EXPECT);
if (expect != NULL) {
const char *expect_hdr_val = NULL;
int expect_hdr_val_len = 0;
expect_hdr_val = expect->value_get(&expect_hdr_val_len);
if (ptr_len_casecmp(expect_hdr_val, expect_hdr_val_len, HTTP_VALUE_100_CONTINUE, HTTP_LEN_100_CONTINUE) == 0) {
// Let's error out this request.
DebugTxn("http_trans", "Client sent a post expect: 100-continue, sending 405.");
HTTP_INCREMENT_DYN_STAT(disallowed_post_100_continue);
build_error_response(s, HTTP_STATUS_METHOD_NOT_ALLOWED, "Method Not Allowed", "request#method_unsupported", NULL);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
}
}
// Cache lookup or not will be decided later at DecideCacheLookup().
// Before it's decided to do a cache lookup,
// assume no cache lookup and using proxy (not tunneling)
s->cache_info.action = CACHE_DO_NO_ACTION;
s->current.mode = GENERIC_PROXY;
// initialize the cache_control structure read from cache.config
update_cache_control_information_from_config(s);
// We still need to decide whether or not to do a cache lookup since
// the scheduled update code depends on this info.
if (is_request_cache_lookupable(s)) {
s->cache_info.action = CACHE_DO_LOOKUP;
}
// If the hostname is "$internal$" then this is a request for
// internal proxy information.
if (handle_internal_request(s, &s->hdr_info.client_request)) {
TRANSACT_RETURN(SM_ACTION_INTERNAL_REQUEST, NULL);
}
// this needs to be called after initializing state variables from request
// it adds the client-ip to the incoming client request.
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", &s->hdr_info.client_request, s->state_machine_id, "Incoming Request");
if (s->state_machine->plugin_tunnel_type == HTTP_PLUGIN_AS_INTERCEPT) {
setup_plugin_request_intercept(s);
return;
}
// if ip in url or cop test page, not do srv lookup.
if (s->txn_conf->srv_enabled) {
if (s->cop_test_page) {
s->txn_conf->srv_enabled = false;
} else {
IpEndpoint addr;
ats_ip_pton(s->server_info.name, &addr);
s->txn_conf->srv_enabled = !ats_is_ip(&addr);
}
}
// if the request is a trace or options request, decrement the
// max-forwards value. if the incoming max-forwards value was 0,
// then we have to return a response to the client with the
// appropriate action for trace/option. in this case this routine
// is responsible for building the response.
if (handle_trace_and_options_requests(s, &s->hdr_info.client_request)) {
TRANSACT_RETURN(SM_ACTION_INTERNAL_CACHE_NOOP, NULL);
}
if (s->http_config_param->no_dns_forward_to_parent && s->scheme != URL_WKSIDX_HTTPS &&
strcmp(s->server_info.name, "127.0.0.1") != 0) {
// for HTTPS requests, we must go directly to the
// origin server. Ignore the no_dns_just_forward_to_parent setting.
// we need to see if the hostname is an
// ip address since the parent selection code result
// could change as a result of this ip address
IpEndpoint addr;
ats_ip_pton(s->server_info.name, &addr);
if (ats_is_ip(&addr)) {
ats_ip_copy(&s->request_data.dest_ip, &addr);
}
if (s->parent_params->parentExists(&s->request_data)) {
// If the proxy is behind and firewall and there is no
// DNS service available, we just want to forward the request
// the parent proxy. In this case, we never find out the
// origin server's ip. So just skip past OSDNS
ats_ip_invalidate(&s->server_info.dst_addr);
StartAccessControl(s);
return;
} else if (s->http_config_param->no_origin_server_dns) {
build_error_response(s, HTTP_STATUS_BAD_GATEWAY, "Next Hop Connection Failed", "connect#failed_connect", NULL);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
}
// Added to skip the dns if the document is in the cache.
// DNS is requested before cache lookup only if there are rules in cache.config , parent.config or
// if the newly added varible doc_in_cache_skip_dns is not enabled
if (s->dns_info.lookup_name[0] <= '9' && s->dns_info.lookup_name[0] >= '0' &&
(!s->state_machine->enable_redirection || !s->redirect_info.redirect_in_process) &&
s->parent_params->parent_table->hostMatch) {
s->force_dns = 1;
}
/* A redirect means we need to check some things again.
If the cache is enabled then we need to check the new (redirected) request against the cache.
If not, then we need to at least do DNS again to guarantee we are using the correct IP address
(if the host changed). Note DNS comes after cache lookup so in both cases we do the DNS.
*/
if (s->redirect_info.redirect_in_process && s->state_machine->enable_redirection) {
if (s->txn_conf->cache_http) {
TRANSACT_RETURN(SM_ACTION_CACHE_LOOKUP, NULL);
} else {
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, OSDNSLookup); // effectively s->force_dns
}
}
if (s->force_dns) {
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, OSDNSLookup); // After handling the request, DNS is done.
} else {
// After the requested is properly handled No need of requesting the DNS directly check the ACLs
// if the request is authorized
StartAccessControl(s);
}
}
void
HttpTransact::setup_plugin_request_intercept(State *s)
{
ink_assert(s->state_machine->plugin_tunnel != NULL);
// Plugin is intercepting the request which means
// that we don't do dns, cache read or cache write
//
// We just want to write the request straight to the plugin
if (s->cache_info.action != HttpTransact::CACHE_DO_NO_ACTION) {
s->cache_info.action = HttpTransact::CACHE_DO_NO_ACTION;
s->current.mode = TUNNELLING_PROXY;
HTTP_INCREMENT_DYN_STAT(http_tunnels_stat);
}
// Regardless of the protocol we're gatewaying to
// we see the scheme as http
s->scheme = s->next_hop_scheme = URL_WKSIDX_HTTP;
// Set up a "fake" server server entry
update_current_info(&s->current, &s->server_info, HttpTransact::ORIGIN_SERVER, 0);
// Also "fake" the info we'd normally get from
// hostDB
s->server_info.http_version.set(1, 0);
s->server_info.keep_alive = HTTP_NO_KEEPALIVE;
s->host_db_info.app.http_data.http_version = HostDBApplicationInfo::HTTP_VERSION_10;
s->host_db_info.app.http_data.pipeline_max = 1;
s->server_info.dst_addr.setToAnyAddr(AF_INET); // must set an address or we can't set the port.
s->server_info.dst_addr.port() = htons(s->hdr_info.client_request.port_get()); // this is the info that matters.
// Build the request to the server
build_request(s, &s->hdr_info.client_request, &s->hdr_info.server_request, s->client_info.http_version);
// We don't do keep alive over these impersonated
// NetVCs so nuke the connection header
s->hdr_info.server_request.field_delete(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION);
TRANSACT_RETURN(SM_ACTION_ORIGIN_SERVER_OPEN, NULL);
}
////////////////////////////////////////////////////////////////////////
// void HttpTransact::HandleApiErrorJump(State* s)
//
// Called after an API function indicates it wished to send an
// error to the user agent
////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleApiErrorJump(State *s)
{
DebugTxn("http_trans", "[HttpTransact::HandleApiErrorJump]");
// since the READ_REQUEST_HDR_HOOK is processed before
// we examine the request, returning TS_EVENT_ERROR will cause
// the protocol in the via string to be "?" Set it here
// since we know it has to be http
// For CONNECT method, next_hop_scheme is NULL
if (s->next_hop_scheme < 0) {
s->next_hop_scheme = URL_WKSIDX_HTTP;
}
// The client response may not be empty in the
// case the txn was reenabled in error by a plugin from hook SEND_RESPONSE_HDR.
// build_response doesn't clean the header. So clean it up before.
// Do fields_clear() instead of clear() to prevent memory leak
if (s->hdr_info.client_response.valid()) {
s->hdr_info.client_response.fields_clear();
}
// Set the source to internal so chunking is handled correctly
s->source = SOURCE_INTERNAL;
/**
The API indicated an error. Lets use a >=400 error from the state (if one's set) or fallback to a
generic HTTP/1.X 500 INKApi Error
**/
if (s->http_return_code && s->http_return_code >= HTTP_STATUS_BAD_REQUEST) {
const char *reason = http_hdr_reason_lookup(s->http_return_code);
;
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, s->http_return_code, reason ? reason : "Error");
} else {
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, HTTP_STATUS_INTERNAL_SERVER_ERROR, "INKApi Error");
}
TRANSACT_RETURN(SM_ACTION_INTERNAL_CACHE_NOOP, NULL);
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : PPDNSLookup
// Description: called after DNS lookup of parent proxy name
//
// Details :
//
// the configuration information gave us the name of the parent proxy
// to send the request to. this function is called after the dns lookup
// for that name. it may fail, in which case we look for the next parent
// proxy to try and if none exist, then go to the origin server.
// if the lookup succeeds, we open a connection to the parent proxy.
//
//
// Possible Next States From Here:
// - HttpTransact::SM_ACTION_DNS_LOOKUP;
// - HttpTransact::ORIGIN_SERVER_RAW_OPEN;
// - HttpTransact::ORIGIN_SERVER_OPEN;
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::PPDNSLookup(State *s)
{
++s->dns_info.attempts;
DebugTxn("http_trans", "[HttpTransact::PPDNSLookup] This was attempt %d", s->dns_info.attempts);
ink_assert(s->dns_info.looking_up == PARENT_PROXY);
if (!s->dns_info.lookup_success) {
// Mark parent as down due to resolving failure
s->parent_params->markParentDown(&s->parent_result);
// DNS lookup of parent failed, find next parent or o.s.
find_server_and_update_current_info(s);
if (!s->current.server->dst_addr.isValid()) {
if (s->current.request_to == PARENT_PROXY) {
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, PPDNSLookup);
} else {
// We could be out of parents here if all the parents failed DNS lookup
ink_assert(s->current.request_to == HOST_NONE);
handle_parent_died(s);
}
return;
}
} else {
// lookup succeeded, open connection to p.p.
ats_ip_copy(&s->parent_info.dst_addr, s->host_db_info.ip());
s->parent_info.dst_addr.port() = htons(s->parent_result.port);
get_ka_info_from_host_db(s, &s->parent_info, &s->client_info, &s->host_db_info);
char addrbuf[INET6_ADDRSTRLEN];
DebugTxn("http_trans", "[PPDNSLookup] DNS lookup for sm_id[%" PRId64 "] successful IP: %s", s->state_machine->sm_id,
ats_ip_ntop(&s->parent_info.dst_addr.sa, addrbuf, sizeof(addrbuf)));
}
// Since this function can be called several times while retrying
// parents, check to see if we've already built our request
if (!s->hdr_info.server_request.valid()) {
build_request(s, &s->hdr_info.client_request, &s->hdr_info.server_request, s->current.server->http_version);
// Take care of deferred (issue revalidate) work in building
// the request
if (s->pending_work != NULL) {
ink_assert(s->pending_work == issue_revalidate);
(*s->pending_work)(s);
s->pending_work = NULL;
}
}
// what kind of a connection (raw, simple)
s->next_action = how_to_open_connection(s);
}
///////////////////////////////////////////////////////////////////////////////
//
// Name : ReDNSRoundRobin
// Description: Called after we fail to contact part of a round-robin
// robin server set and we found a another ip address.
//
// Details :
//
//
//
// Possible Next States From Here:
// - HttpTransact::ORIGIN_SERVER_RAW_OPEN;
// - HttpTransact::ORIGIN_SERVER_OPEN;
// - HttpTransact::PROXY_INTERNAL_CACHE_NOOP;
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::ReDNSRoundRobin(State *s)
{
ink_assert(s->current.server == &s->server_info);
ink_assert(s->current.server->had_connect_fail());
if (s->dns_info.lookup_success) {
// We using a new server now so clear the connection
// failure mark
s->current.server->clear_connect_fail();
// Our ReDNS of the server succeeded so update the necessary
// information and try again. Need to preserve the current port value if possible.
in_port_t server_port = s->current.server->dst_addr.host_order_port();
// Temporary check to make sure the port preservation can be depended upon. That should be the case
// because we get here only after trying a connection. Remove for 6.2.
ink_assert(s->current.server->dst_addr.isValid() && 0 != server_port);
ats_ip_copy(&s->server_info.dst_addr, s->host_db_info.ip());
s->server_info.dst_addr.port() = htons(server_port);
ats_ip_copy(&s->request_data.dest_ip, &s->server_info.dst_addr);
get_ka_info_from_host_db(s, &s->server_info, &s->client_info, &s->host_db_info);
char addrbuf[INET6_ADDRSTRLEN];
DebugTxn("http_trans", "[ReDNSRoundRobin] DNS lookup for O.S. successful IP: %s",
ats_ip_ntop(&s->server_info.dst_addr.sa, addrbuf, sizeof(addrbuf)));
s->next_action = how_to_open_connection(s);
} else {
// Our ReDNS failed so output the DNS failure error message
build_error_response(s, HTTP_STATUS_BAD_GATEWAY, "Cannot find server.", "connect#dns_failed", NULL);
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_SEND_ERROR_CACHE_NOOP;
// s->next_action = PROXY_INTERNAL_CACHE_NOOP;
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : OSDNSLookup
// Description: called after the DNS lookup of origin server name
//
// Details :
//
// normally called after Start. may be called more than once, however,
// if the dns lookup fails. this may be if the client does not specify
// the full hostname (e.g. just cnn, instead of www.cnn.com), or because
// it was not possible to resolve the name after several attempts.
//
// the next action depends. since this function is normally called after
// a request has come in, which is valid and does not require an immediate
// response, the next action may just be to open a connection to the
// origin server, or a parent proxy, or the next action may be to do a
// cache lookup, or in the event of an error, the next action may be to
// send a response back to the client.
//
//
// Possible Next States From Here:
// - HttpTransact::PROXY_INTERNAL_CACHE_NOOP;
// - HttpTransact::CACHE_LOOKUP;
// - HttpTransact::SM_ACTION_DNS_LOOKUP;
// - HttpTransact::ORIGIN_SERVER_RAW_OPEN;
// - HttpTransact::ORIGIN_SERVER_OPEN;
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::OSDNSLookup(State *s)
{
static int max_dns_lookups = 3 + s->http_config_param->num_url_expansions;
++s->dns_info.attempts;
DebugTxn("http_trans", "[HttpTransact::OSDNSLookup] This was attempt %d", s->dns_info.attempts);
ink_assert(s->dns_info.looking_up == ORIGIN_SERVER);
// detect whether we are about to self loop. the client may have
// specified the proxy as the origin server (badness).
// Check if this procedure is already done - YTS Team, yamsat
if (!s->request_will_not_selfloop) {
if (will_this_request_self_loop(s)) {
DebugTxn("http_trans", "[OSDNSLookup] request will selfloop - bailing out");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
}
if (!s->dns_info.lookup_success) {
// maybe the name can be expanded (e.g cnn -> www.cnn.com)
HostNameExpansionError_t host_name_expansion = try_to_expand_host_name(s);
switch (host_name_expansion) {
case RETRY_EXPANDED_NAME:
// expansion successful, do a dns lookup on expanded name
HTTP_RELEASE_ASSERT(s->dns_info.attempts < max_dns_lookups);
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, OSDNSLookup);
break;
case EXPANSION_NOT_ALLOWED:
case EXPANSION_FAILED:
case DNS_ATTEMPTS_EXHAUSTED:
if (DNSLookupInfo::OS_ADDR_TRY_HOSTDB == s->dns_info.os_addr_style) {
/*
* We tried to connect to client target address, failed and tried to use a different addr
* No HostDB data, just keep on with the CTA.
*/
s->dns_info.lookup_success = true;
s->dns_info.os_addr_style = DNSLookupInfo::OS_ADDR_USE_CLIENT;
DebugTxn("http_seq", "[HttpTransact::OSDNSLookup] DNS lookup unsuccessful, using client target address");
} else {
if (host_name_expansion == EXPANSION_NOT_ALLOWED) {
// config file doesn't allow automatic expansion of host names
HTTP_RELEASE_ASSERT(!(s->http_config_param->enable_url_expandomatic));
DebugTxn("http_seq", "[HttpTransact::OSDNSLookup] DNS Lookup unsuccessful");
} else if (host_name_expansion == EXPANSION_FAILED) {
// not able to expand the hostname. dns lookup failed
DebugTxn("http_seq", "[HttpTransact::OSDNSLookup] DNS Lookup unsuccessful");
} else if (host_name_expansion == DNS_ATTEMPTS_EXHAUSTED) {
// retry attempts exhausted --- can't find dns entry for this host name
HTTP_RELEASE_ASSERT(s->dns_info.attempts >= max_dns_lookups);
DebugTxn("http_seq", "[HttpTransact::OSDNSLookup] DNS Lookup unsuccessful");
}
// output the DNS failure error message
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_BAD_GATEWAY, "Cannot find server.", "connect#dns_failed", NULL);
// s->cache_info.action = CACHE_DO_NO_ACTION;
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
break;
default:
ink_assert(!("try_to_expand_hostname returned an unsupported code"));
break;
}
return;
}
// ok, so the dns lookup succeeded
ink_assert(s->dns_info.lookup_success);
DebugTxn("http_seq", "[HttpTransact::OSDNSLookup] DNS Lookup successful");
if (DNSLookupInfo::OS_ADDR_TRY_HOSTDB == s->dns_info.os_addr_style) {
// We've backed off from a client supplied address and found some
// HostDB addresses. We use those if they're different from the CTA.
// In all cases we now commit to client or HostDB for our source.
if (s->host_db_info.round_robin) {
HostDBInfo *cta = s->host_db_info.rr()->select_next(&s->current.server->dst_addr.sa);
if (cta) {
// found another addr, lock in host DB.
s->host_db_info = *cta;
s->dns_info.os_addr_style = DNSLookupInfo::OS_ADDR_USE_HOSTDB;
} else {
// nothing else there, continue with CTA.
s->dns_info.os_addr_style = DNSLookupInfo::OS_ADDR_USE_CLIENT;
}
} else if (ats_ip_addr_eq(s->host_db_info.ip(), &s->server_info.dst_addr.sa)) {
s->dns_info.os_addr_style = DNSLookupInfo::OS_ADDR_USE_CLIENT;
} else {
s->dns_info.os_addr_style = DNSLookupInfo::OS_ADDR_USE_HOSTDB;
}
}
// Check to see if can fullfill expect requests based on the cached
// update some state variables with hostdb information that has
// been provided.
ats_ip_copy(&s->server_info.dst_addr, s->host_db_info.ip());
// If the SRV response has a port number, we should honor it. Otherwise we do the port defined in remap
if (s->dns_info.srv_lookup_success) {
s->server_info.dst_addr.port() = htons(s->dns_info.srv_port);
} else {
s->server_info.dst_addr.port() = htons(s->hdr_info.client_request.port_get()); // now we can set the port.
}
ats_ip_copy(&s->request_data.dest_ip, &s->server_info.dst_addr);
get_ka_info_from_host_db(s, &s->server_info, &s->client_info, &s->host_db_info);
char addrbuf[INET6_ADDRSTRLEN];
DebugTxn("http_trans", "[OSDNSLookup] DNS lookup for O.S. successful "
"IP: %s",
ats_ip_ntop(&s->server_info.dst_addr.sa, addrbuf, sizeof(addrbuf)));
// so the dns lookup was a success, but the lookup succeeded on
// a hostname which was expanded by the traffic server. we should
// not automatically forward the request to this expanded hostname.
// return a response to the client with the expanded host name
// and a tasty little blurb explaining what happened.
// if a DNS lookup succeeded on a user-defined
// hostname expansion, forward the request to the expanded hostname.
// On the other hand, if the lookup succeeded on a www.<hostname>.com
// expansion, return a 302 response.
// [amc] Also don't redirect if we backed off using HostDB instead of CTA.
if (s->dns_info.attempts == max_dns_lookups && s->dns_info.looking_up == ORIGIN_SERVER &&
DNSLookupInfo::OS_ADDR_USE_CLIENT != s->dns_info.os_addr_style) {
DebugTxn("http_trans", "[OSDNSLookup] DNS name resolution on expansion");
DebugTxn("http_seq", "[OSDNSLookup] DNS name resolution on expansion - returning");
build_redirect_response(s);
// s->cache_info.action = CACHE_DO_NO_ACTION;
TRANSACT_RETURN(SM_ACTION_INTERNAL_CACHE_NOOP, NULL);
}
// everything succeeded with the DNS lookup so do an API callout
// that allows for filtering. We'll do traffic_server internal
// filtering after API filtering
// After SM_ACTION_DNS_LOOKUP, goto the saved action/state ORIGIN_SERVER_(RAW_)OPEN.
// Should we skip the StartAccessControl()? why?
if (s->cdn_remap_complete) {
DebugTxn("cdn", "This is a late DNS lookup. We are going to the OS, "
"not to HandleFiltering.");
ink_assert(s->cdn_saved_next_action == SM_ACTION_ORIGIN_SERVER_OPEN ||
s->cdn_saved_next_action == SM_ACTION_ORIGIN_SERVER_RAW_OPEN);
DebugTxn("cdn", "outgoing version -- (pre conversion) %d", s->hdr_info.server_request.m_http->m_version);
(&s->hdr_info.server_request)->version_set(HTTPVersion(1, 1));
HttpTransactHeaders::convert_request(s->current.server->http_version, &s->hdr_info.server_request);
DebugTxn("cdn", "outgoing version -- (post conversion) %d", s->hdr_info.server_request.m_http->m_version);
TRANSACT_RETURN(s->cdn_saved_next_action, NULL);
} else if (DNSLookupInfo::OS_ADDR_USE_CLIENT == s->dns_info.os_addr_style ||
DNSLookupInfo::OS_ADDR_USE_HOSTDB == s->dns_info.os_addr_style) {
// we've come back after already trying the server to get a better address
// and finished with all backtracking - return to trying the server.
TRANSACT_RETURN(how_to_open_connection(s), HttpTransact::HandleResponse);
} else if (s->dns_info.lookup_name[0] <= '9' && s->dns_info.lookup_name[0] >= '0' && s->parent_params->parent_table->hostMatch &&
!s->http_config_param->no_dns_forward_to_parent) {
// note, broken logic: ACC fudges the OR stmt to always be true,
// 'AuthHttpAdapter' should do the rev-dns if needed, not here .
TRANSACT_RETURN(SM_ACTION_DNS_REVERSE_LOOKUP, HttpTransact::StartAccessControl);
} else {
//(s->state_machine->authAdapter).StartLookup (s);
// TRANSACT_RETURN(SM_ACTION_AUTH_LOOKUP, NULL);
if (s->force_dns) {
StartAccessControl(s); // If skip_dns is enabled and no ip based rules in cache.config and parent.config
// Access Control is called after DNS response
} else {
if ((s->cache_info.action == CACHE_DO_NO_ACTION) &&
(((s->hdr_info.client_request.presence(MIME_PRESENCE_RANGE) && !s->txn_conf->cache_range_write) ||
s->range_setup == RANGE_NOT_SATISFIABLE || s->range_setup == RANGE_NOT_HANDLED))) {
TRANSACT_RETURN(SM_ACTION_API_OS_DNS, HandleCacheOpenReadMiss);
} else if (!s->txn_conf->cache_http || s->cache_lookup_result == HttpTransact::CACHE_LOOKUP_SKIPPED) {
TRANSACT_RETURN(SM_ACTION_API_OS_DNS, LookupSkipOpenServer);
// DNS Lookup is done after LOOKUP Skipped and after we get response
// from the DNS we need to call LookupSkipOpenServer
} else if (s->cache_lookup_result == CACHE_LOOKUP_HIT_FRESH || s->cache_lookup_result == CACHE_LOOKUP_HIT_WARNING ||
s->cache_lookup_result == CACHE_LOOKUP_HIT_STALE) {
// DNS lookup is done if the content is state need to call handle cache open read hit
TRANSACT_RETURN(SM_ACTION_API_OS_DNS, HandleCacheOpenReadHit);
} else if (s->cache_lookup_result == CACHE_LOOKUP_MISS || s->cache_info.action == CACHE_DO_NO_ACTION) {
TRANSACT_RETURN(SM_ACTION_API_OS_DNS, HandleCacheOpenReadMiss);
// DNS lookup is done if the lookup failed and need to call Handle Cache Open Read Miss
} else {
build_error_response(s, HTTP_STATUS_INTERNAL_SERVER_ERROR, "Invalid Cache Lookup result", "default", NULL);
Log::error("HTTP: Invalid CACHE LOOKUP RESULT : %d", s->cache_lookup_result);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
}
}
}
void
HttpTransact::StartAccessControl(State *s)
{
// if (s->cop_test_page || (s->state_machine->authAdapter.disabled() == true)) {
// Heartbeats should always be allowed.
// s->content_control.access = ACCESS_ALLOW;
HandleRequestAuthorized(s);
// return;
// }
// ua_session is NULL for scheduled updates.
// Don't use req_flavor to do the test because if updated
// urls are remapped, the req_flavor is changed to REV_PROXY.
// if (s->state_machine->ua_session == NULL) {
// Scheduled updates should always be allowed
// return;
//}
// pass the access control logic to the ACC module.
//(s->state_machine->authAdapter).StartLookup(s);
}
void
HttpTransact::HandleRequestAuthorized(State *s)
{
//(s->state_machine->authAdapter).SetState(s);
//(s->state_machine->authAdapter).UserAuthorized(NULL);
// TRANSACT_RETURN(HTTP_API_OS_DNS, HandleFiltering);
if (s->force_dns) {
TRANSACT_RETURN(SM_ACTION_API_OS_DNS, HttpTransact::DecideCacheLookup);
} else {
HttpTransact::DecideCacheLookup(s);
}
}
void
HttpTransact::HandleFiltering(State *s)
{
ink_release_assert(!"Fix-Me AUTH MERGE");
if (s->method == HTTP_WKSIDX_PUSH && s->http_config_param->push_method_enabled == 0) {
// config file says this request is not authorized.
// send back error response to client.
DebugTxn("http_trans", "[HandleFiltering] access denied.");
DebugTxn("http_seq", "[HttpTransact::HandleFiltering] Access Denied.");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
// adding a comment so that cvs recognizes that I added a space in the text below
build_error_response(s, HTTP_STATUS_FORBIDDEN, "Access Denied", "access#denied", NULL);
// s->cache_info.action = CACHE_DO_NO_ACTION;
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
DebugTxn("http_seq", "[HttpTransact::HandleFiltering] Request Authorized.");
//////////////////////////////////////////////////////////////
// ok, the config file says that the request is authorized. //
//////////////////////////////////////////////////////////////
// request is not black listed so now decided if we ought to
// lookup the cache
DecideCacheLookup(s);
}
void
HttpTransact::DecideCacheLookup(State *s)
{
// Check if a client request is lookupable.
if (s->redirect_info.redirect_in_process || s->cop_test_page) {
// for redirect, we want to skip cache lookup and write into
// the cache directly with the URL before the redirect
s->cache_info.action = CACHE_DO_NO_ACTION;
s->current.mode = GENERIC_PROXY;
} else {
if (is_request_cache_lookupable(s) && !s->is_upgrade_request) {
s->cache_info.action = CACHE_DO_LOOKUP;
s->current.mode = GENERIC_PROXY;
} else {
s->cache_info.action = CACHE_DO_NO_ACTION;
s->current.mode = TUNNELLING_PROXY;
HTTP_INCREMENT_DYN_STAT(http_tunnels_stat);
}
}
if (service_transaction_in_proxy_only_mode(s)) {
s->cache_info.action = CACHE_DO_NO_ACTION;
s->current.mode = TUNNELLING_PROXY;
HTTP_INCREMENT_DYN_STAT(http_throttled_proxy_only_stat);
}
// at this point the request is ready to continue down the
// traffic server path.
// now decide whether the cache can even be looked up.
if (s->cache_info.action == CACHE_DO_LOOKUP) {
DebugTxn("http_trans", "[DecideCacheLookup] Will do cache lookup.");
DebugTxn("http_seq", "[DecideCacheLookup] Will do cache lookup");
ink_assert(s->current.mode != TUNNELLING_PROXY);
if (s->cache_info.lookup_url == NULL) {
HTTPHdr *incoming_request = &s->hdr_info.client_request;
if (s->txn_conf->maintain_pristine_host_hdr) {
s->cache_info.lookup_url_storage.create(NULL);
s->cache_info.lookup_url_storage.copy(incoming_request->url_get());
s->cache_info.lookup_url = &s->cache_info.lookup_url_storage;
// if the target isn't in the URL, put it in the copy for
// cache lookup.
incoming_request->set_url_target_from_host_field(s->cache_info.lookup_url);
} else {
// make sure the target is in the URL.
incoming_request->set_url_target_from_host_field();
s->cache_info.lookup_url = incoming_request->url_get();
}
// *somebody* wants us to not hack the host header in a reverse proxy setup.
// In addition, they want us to reverse proxy for 6000 servers, which vary
// the stupid content on the Host header!!!!
// We could a) have 6000 alts (barf, puke, vomit) or b) use the original
// host header in the url before doing all cache actions (lookups, writes, etc.)
if (s->txn_conf->maintain_pristine_host_hdr) {
char const *host_hdr;
char const *port_hdr;
int host_len, port_len;
// So, the host header will have the original host header.
if (incoming_request->get_host_port_values(&host_hdr, &host_len, &port_hdr, &port_len)) {
int port = 0;
if (port_hdr) {
s->cache_info.lookup_url->host_set(host_hdr, host_len);
port = ink_atoi(port_hdr, port_len);
} else {
s->cache_info.lookup_url->host_set(host_hdr, host_len);
}
s->cache_info.lookup_url->port_set(port);
}
}
ink_assert(s->cache_info.lookup_url->valid() == true);
}
TRANSACT_RETURN(SM_ACTION_CACHE_LOOKUP, NULL);
} else {
ink_assert(s->cache_info.action != CACHE_DO_LOOKUP && s->cache_info.action != CACHE_DO_SERVE);
DebugTxn("http_trans", "[DecideCacheLookup] Will NOT do cache lookup.");
DebugTxn("http_seq", "[DecideCacheLookup] Will NOT do cache lookup");
// If this is a push request, we need send an error because
// since what ever was sent is not cachable
if (s->method == HTTP_WKSIDX_PUSH) {
HandlePushError(s, "Request Not Cachable");
return;
}
// for redirect, we skipped cache lookup to do the automatic redirection
if (s->redirect_info.redirect_in_process) {
// without calling out the CACHE_LOOKUP_COMPLETE_HOOK
if (s->txn_conf->cache_http) {
s->cache_info.action = CACHE_DO_WRITE;
}
LookupSkipOpenServer(s);
} else {
// calling out CACHE_LOOKUP_COMPLETE_HOOK even when the cache
// lookup is skipped
s->cache_lookup_result = HttpTransact::CACHE_LOOKUP_SKIPPED;
if (s->force_dns) {
TRANSACT_RETURN(SM_ACTION_API_CACHE_LOOKUP_COMPLETE, LookupSkipOpenServer);
} else {
// Returning to dns lookup as cache lookup is skipped
TRANSACT_RETURN(SM_ACTION_API_CACHE_LOOKUP_COMPLETE, CallOSDNSLookup);
}
}
}
return;
}
void
HttpTransact::LookupSkipOpenServer(State *s)
{
// cache will not be looked up. open a connection
// to a parent proxy or to the origin server.
find_server_and_update_current_info(s);
if (s->current.request_to == PARENT_PROXY) {
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, PPDNSLookup);
}
ink_assert(s->current.request_to == ORIGIN_SERVER);
// ink_assert(s->current.server->ip != 0);
build_request(s, &s->hdr_info.client_request, &s->hdr_info.server_request, s->current.server->http_version);
StateMachineAction_t next = how_to_open_connection(s);
s->next_action = next;
if (next == SM_ACTION_ORIGIN_SERVER_OPEN || next == SM_ACTION_ORIGIN_SERVER_RAW_OPEN) {
TRANSACT_RETURN(next, HttpTransact::HandleResponse);
}
}
//////////////////////////////////////////////////////////////////////////////
// Name : HandleCacheOpenReadPush
// Description:
//
// Details :
//
// Called on PUSH requests from HandleCacheOpenRead
//////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleCacheOpenReadPush(State *s, bool read_successful)
{
if (read_successful) {
s->cache_info.action = CACHE_PREPARE_TO_UPDATE;
} else {
s->cache_info.action = CACHE_PREPARE_TO_WRITE;
}
TRANSACT_RETURN(SM_ACTION_READ_PUSH_HDR, HandlePushResponseHdr);
}
//////////////////////////////////////////////////////////////////////////////
// Name : HandlePushResponseHdr
// Description:
//
// Details :
//
// Called after reading the response header on PUSH request
//////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandlePushResponseHdr(State *s)
{
// Verify the pushed header wasn't longer than the content length
int64_t body_bytes = s->hdr_info.request_content_length - s->state_machine->pushed_response_hdr_bytes;
if (body_bytes < 0) {
HandlePushError(s, "Bad Content Length");
return;
}
// We need to create the request header storing in the cache
s->hdr_info.server_request.create(HTTP_TYPE_REQUEST);
s->hdr_info.server_request.copy(&s->hdr_info.client_request);
s->hdr_info.server_request.method_set(HTTP_METHOD_GET, HTTP_LEN_GET);
s->hdr_info.server_request.value_set("X-Inktomi-Source", 16, "http PUSH", 9);
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", &s->hdr_info.server_response, s->state_machine_id, "Pushed Response Header");
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", &s->hdr_info.server_request, s->state_machine_id, "Generated Request Header");
s->response_received_time = s->request_sent_time = ink_cluster_time();
if (is_response_cacheable(s, &s->hdr_info.server_request, &s->hdr_info.server_response)) {
ink_assert(s->cache_info.action == CACHE_PREPARE_TO_WRITE || s->cache_info.action == CACHE_PREPARE_TO_UPDATE);
TRANSACT_RETURN(SM_ACTION_CACHE_ISSUE_WRITE, HandlePushCacheWrite);
} else {
HandlePushError(s, "Response Not Cachable");
}
}
//////////////////////////////////////////////////////////////////////////////
// Name : HandlePushCacheWrite
// Description:
//
// Details :
//
// Called after performing the cache write on a push request
//////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandlePushCacheWrite(State *s)
{
switch (s->cache_info.write_lock_state) {
case CACHE_WL_SUCCESS:
// We were able to get the lock for the URL vector in the cache
if (s->cache_info.action == CACHE_PREPARE_TO_WRITE) {
s->cache_info.action = CACHE_DO_WRITE;
} else if (s->cache_info.action == CACHE_PREPARE_TO_UPDATE) {
s->cache_info.action = CACHE_DO_REPLACE;
} else {
ink_release_assert(0);
}
set_headers_for_cache_write(s, &s->cache_info.object_store, &s->hdr_info.server_request, &s->hdr_info.server_response);
TRANSACT_RETURN(SM_ACTION_STORE_PUSH_BODY, NULL);
break;
case CACHE_WL_FAIL:
case CACHE_WL_READ_RETRY:
// No write lock, can not complete request so bail
HandlePushError(s, "Cache Write Failed");
break;
case CACHE_WL_INIT:
default:
ink_release_assert(0);
}
}
void
HttpTransact::HandlePushTunnelSuccess(State *s)
{
ink_assert(s->cache_info.action == CACHE_DO_WRITE || s->cache_info.action == CACHE_DO_REPLACE);
// FIX ME: check PUSH spec for status codes
HTTPStatus resp_status = (s->cache_info.action == CACHE_DO_WRITE) ? HTTP_STATUS_CREATED : HTTP_STATUS_OK;
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, resp_status);
TRANSACT_RETURN(SM_ACTION_INTERNAL_CACHE_NOOP, NULL);
}
void
HttpTransact::HandlePushTunnelFailure(State *s)
{
HandlePushError(s, "Cache Error");
}
void
HttpTransact::HandleBadPushRespHdr(State *s)
{
HandlePushError(s, "Malformed Pushed Response Header");
}
void
HttpTransact::HandlePushError(State *s, const char *reason)
{
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
// Set half close flag to prevent TCP
// reset from the body still being transfered
s->state_machine->set_ua_half_close_flag();
build_error_response(s, HTTP_STATUS_BAD_REQUEST, reason, "default", NULL);
}
///////////////////////////////////////////////////////////////////////////////
// Name : HandleCacheOpenRead
// Description: the cache lookup succeeded - may have been a hit or a miss
//
// Details :
//
// the cache lookup succeeded. first check if the lookup resulted in
// a hit or a miss, if the lookup was for an http request.
// This function just funnels the result into the appropriate
// functions which handle these different cases.
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleCacheOpenRead(State *s)
{
DebugTxn("http_trans", "[HttpTransact::HandleCacheOpenRead]");
SET_VIA_STRING(VIA_DETAIL_CACHE_TYPE, VIA_DETAIL_CACHE);
bool read_successful = true;
if (s->cache_info.object_read == 0) {
read_successful = false;
//
// If somebody else was writing the document, proceed just like it was
// a normal cache miss, except don't try to write to the cache
//
if (s->cache_lookup_result == CACHE_LOOKUP_DOC_BUSY) {
s->cache_lookup_result = CACHE_LOOKUP_MISS;
s->cache_info.action = CACHE_DO_NO_ACTION;
}
} else {
CacheHTTPInfo *obj = s->cache_info.object_read;
if (obj->response_get()->type_get() == HTTP_TYPE_UNKNOWN) {
read_successful = false;
}
if (obj->request_get()->type_get() == HTTP_TYPE_UNKNOWN) {
read_successful = false;
}
}
if (s->method == HTTP_WKSIDX_PUSH) {
HandleCacheOpenReadPush(s, read_successful);
} else if (read_successful == false) {
// cache miss
DebugTxn("http_trans", "CacheOpenRead -- miss");
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_NOT_CACHED);
// StartAccessControl(s);
if (s->force_dns) {
HandleCacheOpenReadMiss(s);
} else {
// Cache Lookup Unsuccessful ..calling dns lookup
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, OSDNSLookup);
}
} else {
// cache hit
DebugTxn("http_trans", "CacheOpenRead -- hit");
TRANSACT_RETURN(SM_ACTION_API_READ_CACHE_HDR, HandleCacheOpenReadHitFreshness);
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : issue_revalidate
// Description: Sets cache action and does various bookkeeping
//
// Details :
//
// The Cache Lookup was hit but the document was stale so after
// calling build_request, we need setup up the cache action,
// set the via code, and possibly conditionalize the request
// The paths that we take to get this code are:
// Directly from HandleOpenReadHit if we are going to the origin server
// After PPDNS if we are going to a parent proxy
//
//
// Possible Next States From Here:
// -
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::issue_revalidate(State *s)
{
HTTPHdr *c_resp = find_appropriate_cached_resp(s);
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_CACHE_STALE);
ink_assert(GET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP) != ' ');
if (s->www_auth_content == CACHE_AUTH_FRESH) {
s->hdr_info.server_request.method_set(HTTP_METHOD_HEAD, HTTP_LEN_HEAD);
// The document is fresh in cache and we just want to see if the
// the client has the right credentials
// this cache action is just to get us into the hcoofsr function
s->cache_info.action = CACHE_DO_UPDATE;
if (!s->cop_test_page) {
DUMP_HEADER("http_hdrs", &s->hdr_info.server_request, s->state_machine_id, "Proxy's Request (Conditionalized)");
}
return;
}
if (s->cache_info.write_lock_state == CACHE_WL_INIT) {
// We do a cache lookup for DELETE, PUT and POST requests as well.
// We must, however, delete the cached copy after forwarding the
// request to the server. is_cache_response_returnable will ensure
// that we forward the request. We now specify what the cache
// action should be when the response is received.
if (does_method_require_cache_copy_deletion(s->http_config_param, s->method)) {
s->cache_info.action = CACHE_PREPARE_TO_DELETE;
DebugTxn("http_seq", "[HttpTransact::issue_revalidate] cache action: DELETE");
} else {
s->cache_info.action = CACHE_PREPARE_TO_UPDATE;
DebugTxn("http_seq", "[HttpTransact::issue_revalidate] cache action: UPDATE");
}
} else {
// We've looped back around due to missing the write lock
// for the cache. At this point we want to forget about the cache
ink_assert(s->cache_info.write_lock_state == CACHE_WL_READ_RETRY);
s->cache_info.action = CACHE_DO_NO_ACTION;
return;
}
// if the document is cached, just send a conditional request to the server
// So the request does not have preconditions. It can, however
// be a simple GET request with a Pragma:no-cache. As on 8/28/98
// we have fixed the whole Reload/Shift-Reload cached copy
// corruption problem. This means that we can issue a conditional
// request to the server only if the incoming request has a conditional
// or the incoming request does NOT have a no-cache header.
// In other words, if the incoming request is not conditional
// but has a no-cache header we can not issue an IMS. check for
// that case here.
bool no_cache_in_request = false;
if (s->hdr_info.client_request.is_pragma_no_cache_set() || s->hdr_info.client_request.is_cache_control_set(HTTP_VALUE_NO_CACHE)) {
DebugTxn("http_trans", "[issue_revalidate] no-cache header directive in request, folks");
no_cache_in_request = true;
}
if ((!(s->hdr_info.client_request.presence(MIME_PRESENCE_IF_MODIFIED_SINCE))) &&
(!(s->hdr_info.client_request.presence(MIME_PRESENCE_IF_NONE_MATCH))) && (no_cache_in_request == true) &&
(!s->txn_conf->cache_ims_on_client_no_cache) && (s->www_auth_content == CACHE_AUTH_NONE)) {
DebugTxn("http_trans",
"[issue_revalidate] Can not make this a conditional request. This is the force update of the cached copy case");
// set cache action to update. response will be a 200 or error,
// causing cached copy to be replaced (if 200).
s->cache_info.action = CACHE_PREPARE_TO_UPDATE;
return;
}
// do not conditionalize if the cached response is not a 200
switch (c_resp->status_get()) {
case HTTP_STATUS_OK: // 200
// don't conditionalize if we are configured to repeat the clients
// conditionals
if (s->txn_conf->cache_when_to_revalidate == 4) {
break;
}
// ok, request is either a conditional or does not have a no-cache.
// (or is method that we don't conditionalize but lookup the
// cache on like DELETE)
if (c_resp->get_last_modified() > 0 && (s->hdr_info.server_request.method_get_wksidx() == HTTP_WKSIDX_GET ||
s->hdr_info.server_request.method_get_wksidx() == HTTP_WKSIDX_HEAD) &&
s->range_setup == RANGE_NONE) {
// make this a conditional request
int length;
const char *str = c_resp->value_get(MIME_FIELD_LAST_MODIFIED, MIME_LEN_LAST_MODIFIED, &length);
s->hdr_info.server_request.value_set(MIME_FIELD_IF_MODIFIED_SINCE, MIME_LEN_IF_MODIFIED_SINCE, str, length);
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", &s->hdr_info.server_request, s->state_machine_id, "Proxy's Request (Conditionalized)");
}
// if Etag exists, also add if-non-match header
if (c_resp->presence(MIME_PRESENCE_ETAG) && (s->hdr_info.server_request.method_get_wksidx() == HTTP_WKSIDX_GET ||
s->hdr_info.server_request.method_get_wksidx() == HTTP_WKSIDX_HEAD)) {
int length;
const char *etag = c_resp->value_get(MIME_FIELD_ETAG, MIME_LEN_ETAG, &length);
if ((length >= 2) && (etag[0] == 'W') && (etag[1] == '/')) {
etag += 2;
length -= 2;
}
s->hdr_info.server_request.value_set(MIME_FIELD_IF_NONE_MATCH, MIME_LEN_IF_NONE_MATCH, etag, length);
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", &s->hdr_info.server_request, s->state_machine_id, "Proxy's Request (Conditionalized)");
}
break;
case HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: // 203
/* fall through */
case HTTP_STATUS_MULTIPLE_CHOICES: // 300
/* fall through */
case HTTP_STATUS_MOVED_PERMANENTLY: // 301
/* fall through */
case HTTP_STATUS_GONE: // 410
/* fall through */
default:
DebugTxn("http_trans", "[issue_revalidate] cached response is"
"not a 200 response so no conditionalization.");
s->cache_info.action = CACHE_PREPARE_TO_UPDATE;
break;
case HTTP_STATUS_PARTIAL_CONTENT:
ink_assert(!"unexpected status code");
break;
}
}
void
HttpTransact::HandleCacheOpenReadHitFreshness(State *s)
{
CacheHTTPInfo *&obj = s->cache_info.object_read;
ink_release_assert((s->request_sent_time == UNDEFINED_TIME) && (s->response_received_time == UNDEFINED_TIME));
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHitFreshness] Hit in cache");
if (delete_all_document_alternates_and_return(s, true)) {
DebugTxn("http_trans", "[HandleCacheOpenReadHitFreshness] Delete and return");
s->cache_info.action = CACHE_DO_DELETE;
s->next_action = HttpTransact::SM_ACTION_INTERNAL_CACHE_DELETE;
return;
}
s->request_sent_time = obj->request_sent_time_get();
s->response_received_time = obj->response_received_time_get();
// There may be clock skew if one of the machines
// went down and we do not have the correct delta
// for it. this is just to deal with the effects
// of the skew by setting minimum and maximum times
// so that ages are not negative, etc.
s->request_sent_time = min(s->client_request_time, s->request_sent_time);
s->response_received_time = min(s->client_request_time, s->response_received_time);
ink_assert(s->request_sent_time <= s->response_received_time);
DebugTxn("http_trans", "[HandleCacheOpenReadHitFreshness] request_sent_time : %" PRId64, (int64_t)s->request_sent_time);
DebugTxn("http_trans", "[HandleCacheOpenReadHitFreshness] response_received_time : %" PRId64, (int64_t)s->response_received_time);
// if the plugin has already decided the freshness, we don't need to
// do it again
if (s->cache_lookup_result == HttpTransact::CACHE_LOOKUP_NONE) {
// is the document still fresh enough to be served back to
// the client without revalidation?
Freshness_t freshness = what_is_document_freshness(s, &s->hdr_info.client_request, obj->response_get());
switch (freshness) {
case FRESHNESS_FRESH:
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHitFreshness] "
"Fresh copy");
s->cache_lookup_result = HttpTransact::CACHE_LOOKUP_HIT_FRESH;
break;
case FRESHNESS_WARNING:
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHitFreshness] "
"Heuristic-based Fresh copy");
s->cache_lookup_result = HttpTransact::CACHE_LOOKUP_HIT_WARNING;
break;
case FRESHNESS_STALE:
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHitFreshness] "
"Stale in cache");
s->cache_lookup_result = HttpTransact::CACHE_LOOKUP_HIT_STALE;
s->is_revalidation_necessary = true; // to identify a revalidation occurrence
break;
default:
ink_assert(!("what_is_document_freshness has returned unsupported code."));
break;
}
}
ink_assert(s->cache_lookup_result != HttpTransact::CACHE_LOOKUP_MISS);
if (s->cache_lookup_result == HttpTransact::CACHE_LOOKUP_HIT_STALE)
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_EXPIRED);
if (!s->force_dns) { // If DNS is not performed before
if (need_to_revalidate(s)) {
TRANSACT_RETURN(SM_ACTION_API_CACHE_LOOKUP_COMPLETE,
CallOSDNSLookup); // content needs to be revalidated and we did not perform a dns ....calling DNS lookup
} else { // document can be served can cache
TRANSACT_RETURN(SM_ACTION_API_CACHE_LOOKUP_COMPLETE, HttpTransact::HandleCacheOpenReadHit);
}
} else { // we have done dns . Its up to HandleCacheOpenReadHit to decide to go OS or serve from cache
TRANSACT_RETURN(SM_ACTION_API_CACHE_LOOKUP_COMPLETE, HttpTransact::HandleCacheOpenReadHit);
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : CallOSDNSLookup
// Description: Moves in SM_ACTION_DNS_LOOKUP state and sets the transact return to OSDNSLookup
//
// Details :
/////////////////////////////////////////////////////////////////////////////
void
HttpTransact::CallOSDNSLookup(State *s)
{
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, OSDNSLookup);
}
///////////////////////////////////////////////////////////////////////////////
// Name : need_to_revalidate
// Description: Checks if a document which is in the cache needs to be revalidates
//
// Details : Function calls AuthenticationNeeded and is_cache_response_returnable to determine
// if the cached document can be served
/////////////////////////////////////////////////////////////////////////////
bool
HttpTransact::need_to_revalidate(State *s)
{
bool needs_revalidate, needs_authenticate = false;
bool needs_cache_auth = false;
CacheHTTPInfo *obj;
if (s->api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE) {
obj = &s->cache_info.object_store;
ink_assert(obj->valid());
if (!obj->valid()) {
return true;
}
} else {
obj = s->cache_info.object_read;
}
// do we have to authenticate with the server before
// sending back the cached response to the client?
Authentication_t authentication_needed = AuthenticationNeeded(s->txn_conf, &s->hdr_info.client_request, obj->response_get());
switch (authentication_needed) {
case AUTHENTICATION_SUCCESS:
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHit] "
"Authentication not needed");
needs_authenticate = false;
break;
case AUTHENTICATION_MUST_REVALIDATE:
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_METHOD);
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHit] "
"Authentication needed");
needs_authenticate = true;
break;
case AUTHENTICATION_MUST_PROXY:
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHit] "
"Authentication needed");
needs_authenticate = true;
break;
case AUTHENTICATION_CACHE_AUTH:
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHit] "
"Authentication needed for cache_auth_content");
needs_authenticate = false;
needs_cache_auth = true;
break;
default:
ink_assert(!("AuthenticationNeeded has returned unsupported code."));
return true;
break;
}
ink_assert(s->cache_lookup_result == CACHE_LOOKUP_HIT_FRESH || s->cache_lookup_result == CACHE_LOOKUP_HIT_WARNING ||
s->cache_lookup_result == CACHE_LOOKUP_HIT_STALE);
if (s->cache_lookup_result == CACHE_LOOKUP_HIT_STALE &&
s->api_update_cached_object != HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE) {
needs_revalidate = true;
} else {
needs_revalidate = false;
}
bool send_revalidate = ((needs_authenticate == true) || (needs_revalidate == true) || (is_cache_response_returnable(s) == false));
if (needs_cache_auth == true) {
s->www_auth_content = send_revalidate ? CACHE_AUTH_STALE : CACHE_AUTH_FRESH;
send_revalidate = true;
}
return send_revalidate;
}
///////////////////////////////////////////////////////////////////////////////
// Name : HandleCacheOpenReadHit
// Description: handle result of a cache hit
//
// Details :
//
// Cache lookup succeeded and resulted in a cache hit. This means
// that the Accept* and Etags fields also matched. The cache lookup
// may have resulted in a vector of alternates (since lookup may
// be based on a url). A different function (SelectFromAlternates)
// goes through the alternates and finds the best match. That is
// then returned to this function. The result may not be sent back
// to the client, still, if the document is not fresh enough, or
// does not have enough authorization, or if the client wants a
// reload, etc. that decision will be made in this routine.
//
//
// Possible Next States From Here:
// - HttpTransact::PROXY_INTERNAL_CACHE_DELETE;
// - HttpTransact::SM_ACTION_DNS_LOOKUP;
// - HttpTransact::ORIGIN_SERVER_OPEN;
// - HttpTransact::PROXY_INTERNAL_CACHE_NOOP;
// - HttpTransact::SERVE_FROM_CACHE;
// - result of how_to_open_connection()
//
//
// For Range requests, we will decide to do simple tunneling if one of the
// following conditions hold:
// - document stale
// - cached response doesn't have Accept-Ranges and Content-Length
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleCacheOpenReadHit(State *s)
{
bool needs_revalidate, needs_authenticate = false;
bool needs_cache_auth = false;
bool server_up = true;
CacheHTTPInfo *obj;
if (s->api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE) {
obj = &s->cache_info.object_store;
ink_assert(obj->valid());
} else {
obj = s->cache_info.object_read;
}
// do we have to authenticate with the server before
// sending back the cached response to the client?
Authentication_t authentication_needed = AuthenticationNeeded(s->txn_conf, &s->hdr_info.client_request, obj->response_get());
switch (authentication_needed) {
case AUTHENTICATION_SUCCESS:
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHit] "
"Authentication not needed");
needs_authenticate = false;
break;
case AUTHENTICATION_MUST_REVALIDATE:
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_METHOD);
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHit] "
"Authentication needed");
needs_authenticate = true;
break;
case AUTHENTICATION_MUST_PROXY:
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHit] "
"Authentication needed");
HandleCacheOpenReadMiss(s);
return;
case AUTHENTICATION_CACHE_AUTH:
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHit] "
"Authentication needed for cache_auth_content");
needs_authenticate = false;
needs_cache_auth = true;
break;
default:
ink_assert(!("AuthenticationNeeded has returned unsupported code."));
break;
}
ink_assert(s->cache_lookup_result == CACHE_LOOKUP_HIT_FRESH || s->cache_lookup_result == CACHE_LOOKUP_HIT_WARNING ||
s->cache_lookup_result == CACHE_LOOKUP_HIT_STALE);
if (s->cache_lookup_result == CACHE_LOOKUP_HIT_STALE &&
s->api_update_cached_object != HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE) {
needs_revalidate = true;
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_EXPIRED);
} else {
needs_revalidate = false;
}
// the response may not be directly returnable to the client. there
// are several reasons for this: config may force revalidation or
// client may have forced a refresh by sending a Pragma:no-cache
// or a Cache-Control:no-cache, or the client may have sent a
// non-GET/HEAD request for a document that is cached. an example
// of a situation for this is when a client sends a DELETE, PUT
// or POST request for a url that is cached. except for DELETE,
// we may actually want to update the cached copy with the contents
// of the PUT/POST, but the easiest, safest and most robust solution
// is to simply delete the cached copy (in order to maintain cache
// consistency). this is particularly true if the server does not
// accept or conditionally accepts the PUT/POST requests.
// anyhow, this is an overloaded function and will return false
// if the origin server still has to be looked up.
bool response_returnable = is_cache_response_returnable(s);
// do we need to revalidate. in other words if the response
// has to be authorized, is stale or can not be returned, do
// a revalidate.
bool send_revalidate = ((needs_authenticate == true) || (needs_revalidate == true) || (response_returnable == false));
if (needs_cache_auth == true) {
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_EXPIRED);
s->www_auth_content = send_revalidate ? CACHE_AUTH_STALE : CACHE_AUTH_FRESH;
send_revalidate = true;
}
DebugTxn("http_trans", "CacheOpenRead --- needs_auth = %d", needs_authenticate);
DebugTxn("http_trans", "CacheOpenRead --- needs_revalidate = %d", needs_revalidate);
DebugTxn("http_trans", "CacheOpenRead --- response_returnable = %d", response_returnable);
DebugTxn("http_trans", "CacheOpenRead --- needs_cache_auth = %d", needs_cache_auth);
DebugTxn("http_trans", "CacheOpenRead --- send_revalidate = %d", send_revalidate);
if (send_revalidate) {
DebugTxn("http_trans", "CacheOpenRead --- HIT-STALE");
s->dns_info.attempts = 0;
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHit] "
"Revalidate document with server");
if (s->http_config_param->icp_enabled && icp_dynamic_enabled && s->http_config_param->stale_icp_enabled &&
needs_authenticate == false && needs_cache_auth == false && !s->hdr_info.client_request.is_pragma_no_cache_set() &&
!s->hdr_info.client_request.is_cache_control_set(HTTP_VALUE_NO_CACHE)) {
DebugTxn("http_trans", "[HandleCacheOpenReadHit] ICP is configured"
" and no no-cache in request; checking ICP for a STALE hit");
s->stale_icp_lookup = true;
// we haven't done the ICP lookup yet. The following is to
// fake an icp_info to cater for build_request's needs
s->icp_info.http_version.set(1, 0);
if (!s->txn_conf->keep_alive_enabled_out) {
s->icp_info.keep_alive = HTTP_NO_KEEPALIVE;
} else {
s->icp_info.keep_alive = HTTP_KEEPALIVE;
}
update_current_info(&s->current, &s->icp_info, HttpTransact::ICP_SUGGESTED_HOST, 1);
}
if (s->stale_icp_lookup == false) {
find_server_and_update_current_info(s);
// We do not want to try to revalidate documents if we think
// the server is down due to the something report problem
//
// Note: we only want to skip origin servers because 1)
// parent proxies have their own negative caching
// scheme & 2) If we skip down parents, every page
// we serve is potentially stale
//
if (s->current.request_to == ORIGIN_SERVER && is_server_negative_cached(s) && response_returnable == true &&
is_stale_cache_response_returnable(s) == true) {
server_up = false;
update_current_info(&s->current, NULL, UNDEFINED_LOOKUP, 0);
DebugTxn("http_trans", "CacheOpenReadHit - server_down, returning stale document");
}
// a parent lookup could come back as PARENT_FAIL if in parent.config, go_direct == false and
// there are no available parents (all down).
else if (s->current.request_to == HOST_NONE && s->parent_result.result == PARENT_FAIL) {
if (is_server_negative_cached(s) && response_returnable == true && is_stale_cache_response_returnable(s) == true) {
server_up = false;
update_current_info(&s->current, NULL, UNDEFINED_LOOKUP, 0);
DebugTxn("http_trans", "CacheOpenReadHit - server_down, returning stale document");
} else {
handle_parent_died(s);
return;
}
}
}
if (server_up || s->stale_icp_lookup) {
bool check_hostdb = get_ka_info_from_config(s, s->current.server);
DebugTxn("http_trans", "CacheOpenReadHit - check_hostdb %d", check_hostdb);
if (!s->stale_icp_lookup && (check_hostdb || !s->current.server->dst_addr.isValid())) {
// ink_release_assert(s->current.request_to == PARENT_PROXY ||
// s->http_config_param->no_dns_forward_to_parent != 0);
// We must be going a PARENT PROXY since so did
// origin server DNS lookup right after state Start
//
// If we end up here in the release case just fall
// through. The request will fail because of the
// missing ip but we won't take down the system
//
if (s->current.request_to == PARENT_PROXY) {
// Set ourselves up to handle pending revalidate issues
// after the PP DNS lookup
ink_assert(s->pending_work == NULL);
s->pending_work = issue_revalidate;
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, PPDNSLookup);
} else if (s->current.request_to == ORIGIN_SERVER) {
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, OSDNSLookup);
} else {
handle_parent_died(s);
return;
}
}
DebugTxn("http_trans", "CacheOpenReadHit - version %d", s->current.server->http_version.m_version);
build_request(s, &s->hdr_info.client_request, &s->hdr_info.server_request, s->current.server->http_version);
issue_revalidate(s);
// this can not be anything but a simple origin server connection.
// in other words, we would not have looked up the cache for a
// connect request, so the next action can not be origin_server_raw_open.
s->next_action = how_to_open_connection(s);
if (s->stale_icp_lookup && s->next_action == SM_ACTION_ORIGIN_SERVER_OPEN) {
s->next_action = SM_ACTION_ICP_QUERY;
}
ink_release_assert(s->next_action != SM_ACTION_ORIGIN_SERVER_RAW_OPEN);
return;
} else { // server is down but stale response is returnable
SET_VIA_STRING(VIA_DETAIL_CACHE_TYPE, VIA_DETAIL_CACHE);
}
}
// cache hit, document is fresh, does not authorization,
// is valid, etc. etc. send it back to the client.
//
// the important thing to keep in mind is that if we are
// here then we found a match in the cache and the document
// is fresh and we have enough authorization for it to send
// it back to the client without revalidating first with the
// origin server. we are, therefore, allowed to behave as the
// origin server. we can, therefore, make the claim that the
// document has not been modified since or has not been unmodified
// since the time requested by the client. this may not be
// the case in reality, but since the document is fresh in
// the cache, we can make the claim that this is the truth.
//
// so, any decision we make at this point can be made with authority.
// realistically, if we can not make this claim, then there
// is no reason to cache anything.
//
ink_assert((send_revalidate == true && server_up == false) || (send_revalidate == false && server_up == true));
DebugTxn("http_trans", "CacheOpenRead --- HIT-FRESH");
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHit] "
"Serve from cache");
// ToDo: Should support other levels of cache hits here, but the cache does not support it (yet)
if (SQUID_HIT_RAM == s->cache_info.hit_miss_code) {
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_RAM_CACHE_FRESH);
} else {
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_CACHE_FRESH);
}
if (s->cache_lookup_result == CACHE_LOOKUP_HIT_WARNING) {
build_response_from_cache(s, HTTP_WARNING_CODE_HERUISTIC_EXPIRATION);
} else if (s->cache_lookup_result == CACHE_LOOKUP_HIT_STALE) {
ink_assert(server_up == false);
build_response_from_cache(s, HTTP_WARNING_CODE_REVALIDATION_FAILED);
} else {
build_response_from_cache(s, HTTP_WARNING_CODE_NONE);
}
if (s->api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE) {
s->saved_update_next_action = s->next_action;
s->saved_update_cache_action = s->cache_info.action;
s->next_action = SM_ACTION_CACHE_PREPARE_UPDATE;
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : build_response_from_cache()
// Description: build a client response from cached response and client request
//
// Input : State, warning code to be inserted into the response header
// Output :
//
// Details : This function is called if we decided to serve a client request
// using a cached response.
// It is called by handle_server_connection_not_open()
// and HandleCacheOpenReadHit().
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::build_response_from_cache(State *s, HTTPWarningCode warning_code)
{
HTTPHdr *client_request = &s->hdr_info.client_request;
HTTPHdr *cached_response = NULL;
HTTPHdr *to_warn = &s->hdr_info.client_response;
CacheHTTPInfo *obj;
if (s->api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE) {
obj = &s->cache_info.object_store;
ink_assert(obj->valid());
} else {
obj = s->cache_info.object_read;
}
cached_response = obj->response_get();
// If the client request is conditional, and the cached copy meets
// the conditions, do not need to send back the full document,
// just a NOT_MODIFIED response.
// If the request is not conditional,
// the function match_response_to_request_conditionals() returns
// the code of the cached response, which means that we should send
// back the full document.
HTTPStatus client_response_code =
HttpTransactCache::match_response_to_request_conditionals(client_request, cached_response, s->response_received_time);
switch (client_response_code) {
case HTTP_STATUS_NOT_MODIFIED:
// A IMS or INM GET client request with conditions being met
// by the cached response. Send back a NOT MODIFIED response.
DebugTxn("http_trans", "[build_response_from_cache] Not modified");
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_HIT_CONDITIONAL);
build_response(s, cached_response, &s->hdr_info.client_response, s->client_info.http_version, client_response_code);
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
break;
case HTTP_STATUS_PRECONDITION_FAILED:
// A conditional request with conditions not being met by the cached
// response. Send back a PRECONDITION FAILED response.
DebugTxn("http_trans", "[build_response_from_cache] Precondition Failed");
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_CONDITIONAL);
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, client_response_code);
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
break;
case HTTP_STATUS_RANGE_NOT_SATISFIABLE:
// Check if cached response supports Range. If it does, append
// Range transformation plugin
// A little misnomer. HTTP_STATUS_RANGE_NOT_SATISFIABLE
// acutally means If-Range match fails here.
// fall through
default:
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_HIT_SERVED);
if (s->method == HTTP_WKSIDX_GET || s->api_resp_cacheable == true) {
// send back the full document to the client.
DebugTxn("http_trans", "[build_response_from_cache] Match! Serving full document.");
s->cache_info.action = CACHE_DO_SERVE;
// Check if cached response supports Range. If it does, append
// Range transformation plugin
// only if the cached response is a 200 OK
if (client_response_code == HTTP_STATUS_OK && client_request->presence(MIME_PRESENCE_RANGE)) {
s->state_machine->do_range_setup_if_necessary();
if (s->range_setup == RANGE_NOT_SATISFIABLE) {
build_error_response(s, HTTP_STATUS_RANGE_NOT_SATISFIABLE, "Requested Range Not Satisfiable", "default", NULL);
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
break;
} else if ((s->range_setup == RANGE_NOT_HANDLED) || !s->range_in_cache) {
// we switch to tunneling for Range requests if it is out of order.
// or if the range can't be satisfied from the cache
// In that case we fetch the entire source so it's OK to switch
// this late.
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHit] Out-of-order Range request - tunneling");
s->cache_info.action = CACHE_DO_NO_ACTION;
if (s->force_dns) {
HandleCacheOpenReadMiss(s); // DNS is already completed no need of doing DNS
} else {
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP,
OSDNSLookup); // DNS not done before need to be done now as we are connecting to OS
}
return;
}
}
if (s->state_machine->do_transform_open()) {
set_header_for_transform(s, cached_response);
to_warn = &s->hdr_info.transform_response;
} else {
build_response(s, cached_response, &s->hdr_info.client_response, s->client_info.http_version);
}
s->next_action = SM_ACTION_SERVE_FROM_CACHE;
}
// If the client request is a HEAD, then serve the header from cache.
else if (s->method == HTTP_WKSIDX_HEAD) {
DebugTxn("http_trans", "[build_response_from_cache] Match! Serving header only.");
build_response(s, cached_response, &s->hdr_info.client_response, s->client_info.http_version);
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
} else {
// We handled the request but it's not GET or HEAD (eg. DELETE),
// and server is not reacheable: 502
//
DebugTxn("http_trans", "[build_response_from_cache] No match! Connection failed.");
build_error_response(s, HTTP_STATUS_BAD_GATEWAY, "Connection Failed", "connect#failed_connect", NULL);
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
warning_code = HTTP_WARNING_CODE_NONE;
}
break;
}
// After building the client response, add the given warning if provided.
if (warning_code != HTTP_WARNING_CODE_NONE) {
delete_warning_value(to_warn, warning_code);
HttpTransactHeaders::insert_warning_header(s->http_config_param, to_warn, warning_code);
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : handle_cache_write_lock
// Description:
//
// Details :
//
//
//
// Possible Next States From Here:
// - result of how_to_open_connection
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_cache_write_lock(State *s)
{
bool remove_ims = false;
ink_assert(s->cache_info.action == CACHE_PREPARE_TO_DELETE || s->cache_info.action == CACHE_PREPARE_TO_UPDATE ||
s->cache_info.action == CACHE_PREPARE_TO_WRITE);
switch (s->cache_info.write_lock_state) {
case CACHE_WL_SUCCESS:
// We were able to get the lock for the URL vector in the cache
SET_UNPREPARE_CACHE_ACTION(s->cache_info);
break;
case CACHE_WL_FAIL:
// No write lock, ignore the cache and proxy only;
// FIX: Should just serve from cache if this is a revalidate
s->cache_info.action = CACHE_DO_NO_ACTION;
switch (s->cache_open_write_fail_action) {
case CACHE_WL_FAIL_ACTION_ERROR_ON_MISS:
case CACHE_WL_FAIL_ACTION_ERROR_ON_MISS_STALE_ON_REVALIDATE:
case CACHE_WL_FAIL_ACTION_ERROR_ON_MISS_OR_REVALIDATE:
DebugTxn("http_error", "cache_open_write_fail_action %d, cache miss, return error", s->cache_open_write_fail_action);
s->cache_info.write_status = CACHE_WRITE_ERROR;
build_error_response(s, HTTP_STATUS_BAD_GATEWAY, "Connection Failed", "connect#failed_connect", NULL);
MIMEField *ats_field;
HTTPHdr *header;
header = &(s->hdr_info.client_response);
if ((ats_field = header->field_find(MIME_FIELD_ATS_INTERNAL, MIME_LEN_ATS_INTERNAL)) == NULL) {
if (likely((ats_field = header->field_create(MIME_FIELD_ATS_INTERNAL, MIME_LEN_ATS_INTERNAL)) != NULL)) {
header->field_attach(ats_field);
}
}
if (likely(ats_field)) {
int value = (s->cache_info.object_read) ? 1 : 0;
Debug("http_error", "Adding Ats-Internal-Messages: %d", value);
header->field_value_set_int(ats_field, value);
} else {
Debug("http_error", "failed to add Ats-Internal-Messages");
}
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
return;
default:
s->cache_info.write_status = CACHE_WRITE_LOCK_MISS;
remove_ims = true;
break;
}
break;
case CACHE_WL_READ_RETRY:
// Write failed but retried and got a vector to read
// We need to clean up our state so that transact does
// not assert later on. Then handle the open read hit
//
s->request_sent_time = UNDEFINED_TIME;
s->response_received_time = UNDEFINED_TIME;
s->cache_info.action = CACHE_DO_LOOKUP;
remove_ims = true;
SET_VIA_STRING(VIA_DETAIL_CACHE_TYPE, VIA_DETAIL_CACHE);
break;
case CACHE_WL_INIT:
default:
ink_release_assert(0);
break;
}
// Since we've already built the server request and we can't get the write
// lock we need to remove the ims field from the request since we're
// ignoring the cache. If their is a client ims field, copy that since
// we're tunneling response anyway
if (remove_ims) {
s->hdr_info.server_request.field_delete(MIME_FIELD_IF_MODIFIED_SINCE, MIME_LEN_IF_MODIFIED_SINCE);
s->hdr_info.server_request.field_delete(MIME_FIELD_IF_NONE_MATCH, MIME_LEN_IF_NONE_MATCH);
MIMEField *c_ims = s->hdr_info.client_request.field_find(MIME_FIELD_IF_MODIFIED_SINCE, MIME_LEN_IF_MODIFIED_SINCE);
MIMEField *c_inm = s->hdr_info.client_request.field_find(MIME_FIELD_IF_NONE_MATCH, MIME_LEN_IF_NONE_MATCH);
if (c_ims) {
int len;
const char *value = c_ims->value_get(&len);
s->hdr_info.server_request.value_set(MIME_FIELD_IF_MODIFIED_SINCE, MIME_LEN_IF_MODIFIED_SINCE, value, len);
}
if (c_inm) {
int len;
const char *value = c_inm->value_get(&len);
s->hdr_info.server_request.value_set(MIME_FIELD_IF_NONE_MATCH, MIME_LEN_IF_NONE_MATCH, value, len);
}
}
if (s->cache_info.write_lock_state == CACHE_WL_READ_RETRY) {
DebugTxn("http_error", "calling hdr_info.server_request.destroy");
s->hdr_info.server_request.destroy();
HandleCacheOpenReadHitFreshness(s);
} else {
StateMachineAction_t next;
if (s->stale_icp_lookup == false) {
next = how_to_open_connection(s);
if (next == SM_ACTION_ORIGIN_SERVER_OPEN || next == SM_ACTION_ORIGIN_SERVER_RAW_OPEN) {
s->next_action = next;
TRANSACT_RETURN(next, NULL);
} else {
// hehe!
s->next_action = next;
ink_assert(s->next_action == SM_ACTION_DNS_LOOKUP);
return;
}
} else {
next = SM_ACTION_ICP_QUERY;
}
TRANSACT_RETURN(next, NULL);
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : HandleCacheOpenReadMiss
// Description: cache looked up, miss or hit, but needs authorization
//
// Details :
//
//
//
// Possible Next States From Here:
// - HttpTransact::ICP_QUERY;
// - HttpTransact::SM_ACTION_DNS_LOOKUP;
// - HttpTransact::ORIGIN_SERVER_OPEN;
// - HttpTransact::PROXY_INTERNAL_CACHE_NOOP;
// - result of how_to_open_connection()
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleCacheOpenReadMiss(State *s)
{
DebugTxn("http_trans", "[HandleCacheOpenReadMiss] --- MISS");
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadMiss] "
"Miss in cache");
if (delete_all_document_alternates_and_return(s, false)) {
DebugTxn("http_trans", "[HandleCacheOpenReadMiss] Delete and return");
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
return;
}
// reinitialize some variables to reflect cache miss state.
s->cache_info.object_read = NULL;
s->request_sent_time = UNDEFINED_TIME;
s->response_received_time = UNDEFINED_TIME;
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_CACHE_MISS);
if (GET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP) == ' ') {
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_NOT_CACHED);
}
// We do a cache lookup for DELETE and PUT requests as well.
// We must, however, not cache the responses to these requests.
if (does_method_require_cache_copy_deletion(s->http_config_param, s->method) && s->api_req_cacheable == false) {
s->cache_info.action = CACHE_DO_NO_ACTION;
} else if ((s->hdr_info.client_request.presence(MIME_PRESENCE_RANGE) && !s->txn_conf->cache_range_write) ||
does_method_effect_cache(s->method) == false || s->range_setup == RANGE_NOT_SATISFIABLE ||
s->range_setup == RANGE_NOT_HANDLED) {
s->cache_info.action = CACHE_DO_NO_ACTION;
} else {
s->cache_info.action = CACHE_PREPARE_TO_WRITE;
}
// We should not issue an ICP lookup if the request has a
// no-cache header. First check if the request has a no
// cache header. Then, if icp is enabled and the request
// does not have a no-cache header, issue an icp lookup.
// does the request have a no-cache?
bool no_cache_in_request = false;
if (s->hdr_info.client_request.is_pragma_no_cache_set() || s->hdr_info.client_request.is_cache_control_set(HTTP_VALUE_NO_CACHE)) {
no_cache_in_request = true;
}
// if ICP is enabled and above test indicates that request
// does not have a no-cache, issue icp query to sibling cache.
if (s->http_config_param->icp_enabled && icp_dynamic_enabled != 0 && (no_cache_in_request == false)) {
DebugTxn("http_trans", "[HandleCacheOpenReadMiss] "
"ICP is configured and no no-cache in request; checking ICP");
s->next_action = SM_ACTION_ICP_QUERY;
return;
}
///////////////////////////////////////////////////////////////
// a normal miss would try to fetch the document from the //
// origin server, unless the origin server isn't resolvable, //
// but if "CacheControl: only-if-cached" is set, then we are //
// supposed to send a 504 (GATEWAY TIMEOUT) response. //
///////////////////////////////////////////////////////////////
HTTPHdr *h = &s->hdr_info.client_request;
if (!h->is_cache_control_set(HTTP_VALUE_ONLY_IF_CACHED)) {
find_server_and_update_current_info(s);
// a parent lookup could come back as PARENT_FAIL if in parent.config go_direct == false and
// there are no available parents (all down).
if (s->parent_result.result == PARENT_FAIL) {
handle_parent_died(s);
return;
}
if (!s->current.server->dst_addr.isValid()) {
ink_release_assert(s->current.request_to == PARENT_PROXY || s->http_config_param->no_dns_forward_to_parent != 0);
if (s->current.request_to == PARENT_PROXY) {
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, HttpTransact::PPDNSLookup);
} else {
handle_parent_died(s);
return;
}
}
build_request(s, &s->hdr_info.client_request, &s->hdr_info.server_request, s->current.server->http_version);
s->next_action = how_to_open_connection(s);
} else { // miss, but only-if-cached is set
build_error_response(s, HTTP_STATUS_GATEWAY_TIMEOUT, "Not Cached", "cache#not_in_cache", NULL);
s->next_action = SM_ACTION_SEND_ERROR_CACHE_NOOP;
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : HandleICPLookup
// Description:
//
// Details :
//
//
//
// Possible Next States From Here:
// - HttpTransact::SM_ACTION_DNS_LOOKUP;
// - HttpTransact::PROXY_INTERNAL_CACHE_NOOP;
// - result of how_to_open_connection()
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleICPLookup(State *s)
{
SET_VIA_STRING(VIA_DETAIL_CACHE_TYPE, VIA_DETAIL_ICP);
if (s->icp_lookup_success == true) {
HTTP_INCREMENT_DYN_STAT(http_icp_suggested_lookups_stat);
DebugTxn("http_trans", "[HandleICPLookup] Success, sending request to icp suggested host.");
ats_ip4_set(&s->icp_info.dst_addr, s->icp_ip_result.sin_addr.s_addr);
s->icp_info.dst_addr.port() = ntohs(s->icp_ip_result.sin_port);
// TODO in this case we should go to the miss case
// just a little shy about using goto's, that's all.
ink_release_assert((s->icp_info.dst_addr.port() != s->client_info.dst_addr.port()) ||
(ats_ip_addr_cmp(&s->icp_info.dst_addr.sa, &Machine::instance()->ip.sa) != 0));
// Since the ICPDNSLookup is not called, these two
// values are not initialized.
// Force them to be initialized
s->icp_info.http_version.set(1, 0);
if (!s->txn_conf->keep_alive_enabled_out) {
s->icp_info.keep_alive = HTTP_NO_KEEPALIVE;
} else {
s->icp_info.keep_alive = HTTP_KEEPALIVE;
}
s->icp_info.name = (char *)s->arena.alloc(17);
unsigned char *p = (unsigned char *)&s->icp_ip_result.sin_addr.s_addr;
snprintf(s->icp_info.name, 17, "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
update_current_info(&s->current, &s->icp_info, ICP_SUGGESTED_HOST, 1);
s->next_hop_scheme = URL_WKSIDX_HTTP;
} else {
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_NOT_CACHED);
DebugTxn("http_trans", "[HandleICPLookup] Failure, sending request to forward server.");
s->parent_info.name = NULL;
ink_zero(s->parent_info.dst_addr);
find_server_and_update_current_info(s);
if (!ats_is_ip(&s->current.server->dst_addr)) {
if (s->current.request_to == PARENT_PROXY) {
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, PPDNSLookup);
} else {
ink_release_assert(0);
}
return;
}
}
if (!s->stale_icp_lookup) {
build_request(s, &s->hdr_info.client_request, &s->hdr_info.server_request, s->current.server->http_version);
} else {
ink_assert(s->hdr_info.server_request.valid());
s->stale_icp_lookup = false;
}
s->next_action = how_to_open_connection(s);
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : OriginServerRawOpen
// Description: called for ssl tunneling
//
// Details :
//
// when the method is CONNECT, we open a raw connection to the origin
// server. if the open succeeds, then do ssl tunneling from the client
// to the host.
//
//
// Possible Next States From Here:
// - HttpTransact::PROXY_INTERNAL_CACHE_NOOP;
// - HttpTransact::SSL_TUNNEL;
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::OriginServerRawOpen(State *s)
{
DebugTxn("http_trans", "[HttpTransact::OriginServerRawOpen]");
switch (s->current.state) {
case STATE_UNDEFINED:
/* fall through */
case OPEN_RAW_ERROR:
/* fall through */
case CONNECTION_ERROR:
/* fall through */
case CONNECTION_CLOSED:
/* fall through */
case CONGEST_CONTROL_CONGESTED_ON_F:
/* fall through */
case CONGEST_CONTROL_CONGESTED_ON_M:
handle_server_died(s);
ink_assert(s->cache_info.action == CACHE_DO_NO_ACTION);
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
break;
case CONNECTION_ALIVE:
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, HTTP_STATUS_OK);
DebugTxn("http_trans", "[OriginServerRawOpen] connection alive. next action is ssl_tunnel");
s->next_action = SM_ACTION_SSL_TUNNEL;
break;
default:
ink_assert(!("s->current.state is set to something unsupported"));
break;
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : HandleResponse
// Description: called from the state machine when a response is received
//
// Details :
//
// This is the entry into a coin-sorting machine. There are many different
// bins that the response can fall into. First, the response can be invalid
// if for example it is not a response, or not complete, or the connection
// was closed, etc. Then, the response can be from an icp-suggested-host,
// from a parent proxy or from the origin server. The next action to take
// differs for all three of these cases. Finally, good responses can either
// require a cache action, be it deletion, update, or writing or may just
// need to be tunnelled to the client. This latter case should be handled
// with as little processing as possible, since it should represent a fast
// path.
//
//
// Possible Next States From Here:
//
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleResponse(State *s)
{
DebugTxn("http_trans", "[HttpTransact::HandleResponse]");
DebugTxn("http_seq", "[HttpTransact::HandleResponse] Response received");
s->source = SOURCE_HTTP_ORIGIN_SERVER;
s->response_received_time = ink_cluster_time();
ink_assert(s->response_received_time >= s->request_sent_time);
s->current.now = s->response_received_time;
DebugTxn("http_trans", "[HandleResponse] response_received_time: %" PRId64, (int64_t)s->response_received_time);
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", &s->hdr_info.server_response, s->state_machine_id, "Incoming O.S. Response");
HTTP_INCREMENT_DYN_STAT(http_incoming_responses_stat);
ink_release_assert(s->current.request_to != UNDEFINED_LOOKUP);
if (s->cache_info.action != CACHE_DO_WRITE) {
ink_release_assert(s->cache_info.action != CACHE_DO_LOOKUP);
ink_release_assert(s->cache_info.action != CACHE_DO_SERVE);
ink_release_assert(s->cache_info.action != CACHE_PREPARE_TO_DELETE);
ink_release_assert(s->cache_info.action != CACHE_PREPARE_TO_UPDATE);
ink_release_assert(s->cache_info.action != CACHE_PREPARE_TO_WRITE);
}
if (!is_response_valid(s, &s->hdr_info.server_response)) {
DebugTxn("http_seq", "[HttpTransact::HandleResponse] Response not valid");
} else {
DebugTxn("http_seq", "[HttpTransact::HandleResponse] Response valid");
initialize_state_variables_from_response(s, &s->hdr_info.server_response);
}
switch (s->current.request_to) {
case ICP_SUGGESTED_HOST:
handle_response_from_icp_suggested_host(s);
break;
case PARENT_PROXY:
handle_response_from_parent(s);
break;
case ORIGIN_SERVER:
handle_response_from_server(s);
break;
default:
ink_assert(!("s->current.request_to is not ICP, P.P. or O.S. - hmmm."));
break;
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : HandleUpdateCachedObject
// Description: called from the state machine when we are going to modify
// headers without any server contact.
//
// Details : this function does very little. mainly to satisfy
// the call_transact_and_set_next format and not affect
// the performance of the non-invalidate operations, which
// are the majority
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleUpdateCachedObject(State *s)
{
if (s->cache_info.write_lock_state == HttpTransact::CACHE_WL_SUCCESS) {
ink_assert(s->cache_info.object_store.valid());
ink_assert(s->cache_info.object_store.response_get() != NULL);
ink_assert(s->cache_info.object_read != NULL);
ink_assert(s->cache_info.object_read->valid());
if (!s->cache_info.object_store.request_get()) {
s->cache_info.object_store.request_set(s->cache_info.object_read->request_get());
}
s->request_sent_time = s->cache_info.object_read->request_sent_time_get();
s->response_received_time = s->cache_info.object_read->response_received_time_get();
if (s->api_update_cached_object == UPDATE_CACHED_OBJECT_CONTINUE) {
TRANSACT_RETURN(SM_ACTION_CACHE_ISSUE_UPDATE, HttpTransact::HandleUpdateCachedObjectContinue);
} else {
TRANSACT_RETURN(SM_ACTION_CACHE_ISSUE_UPDATE, HttpTransact::HandleApiErrorJump);
}
} else if (s->api_update_cached_object == UPDATE_CACHED_OBJECT_CONTINUE) {
// even failed to update, continue to serve from cache
HandleUpdateCachedObjectContinue(s);
} else {
s->api_update_cached_object = UPDATE_CACHED_OBJECT_FAIL;
HandleApiErrorJump(s);
}
}
void
HttpTransact::HandleUpdateCachedObjectContinue(State *s)
{
ink_assert(s->api_update_cached_object == UPDATE_CACHED_OBJECT_CONTINUE);
s->cache_info.action = s->saved_update_cache_action;
s->next_action = s->saved_update_next_action;
}
///////////////////////////////////////////////////////////////////////////////
// Name : HandleStatPage
// Description: called from the state machine when a response is received
//
// Details :
//
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleStatPage(State *s)
{
HTTPStatus status;
if (s->internal_msg_buffer) {
status = HTTP_STATUS_OK;
} else {
status = HTTP_STATUS_NOT_FOUND;
}
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, status);
///////////////////////////
// insert content-length //
///////////////////////////
s->hdr_info.client_response.set_content_length(s->internal_msg_buffer_size);
if (s->internal_msg_buffer_type) {
int len = strlen(s->internal_msg_buffer_type);
if (len > 0) {
s->hdr_info.client_response.value_set(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, s->internal_msg_buffer_type, len);
}
} else {
s->hdr_info.client_response.value_set(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, "text/plain", 10);
}
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
}
///////////////////////////////////////////////////////////////////////////////
// Name : handle_response_from_icp_suggested_host
// Description: response came from the host suggested by the icp lookup
//
// Details :
//
// If the response was bad (for whatever reason), may try to open a
// connection with a parent proxy, if there are any, else the request
// should be sent to the client.
// If the response is good, handle_forward_server_connection_open is
// called.
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_response_from_icp_suggested_host(State *s)
{
DebugTxn("http_trans", "[handle_response_from_icp_suggested_host] (hrfish)");
HTTP_RELEASE_ASSERT(s->current.server == &s->icp_info);
s->icp_info.state = s->current.state;
switch (s->current.state) {
case CONNECTION_ALIVE:
DebugTxn("http_trans", "[hrfish] connection alive");
SET_VIA_STRING(VIA_DETAIL_ICP_CONNECT, VIA_DETAIL_ICP_SUCCESS);
handle_forward_server_connection_open(s);
break;
default:
DebugTxn("http_trans", "[hrfish] connection not alive");
SET_VIA_STRING(VIA_DETAIL_ICP_CONNECT, VIA_DETAIL_ICP_FAILURE);
// If the request is not retryable, bail
if (is_request_retryable(s) == false) {
handle_server_died(s);
return;
}
// send request to parent proxy now if there is
// one or else directly to the origin server.
find_server_and_update_current_info(s);
if (!ats_is_ip(&s->current.server->dst_addr)) {
if (s->current.request_to == PARENT_PROXY) {
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, PPDNSLookup);
} else {
ink_release_assert(0);
}
return;
}
ink_assert(s->hdr_info.server_request.valid());
s->next_action = how_to_open_connection(s);
if (s->current.server == &s->server_info && s->next_hop_scheme == URL_WKSIDX_HTTP) {
HttpTransactHeaders::remove_host_name_from_url(&s->hdr_info.server_request);
}
break;
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : handle_response_from_parent
// Description: response came from a parent proxy
//
// Details :
//
// The configuration file can be used to specify more than one parent
// proxy. If a connection to one fails, another can be looked up. This
// function handles responses from parent proxies. If the response is
// bad the next parent proxy (if any) is looked up. If there are no more
// parent proxies that can be looked up, the response is sent to the
// origin server. If the response is good handle_forward_server_connection_open
// is called, as with handle_response_from_icp_suggested_host.
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_response_from_parent(State *s)
{
DebugTxn("http_trans", "[handle_response_from_parent] (hrfp)");
HTTP_RELEASE_ASSERT(s->current.server == &s->parent_info);
// response is from a parent origin server.
if (is_response_valid(s, &s->hdr_info.server_response) && s->current.request_to == HttpTransact::PARENT_PROXY &&
!s->parent_result.parent_is_proxy()) {
// check for a retryable response if simple or unavailable server retry are enabled.
if (s->parent_result.retry_type() & (PARENT_RETRY_SIMPLE | PARENT_RETRY_UNAVAILABLE_SERVER)) {
simple_or_unavailable_server_retry(s);
}
}
s->parent_info.state = s->current.state;
switch (s->current.state) {
case CONNECTION_ALIVE:
DebugTxn("http_trans", "[hrfp] connection alive");
s->current.server->connect_result = 0;
SET_VIA_STRING(VIA_DETAIL_PP_CONNECT, VIA_DETAIL_PP_SUCCESS);
if (s->parent_result.retry) {
s->parent_params->markParentUp(&s->parent_result);
}
handle_forward_server_connection_open(s);
break;
default: {
LookingUp_t next_lookup = UNDEFINED_LOOKUP;
DebugTxn("http_trans", "[hrfp] connection not alive");
SET_VIA_STRING(VIA_DETAIL_PP_CONNECT, VIA_DETAIL_PP_FAILURE);
ink_assert(s->hdr_info.server_request.valid());
s->current.server->connect_result = ENOTCONN;
char addrbuf[INET6_ADDRSTRLEN];
DebugTxn("http_trans", "[%d] failed to connect to parent %s", s->current.attempts,
ats_ip_ntop(&s->current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)));
// If the request is not retryable, just give up!
if (!is_request_retryable(s)) {
s->parent_params->markParentDown(&s->parent_result);
s->parent_result.result = PARENT_FAIL;
handle_parent_died(s);
return;
}
// try a simple retry if we received a simple retryable response from the parent.
if (s->current.retry_type == PARENT_RETRY_SIMPLE || s->current.retry_type == PARENT_RETRY_UNAVAILABLE_SERVER) {
if (s->current.retry_type == PARENT_RETRY_SIMPLE) {
if (s->current.simple_retry_attempts >= s->parent_result.max_retries(PARENT_RETRY_SIMPLE)) {
DebugTxn("http_trans", "PARENT_RETRY_SIMPLE: retried all parents, send error to client.");
s->current.retry_type = PARENT_RETRY_NONE;
} else {
s->current.simple_retry_attempts++;
DebugTxn("http_trans", "PARENT_RETRY_SIMPLE: try another parent.");
s->current.retry_type = PARENT_RETRY_NONE;
next_lookup = find_server_and_update_current_info(s);
}
} else { // try unavailable server retry if we have a unavailable server retry response from the parent.
if (s->current.unavailable_server_retry_attempts >= s->parent_result.max_retries(PARENT_RETRY_UNAVAILABLE_SERVER)) {
DebugTxn("http_trans", "PARENT_RETRY_UNAVAILABLE_SERVER: retried all parents, send error to client.");
s->current.retry_type = PARENT_RETRY_NONE;
} else {
s->current.unavailable_server_retry_attempts++;
DebugTxn("http_trans", "PARENT_RETRY_UNAVAILABLE_SERVER: marking parent down and trying another.");
s->current.retry_type = PARENT_RETRY_NONE;
s->parent_params->markParentDown(&s->parent_result);
next_lookup = find_server_and_update_current_info(s);
}
}
} else if (s->current.attempts < s->txn_conf->parent_connect_attempts) {
s->current.attempts++;
// Are we done with this particular parent?
if ((s->current.attempts - 1) % s->http_config_param->per_parent_connect_attempts != 0) {
// No we are not done with this parent so retry
s->next_action = how_to_open_connection(s);
DebugTxn("http_trans", "%s Retrying parent for attempt %d, max %" PRId64, "[handle_response_from_parent]",
s->current.attempts, s->http_config_param->per_parent_connect_attempts);
return;
} else {
DebugTxn("http_trans", "%s %d per parent attempts exhausted", "[handle_response_from_parent]", s->current.attempts);
// Only mark the parent down if we failed to connect
// to the parent otherwise slow origin servers cause
// us to mark the parent down
if (s->current.state == CONNECTION_ERROR) {
s->parent_params->markParentDown(&s->parent_result);
}
// We are done so look for another parent if any
next_lookup = find_server_and_update_current_info(s);
}
} else {
// Done trying parents... fail over to origin server if that is
// appropriate
DebugTxn("http_trans", "[handle_response_from_parent] Error. No more retries.");
s->parent_params->markParentDown(&s->parent_result);
s->parent_result.result = PARENT_FAIL;
next_lookup = find_server_and_update_current_info(s);
}
// We have either tried to find a new parent or failed over to the
// origin server
switch (next_lookup) {
case PARENT_PROXY:
ink_assert(s->current.request_to == PARENT_PROXY);
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, PPDNSLookup);
break;
case ORIGIN_SERVER:
s->current.attempts = 0;
s->next_action = how_to_open_connection(s);
if (s->current.server == &s->server_info && s->next_hop_scheme == URL_WKSIDX_HTTP) {
HttpTransactHeaders::remove_host_name_from_url(&s->hdr_info.server_request);
}
break;
case HOST_NONE:
handle_parent_died(s);
break;
default:
// This handles:
// UNDEFINED_LOOKUP, ICP_SUGGESTED_HOST,
// INCOMING_ROUTER
break;
}
break;
}
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : handle_response_from_server
// Description: response is from the origin server
//
// Details :
//
// response from the origin server. one of three things can happen now.
// if the response is bad, then we can either retry (by first downgrading
// the request, maybe making it non-keepalive, etc.), or we can give up.
// the latter case is handled by handle_server_connection_not_open and
// sends an error response back to the client. if the response is good
// handle_forward_server_connection_open is called.
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_response_from_server(State *s)
{
DebugTxn("http_trans", "[handle_response_from_server] (hrfs)");
HTTP_RELEASE_ASSERT(s->current.server == &s->server_info);
unsigned max_connect_retries = 0;
// plugin call
s->server_info.state = s->current.state;
if (s->fp_tsremap_os_response) {
s->fp_tsremap_os_response(s->remap_plugin_instance, reinterpret_cast<TSHttpTxn>(s->state_machine), s->current.state);
}
switch (s->current.state) {
case CONNECTION_ALIVE:
DebugTxn("http_trans", "[hrfs] connection alive");
SET_VIA_STRING(VIA_DETAIL_SERVER_CONNECT, VIA_DETAIL_SERVER_SUCCESS);
s->current.server->clear_connect_fail();
handle_forward_server_connection_open(s);
break;
case CONGEST_CONTROL_CONGESTED_ON_F:
case CONGEST_CONTROL_CONGESTED_ON_M:
DebugTxn("http_trans", "[handle_response_from_server] Error. congestion control -- congested.");
SET_VIA_STRING(VIA_DETAIL_SERVER_CONNECT, VIA_DETAIL_SERVER_FAILURE);
s->current.server->set_connect_fail(EUSERS); // too many users
handle_server_connection_not_open(s);
break;
case OPEN_RAW_ERROR:
/* fall through */
case CONNECTION_ERROR:
/* fall through */
case STATE_UNDEFINED:
/* fall through */
case INACTIVE_TIMEOUT:
/* fall through */
case PARSE_ERROR:
/* fall through */
case CONNECTION_CLOSED:
/* fall through */
case BAD_INCOMING_RESPONSE:
// Set to generic I/O error if not already set specifically.
if (!s->current.server->had_connect_fail()) {
s->current.server->set_connect_fail(EIO);
}
if (is_server_negative_cached(s)) {
max_connect_retries = s->txn_conf->connect_attempts_max_retries_dead_server;
} else {
// server not yet negative cached - use default number of retries
max_connect_retries = s->txn_conf->connect_attempts_max_retries;
}
if (s->pCongestionEntry != NULL) {
max_connect_retries = s->pCongestionEntry->connect_retries();
}
if (is_request_retryable(s) && s->current.attempts < max_connect_retries) {
// If this is a round robin DNS entry & we're tried configured
// number of times, we should try another node
if (DNSLookupInfo::OS_ADDR_TRY_CLIENT == s->dns_info.os_addr_style) {
// attempt was based on client supplied server address. Try again
// using HostDB.
// Allow DNS attempt
s->dns_info.lookup_success = false;
// See if we can get data from HostDB for this.
s->dns_info.os_addr_style = DNSLookupInfo::OS_ADDR_TRY_HOSTDB;
// Force host resolution to have the same family as the client.
// Because this is a transparent connection, we can't switch address
// families - that is locked in by the client source address.
s->state_machine->ua_session->set_host_res_style(ats_host_res_match(&s->current.server->dst_addr.sa));
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, OSDNSLookup);
} else if ((s->dns_info.srv_lookup_success || s->host_db_info.is_rr_elt()) &&
(s->txn_conf->connect_attempts_rr_retries > 0) &&
(s->current.attempts % s->txn_conf->connect_attempts_rr_retries == 0)) {
delete_server_rr_entry(s, max_connect_retries);
return;
} else {
retry_server_connection_not_open(s, s->current.state, max_connect_retries);
DebugTxn("http_trans", "[handle_response_from_server] Error. Retrying...");
s->next_action = how_to_open_connection(s);
if (s->api_server_addr_set) {
// If the plugin set a server address, back up to the OS_DNS hook
// to let it try another one. Force OS_ADDR_USE_CLIENT so that
// in OSDNSLoopkup, we back up to how_to_open_connections which
// will tell HttpSM to connect the origin server.
s->dns_info.os_addr_style = DNSLookupInfo::OS_ADDR_USE_CLIENT;
TRANSACT_RETURN(SM_ACTION_API_OS_DNS, OSDNSLookup);
}
return;
}
} else {
DebugTxn("http_trans", "[handle_response_from_server] Error. No more retries.");
SET_VIA_STRING(VIA_DETAIL_SERVER_CONNECT, VIA_DETAIL_SERVER_FAILURE);
handle_server_connection_not_open(s);
}
break;
case ACTIVE_TIMEOUT:
DebugTxn("http_trans", "[hrfs] connection not alive");
SET_VIA_STRING(VIA_DETAIL_SERVER_CONNECT, VIA_DETAIL_SERVER_FAILURE);
s->current.server->set_connect_fail(ETIMEDOUT);
handle_server_connection_not_open(s);
break;
default:
ink_assert(!("s->current.state is set to something unsupported"));
break;
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : delete_server_rr_entry
// Description:
//
// Details :
//
// connection to server failed mark down the server round robin entry
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::delete_server_rr_entry(State *s, int max_retries)
{
char addrbuf[INET6_ADDRSTRLEN];
DebugTxn("http_trans", "[%d] failed to connect to %s", s->current.attempts,
ats_ip_ntop(&s->current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)));
DebugTxn("http_trans", "[delete_server_rr_entry] marking rr entry "
"down and finding next one");
ink_assert(s->current.server->had_connect_fail());
ink_assert(s->current.request_to == ORIGIN_SERVER);
ink_assert(s->current.server == &s->server_info);
update_dns_info(&s->dns_info, &s->current, 0, &s->arena);
s->current.attempts++;
DebugTxn("http_trans", "[delete_server_rr_entry] attempts now: %d, max: %d", s->current.attempts, max_retries);
TRANSACT_RETURN(SM_ACTION_ORIGIN_SERVER_RR_MARK_DOWN, ReDNSRoundRobin);
}
///////////////////////////////////////////////////////////////////////////////
// Name : retry_server_connection_not_open
// Description:
//
// Details :
//
// connection to server failed. retry.
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::retry_server_connection_not_open(State *s, ServerState_t conn_state, unsigned max_retries)
{
ink_assert(s->current.state != CONNECTION_ALIVE);
ink_assert(s->current.state != ACTIVE_TIMEOUT);
ink_assert(s->current.attempts <= max_retries);
ink_assert(s->current.server->had_connect_fail());
char addrbuf[INET6_ADDRSTRLEN];
char *url_string = s->hdr_info.client_request.url_string_get(&s->arena);
DebugTxn("http_trans", "[%d] failed to connect [%d] to %s", s->current.attempts, conn_state,
ats_ip_ntop(&s->current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)));
//////////////////////////////////////////
// on the first connect attempt failure //
// record the failue //
//////////////////////////////////////////
if (0 == s->current.attempts) {
Log::error("CONNECT:[%d] could not connect [%s] to %s for '%s'", s->current.attempts,
HttpDebugNames::get_server_state_name(conn_state),
ats_ip_ntop(&s->current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)), url_string ? url_string : "<none>");
}
if (url_string) {
s->arena.str_free(url_string);
}
//////////////////////////////////////////////
// disable keep-alive for request and retry //
//////////////////////////////////////////////
s->current.server->keep_alive = HTTP_NO_KEEPALIVE;
s->current.attempts++;
DebugTxn("http_trans", "[retry_server_connection_not_open] attempts now: %d, max: %d", s->current.attempts, max_retries);
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : handle_server_connection_not_open
// Description:
//
// Details :
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_server_connection_not_open(State *s)
{
bool serve_from_cache = false;
DebugTxn("http_trans", "[handle_server_connection_not_open] (hscno)");
DebugTxn("http_seq", "[HttpTransact::handle_server_connection_not_open] ");
ink_assert(s->current.state != CONNECTION_ALIVE);
SET_VIA_STRING(VIA_SERVER_RESULT, VIA_SERVER_ERROR);
HTTP_INCREMENT_DYN_STAT(http_broken_server_connections_stat);
// Fire off a hostdb update to mark the server as down
s->state_machine->do_hostdb_update_if_necessary();
switch (s->cache_info.action) {
case CACHE_DO_UPDATE:
serve_from_cache = is_stale_cache_response_returnable(s);
break;
case CACHE_PREPARE_TO_DELETE:
/* fall through */
case CACHE_PREPARE_TO_UPDATE:
/* fall through */
case CACHE_PREPARE_TO_WRITE:
ink_release_assert(!"Why still preparing for cache action - "
"we skipped a step somehow.");
break;
case CACHE_DO_LOOKUP:
/* fall through */
case CACHE_DO_SERVE:
ink_assert(!("Why server response? Should have been a cache operation"));
break;
case CACHE_DO_DELETE:
// decisions, decisions. what should we do here?
// we could theoretically still delete the cached
// copy or serve it back with a warning, or easier
// just punt and biff the user. i say: biff the user.
/* fall through */
case CACHE_DO_UNDEFINED:
/* fall through */
case CACHE_DO_NO_ACTION:
/* fall through */
case CACHE_DO_WRITE:
/* fall through */
default:
serve_from_cache = false;
break;
}
if (serve_from_cache) {
ink_assert(s->cache_info.object_read != NULL);
ink_assert(s->cache_info.action == CACHE_DO_UPDATE);
ink_assert(s->internal_msg_buffer == NULL);
DebugTxn("http_trans", "[hscno] serving stale doc to client");
build_response_from_cache(s, HTTP_WARNING_CODE_REVALIDATION_FAILED);
} else {
handle_server_died(s);
s->next_action = SM_ACTION_SEND_ERROR_CACHE_NOOP;
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : handle_forward_server_connection_open
// Description: connection to a forward server is open and good
//
// Details :
//
// "Forward server" includes the icp-suggested-host or the parent proxy
// or the origin server. This function first determines if the forward
// server uses HTTP 0.9, in which case it simply tunnels the response
// to the client. Else, it updates
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_forward_server_connection_open(State *s)
{
DebugTxn("http_trans", "[handle_forward_server_connection_open] (hfsco)");
DebugTxn("http_seq", "[HttpTransact::handle_server_connection_open] ");
ink_release_assert(s->current.state == CONNECTION_ALIVE);
if (s->hdr_info.server_response.version_get() == HTTPVersion(0, 9)) {
DebugTxn("http_trans", "[hfsco] server sent 0.9 response, reading...");
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, HTTP_STATUS_OK, "Connection Established");
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_SERVER_READ;
return;
} else if (s->hdr_info.server_response.version_get() == HTTPVersion(1, 0)) {
if (s->current.server->http_version == HTTPVersion(0, 9)) {
// update_hostdb_to_indicate_server_version_is_1_0
s->updated_server_version = HostDBApplicationInfo::HTTP_VERSION_10;
} else if (s->current.server->http_version == HTTPVersion(1, 1)) {
// update_hostdb_to_indicate_server_version_is_1_0
s->updated_server_version = HostDBApplicationInfo::HTTP_VERSION_10;
} else {
// dont update the hostdb. let us try again with what we currently think.
}
} else if (s->hdr_info.server_response.version_get() == HTTPVersion(1, 1)) {
if (s->current.server->http_version == HTTPVersion(0, 9)) {
// update_hostdb_to_indicate_server_version_is_1_1
s->updated_server_version = HostDBApplicationInfo::HTTP_VERSION_11;
} else if (s->current.server->http_version == HTTPVersion(1, 0)) {
// update_hostdb_to_indicate_server_version_is_1_1
s->updated_server_version = HostDBApplicationInfo::HTTP_VERSION_11;
} else {
// dont update the hostdb. let us try again with what we currently think.
}
} else {
// dont update the hostdb. let us try again with what we currently think.
}
if (s->hdr_info.server_response.status_get() == HTTP_STATUS_CONTINUE) {
handle_100_continue_response(s);
return;
}
s->state_machine->do_hostdb_update_if_necessary();
if (s->www_auth_content == CACHE_AUTH_FRESH) {
// no update is needed - either to serve from cache if authorized,
// or tunnnel the server response
if (s->hdr_info.server_response.status_get() == HTTP_STATUS_OK) {
// borrow a state variable used by the API function
// this enable us to serve from cache without doing any updating
s->api_server_response_ignore = true;
}
// s->cache_info.action = CACHE_PREPARE_TO_SERVE;
// xing xing in the tunneling case, need to check when the cache_read_vc is closed, make sure the cache_read_vc is closed
// right
// away
}
CacheVConnection *cw_vc = s->state_machine->get_cache_sm().cache_write_vc;
if (s->redirect_info.redirect_in_process && s->state_machine->enable_redirection) {
if (s->cache_info.action == CACHE_DO_NO_ACTION) {
switch (s->hdr_info.server_response.status_get()) {
case HTTP_STATUS_MULTIPLE_CHOICES: // 300
case HTTP_STATUS_MOVED_PERMANENTLY: // 301
case HTTP_STATUS_MOVED_TEMPORARILY: // 302
case HTTP_STATUS_SEE_OTHER: // 303
case HTTP_STATUS_USE_PROXY: // 305
case HTTP_STATUS_TEMPORARY_REDIRECT: // 307
break;
default:
DebugTxn("http_trans", "[hfsco] redirect in progress, non-3xx response, setting cache_do_write");
if (cw_vc && s->txn_conf->cache_http) {
s->cache_info.action = CACHE_DO_WRITE;
}
break;
}
}
}
switch (s->cache_info.action) {
case CACHE_DO_WRITE:
/* fall through */
case CACHE_DO_UPDATE:
/* fall through */
case CACHE_DO_DELETE:
DebugTxn("http_trans", "[hfsco] cache action: %s", HttpDebugNames::get_cache_action_name(s->cache_info.action));
handle_cache_operation_on_forward_server_response(s);
break;
case CACHE_PREPARE_TO_DELETE:
/* fall through */
case CACHE_PREPARE_TO_UPDATE:
/* fall through */
case CACHE_PREPARE_TO_WRITE:
ink_release_assert(!"Why still preparing for cache action - we skipped a step somehow.");
break;
case CACHE_DO_LOOKUP:
/* fall through */
case CACHE_DO_SERVE:
ink_assert(!("Why server response? Should have been a cache operation"));
break;
case CACHE_DO_UNDEFINED:
/* fall through */
case CACHE_DO_NO_ACTION:
/* fall through */
default:
// Just tunnel?
DebugTxn("http_trans", "[hfsco] cache action: %s", HttpDebugNames::get_cache_action_name(s->cache_info.action));
handle_no_cache_operation_on_forward_server_response(s);
break;
}
return;
}
// void HttpTransact::handle_100_continue_response(State* s)
//
// We've received a 100 continue response. Determine if
// we should just swallow the response 100 or forward it
// the client. http-1.1-spec-rev-06 section 8.2.3
//
void
HttpTransact::handle_100_continue_response(State *s)
{
bool forward_100 = false;
HTTPVersion ver = s->hdr_info.client_request.version_get();
if (ver == HTTPVersion(1, 1)) {
forward_100 = true;
} else if (ver == HTTPVersion(1, 0)) {
if (s->hdr_info.client_request.value_get_int(MIME_FIELD_EXPECT, MIME_LEN_EXPECT) == 100) {
forward_100 = true;
}
}
if (forward_100) {
// We just want to copy the server's response. All
// the other build response functions insist on
// adding stuff
build_response_copy(s, &s->hdr_info.server_response, &s->hdr_info.client_response, s->client_info.http_version);
TRANSACT_RETURN(SM_ACTION_INTERNAL_100_RESPONSE, HandleResponse);
} else {
TRANSACT_RETURN(SM_ACTION_SERVER_PARSE_NEXT_HDR, HandleResponse);
}
}
// void HttpTransact::build_response_copy
//
// Build a response with minimal changes from the base response
//
void
HttpTransact::build_response_copy(State *s, HTTPHdr *base_response, HTTPHdr *outgoing_response, HTTPVersion outgoing_version)
{
HttpTransactHeaders::copy_header_fields(base_response, outgoing_response, s->txn_conf->fwd_proxy_auth_to_parent, s->current.now);
HttpTransactHeaders::convert_response(outgoing_version, outgoing_response); // http version conversion
HttpTransactHeaders::add_server_header_to_response(s->txn_conf, outgoing_response);
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", outgoing_response, s->state_machine_id, "Proxy's Response");
}
//////////////////////////////////////////////////////////////////////////
// IMS handling table //
// OS = Origin Server //
// IMS = A GET request w/ an If-Modified-Since header //
// LMs = Last modified state returned by server //
// D, D' are Last modified dates returned by the origin server //
// and are later used for IMS //
// D < D' //
// //
// +------------------------------------------------------------+ //
// | Client's | Cached | Proxy's | Response to client | //
// | Request | State | Request | OS 200 | OS 304 | //
// |------------------------------------------------------------| //
// | GET | Fresh | N/A | N/A | N/A | //
// |------------------------------------------------------------| //
// | GET | Stale, D' | IMS D' | 200, new | 200, cached | //
// |------------------------------------------------------------| //
// | IMS D | None | GET | 200, new *| N/A | //
// |------------------------------------------------------------| //
// | IMS D | Stale, D' | IMS D' | 200, new | Compare | //
// |---------------------------------------------| LMs & D' | //
// | IMS D' | Stale, D' | IMS D' | 200, new | If match, 304| //
// |---------------------------------------------| If no match, | //
// | IMS D' | Stale D | IMS D | 200, new *| 200, cached | //
// +------------------------------------------------------------+ //
// //
// Note: * indicates a case that could be optimized to return //
// 304 to the client but currently is not //
// //
//////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Name : handle_cache_operation_on_forward_server_response
// Description:
//
// Details :
//
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_cache_operation_on_forward_server_response(State *s)
{
DebugTxn("http_trans", "[handle_cache_operation_on_forward_server_response] (hcoofsr)");
DebugTxn("http_seq", "[handle_cache_operation_on_forward_server_response]");
HTTPHdr *base_response = NULL;
HTTPStatus server_response_code = HTTP_STATUS_NONE;
HTTPStatus client_response_code = HTTP_STATUS_NONE;
const char *warn_text = NULL;
bool cacheable = false;
cacheable = is_response_cacheable(s, &s->hdr_info.client_request, &s->hdr_info.server_response);
DebugTxn("http_trans", "[hcoofsr] response %s cacheable", cacheable ? "is" : "is not");
// set the correct next action, cache action, response code, and base response
server_response_code = s->hdr_info.server_response.status_get();
switch (server_response_code) {
case HTTP_STATUS_NOT_MODIFIED: // 304
SET_VIA_STRING(VIA_SERVER_RESULT, VIA_SERVER_NOT_MODIFIED);
// determine the correct cache action, next state, and response
// precondition: s->cache_info.action should be one of the following
// CACHE_DO_DELETE, or CACHE_DO_UPDATE; otherwise, it's an error.
if (s->api_server_response_ignore && s->cache_info.action == CACHE_DO_UPDATE) {
s->api_server_response_ignore = false;
ink_assert(s->cache_info.object_read);
base_response = s->cache_info.object_read->response_get();
s->cache_info.action = CACHE_DO_SERVE;
DebugTxn("http_trans", "[hcoofsr] not merging, cache action changed to: %s",
HttpDebugNames::get_cache_action_name(s->cache_info.action));
s->next_action = SM_ACTION_SERVE_FROM_CACHE;
client_response_code = base_response->status_get();
} else if ((s->cache_info.action == CACHE_DO_DELETE) || ((s->cache_info.action == CACHE_DO_UPDATE) && !cacheable)) {
if (is_request_conditional(&s->hdr_info.client_request)) {
client_response_code = HttpTransactCache::match_response_to_request_conditionals(
&s->hdr_info.client_request, s->cache_info.object_read->response_get(), s->response_received_time);
} else {
client_response_code = HTTP_STATUS_OK;
}
if (client_response_code != HTTP_STATUS_OK) {
// we can just forward the not modified response
// from the server and delete the cached copy
base_response = &s->hdr_info.server_response;
client_response_code = base_response->status_get();
s->cache_info.action = CACHE_DO_DELETE;
s->next_action = SM_ACTION_INTERNAL_CACHE_DELETE;
} else {
// We got screwed. The client did not send a conditional request,
// but we had a cached copy which we revalidated. The server has
// now told us to delete the cached copy and sent back a 304.
// We need to send the cached copy to the client, then delete it.
if (s->method == HTTP_WKSIDX_HEAD) {
s->cache_info.action = CACHE_DO_DELETE;
s->next_action = SM_ACTION_SERVER_READ;
} else {
s->cache_info.action = CACHE_DO_SERVE_AND_DELETE;
s->next_action = SM_ACTION_SERVE_FROM_CACHE;
}
base_response = s->cache_info.object_read->response_get();
client_response_code = base_response->status_get();
}
} else if (s->cache_info.action == CACHE_DO_UPDATE && is_request_conditional(&s->hdr_info.server_request)) {
// CACHE_DO_UPDATE and server response is cacheable
if (is_request_conditional(&s->hdr_info.client_request)) {
if (s->txn_conf->cache_when_to_revalidate != 4) {
client_response_code = HttpTransactCache::match_response_to_request_conditionals(
&s->hdr_info.client_request, s->cache_info.object_read->response_get(), s->response_received_time);
} else {
client_response_code = server_response_code;
}
} else {
client_response_code = HTTP_STATUS_OK;
}
if (client_response_code != HTTP_STATUS_OK) {
// delete the cached copy unless configured to always verify IMS
if (s->txn_conf->cache_when_to_revalidate != 4) {
s->cache_info.action = CACHE_DO_UPDATE;
s->next_action = SM_ACTION_INTERNAL_CACHE_UPDATE_HEADERS;
/* base_response will be set after updating headers below */
} else {
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
base_response = &s->hdr_info.server_response;
}
} else {
if (s->method == HTTP_WKSIDX_HEAD) {
s->cache_info.action = CACHE_DO_UPDATE;
s->next_action = SM_ACTION_SERVER_READ;
} else {
if (s->hdr_info.client_request.presence(MIME_PRESENCE_RANGE)) {
s->state_machine->do_range_setup_if_necessary();
// Note that even if the Range request is not satisfiable, we
// update and serve this cache. This will give a 200 response to
// a bad client, but allows us to avoid pegging the origin (e.g. abuse).
}
s->cache_info.action = CACHE_DO_SERVE_AND_UPDATE;
s->next_action = SM_ACTION_SERVE_FROM_CACHE;
}
/* base_response will be set after updating headers below */
}
} else { // cache action != CACHE_DO_DELETE and != CACHE_DO_UPDATE
// bogus response from server. deal by tunnelling to client.
// server should not have sent back a 304 because our request
// should not have been an conditional.
DebugTxn("http_trans", "[hcoofsr] 304 for non-conditional request");
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
client_response_code = s->hdr_info.server_response.status_get();
base_response = &s->hdr_info.server_response;
// since this is bad, insert warning header into client response
// The only exception case is conditional client request,
// cache miss, and client request being unlikely cacheable.
// In this case, the server request is given the same
// conditional headers as client request (see build_request()).
// So an unexpected 304 might be received.
// FIXME: check this case
if (is_request_likely_cacheable(s, &s->hdr_info.client_request)) {
warn_text = "Proxy received unexpected 304 response; "
"content may be stale";
}
}
break;
case HTTP_STATUS_HTTPVER_NOT_SUPPORTED: // 505
{
bool keep_alive = (s->current.server->keep_alive == HTTP_KEEPALIVE);
s->next_action = how_to_open_connection(s);
/* Downgrade the request level and retry */
if (!HttpTransactHeaders::downgrade_request(&keep_alive, &s->hdr_info.server_request)) {
build_error_response(s, HTTP_STATUS_HTTPVER_NOT_SUPPORTED, "HTTP Version Not Supported", "response#bad_version", NULL);
s->next_action = SM_ACTION_SEND_ERROR_CACHE_NOOP;
s->already_downgraded = true;
} else {
if (!keep_alive) {
/* START Hack */
(s->hdr_info.server_request).field_delete(MIME_FIELD_PROXY_CONNECTION, MIME_LEN_PROXY_CONNECTION);
/* END Hack */
}
s->already_downgraded = true;
s->next_action = how_to_open_connection(s);
}
}
return;
default:
DebugTxn("http_trans", "[hcoofsr] response code: %d", server_response_code);
SET_VIA_STRING(VIA_SERVER_RESULT, VIA_SERVER_SERVED);
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_SERVED);
/* if we receive a 500, 502, 503 or 504 while revalidating
a document, treat the response as a 304 and in effect revalidate the document for
negative_revalidating_lifetime. (negative revalidating)
*/
if ((server_response_code == HTTP_STATUS_INTERNAL_SERVER_ERROR || server_response_code == HTTP_STATUS_GATEWAY_TIMEOUT ||
server_response_code == HTTP_STATUS_BAD_GATEWAY || server_response_code == HTTP_STATUS_SERVICE_UNAVAILABLE) &&
s->cache_info.action == CACHE_DO_UPDATE && s->txn_conf->negative_revalidating_enabled &&
is_stale_cache_response_returnable(s)) {
DebugTxn("http_trans", "[hcoofsr] negative revalidating: revalidate stale object and serve from cache");
s->cache_info.object_store.create();
s->cache_info.object_store.request_set(&s->hdr_info.client_request);
s->cache_info.object_store.response_set(s->cache_info.object_read->response_get());
base_response = s->cache_info.object_store.response_get();
time_t exp_time = s->txn_conf->negative_revalidating_lifetime + ink_cluster_time();
base_response->set_expires(exp_time);
SET_VIA_STRING(VIA_CACHE_FILL_ACTION, VIA_CACHE_UPDATED);
HTTP_INCREMENT_DYN_STAT(http_cache_updates_stat);
// unset Cache-control: "need-revalidate-once" (if it's set)
// This directive is used internally by T.S. to invalidate
// documents so that an invalidated document needs to be
// revalidated again.
base_response->unset_cooked_cc_need_revalidate_once();
if (is_request_conditional(&s->hdr_info.client_request) &&
HttpTransactCache::match_response_to_request_conditionals(&s->hdr_info.client_request,
s->cache_info.object_read->response_get(),
s->response_received_time) == HTTP_STATUS_NOT_MODIFIED) {
s->next_action = SM_ACTION_INTERNAL_CACHE_UPDATE_HEADERS;
client_response_code = HTTP_STATUS_NOT_MODIFIED;
} else {
if (s->method == HTTP_WKSIDX_HEAD) {
s->cache_info.action = CACHE_DO_UPDATE;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
} else {
s->cache_info.action = CACHE_DO_SERVE_AND_UPDATE;
s->next_action = SM_ACTION_SERVE_FROM_CACHE;
}
client_response_code = s->cache_info.object_read->response_get()->status_get();
}
ink_assert(base_response->valid());
if (client_response_code == HTTP_STATUS_NOT_MODIFIED) {
ink_assert(GET_VIA_STRING(VIA_CLIENT_REQUEST) != VIA_CLIENT_SIMPLE);
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_IMS);
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_NOT_MODIFIED);
} else {
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_SERVED);
}
ink_assert(client_response_code != HTTP_STATUS_NONE);
if (s->next_action == SM_ACTION_SERVE_FROM_CACHE && s->state_machine->do_transform_open()) {
set_header_for_transform(s, base_response);
} else {
build_response(s, base_response, &s->hdr_info.client_response, s->client_info.http_version, client_response_code);
}
return;
}
s->next_action = SM_ACTION_SERVER_READ;
client_response_code = server_response_code;
base_response = &s->hdr_info.server_response;
s->negative_caching = is_negative_caching_appropriate(s) && cacheable;
// determine the correct cache action given the original cache action,
// cacheability of server response, and request method
// precondition: s->cache_info.action is one of the following
// CACHE_DO_UPDATE, CACHE_DO_WRITE, or CACHE_DO_DELETE
if (s->api_server_response_no_store) {
s->cache_info.action = CACHE_DO_NO_ACTION;
} else if (s->api_server_response_ignore && server_response_code == HTTP_STATUS_OK &&
s->hdr_info.server_request.method_get_wksidx() == HTTP_WKSIDX_HEAD) {
s->api_server_response_ignore = false;
ink_assert(s->cache_info.object_read);
base_response = s->cache_info.object_read->response_get();
s->cache_info.action = CACHE_DO_SERVE;
DebugTxn("http_trans", "[hcoofsr] ignoring server response, "
"cache action changed to: %s",
HttpDebugNames::get_cache_action_name(s->cache_info.action));
s->next_action = SM_ACTION_SERVE_FROM_CACHE;
client_response_code = base_response->status_get();
} else if (s->cache_info.action == CACHE_DO_UPDATE) {
if (s->www_auth_content == CACHE_AUTH_FRESH || s->api_server_response_ignore) {
s->cache_info.action = CACHE_DO_NO_ACTION;
} else if (s->www_auth_content == CACHE_AUTH_STALE && server_response_code == HTTP_STATUS_UNAUTHORIZED) {
s->cache_info.action = CACHE_DO_NO_ACTION;
} else if (!cacheable) {
s->cache_info.action = CACHE_DO_DELETE;
} else if (s->method == HTTP_WKSIDX_HEAD) {
s->cache_info.action = CACHE_DO_DELETE;
} else {
ink_assert(s->cache_info.object_read != 0);
s->cache_info.action = CACHE_DO_REPLACE;
}
} else if (s->cache_info.action == CACHE_DO_WRITE) {
if (!cacheable && !s->negative_caching) {
s->cache_info.action = CACHE_DO_NO_ACTION;
} else if (s->method == HTTP_WKSIDX_HEAD) {
s->cache_info.action = CACHE_DO_NO_ACTION;
} else {
s->cache_info.action = CACHE_DO_WRITE;
}
} else if (s->cache_info.action == CACHE_DO_DELETE) {
// do nothing
} else {
ink_assert(!("cache action inconsistent with current state"));
}
// postcondition: s->cache_info.action is one of the following
// CACHE_DO_REPLACE, CACHE_DO_WRITE, CACHE_DO_DELETE, or
// CACHE_DO_NO_ACTION
// Check see if we ought to serve the client a 304 based on
// it's IMS date. We may gotten a 200 back from the origin
// server if our (the proxies's) cached copy was out of date
// but the client's wasn't. However, if the response is
// not cacheable we ought not issue a 304 to the client so
// make sure we are writing the document to the cache if
// before issuing a 304
if (s->cache_info.action == CACHE_DO_WRITE || s->cache_info.action == CACHE_DO_NO_ACTION ||
s->cache_info.action == CACHE_DO_REPLACE) {
if (s->negative_caching) {
HTTPHdr *resp;
s->cache_info.object_store.create();
s->cache_info.object_store.request_set(&s->hdr_info.client_request);
s->cache_info.object_store.response_set(&s->hdr_info.server_response);
resp = s->cache_info.object_store.response_get();
if (!resp->presence(MIME_PRESENCE_EXPIRES)) {
time_t exp_time = s->txn_conf->negative_caching_lifetime + ink_cluster_time();
resp->set_expires(exp_time);
}
} else if (is_request_conditional(&s->hdr_info.client_request) && server_response_code == HTTP_STATUS_OK) {
client_response_code = HttpTransactCache::match_response_to_request_conditionals(
&s->hdr_info.client_request, &s->hdr_info.server_response, s->response_received_time);
DebugTxn("http_trans", "[hcoofsr] conditional request, 200 "
"response, send back 304 if possible [crc=%d]",
client_response_code);
if ((client_response_code == HTTP_STATUS_NOT_MODIFIED) || (client_response_code == HTTP_STATUS_PRECONDITION_FAILED)) {
switch (s->cache_info.action) {
case CACHE_DO_WRITE:
case CACHE_DO_REPLACE:
s->next_action = SM_ACTION_INTERNAL_CACHE_WRITE;
break;
case CACHE_DO_DELETE:
s->next_action = SM_ACTION_INTERNAL_CACHE_DELETE;
break;
default:
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
break;
}
} else {
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_SERVER_REVALIDATED);
}
}
} else if (s->negative_caching) {
s->negative_caching = false;
}
break;
}
// update stat, set via string, etc
switch (s->cache_info.action) {
case CACHE_DO_SERVE_AND_DELETE:
// fall through
case CACHE_DO_DELETE:
DebugTxn("http_trans", "[hcoofsr] delete cached copy");
SET_VIA_STRING(VIA_CACHE_FILL_ACTION, VIA_CACHE_DELETED);
HTTP_INCREMENT_DYN_STAT(http_cache_deletes_stat);
break;
case CACHE_DO_WRITE:
DebugTxn("http_trans", "[hcoofsr] cache write");
SET_VIA_STRING(VIA_CACHE_FILL_ACTION, VIA_CACHE_WRITTEN);
HTTP_INCREMENT_DYN_STAT(http_cache_writes_stat);
break;
case CACHE_DO_SERVE_AND_UPDATE:
// fall through
case CACHE_DO_UPDATE:
// fall through
case CACHE_DO_REPLACE:
DebugTxn("http_trans", "[hcoofsr] cache update/replace");
SET_VIA_STRING(VIA_CACHE_FILL_ACTION, VIA_CACHE_UPDATED);
HTTP_INCREMENT_DYN_STAT(http_cache_updates_stat);
break;
default:
break;
}
if ((client_response_code == HTTP_STATUS_NOT_MODIFIED) && (s->cache_info.action != CACHE_DO_NO_ACTION)) {
/* ink_assert(GET_VIA_STRING(VIA_CLIENT_REQUEST)
!= VIA_CLIENT_SIMPLE); */
DebugTxn("http_trans", "[hcoofsr] Client request was conditional");
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_IMS);
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_NOT_MODIFIED);
} else {
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_SERVED);
}
ink_assert(client_response_code != HTTP_STATUS_NONE);
// The correct cache action, next action, and response code are set.
// Do the real work below.
// first update the cached object
if ((s->cache_info.action == CACHE_DO_UPDATE) || (s->cache_info.action == CACHE_DO_SERVE_AND_UPDATE)) {
DebugTxn("http_trans", "[hcoofsr] merge and update cached copy");
merge_and_update_headers_for_cache_update(s);
base_response = s->cache_info.object_store.response_get();
// unset Cache-control: "need-revalidate-once" (if it's set)
// This directive is used internally by T.S. to invalidate documents
// so that an invalidated document needs to be revalidated again.
base_response->unset_cooked_cc_need_revalidate_once();
// unset warning revalidation failed header if it set
// (potentially added by negative revalidating)
delete_warning_value(base_response, HTTP_WARNING_CODE_REVALIDATION_FAILED);
}
ink_assert(base_response->valid());
if ((s->cache_info.action == CACHE_DO_WRITE) || (s->cache_info.action == CACHE_DO_REPLACE)) {
set_headers_for_cache_write(s, &s->cache_info.object_store, &s->hdr_info.server_request, &s->hdr_info.server_response);
}
// 304, 412, and 416 responses are handled here
if ((client_response_code == HTTP_STATUS_NOT_MODIFIED) || (client_response_code == HTTP_STATUS_PRECONDITION_FAILED)) {
// Because we are decoupling User-Agent validation from
// Traffic Server validation just build a regular 304
// if the exception of adding prepending the VIA
// header to show the revalidation path
build_response(s, base_response, &s->hdr_info.client_response, s->client_info.http_version, client_response_code);
// Copy over the response via field (if any) preserving
// the order of the fields
MIMEField *resp_via = s->hdr_info.server_response.field_find(MIME_FIELD_VIA, MIME_LEN_VIA);
if (resp_via) {
MIMEField *our_via;
our_via = s->hdr_info.client_response.field_find(MIME_FIELD_VIA, MIME_LEN_VIA);
if (our_via == NULL) {
our_via = s->hdr_info.client_response.field_create(MIME_FIELD_VIA, MIME_LEN_VIA);
s->hdr_info.client_response.field_attach(our_via);
}
// HDR FIX ME - Mulitple appends are VERY slow
while (resp_via) {
int clen;
const char *cfield = resp_via->value_get(&clen);
s->hdr_info.client_response.field_value_append(our_via, cfield, clen, true);
resp_via = resp_via->m_next_dup;
}
}
// a warning text is added only in the case of a NOT MODIFIED response
if (warn_text) {
HttpTransactHeaders::insert_warning_header(s->http_config_param, &s->hdr_info.client_response, HTTP_WARNING_CODE_MISC_WARNING,
warn_text, strlen(warn_text));
}
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", &s->hdr_info.client_response, s->state_machine_id, "Proxy's Response (Client Conditionals)");
return;
}
// all other responses (not 304, 412, 416) are handled here
else {
if (((s->next_action == SM_ACTION_SERVE_FROM_CACHE) || (s->next_action == SM_ACTION_SERVER_READ)) &&
s->state_machine->do_transform_open()) {
set_header_for_transform(s, base_response);
} else {
build_response(s, base_response, &s->hdr_info.client_response, s->client_info.http_version, client_response_code);
}
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : handle_no_cache_operation_on_forward_server_response
// Description:
//
// Details :
//
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_no_cache_operation_on_forward_server_response(State *s)
{
DebugTxn("http_trans", "[handle_no_cache_operation_on_forward_server_response] (hncoofsr)");
DebugTxn("http_seq", "[handle_no_cache_operation_on_forward_server_response]");
bool keep_alive = s->current.server->keep_alive == HTTP_KEEPALIVE;
const char *warn_text = NULL;
switch (s->hdr_info.server_response.status_get()) {
case HTTP_STATUS_OK:
DebugTxn("http_trans", "[hncoofsr] server sent back 200");
SET_VIA_STRING(VIA_SERVER_RESULT, VIA_SERVER_SERVED);
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_SERVED);
if (s->method == HTTP_WKSIDX_CONNECT) {
DebugTxn("http_trans", "[hncoofsr] next action is SSL_TUNNEL");
s->next_action = SM_ACTION_SSL_TUNNEL;
} else {
DebugTxn("http_trans", "[hncoofsr] next action will be OS_READ_CACHE_NOOP");
ink_assert(s->cache_info.action == CACHE_DO_NO_ACTION);
s->next_action = SM_ACTION_SERVER_READ;
}
if (s->state_machine->redirect_url == NULL) {
s->state_machine->enable_redirection = false;
}
break;
case HTTP_STATUS_NOT_MODIFIED:
DebugTxn("http_trans", "[hncoofsr] server sent back 304. IMS from client?");
SET_VIA_STRING(VIA_SERVER_RESULT, VIA_SERVER_NOT_MODIFIED);
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_NOT_MODIFIED);
if (!is_request_conditional(&s->hdr_info.client_request)) {
// bogus server response. not a conditional request
// from the client and probably not a conditional
// request from the proxy.
// since this is bad, insert warning header into client response
warn_text = "Proxy received unexpected 304 response; content may be stale";
}
ink_assert(s->cache_info.action == CACHE_DO_NO_ACTION);
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
break;
case HTTP_STATUS_HTTPVER_NOT_SUPPORTED:
s->next_action = how_to_open_connection(s);
/* Downgrade the request level and retry */
if (!HttpTransactHeaders::downgrade_request(&keep_alive, &s->hdr_info.server_request)) {
s->already_downgraded = true;
build_error_response(s, HTTP_STATUS_HTTPVER_NOT_SUPPORTED, "HTTP Version Not Supported", "response#bad_version", NULL);
s->next_action = SM_ACTION_SEND_ERROR_CACHE_NOOP;
} else {
s->already_downgraded = true;
s->next_action = how_to_open_connection(s);
}
return;
case HTTP_STATUS_PARTIAL_CONTENT:
// If we get this back we should be just passing it through.
ink_assert(s->cache_info.action == CACHE_DO_NO_ACTION);
s->next_action = SM_ACTION_SERVER_READ;
break;
default:
DebugTxn("http_trans", "[hncoofsr] server sent back something other than 100,304,200");
/* Default behavior is to pass-through response to the client */
ink_assert(s->cache_info.action == CACHE_DO_NO_ACTION);
s->next_action = SM_ACTION_SERVER_READ;
break;
}
HTTPHdr *to_warn;
if (s->next_action == SM_ACTION_SERVER_READ && s->state_machine->do_transform_open()) {
set_header_for_transform(s, &s->hdr_info.server_response);
to_warn = &s->hdr_info.transform_response;
} else {
build_response(s, &s->hdr_info.server_response, &s->hdr_info.client_response, s->client_info.http_version);
to_warn = &s->hdr_info.server_response;
}
if (warn_text) {
HttpTransactHeaders::insert_warning_header(s->http_config_param, to_warn, HTTP_WARNING_CODE_MISC_WARNING, warn_text,
strlen(warn_text));
}
return;
}
void
HttpTransact::merge_and_update_headers_for_cache_update(State *s)
{
URL *s_url = NULL;
HTTPHdr *cached_hdr = NULL;
if (!s->cache_info.object_store.valid()) {
s->cache_info.object_store.create();
}
s->cache_info.object_store.request_set(&s->hdr_info.server_request);
cached_hdr = s->cache_info.object_store.response_get();
if (s->redirect_info.redirect_in_process) {
s_url = &s->redirect_info.original_url;
} else {
s_url = &s->cache_info.original_url;
}
ink_assert(s_url != NULL);
s->cache_info.object_store.request_get()->url_set(s_url->valid() ? s_url : s->hdr_info.client_request.url_get());
if (s->cache_info.object_store.request_get()->method_get_wksidx() == HTTP_WKSIDX_HEAD) {
s->cache_info.object_store.request_get()->method_set(HTTP_METHOD_GET, HTTP_LEN_GET);
}
if (s->api_modifiable_cached_resp) {
ink_assert(cached_hdr != NULL && cached_hdr->valid());
s->api_modifiable_cached_resp = false;
} else {
s->cache_info.object_store.response_set(s->cache_info.object_read->response_get());
}
// Delete caching headers from the cached response. If these are
// still being served by the origin we will copy new versions in
// from the server response. RFC 2616 says that a 304 response may
// omit some headers if they were sent in a 200 response (see section
// 10.3.5), but RFC 7232) is clear that the 304 and 200 responses
// must be identical (see section 4.1). This code attempts to strike
// a balance between the two.
cached_hdr->field_delete(MIME_FIELD_AGE, MIME_LEN_AGE);
cached_hdr->field_delete(MIME_FIELD_ETAG, MIME_LEN_ETAG);
cached_hdr->field_delete(MIME_FIELD_EXPIRES, MIME_LEN_EXPIRES);
merge_response_header_with_cached_header(cached_hdr, &s->hdr_info.server_response);
// Some special processing for 304
if (s->hdr_info.server_response.status_get() == HTTP_STATUS_NOT_MODIFIED) {
// Hack fix. If the server sends back
// a 304 without a Date Header, use the current time
// as the new Date value in the header to be cached.
time_t date_value = s->hdr_info.server_response.get_date();
if (date_value <= 0) {
cached_hdr->set_date(s->request_sent_time);
date_value = s->request_sent_time;
}
// If the cached response has an Age: we should update it
// We could use calculate_document_age but my guess is it's overkill
// Just use 'now' - 304's Date: + Age: (response's Age: if there)
date_value = max(s->current.now - date_value, (ink_time_t)0);
if (s->hdr_info.server_response.presence(MIME_PRESENCE_AGE)) {
time_t new_age = s->hdr_info.server_response.get_age();
if (new_age >= 0) {
cached_hdr->set_age(date_value + new_age);
} else {
cached_hdr->set_age(-1); // Overflow
}
}
delete_warning_value(cached_hdr, HTTP_WARNING_CODE_REVALIDATION_FAILED);
}
s->cache_info.object_store.request_get()->field_delete(MIME_FIELD_VIA, MIME_LEN_VIA);
}
void
HttpTransact::handle_transform_cache_write(State *s)
{
ink_assert(s->cache_info.transform_action == CACHE_PREPARE_TO_WRITE);
switch (s->cache_info.write_lock_state) {
case CACHE_WL_SUCCESS:
// We were able to get the lock for the URL vector in the cache
s->cache_info.transform_action = CACHE_DO_WRITE;
break;
case CACHE_WL_FAIL:
// No write lock, ignore the cache
s->cache_info.transform_action = CACHE_DO_NO_ACTION;
s->cache_info.transform_write_status = CACHE_WRITE_LOCK_MISS;
break;
default:
ink_release_assert(0);
}
TRANSACT_RETURN(SM_ACTION_TRANSFORM_READ, NULL);
}
void
HttpTransact::handle_transform_ready(State *s)
{
ink_assert(s->hdr_info.transform_response.valid() == true);
s->pre_transform_source = s->source;
s->source = SOURCE_TRANSFORM;
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", &s->hdr_info.transform_response, s->state_machine_id, "Header From Transform");
build_response(s, &s->hdr_info.transform_response, &s->hdr_info.client_response, s->client_info.http_version);
if (s->cache_info.action != CACHE_DO_NO_ACTION && s->cache_info.action != CACHE_DO_DELETE && s->api_info.cache_transformed &&
!s->range_setup) {
HTTPHdr *transform_store_request = 0;
switch (s->pre_transform_source) {
case SOURCE_CACHE:
// If we are transforming from the cache, treat
// the transform as if it were virtual server
// use in the incoming request
transform_store_request = &s->hdr_info.client_request;
break;
case SOURCE_HTTP_ORIGIN_SERVER:
transform_store_request = &s->hdr_info.server_request;
break;
default:
ink_release_assert(0);
}
ink_assert(transform_store_request->valid() == true);
set_headers_for_cache_write(s, &s->cache_info.transform_store, transform_store_request, &s->hdr_info.transform_response);
// For debugging
if (is_action_tag_set("http_nullt")) {
s->cache_info.transform_store.request_get()->value_set("InkXform", 8, "nullt", 5);
s->cache_info.transform_store.response_get()->value_set("InkXform", 8, "nullt", 5);
}
s->cache_info.transform_action = CACHE_PREPARE_TO_WRITE;
TRANSACT_RETURN(SM_ACTION_CACHE_ISSUE_WRITE_TRANSFORM, handle_transform_cache_write);
} else {
s->cache_info.transform_action = CACHE_DO_NO_ACTION;
TRANSACT_RETURN(SM_ACTION_TRANSFORM_READ, NULL);
}
}
void
HttpTransact::set_header_for_transform(State *s, HTTPHdr *base_header)
{
s->hdr_info.transform_response.create(HTTP_TYPE_RESPONSE);
s->hdr_info.transform_response.copy(base_header);
// Nuke the content length since 1) the transform will probably
// change it. 2) it would only be valid for the first transform
// in the chain
s->hdr_info.transform_response.field_delete(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH);
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", &s->hdr_info.transform_response, s->state_machine_id, "Header To Transform");
}
void
HttpTransact::set_headers_for_cache_write(State *s, HTTPInfo *cache_info, HTTPHdr *request, HTTPHdr *response)
{
URL *temp_url;
ink_assert(request->type_get() == HTTP_TYPE_REQUEST);
ink_assert(response->type_get() == HTTP_TYPE_RESPONSE);
if (!cache_info->valid()) {
cache_info->create();
}
/* Store the requested URI */
// Nasty hack. The set calls for
// marshalled types current do handle something being
// set to itself. Make the check here for that case.
// Why the request url is set before a copy made is
// quite beyond me. Seems like a unsafe practice so
// FIX ME!
// Logic added to restore the orignal URL for multiple cache lookup
// and automatic redirection
if (s->redirect_info.redirect_in_process) {
temp_url = &s->redirect_info.original_url;
ink_assert(temp_url->valid());
request->url_set(temp_url);
} else if ((temp_url = &(s->cache_info.original_url))->valid()) {
request->url_set(temp_url);
} else if (request != &s->hdr_info.client_request) {
request->url_set(s->hdr_info.client_request.url_get());
}
cache_info->request_set(request);
/* Why do we check the negative caching case? No one knows. This used to assert if the cache_info
response wasn't already valid, which broke negative caching when a transform is active. Why it
wasn't OK to pull in the @a response explicitly passed in isn't clear and looking at the call
sites yields no insight. So the assert is removed and we keep the behavior that if the response
in @a cache_info is already set, we don't override it.
*/
if (!s->negative_caching || !cache_info->response_get()->valid()) {
cache_info->response_set(response);
}
if (s->api_server_request_body_set) {
cache_info->request_get()->method_set(HTTP_METHOD_GET, HTTP_LEN_GET);
}
// Set-Cookie should not be put in the cache to prevent
// sending person A's cookie to person B
cache_info->response_get()->field_delete(MIME_FIELD_SET_COOKIE, MIME_LEN_SET_COOKIE);
cache_info->request_get()->field_delete(MIME_FIELD_VIA, MIME_LEN_VIA);
// server 200 Ok for Range request
cache_info->request_get()->field_delete(MIME_FIELD_RANGE, MIME_LEN_RANGE);
// If we're ignoring auth, then we don't want to cache WWW-Auth
// headers
if (s->txn_conf->cache_ignore_auth) {
cache_info->response_get()->field_delete(MIME_FIELD_WWW_AUTHENTICATE, MIME_LEN_WWW_AUTHENTICATE);
}
// if (s->cache_control.cache_auth_content && s->www_auth_content != CACHE_AUTH_NONE) {
// decided to cache authenticated content because of cache.config
// add one marker to the content in cache
// cache_info->response_get()->value_set("@WWW-Auth", 9, "true", 4);
//}
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", cache_info->request_get(), s->state_machine_id, "Cached Request Hdr");
}
void
HttpTransact::merge_response_header_with_cached_header(HTTPHdr *cached_header, HTTPHdr *response_header)
{
MIMEField *field;
MIMEField *new_field;
MIMEFieldIter fiter;
const char *name;
bool dups_seen = false;
field = response_header->iter_get_first(&fiter);
for (; field != NULL; field = response_header->iter_get_next(&fiter)) {
int name_len;
name = field->name_get(&name_len);
///////////////////////////
// is hop-by-hop header? //
///////////////////////////
if (HttpTransactHeaders::is_this_a_hop_by_hop_header(name)) {
continue;
}
/////////////////////////////////////
// dont cache content-length field //
/////////////////////////////////////
if (name == MIME_FIELD_CONTENT_LENGTH) {
continue;
}
/////////////////////////////////////
// dont cache Set-Cookie headers //
/////////////////////////////////////
if (name == MIME_FIELD_SET_COOKIE) {
continue;
}
/////////////////////////////////////////
// dont overwrite the cached content //
// type as this wreaks havoc with //
// transformed content //
/////////////////////////////////////////
if (name == MIME_FIELD_CONTENT_TYPE) {
continue;
}
/////////////////////////////////////
// dont delete warning. a separate//
// functions merges the two in a //
// complex manner //
/////////////////////////////////////
if (name == MIME_FIELD_WARNING) {
continue;
}
// Copy all remaining headers with replacement
// Duplicate header fields cause a bug problem
// since we need to duplicate with replacement.
// Without dups, we can just nuke what is already
// there in the cached header. With dups, we
// can't do this because what is already there
// may be a dup we've already copied in. If
// dups show up we look through the remaining
// header fields in the new reponse, nuke
// them in the cached response and then add in
// the remaining fields one by one from the
// response header
//
if (field->m_next_dup) {
if (dups_seen == false) {
MIMEField *dfield;
// use a second iterator to delete the
// remaining response headers in the cached response,
// so that they will be added in the next iterations.
MIMEFieldIter fiter2 = fiter;
const char *dname = name;
int dlen = name_len;
while (dname) {
cached_header->field_delete(dname, dlen);
dfield = response_header->iter_get_next(&fiter2);
if (dfield) {
dname = dfield->name_get(&dlen);
} else {
dname = NULL;
}
}
dups_seen = true;
}
}
int value_len;
const char *value = field->value_get(&value_len);
if (dups_seen == false) {
cached_header->value_set(name, name_len, value, value_len);
} else {
new_field = cached_header->field_create(name, name_len);
cached_header->field_attach(new_field);
cached_header->field_value_set(new_field, value, value_len);
}
}
merge_warning_header(cached_header, response_header);
Debug("http_hdr_space", "Merged response header with %d dead bytes", cached_header->m_heap->m_lost_string_space);
}
void
HttpTransact::merge_warning_header(HTTPHdr *cached_header, HTTPHdr *response_header)
{
// The plan:
//
// 1) The cached header has it's warning codes untouched
// since merge_response_header_with_cached_header()
// doesn't deal with warning headers.
// 2) If there are 1xx warning codes in the cached
// header, they need to be removed. Removal
// is difficult since the hdrs don't comma
// separate values, so build up a new header
// piecemal. Very slow but shouldn't happen
// very often
// 3) Since we keep the all the warning codes from
// the response header, append if to
// the cached header
//
MIMEField *c_warn = cached_header->field_find(MIME_FIELD_WARNING, MIME_LEN_WARNING);
MIMEField *r_warn = response_header->field_find(MIME_FIELD_WARNING, MIME_LEN_WARNING);
MIMEField *new_cwarn = NULL;
int move_warn_len;
const char *move_warn;
// Loop over the cached warning header and transfer all non 1xx
// warning values to a new header
if (c_warn) {
HdrCsvIter csv;
move_warn = csv.get_first(c_warn, &move_warn_len);
while (move_warn) {
int code = ink_atoi(move_warn, move_warn_len);
if (code < 100 || code > 199) {
bool first_move;
if (!new_cwarn) {
new_cwarn = cached_header->field_create();
first_move = true;
} else {
first_move = false;
}
cached_header->field_value_append(new_cwarn, move_warn, move_warn_len, !first_move);
}
move_warn = csv.get_next(&move_warn_len);
}
// At this point we can nuke the old warning headers
cached_header->field_delete(MIME_FIELD_WARNING, MIME_LEN_WARNING);
// Add in the new header if it has anything in it
if (new_cwarn) {
new_cwarn->name_set(cached_header->m_heap, cached_header->m_mime, MIME_FIELD_WARNING, MIME_LEN_WARNING);
cached_header->field_attach(new_cwarn);
}
}
// Loop over all the dups in the response warning header and append
// them one by one on to the cached warning header
while (r_warn) {
move_warn = r_warn->value_get(&move_warn_len);
if (new_cwarn) {
cached_header->field_value_append(new_cwarn, move_warn, move_warn_len, true);
} else {
new_cwarn = cached_header->field_create(MIME_FIELD_WARNING, MIME_LEN_WARNING);
cached_header->field_attach(new_cwarn);
cached_header->field_value_set(new_cwarn, move_warn, move_warn_len);
}
r_warn = r_warn->m_next_dup;
}
}
////////////////////////////////////////////////////////
// Set the keep-alive and version flags for later use //
// in request construction //
// this is also used when opening a connection to //
// the origin server, and search_keepalive_to(). //
////////////////////////////////////////////////////////
bool
HttpTransact::get_ka_info_from_config(State *s, ConnectionAttributes *server_info)
{
bool check_hostdb = false;
if (server_info->http_version > HTTPVersion(0, 9)) {
DebugTxn("http_trans", "get_ka_info_from_config, version already set server_info->http_version %d",
server_info->http_version.m_version);
return false;
}
switch (s->txn_conf->send_http11_requests) {
case HttpConfigParams::SEND_HTTP11_NEVER:
server_info->http_version = HTTPVersion(1, 0);
break;
case HttpConfigParams::SEND_HTTP11_UPGRADE_HOSTDB:
server_info->http_version = HTTPVersion(1, 0);
check_hostdb = true;
break;
case HttpConfigParams::SEND_HTTP11_IF_REQUEST_11_AND_HOSTDB:
server_info->http_version = HTTPVersion(1, 0);
if (s->hdr_info.client_request.version_get() == HTTPVersion(1, 1)) {
// check hostdb only if client req is http/1.1
check_hostdb = true;
}
break;
default:
// The default is the "1" config, SEND_HTTP11_ALWAYS, but assert in debug builds since we shouldn't be here
ink_assert(0);
// FALL THROUGH in a release build
case HttpConfigParams::SEND_HTTP11_ALWAYS:
server_info->http_version = HTTPVersion(1, 1);
break;
}
DebugTxn("http_trans", "get_ka_info_from_config, server_info->http_version %d, check_hostdb %d",
server_info->http_version.m_version, check_hostdb);
// Set keep_alive info based on the records.config setting
server_info->keep_alive = s->txn_conf->keep_alive_enabled_out ? HTTP_KEEPALIVE : HTTP_NO_KEEPALIVE;
return check_hostdb;
}
////////////////////////////////////////////////////////
// Set the keep-alive and version flags for later use //
// in request construction //
// this is also used when opening a connection to //
// the origin server, and search_keepalive_to(). //
////////////////////////////////////////////////////////
void
HttpTransact::get_ka_info_from_host_db(State *s, ConnectionAttributes *server_info,
ConnectionAttributes * /* client_info ATS_UNUSED */, HostDBInfo *host_db_info)
{
bool force_http11 = false;
bool http11_if_hostdb = false;
switch (s->txn_conf->send_http11_requests) {
case HttpConfigParams::SEND_HTTP11_NEVER:
// No need to do anything since above vars
// are defaulted false
break;
case HttpConfigParams::SEND_HTTP11_UPGRADE_HOSTDB:
http11_if_hostdb = true;
break;
case HttpConfigParams::SEND_HTTP11_IF_REQUEST_11_AND_HOSTDB:
if (s->hdr_info.client_request.version_get() == HTTPVersion(1, 1)) {
http11_if_hostdb = true;
}
break;
default:
// The default is the "1" config, SEND_HTTP11_ALWAYS, but assert in debug builds since we shouldn't be here
ink_assert(0);
// FALL THROUGH in a release build
case HttpConfigParams::SEND_HTTP11_ALWAYS:
force_http11 = true;
break;
}
if (force_http11 == true ||
(http11_if_hostdb == true && host_db_info->app.http_data.http_version == HostDBApplicationInfo::HTTP_VERSION_11)) {
server_info->http_version.set(1, 1);
server_info->keep_alive = HTTP_KEEPALIVE;
} else if (host_db_info->app.http_data.http_version == HostDBApplicationInfo::HTTP_VERSION_10) {
server_info->http_version.set(1, 0);
server_info->keep_alive = HTTP_KEEPALIVE;
} else if (host_db_info->app.http_data.http_version == HostDBApplicationInfo::HTTP_VERSION_09) {
server_info->http_version.set(0, 9);
server_info->keep_alive = HTTP_NO_KEEPALIVE;
} else {
//////////////////////////////////////////////
// not set yet for this host. set defaults. //
//////////////////////////////////////////////
server_info->http_version.set(1, 0);
server_info->keep_alive = HTTP_KEEPALIVE;
host_db_info->app.http_data.http_version = HostDBApplicationInfo::HTTP_VERSION_10;
}
/////////////////////////////
// origin server keep_alive //
/////////////////////////////
if (!s->txn_conf->keep_alive_enabled_out) {
server_info->keep_alive = HTTP_NO_KEEPALIVE;
}
return;
}
void
HttpTransact::add_client_ip_to_outgoing_request(State *s, HTTPHdr *request)
{
char ip_string[INET6_ADDRSTRLEN + 1] = {'\0'};
size_t ip_string_size = 0;
if (!ats_is_ip(&s->client_info.src_addr.sa)) {
return;
}
// Always prepare the IP string.
if (ats_ip_ntop(&s->client_info.src_addr.sa, ip_string, sizeof(ip_string)) != NULL) {
ip_string_size += strlen(ip_string);
} else {
// Failure, omg
ip_string_size = 0;
ip_string[0] = 0;
}
////////////////////////////////////////////////////////////////
// if we want client-ip headers, and there isn't one, add one //
////////////////////////////////////////////////////////////////
if ((s->txn_conf->anonymize_insert_client_ip) && (!s->txn_conf->anonymize_remove_client_ip)) {
bool client_ip_set = request->presence(MIME_PRESENCE_CLIENT_IP);
DebugTxn("http_trans", "client_ip_set = %d", client_ip_set);
if (!client_ip_set && ip_string_size > 0) {
request->value_set(MIME_FIELD_CLIENT_IP, MIME_LEN_CLIENT_IP, ip_string, ip_string_size);
DebugTxn("http_trans", "inserted request header 'Client-ip: %s'", ip_string);
}
}
if (s->txn_conf->insert_squid_x_forwarded_for) {
if (ip_string_size > 0) {
MIMEField *x_for;
if ((x_for = request->field_find(MIME_FIELD_X_FORWARDED_FOR, MIME_LEN_X_FORWARDED_FOR)) != 0) {
// http://en.wikipedia.org/wiki/X-Forwarded-For
// The X-Forwarded-For (XFF) HTTP header field is a de facto standard
// for identifying the originating IP address of a client connecting
// to a web server through an HTTP proxy or load balancer. This is a
// non-RFC-standard request field which was introduced by the Squid
// caching proxy server's developers.
// X-Forwarded-For: client1, proxy1, proxy2
request->field_value_append(x_for, ip_string, ip_string_size, true); // true => comma must be inserted
} else {
request->value_set(MIME_FIELD_X_FORWARDED_FOR, MIME_LEN_X_FORWARDED_FOR, ip_string, ip_string_size);
}
DebugTxn("http_trans", "[add_client_ip_to_outgoing_request] Appended connecting client's "
"(%s) to the X-Forwards header",
ip_string);
}
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : check_request_validity()
// Description: checks to see if incoming request has necessary fields
//
// Input : State, header (can we do this without the state?)
// Output : enum RequestError_t of the error type, if any
//
// Details :
//
//
///////////////////////////////////////////////////////////////////////////////
HttpTransact::RequestError_t
HttpTransact::check_request_validity(State *s, HTTPHdr *incoming_hdr)
{
if (incoming_hdr == 0) {
return NON_EXISTANT_REQUEST_HEADER;
}
if (!(HttpTransactHeaders::is_request_proxy_authorized(incoming_hdr))) {
return FAILED_PROXY_AUTHORIZATION;
}
URL *incoming_url = incoming_hdr->url_get();
int hostname_len;
const char *hostname = incoming_hdr->host_get(&hostname_len);
if (hostname == NULL) {
return MISSING_HOST_FIELD;
}
if (hostname_len >= MAXDNAME || hostname_len <= 0 || memchr(hostname, '\0', hostname_len)) {
return BAD_HTTP_HEADER_SYNTAX;
}
int scheme = incoming_url->scheme_get_wksidx();
int method = incoming_hdr->method_get_wksidx();
// Check for chunked encoding
if (incoming_hdr->presence(MIME_PRESENCE_TRANSFER_ENCODING)) {
MIMEField *field = incoming_hdr->field_find(MIME_FIELD_TRANSFER_ENCODING, MIME_LEN_TRANSFER_ENCODING);
HdrCsvIter enc_val_iter;
int enc_val_len;
const char *enc_value = enc_val_iter.get_first(field, &enc_val_len);
while (enc_value) {
const char *wks_value = hdrtoken_string_to_wks(enc_value, enc_val_len);
if (wks_value == HTTP_VALUE_CHUNKED) {
s->client_info.transfer_encoding = CHUNKED_ENCODING;
break;
}
enc_value = enc_val_iter.get_next(&enc_val_len);
}
}
/////////////////////////////////////////////////////
// get request content length //
// To avoid parsing content-length twice, we set //
// s->hdr_info.request_content_length here rather //
// than in initialize_state_variables_from_request //
/////////////////////////////////////////////////////
if (method != HTTP_WKSIDX_TRACE) {
int64_t length = incoming_hdr->get_content_length();
s->hdr_info.request_content_length = (length >= 0) ? length : HTTP_UNDEFINED_CL; // content length less than zero is invalid
DebugTxn("http_trans", "[init_stat_vars_from_req] set req cont length to %" PRId64, s->hdr_info.request_content_length);
} else {
s->hdr_info.request_content_length = 0;
}
if (!((scheme == URL_WKSIDX_HTTP) && (method == HTTP_WKSIDX_GET))) {
if (scheme != URL_WKSIDX_HTTP && scheme != URL_WKSIDX_HTTPS && method != HTTP_WKSIDX_CONNECT &&
!((scheme == URL_WKSIDX_WS || scheme == URL_WKSIDX_WSS) && s->is_websocket)) {
if (scheme < 0) {
return NO_REQUEST_SCHEME;
} else {
return SCHEME_NOT_SUPPORTED;
}
}
if (!HttpTransactHeaders::is_this_method_supported(scheme, method)) {
return METHOD_NOT_SUPPORTED;
}
if ((method == HTTP_WKSIDX_CONNECT) && !s->transparent_passthrough &&
(!is_port_in_range(incoming_hdr->url_get()->port_get(), s->http_config_param->connect_ports))) {
return BAD_CONNECT_PORT;
}
// Require Content-Length/Transfer-Encoding for POST/PUSH/PUT
if ((scheme == URL_WKSIDX_HTTP || scheme == URL_WKSIDX_HTTPS) &&
(method == HTTP_WKSIDX_POST || method == HTTP_WKSIDX_PUSH || method == HTTP_WKSIDX_PUT) &&
s->client_info.transfer_encoding != CHUNKED_ENCODING) {
if ((s->txn_conf->post_check_content_length_enabled) && !incoming_hdr->presence(MIME_PRESENCE_CONTENT_LENGTH)) {
return NO_POST_CONTENT_LENGTH;
}
if (HTTP_UNDEFINED_CL == s->hdr_info.request_content_length) {
return INVALID_POST_CONTENT_LENGTH;
}
}
}
// Check whether a Host header field is missing in the request.
if (!incoming_hdr->presence(MIME_PRESENCE_HOST) && incoming_hdr->version_get() != HTTPVersion(0, 9)) {
// Update the number of incoming 1.0 or 1.1 requests that do
// not contain Host header fields.
HTTP_INCREMENT_DYN_STAT(http_missing_host_hdr_stat);
}
// Did the client send a "TE: identity;q=0"? We have to respond
// with an error message because we only support identity
// Transfer Encoding.
if (incoming_hdr->presence(MIME_PRESENCE_TE)) {
MIMEField *te_field = incoming_hdr->field_find(MIME_FIELD_TE, MIME_LEN_TE);
HTTPValTE *te_val;
if (te_field) {
HdrCsvIter csv_iter;
int te_raw_len;
const char *te_raw = csv_iter.get_first(te_field, &te_raw_len);
while (te_raw) {
te_val = http_parse_te(te_raw, te_raw_len, &s->arena);
if (te_val->encoding == HTTP_VALUE_IDENTITY) {
if (te_val->qvalue <= 0.0) {
s->arena.free(te_val, sizeof(HTTPValTE));
return UNACCEPTABLE_TE_REQUIRED;
}
}
s->arena.free(te_val, sizeof(HTTPValTE));
te_raw = csv_iter.get_next(&te_raw_len);
}
}
}
return NO_REQUEST_HEADER_ERROR;
}
HttpTransact::ResponseError_t
HttpTransact::check_response_validity(State *s, HTTPHdr *incoming_hdr)
{
ink_assert(s->next_hop_scheme == URL_WKSIDX_HTTP || s->next_hop_scheme == URL_WKSIDX_HTTPS);
if (incoming_hdr == 0) {
return NON_EXISTANT_RESPONSE_HEADER;
}
if (incoming_hdr->type_get() != HTTP_TYPE_RESPONSE) {
return NOT_A_RESPONSE_HEADER;
}
// If the response is 0.9 then there is no status
// code or date
if (did_forward_server_send_0_9_response(s) == true) {
return NO_RESPONSE_HEADER_ERROR;
}
HTTPStatus incoming_status = incoming_hdr->status_get();
if (!incoming_status) {
return MISSING_STATUS_CODE;
}
if (incoming_status == HTTP_STATUS_INTERNAL_SERVER_ERROR) {
return STATUS_CODE_SERVER_ERROR;
}
if (!incoming_hdr->presence(MIME_PRESENCE_DATE)) {
incoming_hdr->set_date(s->current.now);
}
// if (! incoming_hdr->get_reason_phrase()) {
// return MISSING_REASON_PHRASE;
// }
#ifdef REALLY_NEED_TO_CHECK_DATE_VALIDITY
if (incoming_hdr->presence(MIME_PRESENCE_DATE)) {
time_t date_value = incoming_hdr->get_date();
if (date_value <= 0) {
// following lines commented out because of performance
// concerns
// if (s->http_config_param->errors_log_error_pages) {
// const char *date_string =
// incoming_hdr->value_get(MIME_FIELD_DATE);
// Log::error ("Incoming response has bogus date value: %d: %s",
// date_value, date_string ? date_string : "(null)");
// }
DebugTxn("http_trans", "[check_response_validity] Bogus date in response");
return BOGUS_OR_NO_DATE_IN_RESPONSE;
}
} else {
DebugTxn("http_trans", "[check_response_validity] No date in response");
return BOGUS_OR_NO_DATE_IN_RESPONSE;
}
#endif
return NO_RESPONSE_HEADER_ERROR;
}
bool
HttpTransact::did_forward_server_send_0_9_response(State *s)
{
if (s->hdr_info.server_response.version_get() == HTTPVersion(0, 9)) {
s->current.server->http_version.set(0, 9);
return true;
}
return false;
}
bool
HttpTransact::handle_internal_request(State * /* s ATS_UNUSED */, HTTPHdr *incoming_hdr)
{
URL *url;
ink_assert(incoming_hdr->type_get() == HTTP_TYPE_REQUEST);
if (incoming_hdr->method_get_wksidx() != HTTP_WKSIDX_GET) {
return false;
}
url = incoming_hdr->url_get();
int scheme = url->scheme_get_wksidx();
if (scheme != URL_WKSIDX_HTTP && scheme != URL_WKSIDX_HTTPS) {
return false;
}
if (!statPagesManager.is_stat_page(url)) {
return false;
}
return true;
}
bool
HttpTransact::handle_trace_and_options_requests(State *s, HTTPHdr *incoming_hdr)
{
ink_assert(incoming_hdr->type_get() == HTTP_TYPE_REQUEST);
// This only applies to TRACE and OPTIONS
if ((s->method != HTTP_WKSIDX_TRACE) && (s->method != HTTP_WKSIDX_OPTIONS)) {
return false;
}
// If there is no Max-Forwards request header, just return false.
if (!incoming_hdr->presence(MIME_PRESENCE_MAX_FORWARDS)) {
// Trace and Options requests should not be looked up in cache.
// s->cache_info.action = CACHE_DO_NO_ACTION;
s->current.mode = TUNNELLING_PROXY;
HTTP_INCREMENT_DYN_STAT(http_tunnels_stat);
return false;
}
int max_forwards = incoming_hdr->get_max_forwards();
if (max_forwards <= 0) {
//////////////////////////////////////////////
// if max-forward is 0 the request must not //
// be forwarded to the origin server. //
//////////////////////////////////////////////
DebugTxn("http_trans", "[handle_trace] max-forwards: 0, building response...");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, HTTP_STATUS_OK);
////////////////////////////////////////
// if method is trace we should write //
// the request header as the body. //
////////////////////////////////////////
if (s->method == HTTP_WKSIDX_TRACE) {
DebugTxn("http_trans", "[handle_trace] inserting request in body.");
int req_length = incoming_hdr->length_get();
HTTP_RELEASE_ASSERT(req_length > 0);
s->free_internal_msg_buffer();
s->internal_msg_buffer_size = req_length * 2;
if (s->internal_msg_buffer_size <= max_iobuffer_size) {
s->internal_msg_buffer_fast_allocator_size = buffer_size_to_index(s->internal_msg_buffer_size);
s->internal_msg_buffer = (char *)ioBufAllocator[s->internal_msg_buffer_fast_allocator_size].alloc_void();
} else {
s->internal_msg_buffer_fast_allocator_size = -1;
s->internal_msg_buffer = (char *)ats_malloc(s->internal_msg_buffer_size);
}
// clear the stupid buffer
memset(s->internal_msg_buffer, '\0', s->internal_msg_buffer_size);
int offset = 0;
int used = 0;
int done;
done = incoming_hdr->print(s->internal_msg_buffer, s->internal_msg_buffer_size, &used, &offset);
HTTP_RELEASE_ASSERT(done);
s->internal_msg_buffer_size = used;
s->hdr_info.client_response.set_content_length(used);
} else {
// For OPTIONS request insert supported methods in ALLOW field
DebugTxn("http_trans", "[handle_options] inserting methods in Allow.");
HttpTransactHeaders::insert_supported_methods_in_response(&s->hdr_info.client_response, s->scheme);
}
return true;
} else { /* max-forwards != 0 */
if ((max_forwards <= 0) || (max_forwards > INT_MAX)) {
Log::error("HTTP: snapping invalid max-forwards value %d to %d", max_forwards, INT_MAX);
max_forwards = INT_MAX;
}
--max_forwards;
DebugTxn("http_trans", "[handle_trace_options] Decrementing max_forwards to %d", max_forwards);
incoming_hdr->set_max_forwards(max_forwards);
// Trace and Options requests should not be looked up in cache.
// s->cache_info.action = CACHE_DO_NO_ACTION;
s->current.mode = TUNNELLING_PROXY;
HTTP_INCREMENT_DYN_STAT(http_tunnels_stat);
}
return false;
}
void
HttpTransact::initialize_state_variables_for_origin_server(State *s, HTTPHdr *incoming_request, bool second_time)
{
if (s->server_info.name && !second_time) {
ink_assert(s->server_info.dst_addr.port() != 0);
}
int host_len;
const char *host = incoming_request->host_get(&host_len);
s->server_info.name = s->arena.str_store(host, host_len);
if (second_time) {
s->dns_info.attempts = 0;
s->dns_info.lookup_name = s->server_info.name;
}
}
void
HttpTransact::bootstrap_state_variables_from_request(State *s, HTTPHdr *incoming_request)
{
s->current.now = s->client_request_time = ink_cluster_time();
s->client_info.http_version = incoming_request->version_get();
}
void
HttpTransact::initialize_state_variables_from_request(State *s, HTTPHdr *obsolete_incoming_request)
{
HTTPHdr *incoming_request = &s->hdr_info.client_request;
// Temporary, until we're confident that the second argument is redundant.
ink_assert(incoming_request == obsolete_incoming_request);
int host_len;
const char *host_name = incoming_request->host_get(&host_len);
// check if the request is conditional (IMS or INM)
if (incoming_request->presence(MIME_PRESENCE_IF_MODIFIED_SINCE | MIME_PRESENCE_IF_NONE_MATCH)) {
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_IMS);
} else {
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_SIMPLE);
}
// Is the user agent Keep-Alive?
// If we are transparent or if the user-agent is following
// the 1.1 spec, we will see a "Connection" header to
// indicate a keep-alive. However most user-agents including
// MSIE3.0, Netscape4.04 and Netscape3.01 send Proxy-Connection
// when they are configured to use a proxy. Proxy-Connection
// is not in the spec but was added to prevent problems
// with a dumb proxy forwarding all headers (including "Connection")
// to the origin server and confusing it. In cases of transparent
// deployments we use the Proxy-Connect hdr (to be as transparent
// as possible).
MIMEField *pc = incoming_request->field_find(MIME_FIELD_PROXY_CONNECTION, MIME_LEN_PROXY_CONNECTION);
// If we need to send a close header later check to see if it should be "Proxy-Connection"
if (pc != NULL) {
s->client_info.proxy_connect_hdr = true;
}
if (s->state_machine->ua_session) {
s->request_data.incoming_port = s->state_machine->ua_session->get_netvc()->get_local_port();
s->request_data.internal_txn = s->state_machine->ua_session->get_netvc()->get_is_internal_request();
}
NetVConnection *vc = NULL;
if (s->state_machine->ua_session) {
vc = s->state_machine->ua_session->get_netvc();
}
// If this is an internal request, never keep alive
if (!s->txn_conf->keep_alive_enabled_in || (vc && vc->get_is_internal_request()) ||
(s->state_machine->ua_session && s->state_machine->ua_session->ignore_keep_alive())) {
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
} else {
s->client_info.keep_alive = incoming_request->keep_alive_get();
}
if (s->client_info.keep_alive == HTTP_KEEPALIVE && s->client_info.http_version == HTTPVersion(1, 1)) {
s->client_info.pipeline_possible = true;
}
if (!s->server_info.name || s->redirect_info.redirect_in_process) {
s->server_info.name = s->arena.str_store(host_name, host_len);
}
s->next_hop_scheme = s->scheme = incoming_request->url_get()->scheme_get_wksidx();
// With websockets we need to make an outgoing request
// as http or https.
// We switch back to HTTP or HTTPS for the next hop
// I think this is required to properly establish outbound WSS connections,
// you'll need to force the next hop to be https.
if (s->is_websocket) {
if (s->next_hop_scheme == URL_WKSIDX_WS) {
DebugTxn("http_trans", "Switching WS next hop scheme to http.");
s->next_hop_scheme = URL_WKSIDX_HTTP;
s->scheme = URL_WKSIDX_HTTP;
// s->request_data.hdr->url_get()->scheme_set(URL_SCHEME_HTTP, URL_LEN_HTTP);
} else if (s->next_hop_scheme == URL_WKSIDX_WSS) {
DebugTxn("http_trans", "Switching WSS next hop scheme to https.");
s->next_hop_scheme = URL_WKSIDX_HTTPS;
s->scheme = URL_WKSIDX_HTTPS;
// s->request_data.hdr->url_get()->scheme_set(URL_SCHEME_HTTPS, URL_LEN_HTTPS);
} else {
Error("Scheme doesn't match websocket...!");
}
s->current.mode = GENERIC_PROXY;
s->cache_info.action = CACHE_DO_NO_ACTION;
}
s->method = incoming_request->method_get_wksidx();
if (s->method == HTTP_WKSIDX_GET) {
HTTP_INCREMENT_DYN_STAT(http_get_requests_stat);
} else if (s->method == HTTP_WKSIDX_HEAD) {
HTTP_INCREMENT_DYN_STAT(http_head_requests_stat);
} else if (s->method == HTTP_WKSIDX_POST) {
HTTP_INCREMENT_DYN_STAT(http_post_requests_stat);
} else if (s->method == HTTP_WKSIDX_PUT) {
HTTP_INCREMENT_DYN_STAT(http_put_requests_stat);
} else if (s->method == HTTP_WKSIDX_CONNECT) {
HTTP_INCREMENT_DYN_STAT(http_connect_requests_stat);
} else if (s->method == HTTP_WKSIDX_DELETE) {
HTTP_INCREMENT_DYN_STAT(http_delete_requests_stat);
} else if (s->method == HTTP_WKSIDX_PURGE) {
HTTP_INCREMENT_DYN_STAT(http_purge_requests_stat);
} else if (s->method == HTTP_WKSIDX_TRACE) {
HTTP_INCREMENT_DYN_STAT(http_trace_requests_stat);
} else if (s->method == HTTP_WKSIDX_PUSH) {
HTTP_INCREMENT_DYN_STAT(http_push_requests_stat);
} else if (s->method == HTTP_WKSIDX_OPTIONS) {
HTTP_INCREMENT_DYN_STAT(http_options_requests_stat);
} else if (s->method == HTTP_WKSIDX_TRACE) {
HTTP_INCREMENT_DYN_STAT(http_trace_requests_stat);
} else {
HTTP_INCREMENT_DYN_STAT(http_extension_method_requests_stat);
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_METHOD);
s->squid_codes.log_code = SQUID_LOG_TCP_MISS;
s->hdr_info.extension_method = true;
}
// if transfer encoding is chunked content length is undefined
if (s->client_info.transfer_encoding == CHUNKED_ENCODING) {
s->hdr_info.request_content_length = HTTP_UNDEFINED_CL;
}
s->request_data.hdr = &s->hdr_info.client_request;
s->request_data.hostname_str = s->arena.str_store(host_name, host_len);
ats_ip_copy(&s->request_data.src_ip, &s->client_info.src_addr);
memset(&s->request_data.dest_ip, 0, sizeof(s->request_data.dest_ip));
if (s->state_machine->ua_session) {
NetVConnection *netvc = s->state_machine->ua_session->get_netvc();
if (netvc) {
s->request_data.incoming_port = netvc->get_local_port();
}
}
s->request_data.xact_start = s->client_request_time;
s->request_data.api_info = &s->api_info;
/////////////////////////////////////////////
// Do dns lookup for the host. We need //
// the expanded host for cache lookup, and //
// the host ip for reverse proxy. //
/////////////////////////////////////////////
s->dns_info.looking_up = ORIGIN_SERVER;
s->dns_info.attempts = 0;
s->dns_info.lookup_name = s->server_info.name;
}
void
HttpTransact::initialize_state_variables_from_response(State *s, HTTPHdr *incoming_response)
{
/* check if the server permits caching */
s->cache_info.directives.does_server_permit_storing =
HttpTransactHeaders::does_server_allow_response_to_be_stored(&s->hdr_info.server_response);
/*
* A stupid moronic broken pathetic excuse
* for a server may send us a keep alive response even
* if we sent "Connection: close" We need check the response
* header regardless of what we sent to the server
*/
s->current.server->keep_alive = s->hdr_info.server_response.keep_alive_get();
// Don't allow an upgrade request to Keep Alive
if (s->is_upgrade_request) {
s->current.server->keep_alive = HTTP_NO_KEEPALIVE;
}
if (s->current.server->keep_alive == HTTP_KEEPALIVE) {
if (!s->cop_test_page) {
DebugTxn("http_hdrs", "[initialize_state_variables_from_response]"
"Server is keep-alive.");
}
} else if (s->state_machine->ua_session && s->state_machine->ua_session->is_outbound_transparent() &&
s->state_machine->t_state.http_config_param->use_client_source_port) {
/* If we are reusing the client<->ATS 4-tuple for ATS<->server then if the server side is closed, we can't
re-open it because the 4-tuple may still be in the processing of shutting down. So if the server isn't
keep alive we must turn that off for the client as well.
*/
s->state_machine->t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE;
}
HTTPStatus status_code = incoming_response->status_get();
if (is_response_body_precluded(status_code, s->method)) {
s->hdr_info.response_content_length = 0;
s->hdr_info.trust_response_cl = true;
} else {
// This code used to discriminate CL: headers when the origin disabled keep-alive.
if (incoming_response->presence(MIME_PRESENCE_CONTENT_LENGTH)) {
int64_t cl = incoming_response->get_content_length();
s->hdr_info.response_content_length = (cl >= 0) ? cl : HTTP_UNDEFINED_CL;
s->hdr_info.trust_response_cl = true;
} else {
s->hdr_info.response_content_length = HTTP_UNDEFINED_CL;
s->hdr_info.trust_response_cl = false;
}
}
if (incoming_response->presence(MIME_PRESENCE_TRANSFER_ENCODING)) {
MIMEField *field = incoming_response->field_find(MIME_FIELD_TRANSFER_ENCODING, MIME_LEN_TRANSFER_ENCODING);
ink_assert(field != NULL);
HdrCsvIter enc_val_iter;
int enc_val_len;
const char *enc_value = enc_val_iter.get_first(field, &enc_val_len);
while (enc_value) {
const char *wks_value = hdrtoken_string_to_wks(enc_value, enc_val_len);
if (wks_value == HTTP_VALUE_CHUNKED) {
if (!s->cop_test_page) {
DebugTxn("http_hdrs", "[init_state_vars_from_resp] transfer encoding: chunked!");
}
s->current.server->transfer_encoding = CHUNKED_ENCODING;
s->hdr_info.response_content_length = HTTP_UNDEFINED_CL;
s->hdr_info.trust_response_cl = false;
// OBJECTIVE: Since we are dechunking the request remove the
// chunked value If this is the only value, we need to remove
// the whole field.
MIMEField *new_enc_field = NULL;
HdrCsvIter new_enc_iter;
int new_enc_len;
const char *new_enc_val = new_enc_iter.get_first(field, &new_enc_len);
// Loop over the all the values in existing Trans-enc header and
// copy the ones that aren't our chunked value to a new field
while (new_enc_val) {
const char *new_wks_value = hdrtoken_string_to_wks(new_enc_val, new_enc_len);
if (new_wks_value != wks_value) {
if (new_enc_field) {
new_enc_field->value_append(incoming_response->m_heap, incoming_response->m_mime, new_enc_val, new_enc_len, true);
} else {
new_enc_field = incoming_response->field_create();
incoming_response->field_value_set(new_enc_field, new_enc_val, new_enc_len);
}
}
new_enc_val = new_enc_iter.get_next(&new_enc_len);
}
// We're done with the old field since we copied out everything
// we needed
incoming_response->field_delete(field);
// If there is a new field (ie: there was more than one
// transfer-encoding), insert it to the list
if (new_enc_field) {
new_enc_field->name_set(incoming_response->m_heap, incoming_response->m_mime, MIME_FIELD_TRANSFER_ENCODING,
MIME_LEN_TRANSFER_ENCODING);
incoming_response->field_attach(new_enc_field);
}
return;
} // if (enc_value == CHUNKED)
enc_value = enc_val_iter.get_next(&enc_val_len);
}
}
s->current.server->transfer_encoding = NO_TRANSFER_ENCODING;
}
bool
HttpTransact::is_cache_response_returnable(State *s)
{
if (s->cache_control.never_cache) {
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_CONFIG);
return false;
}
if (!s->cache_info.directives.does_client_permit_lookup) {
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_CLIENT);
return false;
}
if (!HttpTransactHeaders::is_method_cacheable(s->http_config_param, s->method) && s->api_resp_cacheable == false) {
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_CACHE_NOT_ACCEPTABLE);
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_METHOD);
return false;
}
// If cookies in response and no TTL set, we do not cache the doc
if ((s->cache_control.ttl_in_cache <= 0) &&
do_cookies_prevent_caching((int)s->txn_conf->cache_responses_to_cookies, &s->hdr_info.client_request,
s->cache_info.object_read->response_get(), s->cache_info.object_read->request_get())) {
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_CACHE_NOT_ACCEPTABLE);
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_COOKIE);
return false;
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
// Name : is_stale_cache_response_returnable()
// Description: check if a stale cached response is returnable to a client
//
// Input : State
// Output : true or false
//
// Details :
//
///////////////////////////////////////////////////////////////////////////////
bool
HttpTransact::is_stale_cache_response_returnable(State *s)
{
HTTPHdr *cached_response = s->cache_info.object_read->response_get();
// First check if client allows cached response
// Note does_client_permit_lookup was set to
// does_client_Request_permit_cached_response()
// in update_cache_control_information_from_config().
if (!s->cache_info.directives.does_client_permit_lookup) {
return false;
}
// Spec says that we can not serve a stale document with a
// "must-revalidate header"
// How about "s-maxage" and "no-cache" directives?
uint32_t cc_mask;
cc_mask = (MIME_COOKED_MASK_CC_MUST_REVALIDATE | MIME_COOKED_MASK_CC_PROXY_REVALIDATE | MIME_COOKED_MASK_CC_NEED_REVALIDATE_ONCE |
MIME_COOKED_MASK_CC_NO_CACHE | MIME_COOKED_MASK_CC_NO_STORE | MIME_COOKED_MASK_CC_S_MAXAGE);
if ((cached_response->get_cooked_cc_mask() & cc_mask) || cached_response->is_pragma_no_cache_set()) {
DebugTxn("http_trans", "[is_stale_cache_response_returnable] "
"document headers prevent serving stale");
return false;
}
// See how old the document really is. We don't want create a
// stale content museum of documents that are no longer available
time_t current_age = HttpTransactHeaders::calculate_document_age(s->cache_info.object_read->request_sent_time_get(),
s->cache_info.object_read->response_received_time_get(),
cached_response, cached_response->get_date(), s->current.now);
// Negative age is overflow
if ((current_age < 0) || (current_age > s->txn_conf->cache_max_stale_age)) {
DebugTxn("http_trans", "[is_stale_cache_response_returnable] "
"document age is too large %" PRId64,
(int64_t)current_age);
return false;
}
// If the stale document requires authorization, we can't return it either.
Authentication_t auth_needed = AuthenticationNeeded(s->txn_conf, &s->hdr_info.client_request, cached_response);
if (auth_needed != AUTHENTICATION_SUCCESS) {
DebugTxn("http_trans", "[is_stale_cache_response_returnable] "
"authorization prevent serving stale");
return false;
}
DebugTxn("http_trans", "[is_stale_cache_response_returnable] can serve stale");
return true;
}
bool
HttpTransact::url_looks_dynamic(URL *url)
{
const char *p_start, *p, *t;
static const char *asp = ".asp";
const char *part;
int part_length;
if (url->scheme_get_wksidx() != URL_WKSIDX_HTTP && url->scheme_get_wksidx() != URL_WKSIDX_HTTPS) {
return false;
}
////////////////////////////////////////////////////////////
// (1) If URL contains query stuff in it, call it dynamic //
////////////////////////////////////////////////////////////
part = url->params_get(&part_length);
if (part != NULL) {
return true;
}
part = url->query_get(&part_length);
if (part != NULL) {
return true;
}
///////////////////////////////////////////////
// (2) If path ends in "asp" call it dynamic //
///////////////////////////////////////////////
part = url->path_get(&part_length);
if (part) {
p = &part[part_length - 1];
t = &asp[3];
while (p != part) {
if (ParseRules::ink_tolower(*p) == ParseRules::ink_tolower(*t)) {
p -= 1;
t -= 1;
if (t == asp) {
return true;
}
} else {
break;
}
}
}
/////////////////////////////////////////////////////////////////
// (3) If the path of the url contains "cgi", call it dynamic. //
/////////////////////////////////////////////////////////////////
if (part && part_length >= 3) {
for (p_start = part; p_start <= &part[part_length - 3]; p_start++) {
if (((p_start[0] == 'c') || (p_start[0] == 'C')) && ((p_start[1] == 'g') || (p_start[1] == 'G')) &&
((p_start[2] == 'i') || (p_start[2] == 'I'))) {
return (true);
}
}
}
return (false);
}
///////////////////////////////////////////////////////////////////////////////
// Name : is_request_cache_lookupable()
// Description: check if a request should be looked up in cache
//
// Input : State, request header
// Output : true or false
//
// Details :
//
//
///////////////////////////////////////////////////////////////////////////////
bool
HttpTransact::is_request_cache_lookupable(State *s)
{
// ummm, someone has already decided that proxy should tunnel
if (s->current.mode == TUNNELLING_PROXY) {
return false;
}
// don't bother with remaining checks if we already did a cache lookup
if (s->cache_info.lookup_count > 0) {
return true;
}
// is cache turned on?
if (!s->txn_conf->cache_http) {
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_CACHE_OFF);
return false;
}
// GET, HEAD, POST, DELETE, and PUT are all cache lookupable
if (!HttpTransactHeaders::is_method_cache_lookupable(s->method) && s->api_req_cacheable == false) {
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_METHOD);
return false;
}
// don't cache page if URL "looks dynamic" and this filter is enabled
// We can do the check in is_response_cacheable() or here.
// It may be more efficient if we are not going to cache dynamic looking urls
// (the default config?) since we don't even need to do cache lookup.
// So for the time being, it'll be left here.
// If url looks dynamic but a ttl is set, request is cache lookupable
if ((!s->txn_conf->cache_urls_that_look_dynamic) && url_looks_dynamic(s->hdr_info.client_request.url_get()) &&
(s->cache_control.ttl_in_cache <= 0)) {
// We do not want to forward the request for a dynamic URL onto the
// origin server if the value of the Max-Forwards header is zero.
int max_forwards = -1;
if (s->hdr_info.client_request.presence(MIME_PRESENCE_MAX_FORWARDS)) {
MIMEField *max_forwards_f = s->hdr_info.client_request.field_find(MIME_FIELD_MAX_FORWARDS, MIME_LEN_MAX_FORWARDS);
if (max_forwards_f) {
max_forwards = max_forwards_f->value_get_int();
}
}
if (max_forwards != 0) {
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_URL);
return false;
}
}
// Don't look in cache if it's a RANGE request but the cache is not enabled for RANGE.
if (!s->txn_conf->cache_range_lookup && s->hdr_info.client_request.presence(MIME_PRESENCE_RANGE)) {
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_HEADER_FIELD);
return false;
}
// Even with "no-cache" directive, we want to do a cache lookup
// because we need to update our cached copy.
// Client request "no-cache" directive is handle elsewhere:
// update_cache_control_information_from_config()
return true;
}
///////////////////////////////////////////////////////////////////////////////
// Name : response_cacheable_indicated_by_cc()
// Description: check if a response is cacheable as indicated by Cache-Control
//
// Input : Response header
// Output : -1, 0, or +1
//
// Details :
// (1) return -1 if cache control indicates response not cacheable,
// ie, with no-store, or private directives;
// (2) return +1 if cache control indicates response cacheable
// ie, with public, max-age, s-maxage, must-revalidate, or proxy-revalidate;
// (3) otherwise, return 0 if cache control does not indicate.
//
///////////////////////////////////////////////////////////////////////////////
int
response_cacheable_indicated_by_cc(HTTPHdr *response)
{
uint32_t cc_mask;
// the following directives imply not cacheable
cc_mask = (MIME_COOKED_MASK_CC_NO_STORE | MIME_COOKED_MASK_CC_PRIVATE);
if (response->get_cooked_cc_mask() & cc_mask) {
return -1;
}
// the following directives imply cacheable
cc_mask = (MIME_COOKED_MASK_CC_PUBLIC | MIME_COOKED_MASK_CC_MAX_AGE | MIME_COOKED_MASK_CC_S_MAXAGE |
MIME_COOKED_MASK_CC_MUST_REVALIDATE | MIME_COOKED_MASK_CC_PROXY_REVALIDATE);
if (response->get_cooked_cc_mask() & cc_mask) {
return 1;
}
// otherwise, no indication
return 0;
}
///////////////////////////////////////////////////////////////////////////////
// Name : is_response_cacheable()
// Description: check if a response is cacheable
//
// Input : State, request header, response header
// Output : true or false
//
// Details :
//
///////////////////////////////////////////////////////////////////////////////
bool
HttpTransact::is_response_cacheable(State *s, HTTPHdr *request, HTTPHdr *response)
{
// If the use_client_target_addr is specified but the client
// specified OS addr does not match any of trafficserver's looked up
// host addresses, do not allow cache. This may cause DNS cache poisoning
// of other trafficserver clients. The flag is set in the
// process_host_db_info method
if (!s->dns_info.lookup_validated && s->client_info.is_transparent) {
DebugTxn("http_trans", "[is_response_cacheable] "
"Lookup not validated. Possible DNS cache poison. Don't cache");
return false;
}
// the plugin may decide we don't want to cache the response
if (s->api_server_response_no_store) {
return false;
}
// if method is not GET or HEAD, do not cache.
// Note: POST is also cacheable with Expires or Cache-control.
// but due to INKqa11567, we are not caching POST responses.
// Basically, the problem is the resp for POST url1 req should not
// be served to a GET url1 request, but we just match URL not method.
int req_method = request->method_get_wksidx();
if (!(HttpTransactHeaders::is_method_cacheable(s->http_config_param, req_method)) && s->api_req_cacheable == false) {
DebugTxn("http_trans", "[is_response_cacheable] "
"only GET, and some HEAD and POST are cachable");
return false;
}
// DebugTxn("http_trans", "[is_response_cacheable] method is cacheable");
// If the request was not looked up in the cache, the response
// should not be cached (same subsequent requests will not be
// looked up, either, so why cache this).
if (!(is_request_cache_lookupable(s))) {
DebugTxn("http_trans", "[is_response_cacheable] "
"request is not cache lookupable, response is not cachable");
return false;
}
// already has a fresh copy in the cache
if (s->range_setup == RANGE_NOT_HANDLED) {
return false;
}
// Check whether the response is cachable based on its cookie
// If there are cookies in response but a ttl is set, allow caching
if ((s->cache_control.ttl_in_cache <= 0) &&
do_cookies_prevent_caching((int)s->txn_conf->cache_responses_to_cookies, request, response)) {
DebugTxn("http_trans", "[is_response_cacheable] "
"response has uncachable cookies, response is not cachable");
return false;
}
// if server spits back a WWW-Authenticate
if ((s->txn_conf->cache_ignore_auth) == 0 && response->presence(MIME_PRESENCE_WWW_AUTHENTICATE)) {
DebugTxn("http_trans", "[is_response_cacheable] "
"response has WWW-Authenticate, response is not cachable");
return false;
}
// does server explicitly forbid storing?
// If OS forbids storing but a ttl is set, allow caching
if (!s->cache_info.directives.does_server_permit_storing && !s->cache_control.ignore_server_no_cache &&
(s->cache_control.ttl_in_cache <= 0)) {
DebugTxn("http_trans", "[is_response_cacheable] server does not permit storing and config file does not "
"indicate that server directive should be ignored");
return false;
}
// DebugTxn("http_trans", "[is_response_cacheable] server permits storing");
// does config explicitly forbid storing?
// ttl overides other config parameters
if ((!s->cache_info.directives.does_config_permit_storing && !s->cache_control.ignore_server_no_cache &&
(s->cache_control.ttl_in_cache <= 0)) ||
(s->cache_control.never_cache)) {
DebugTxn("http_trans", "[is_response_cacheable] config doesn't allow storing, and cache control does not "
"say to ignore no-cache and does not specify never-cache or a ttl");
return false;
}
// DebugTxn("http_trans", "[is_response_cacheable] config permits storing");
// does client explicitly forbid storing?
if (!s->cache_info.directives.does_client_permit_storing && !s->cache_control.ignore_client_no_cache) {
DebugTxn("http_trans", "[is_response_cacheable] client does not permit storing, "
"and cache control does not say to ignore client no-cache");
return false;
}
DebugTxn("http_trans", "[is_response_cacheable] client permits storing");
HTTPStatus response_code = response->status_get();
// caching/not-caching based on required headers
// only makes sense when the server sends back a
// 200 and a document.
if (response_code == HTTP_STATUS_OK) {
// If a ttl is set: no header required for caching
// otherwise: follow parameter http.cache.required_headers
if (s->cache_control.ttl_in_cache <= 0) {
uint32_t cc_mask = (MIME_COOKED_MASK_CC_MAX_AGE | MIME_COOKED_MASK_CC_S_MAXAGE);
// server did not send expires header or last modified
// and we are configured to not cache without them.
switch (s->txn_conf->cache_required_headers) {
case HttpConfigParams::CACHE_REQUIRED_HEADERS_NONE:
DebugTxn("http_trans", "[is_response_cacheable] "
"no response headers required");
break;
case HttpConfigParams::CACHE_REQUIRED_HEADERS_AT_LEAST_LAST_MODIFIED:
if (!response->presence(MIME_PRESENCE_EXPIRES) && !(response->get_cooked_cc_mask() & cc_mask) &&
!response->get_last_modified()) {
DebugTxn("http_trans", "[is_response_cacheable] "
"last_modified, expires, or max-age is required");
s->squid_codes.hit_miss_code = ((response->get_date() == 0) ? (SQUID_MISS_HTTP_NO_DLE) : (SQUID_MISS_HTTP_NO_LE));
return false;
}
break;
case HttpConfigParams::CACHE_REQUIRED_HEADERS_CACHE_CONTROL:
if (!response->presence(MIME_PRESENCE_EXPIRES) && !(response->get_cooked_cc_mask() & cc_mask)) {
DebugTxn("http_trans", "[is_response_cacheable] "
"expires header or max-age is required");
return false;
}
break;
default:
break;
}
}
}
// do not cache partial content - Range response
if (response_code == HTTP_STATUS_PARTIAL_CONTENT || response_code == HTTP_STATUS_RANGE_NOT_SATISFIABLE) {
DebugTxn("http_trans", "[is_response_cacheable] "
"response code %d - don't cache",
response_code);
return false;
}
// check if cache control overrides default cacheability
int indicator;
indicator = response_cacheable_indicated_by_cc(response);
if (indicator > 0) { // cacheable indicated by cache control header
DebugTxn("http_trans", "[is_response_cacheable] YES by response cache control");
// even if it is authenticated, this is cacheable based on regular rules
s->www_auth_content = CACHE_AUTH_NONE;
return true;
} else if (indicator < 0) { // not cacheable indicated by cache control header
// If a ttl is set, allow caching even if response contains
// Cache-Control headers to prevent caching
if (s->cache_control.ttl_in_cache > 0) {
DebugTxn("http_trans",
"[is_response_cacheable] Cache-control header directives in response overridden by ttl in cache.config");
} else if (!s->cache_control.ignore_server_no_cache) {
DebugTxn("http_trans", "[is_response_cacheable] NO by response cache control");
return false;
}
}
// else no indication by cache control header
// continue to determine cacheability
// if client contains Authorization header,
// only cache if response has proper Cache-Control
// if (s->www_auth_content == CACHE_AUTH_FRESH) {
// response to the HEAD request
// return false;
//} else if (s->www_auth_content == CACHE_AUTH_TRUE ||
// (s->www_auth_content == CACHE_AUTH_NONE && request->presence(MIME_PRESENCE_AUTHORIZATION))) {
// if (!s->cache_control.cache_auth_content || response_code != HTTP_STATUS_OK || req_method != HTTP_WKSIDX_GET)
// return false;
//}
// s->www_auth_content == CACHE_AUTH_STALE silently continues
if (response->presence(MIME_PRESENCE_EXPIRES)) {
DebugTxn("http_trans", "[is_response_cacheable] YES response w/ Expires");
return true;
}
// if it's a 302 or 307 and no positive indicator from cache-control, reject
if (response_code == HTTP_STATUS_MOVED_TEMPORARILY || response_code == HTTP_STATUS_TEMPORARY_REDIRECT) {
DebugTxn("http_trans", "[is_response_cacheable] cache-control or expires header is required for 302");
return false;
}
// if it's a POST request and no positive indicator from cache-control
if (req_method == HTTP_WKSIDX_POST) {
// allow caching for a POST requests w/o Expires but with a ttl
if (s->cache_control.ttl_in_cache > 0) {
DebugTxn("http_trans", "[is_response_cacheable] POST method with a TTL");
} else {
DebugTxn("http_trans", "[is_response_cacheable] NO POST w/o Expires or CC");
return false;
}
}
// default cacheability
if (!s->txn_conf->negative_caching_enabled) {
if ((response_code == HTTP_STATUS_OK) || (response_code == HTTP_STATUS_NOT_MODIFIED) ||
(response_code == HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION) || (response_code == HTTP_STATUS_MOVED_PERMANENTLY) ||
(response_code == HTTP_STATUS_MULTIPLE_CHOICES) || (response_code == HTTP_STATUS_GONE)) {
DebugTxn("http_trans", "[is_response_cacheable] YES by default ");
return true;
} else {
DebugTxn("http_trans", "[is_response_cacheable] NO by default");
return false;
}
}
if (response_code == HTTP_STATUS_SEE_OTHER || response_code == HTTP_STATUS_UNAUTHORIZED ||
response_code == HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
return false;
}
// let is_negative_caching_approriate decide what to do
return true;
/* Since we weren't caching response obtained with
Authorization (the cache control stuff was commented out previously)
I've moved this check to is_request_cache_lookupable().
We should consider this matter further. It is unclear
how many sites actually add Cache-Control headers for Authorized content.
// if client contains Authorization header, only cache if response
// has proper Cache-Control flags, as in RFC2068, section 14.8.
if (request->field_presence(MIME_PRESENCE_AUTHORIZATION)) {
// if (! (response->is_cache_control_set(HTTP_VALUE_MUST_REVALIDATE)) &&
// ! (response->is_cache_control_set(HTTP_VALUE_PROXY_REVALIDATE)) &&
// ! (response->is_cache_control_set(HTTP_VALUE_PUBLIC))) {
DebugTxn("http_trans", "[is_response_cacheable] request has AUTHORIZATION - not cacheable");
return(false);
// }
// else {
// DebugTxn("http_trans","[is_response_cacheable] request has AUTHORIZATION, "
// "but response has a cache-control that allows caching");
// }
}
*/
}
bool
HttpTransact::is_request_valid(State *s, HTTPHdr *incoming_request)
{
RequestError_t incoming_error;
URL *url = NULL;
if (incoming_request) {
url = incoming_request->url_get();
}
incoming_error = check_request_validity(s, incoming_request);
switch (incoming_error) {
case NO_REQUEST_HEADER_ERROR:
DebugTxn("http_trans", "[is_request_valid] no request header errors");
break;
case FAILED_PROXY_AUTHORIZATION:
DebugTxn("http_trans", "[is_request_valid] failed proxy authorization");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED, "Proxy Authentication Required",
"access#proxy_auth_required", NULL);
return false;
case NON_EXISTANT_REQUEST_HEADER:
/* fall through */
case BAD_HTTP_HEADER_SYNTAX: {
DebugTxn("http_trans", "[is_request_valid] non-existant/bad header");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Invalid HTTP Request", "request#syntax_error", NULL);
return false;
}
case MISSING_HOST_FIELD:
////////////////////////////////////////////////////////////////////
// FIX: are we sure the following logic is right? it seems that //
// we shouldn't complain about the missing host header until //
// we know we really need one --- are we sure we need a host //
// header at this point? //
// //
// FIX: also, let's clean up the transparency code to remove the //
// SunOS conditionals --- we will be transparent on all //
// platforms soon! in fact, I really want a method that i //
// can call for each transaction to say if the transaction //
// is a forward proxy request, a transparent request, a //
// reverse proxy request, etc --- the detail of how we //
// determine the cases should be hidden behind the method. //
////////////////////////////////////////////////////////////////////
DebugTxn("http_trans", "[is_request_valid] missing host field");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
if (s->http_config_param->reverse_proxy_enabled) { // host header missing and reverse proxy on
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Host Header Required", "request#no_host", NULL);
} else {
// host header missing and reverse proxy off
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Host Required In Request", "request#no_host", NULL);
}
return false;
case SCHEME_NOT_SUPPORTED:
case NO_REQUEST_SCHEME: {
DebugTxn("http_trans", "[is_request_valid] unsupported or missing request scheme");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Unsupported URL Scheme", "request#scheme_unsupported", NULL);
return false;
}
/* fall through */
case METHOD_NOT_SUPPORTED:
DebugTxn("http_trans", "[is_request_valid] unsupported method");
s->current.mode = TUNNELLING_PROXY;
return true;
case BAD_CONNECT_PORT:
int port;
port = url ? url->port_get() : 0;
DebugTxn("http_trans", "[is_request_valid] %d is an invalid connect port", port);
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_FORBIDDEN, "Tunnel Forbidden", "access#connect_forbidden", NULL);
return false;
case NO_POST_CONTENT_LENGTH: {
DebugTxn("http_trans", "[is_request_valid] post request without content length");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_LENGTH_REQUIRED, "Content Length Required", "request#no_content_length", NULL);
return false;
}
case UNACCEPTABLE_TE_REQUIRED: {
DebugTxn("http_trans", "[is_request_valid] TE required is unacceptable.");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_NOT_ACCEPTABLE, "Transcoding Not Available", "transcoding#unsupported", NULL);
return false;
}
case INVALID_POST_CONTENT_LENGTH: {
DebugTxn("http_trans", "[is_request_valid] post request with negative content length value");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Invalid Content Length", "request#invalid_content_length", NULL);
return false;
}
default:
return true;
}
return true;
}
// bool HttpTransact::is_request_retryable
//
// In the general case once bytes have been sent on the wire the request cannot be retried.
// The reason we cannot retry is that the rfc2616 does not make any gaurantees about the
// retry-ability of a request. In fact in the reverse proxy case it is quite common for GET
// requests on the origin to fire tracking events etc. So, as a proxy once we have sent bytes
// on the wire to the server we cannot gaurantee that the request is safe to redispatch to another server.
//
bool
HttpTransact::is_request_retryable(State *s)
{
// If there was no error establishing the connection (and we sent bytes)-- we cannot retry
if (s->current.state != CONNECTION_ERROR && s->state_machine->server_request_hdr_bytes > 0) {
return false;
}
if (s->state_machine->plugin_tunnel_type != HTTP_NO_PLUGIN_TUNNEL) {
// API can override
if (s->state_machine->plugin_tunnel_type == HTTP_PLUGIN_AS_SERVER && s->api_info.retry_intercept_failures == true) {
// This used to be an == comparison, which made no sense. Changed
// to be an assignment, hoping the state is correct.
s->state_machine->plugin_tunnel_type = HTTP_NO_PLUGIN_TUNNEL;
} else {
return false;
}
}
return true;
}
bool
HttpTransact::is_response_valid(State *s, HTTPHdr *incoming_response)
{
if (s->current.state != CONNECTION_ALIVE) {
ink_assert((s->current.state == CONNECTION_ERROR) || (s->current.state == OPEN_RAW_ERROR) ||
(s->current.state == PARSE_ERROR) || (s->current.state == CONNECTION_CLOSED) ||
(s->current.state == INACTIVE_TIMEOUT) || (s->current.state == ACTIVE_TIMEOUT) ||
(s->current.state == CONGEST_CONTROL_CONGESTED_ON_M) || (s->current.state == CONGEST_CONTROL_CONGESTED_ON_F));
s->hdr_info.response_error = CONNECTION_OPEN_FAILED;
return false;
}
s->hdr_info.response_error = check_response_validity(s, incoming_response);
switch (s->hdr_info.response_error) {
#ifdef REALLY_NEED_TO_CHECK_DATE_VALIDITY
case BOGUS_OR_NO_DATE_IN_RESPONSE:
// We could modify the response to add the date, if need be.
// incoming_response->set_date(s->request_sent_time);
return true;
#endif
case NO_RESPONSE_HEADER_ERROR:
DebugTxn("http_trans", "[is_response_valid] No errors in response");
return true;
case MISSING_REASON_PHRASE:
DebugTxn("http_trans", "[is_response_valid] Response Error: Missing reason phrase - allowing");
return true;
case STATUS_CODE_SERVER_ERROR:
DebugTxn("http_trans", "[is_response_valid] Response Error: Origin Server returned 500 - allowing");
return true;
case CONNECTION_OPEN_FAILED:
DebugTxn("http_trans", "[is_response_valid] Response Error: connection open failed");
s->current.state = CONNECTION_ERROR;
return false;
case NON_EXISTANT_RESPONSE_HEADER:
DebugTxn("http_trans", "[is_response_valid] Response Error: No response header");
s->current.state = BAD_INCOMING_RESPONSE;
return false;
case NOT_A_RESPONSE_HEADER:
DebugTxn("http_trans", "[is_response_valid] Response Error: Not a response header");
s->current.state = BAD_INCOMING_RESPONSE;
return false;
case MISSING_STATUS_CODE:
DebugTxn("http_trans", "[is_response_valid] Response Error: Missing status code");
s->current.state = BAD_INCOMING_RESPONSE;
return false;
default:
DebugTxn("http_trans", "[is_response_valid] Errors in response");
s->current.state = BAD_INCOMING_RESPONSE;
return false;
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : service_transaction_in_proxy_only_mode
// Description: uses some metric to force this transaction to be proxy-only
//
// Details :
//
// Some metric may be employed to force the traffic server to enter
// a proxy-only mode temporarily. This function is called to determine
// if the current transaction should be proxy-only. The function is
// called from initialize_state_variables_from_request and is used to
// set s->current.mode to TUNNELLING_PROXY and just for safety to set
// s->cache_info.action to CACHE_DO_NO_ACTION.
//
// Currently the function is just a placeholder and always returns false.
//
///////////////////////////////////////////////////////////////////////////////
bool
HttpTransact::service_transaction_in_proxy_only_mode(State * /* s ATS_UNUSED */)
{
return false;
}
void
HttpTransact::process_quick_http_filter(State *s, int method)
{
// connection already disabled by previous ACL filtering, don't modify it.
if (!s->client_connection_enabled) {
return;
}
if (s->state_machine->ua_session) {
const AclRecord *acl_record = s->state_machine->ua_session->get_acl_record();
bool deny_request = (acl_record == NULL);
if (acl_record && (acl_record->_method_mask != AclRecord::ALL_METHOD_MASK)) {
if (method != -1) {
deny_request = !acl_record->isMethodAllowed(method);
} else {
int method_str_len;
const char *method_str = s->hdr_info.client_request.method_get(&method_str_len);
deny_request = !acl_record->isNonstandardMethodAllowed(std::string(method_str, method_str_len));
}
}
if (deny_request) {
if (is_debug_tag_set("ip-allow")) {
ip_text_buffer ipb;
Debug("ip-allow", "Quick filter denial on %s:%s with mask %x", ats_ip_ntop(&s->client_info.src_addr.sa, ipb, sizeof(ipb)),
hdrtoken_index_to_wks(method), acl_record ? acl_record->_method_mask : 0x0);
}
s->client_connection_enabled = false;
}
}
}
HttpTransact::HostNameExpansionError_t
HttpTransact::try_to_expand_host_name(State *s)
{
static int max_dns_lookups = 2 + s->http_config_param->num_url_expansions;
static int last_expansion = max_dns_lookups - 2;
HTTP_RELEASE_ASSERT(!s->dns_info.lookup_success);
if (s->dns_info.looking_up == ORIGIN_SERVER) {
///////////////////////////////////////////////////
// if resolving dns of the origin server failed, //
// we try to expand hostname. //
///////////////////////////////////////////////////
if (s->http_config_param->enable_url_expandomatic) {
int attempts = s->dns_info.attempts;
ink_assert(attempts >= 1 && attempts <= max_dns_lookups);
if (attempts < max_dns_lookups) {
// Try a URL expansion
if (attempts <= last_expansion) {
char *expansion = s->http_config_param->url_expansions[attempts - 1];
int length = strlen(s->server_info.name) + strlen(expansion) + 1;
s->dns_info.lookup_name = s->arena.str_alloc(length);
ink_string_concatenate_strings_n(s->dns_info.lookup_name, length + 1, s->server_info.name, ".", expansion, NULL);
} else {
if (ParseRules::strchr(s->server_info.name, '.')) {
// don't expand if contains '.'
return (EXPANSION_FAILED);
}
// Try www.<server_name>.com
int length = strlen(s->server_info.name) + 8;
s->dns_info.lookup_name = s->arena.str_alloc(length);
ink_string_concatenate_strings_n(s->dns_info.lookup_name, length + 1, "www.", s->server_info.name, ".com", NULL);
}
return RETRY_EXPANDED_NAME;
} else {
return DNS_ATTEMPTS_EXHAUSTED;
}
} else {
return EXPANSION_NOT_ALLOWED;
}
} else {
//////////////////////////////////////////////////////
// we looked up dns of parent proxy, but it failed, //
// try lookup of origin server name. //
//////////////////////////////////////////////////////
ink_assert(s->dns_info.looking_up == PARENT_PROXY);
s->dns_info.lookup_name = s->server_info.name;
s->dns_info.looking_up = ORIGIN_SERVER;
s->dns_info.attempts = 0;
return RETRY_EXPANDED_NAME;
}
}
bool
HttpTransact::will_this_request_self_loop(State *s)
{
////////////////////////////////////////
// check if we are about to self loop //
////////////////////////////////////////
if (s->dns_info.lookup_success) {
if (ats_ip_addr_eq(s->host_db_info.ip(), &Machine::instance()->ip.sa)) {
in_port_t host_port = s->hdr_info.client_request.url_get()->port_get();
in_port_t local_port = s->client_info.src_addr.host_order_port();
if (host_port == local_port) {
switch (s->dns_info.looking_up) {
case ORIGIN_SERVER:
DebugTxn("http_transact", "[will_this_request_self_loop] host ip and port same as local ip and port - bailing");
break;
case PARENT_PROXY:
DebugTxn("http_transact", "[will_this_request_self_loop] "
"parent proxy ip and port same as local ip and port - bailing");
break;
default:
DebugTxn("http_transact", "[will_this_request_self_loop] "
"unknown's ip and port same as local ip and port - bailing");
break;
}
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Cycle Detected", "request#cycle_detected", NULL);
return true;
}
}
// Now check for a loop using the Via string.
const char *uuid = Machine::instance()->uuid.getString();
MIMEField *via_field = s->hdr_info.client_request.field_find(MIME_FIELD_VIA, MIME_LEN_VIA);
while (via_field) {
// No need to waste cycles comma separating the via values since we want to do a match anywhere in the
// in the string. We can just loop over the dup hdr fields
int via_len;
const char *via_string = via_field->value_get(&via_len);
if (via_string && ptr_len_str(via_string, via_len, uuid)) {
DebugTxn("http_transact", "[will_this_request_self_loop] Incoming via: %.*s has (%s[%s] (%s))", via_len, via_string,
s->http_config_param->proxy_hostname, uuid, s->http_config_param->proxy_request_via_string);
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Multi-Hop Cycle Detected", "request#cycle_detected", NULL);
return true;
}
via_field = via_field->m_next_dup;
}
}
s->request_will_not_selfloop = true;
return false;
}
/*
* handle_content_length_header(...)
* Function handles the insertion of content length headers into
* header. header CAN equal base.
*/
void
HttpTransact::handle_content_length_header(State *s, HTTPHdr *header, HTTPHdr *base)
{
int64_t cl = HTTP_UNDEFINED_CL;
ink_assert(header->type_get() == HTTP_TYPE_RESPONSE);
if (base->presence(MIME_PRESENCE_CONTENT_LENGTH)) {
cl = base->get_content_length();
if (cl >= 0) {
// header->set_content_length(cl);
ink_assert(header->get_content_length() == cl);
switch (s->source) {
case SOURCE_HTTP_ORIGIN_SERVER:
// We made our decision about whether to trust the
// response content length in init_state_vars_from_response()
if (s->range_setup != HttpTransact::RANGE_NOT_TRANSFORM_REQUESTED) {
break;
}
case SOURCE_CACHE:
// if we are doing a single Range: request, calculate the new
// C-L: header
if (s->range_setup == HttpTransact::RANGE_NOT_TRANSFORM_REQUESTED) {
change_response_header_because_of_range_request(s, header);
s->hdr_info.trust_response_cl = true;
}
////////////////////////////////////////////////
// Make sure that the cache's object size //
// agrees with the Content-Length //
// Otherwise, set the state's machine view //
// of c-l to undefined to turn off K-A //
////////////////////////////////////////////////
else if ((int64_t)s->cache_info.object_read->object_size_get() == cl) {
s->hdr_info.trust_response_cl = true;
} else {
DebugTxn("http_trans", "Content Length header and cache object size mismatch."
"Disabling keep-alive");
s->hdr_info.trust_response_cl = false;
}
break;
case SOURCE_TRANSFORM:
if (s->range_setup == HttpTransact::RANGE_REQUESTED) {
header->set_content_length(s->range_output_cl);
s->hdr_info.trust_response_cl = true;
} else if (s->hdr_info.transform_response_cl == HTTP_UNDEFINED_CL) {
s->hdr_info.trust_response_cl = false;
} else {
s->hdr_info.trust_response_cl = true;
}
break;
default:
ink_release_assert(0);
break;
}
} else {
header->field_delete(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH);
s->hdr_info.trust_response_cl = false;
}
Debug("http_trans", "[handle_content_length_header] RESPONSE cont len in hdr is %" PRId64, header->get_content_length());
} else {
// No content length header
if (s->source == SOURCE_CACHE) {
// If there is no content-length header, we can
// insert one since the cache knows definately
// how long the object is unless we're in a
// read-while-write mode and object hasn't been
// written into a cache completely.
cl = s->cache_info.object_read->object_size_get();
if (cl == INT64_MAX) { // INT64_MAX cl in cache indicates rww in progress
header->field_delete(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH);
s->hdr_info.trust_response_cl = false;
s->hdr_info.request_content_length = HTTP_UNDEFINED_CL;
ink_assert(s->range_setup == RANGE_NONE);
} else if (s->range_setup == RANGE_NOT_TRANSFORM_REQUESTED) {
// if we are doing a single Range: request, calculate the new
// C-L: header
change_response_header_because_of_range_request(s, header);
s->hdr_info.trust_response_cl = true;
} else {
header->set_content_length(cl);
s->hdr_info.trust_response_cl = true;
}
} else {
// Check to see if there is no content length
// header because the response precludes a
// body
if (is_response_body_precluded(header->status_get(), s->method)) {
// We want to be able to do keep-alive here since
// there can't be body so we don't have any
// issues about trusting the body length
s->hdr_info.trust_response_cl = true;
} else {
s->hdr_info.trust_response_cl = false;
}
header->field_delete(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH);
ink_assert(s->range_setup != RANGE_NOT_TRANSFORM_REQUESTED);
}
}
return;
} /* End HttpTransact::handle_content_length_header */
//////////////////////////////////////////////////////////////////////////////
//
// void HttpTransact::handle_request_keep_alive_headers(
// State* s, bool ka_on, HTTPVersion ver, HTTPHdr *heads)
//
// Removes keep alive headers from user-agent from <heads>
//
// Adds the appropriate keep alive headers (if any) to <heads>
// for keep-alive state <ka_on>, and HTTP version <ver>.
//
//////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_request_keep_alive_headers(State *s, HTTPVersion ver, HTTPHdr *heads)
{
enum KA_Action_t {
KA_UNKNOWN,
KA_DISABLED,
KA_CLOSE,
KA_CONNECTION,
};
KA_Action_t ka_action = KA_UNKNOWN;
bool upstream_ka = (s->current.server->keep_alive == HTTP_KEEPALIVE);
ink_assert(heads->type_get() == HTTP_TYPE_REQUEST);
// Check preconditions for Keep-Alive
if (!upstream_ka) {
ka_action = KA_DISABLED;
} else if (HTTP_MAJOR(ver.m_version) == 0) { /* No K-A for 0.9 apps */
ka_action = KA_DISABLED;
}
// If preconditions are met, figure out what action to take
if (ka_action == KA_UNKNOWN) {
int method = heads->method_get_wksidx();
if (method == HTTP_WKSIDX_GET || method == HTTP_WKSIDX_HEAD || method == HTTP_WKSIDX_OPTIONS || method == HTTP_WKSIDX_PURGE ||
method == HTTP_WKSIDX_DELETE || method == HTTP_WKSIDX_TRACE) {
// These methods do not need a content-length header
ka_action = KA_CONNECTION;
} else {
// All remaining methods require a content length header
if (heads->get_content_length() == -1) {
ka_action = KA_CLOSE;
} else {
ka_action = KA_CONNECTION;
}
}
}
ink_assert(ka_action != KA_UNKNOWN);
// Since connection headers are hop-to-hop, strip the
// the ones we received from the user-agent
heads->field_delete(MIME_FIELD_PROXY_CONNECTION, MIME_LEN_PROXY_CONNECTION);
heads->field_delete(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION);
if (!s->is_upgrade_request) {
// Insert K-A headers as necessary
switch (ka_action) {
case KA_CONNECTION:
ink_assert(s->current.server->keep_alive != HTTP_NO_KEEPALIVE);
if (ver == HTTPVersion(1, 0)) {
if (s->current.request_to == PARENT_PROXY || s->current.request_to == ICP_SUGGESTED_HOST) {
heads->value_set(MIME_FIELD_PROXY_CONNECTION, MIME_LEN_PROXY_CONNECTION, "keep-alive", 10);
} else {
heads->value_set(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION, "keep-alive", 10);
}
}
// NOTE: if the version is 1.1 we don't need to do
// anything since keep-alive is assumed
break;
case KA_DISABLED:
case KA_CLOSE:
if (s->current.server->keep_alive != HTTP_NO_KEEPALIVE || (ver == HTTPVersion(1, 1))) {
/* Had keep-alive */
s->current.server->keep_alive = HTTP_NO_KEEPALIVE;
if (s->current.request_to == PARENT_PROXY || s->current.request_to == ICP_SUGGESTED_HOST) {
heads->value_set(MIME_FIELD_PROXY_CONNECTION, MIME_LEN_PROXY_CONNECTION, "close", 5);
} else {
heads->value_set(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION, "close", 5);
}
}
// Note: if we are 1.1, we always need to send the close
// header since persistant connnections are the default
break;
case KA_UNKNOWN:
default:
ink_assert(0);
break;
}
} else { /* websocket connection */
s->current.server->keep_alive = HTTP_NO_KEEPALIVE;
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
heads->value_set(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION, MIME_FIELD_UPGRADE, MIME_LEN_UPGRADE);
if (s->is_websocket) {
heads->value_set(MIME_FIELD_UPGRADE, MIME_LEN_UPGRADE, "websocket", 9);
}
}
} /* End HttpTransact::handle_request_keep_alive_headers */
//////////////////////////////////////////////////////////////////////////////
//
// void HttpTransact::handle_response_keep_alive_headers(
// State* s, bool ka_on, HTTPVersion ver, HTTPHdr *heads)
//
// Removes keep alive headers from origin server from <heads>
//
// Adds the appropriate Transfer-Encoding: chunked header.
//
// Adds the appropriate keep alive headers (if any) to <heads>
// for keep-alive state <ka_on>, and HTTP version <ver>.
//
//////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_response_keep_alive_headers(State *s, HTTPVersion ver, HTTPHdr *heads)
{
enum KA_Action_t {
KA_UNKNOWN,
KA_DISABLED,
KA_CLOSE,
KA_CONNECTION,
};
KA_Action_t ka_action = KA_UNKNOWN;
ink_assert(heads->type_get() == HTTP_TYPE_RESPONSE);
// Since connection headers are hop-to-hop, strip the
// the ones we received from upstream
heads->field_delete(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION);
heads->field_delete(MIME_FIELD_PROXY_CONNECTION, MIME_LEN_PROXY_CONNECTION);
// Handle the upgrade cases
if (s->is_upgrade_request && heads->status_get() == HTTP_STATUS_SWITCHING_PROTOCOL && s->source == SOURCE_HTTP_ORIGIN_SERVER) {
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
if (s->is_websocket) {
DebugTxn("http_trans", "transaction successfully upgraded to websockets.");
// s->transparent_passthrough = true;
heads->value_set(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION, MIME_FIELD_UPGRADE, MIME_LEN_UPGRADE);
heads->value_set(MIME_FIELD_UPGRADE, MIME_LEN_UPGRADE, "websocket", 9);
}
// We set this state so that we can jump to our blind forwarding state once
// the response is sent to the client.
s->did_upgrade_succeed = true;
return;
}
int c_hdr_field_len;
const char *c_hdr_field_str;
if (s->client_info.proxy_connect_hdr) {
c_hdr_field_str = MIME_FIELD_PROXY_CONNECTION;
c_hdr_field_len = MIME_LEN_PROXY_CONNECTION;
} else {
c_hdr_field_str = MIME_FIELD_CONNECTION;
c_hdr_field_len = MIME_LEN_CONNECTION;
}
// Check pre-conditions for keep-alive
if (HTTP_MAJOR(ver.m_version) == 0) { /* No K-A for 0.9 apps */
ka_action = KA_DISABLED;
} else if (heads->status_get() == HTTP_STATUS_NO_CONTENT &&
((s->source == SOURCE_HTTP_ORIGIN_SERVER && s->current.server->transfer_encoding != NO_TRANSFER_ENCODING) ||
heads->get_content_length() != 0)) {
// some systems hang until the connection closes when receiving a 204 regardless of the K-A headers
// close if there is any body response from the origin
ka_action = KA_CLOSE;
} else {
// Determine if we are going to send either a server-generated or
// proxy-generated chunked response to the client. If we cannot
// trust the content-length, we may be able to chunk the response
// to the client to keep the connection alive.
// Insert a Transfer-Encoding header in the response if necessary.
// check that the client is HTTP 1.1 and the conf allows chunking or the client
// protocol unchunks before returning to the user agent (i.e. is http/2)
if (s->client_info.http_version == HTTPVersion(1, 1) &&
(s->txn_conf->chunking_enabled == 1 ||
(s->state_machine->plugin_tag && (!strncmp(s->state_machine->plugin_tag, "http/2", 6)))) &&
// if we're not sending a body, don't set a chunked header regardless of server response
!is_response_body_precluded(s->hdr_info.client_response.status_get(), s->method) &&
// we do not need chunked encoding for internal error messages
// that are sent to the client if the server response is not valid.
(((s->source == SOURCE_HTTP_ORIGIN_SERVER || s->source == SOURCE_TRANSFORM) && s->hdr_info.server_response.valid() &&
// if we receive a 304, we will serve the client from the
// cache and thus do not need chunked encoding.
s->hdr_info.server_response.status_get() != HTTP_STATUS_NOT_MODIFIED &&
(s->current.server->transfer_encoding == HttpTransact::CHUNKED_ENCODING ||
// we can use chunked encoding if we cannot trust the content
// length (e.g. no Content-Length and Connection:close in HTTP/1.1 responses)
s->hdr_info.trust_response_cl == false)) ||
// handle serve from cache (read-while-write) case
(s->source == SOURCE_CACHE && s->hdr_info.trust_response_cl == false) ||
// any transform will potentially alter the content length. try chunking if possible
(s->source == SOURCE_TRANSFORM && s->hdr_info.trust_response_cl == false))) {
s->client_info.receive_chunked_response = true;
heads->value_append(MIME_FIELD_TRANSFER_ENCODING, MIME_LEN_TRANSFER_ENCODING, HTTP_VALUE_CHUNKED, HTTP_LEN_CHUNKED, true);
} else {
s->client_info.receive_chunked_response = false;
}
// make sure no content length header is send when transfer encoding is chunked
if (s->client_info.receive_chunked_response) {
s->hdr_info.trust_response_cl = false;
// And delete the header if it's already been added...
heads->field_delete(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH);
}
// Close the connection if client_info is not keep-alive.
// Otherwise, if we cannot trust the content length, we will close the connection
// unless we are going to use chunked encoding or the client issued
// a PUSH request
if (s->client_info.keep_alive != HTTP_KEEPALIVE) {
ka_action = KA_DISABLED;
} else if (s->hdr_info.trust_response_cl == false &&
!(s->client_info.receive_chunked_response == true ||
(s->method == HTTP_WKSIDX_PUSH && s->client_info.keep_alive == HTTP_KEEPALIVE))) {
ka_action = KA_CLOSE;
} else {
ka_action = KA_CONNECTION;
}
}
// Insert K-A headers as necessary
switch (ka_action) {
case KA_CONNECTION:
ink_assert(s->client_info.keep_alive != HTTP_NO_KEEPALIVE);
// This is a hack, we send the keep-alive header for both 1.0
// and 1.1, to be "compatible" with Akamai.
// if (ver == HTTPVersion (1, 0)) {
heads->value_set(c_hdr_field_str, c_hdr_field_len, "keep-alive", 10);
// NOTE: if the version is 1.1 we don't need to do
// anything since keep-alive is assumed
break;
case KA_CLOSE:
case KA_DISABLED:
if (s->client_info.keep_alive != HTTP_NO_KEEPALIVE || (ver == HTTPVersion(1, 1))) {
heads->value_set(c_hdr_field_str, c_hdr_field_len, "close", 5);
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
}
// Note: if we are 1.1, we always need to send the close
// header since persistant connnections are the default
break;
case KA_UNKNOWN:
default:
ink_assert(0);
break;
}
} /* End HttpTransact::handle_response_keep_alive_headers */
bool
HttpTransact::delete_all_document_alternates_and_return(State *s, bool cache_hit)
{
if (cache_hit == true) {
// ToDo: Should support other levels of cache hits here, but the cache does not support it (yet)
if (SQUID_HIT_RAM == s->cache_info.hit_miss_code) {
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_RAM_CACHE_FRESH);
} else {
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_CACHE_FRESH);
}
} else {
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_NOT_CACHED);
}
if ((s->method != HTTP_WKSIDX_GET) && (s->method == HTTP_WKSIDX_DELETE || s->method == HTTP_WKSIDX_PURGE)) {
bool valid_max_forwards;
int max_forwards = -1;
MIMEField *max_forwards_f = s->hdr_info.client_request.field_find(MIME_FIELD_MAX_FORWARDS, MIME_LEN_MAX_FORWARDS);
// Check the max forwards value for DELETE
if (max_forwards_f) {
valid_max_forwards = true;
max_forwards = max_forwards_f->value_get_int();
} else {
valid_max_forwards = false;
}
if (s->method == HTTP_WKSIDX_PURGE || (valid_max_forwards && max_forwards <= 0)) {
DebugTxn("http_trans", "[delete_all_document_alternates_and_return] "
"DELETE with Max-Forwards: %d",
max_forwards);
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
// allow deletes to be pipelined
// We want to allow keep-alive so trust the response content
// length. There really isn't one and the SM will add the
// zero content length when setting up the transfer
s->hdr_info.trust_response_cl = true;
build_response(s, &s->hdr_info.client_response, s->client_info.http_version,
(cache_hit == true) ? HTTP_STATUS_OK : HTTP_STATUS_NOT_FOUND);
return true;
} else {
if (valid_max_forwards) {
--max_forwards;
DebugTxn("http_trans", "[delete_all_document_alternates_and_return] "
"Decrementing max_forwards to %d",
max_forwards);
s->hdr_info.client_request.value_set_int(MIME_FIELD_MAX_FORWARDS, MIME_LEN_MAX_FORWARDS, max_forwards);
}
}
}
return false;
}
bool
HttpTransact::does_client_request_permit_cached_response(const OverridableHttpConfigParams *p, CacheControlResult *c, HTTPHdr *h,
char *via_string)
{
////////////////////////////////////////////////////////////////////////
// If aren't ignoring client's cache directives, meet client's wishes //
////////////////////////////////////////////////////////////////////////
if (!c->ignore_client_no_cache) {
if (h->is_cache_control_set(HTTP_VALUE_NO_CACHE)) {
return (false);
}
if (h->is_pragma_no_cache_set()) {
// if we are going to send out an ims anyway,
// no need to flag this as a no-cache.
if (!p->cache_ims_on_client_no_cache) {
via_string[VIA_CLIENT_REQUEST] = VIA_CLIENT_NO_CACHE;
}
return (false);
}
}
return (true);
}
bool
HttpTransact::does_client_request_permit_dns_caching(CacheControlResult *c, HTTPHdr *h)
{
if (h->is_pragma_no_cache_set() && h->is_cache_control_set(HTTP_VALUE_NO_CACHE) && (!c->ignore_client_no_cache)) {
return (false);
}
return (true);
}
bool
HttpTransact::does_client_request_permit_storing(CacheControlResult *c, HTTPHdr *h)
{
////////////////////////////////////////////////////////////////////////
// If aren't ignoring client's cache directives, meet client's wishes //
////////////////////////////////////////////////////////////////////////
if (!c->ignore_client_no_cache) {
if (h->is_cache_control_set(HTTP_VALUE_NO_STORE)) {
return (false);
}
}
return (true);
}
int
HttpTransact::calculate_document_freshness_limit(State *s, HTTPHdr *response, time_t response_date, bool *heuristic)
{
bool expires_set, date_set, last_modified_set;
time_t date_value, expires_value, last_modified_value;
MgmtInt min_freshness_bounds, max_freshness_bounds;
int freshness_limit = 0;
uint32_t cc_mask = response->get_cooked_cc_mask();
*heuristic = false;
if (cc_mask & (MIME_COOKED_MASK_CC_S_MAXAGE | MIME_COOKED_MASK_CC_MAX_AGE)) {
if (cc_mask & MIME_COOKED_MASK_CC_S_MAXAGE) {
freshness_limit = (int)response->get_cooked_cc_s_maxage();
DebugTxn("http_match", "calculate_document_freshness_limit --- s_max_age set, freshness_limit = %d", freshness_limit);
} else if (cc_mask & MIME_COOKED_MASK_CC_MAX_AGE) {
freshness_limit = (int)response->get_cooked_cc_max_age();
DebugTxn("http_match", "calculate_document_freshness_limit --- max_age set, freshness_limit = %d", freshness_limit);
}
freshness_limit = min(max(0, freshness_limit), (int)s->txn_conf->cache_guaranteed_max_lifetime);
} else {
date_set = last_modified_set = false;
if (s->plugin_set_expire_time != UNDEFINED_TIME) {
expires_set = true;
expires_value = s->plugin_set_expire_time;
} else {
expires_set = (response->presence(MIME_PRESENCE_EXPIRES) != 0);
expires_value = response->get_expires();
}
date_value = response_date;
if (date_value > 0) {
date_set = true;
} else {
date_value = s->request_sent_time;
DebugTxn("http_match",
"calculate_document_freshness_limit --- Expires header = %" PRId64 " no date, using sent time %" PRId64,
(int64_t)expires_value, (int64_t)date_value);
}
ink_assert(date_value > 0);
// Getting the cache_sm object
HttpCacheSM &cache_sm = s->state_machine->get_cache_sm();
// Bypassing if loop to set freshness_limit to heuristic value
if (expires_set && !cache_sm.is_readwhilewrite_inprogress()) {
if (expires_value == UNDEFINED_TIME || expires_value <= date_value) {
expires_value = date_value;
DebugTxn("http_match", "calculate_document_freshness_limit --- no expires, using date %" PRId64, (int64_t)expires_value);
}
freshness_limit = (int)(expires_value - date_value);
DebugTxn("http_match", "calculate_document_freshness_limit --- Expires: %" PRId64 ", Date: %" PRId64 ", freshness_limit = %d",
(int64_t)expires_value, (int64_t)date_value, freshness_limit);
freshness_limit = min(max(0, freshness_limit), (int)s->txn_conf->cache_guaranteed_max_lifetime);
} else {
last_modified_value = 0;
if (response->presence(MIME_PRESENCE_LAST_MODIFIED)) {
last_modified_set = true;
last_modified_value = response->get_last_modified();
DebugTxn("http_match", "calculate_document_freshness_limit --- Last Modified header = %" PRId64,
(int64_t)last_modified_value);
if (last_modified_value == UNDEFINED_TIME) {
last_modified_set = false;
} else if (last_modified_value > date_value) {
last_modified_value = date_value;
DebugTxn("http_match", "calculate_document_freshness_limit --- no last-modified, using sent time %" PRId64,
(int64_t)last_modified_value);
}
}
*heuristic = true;
if (date_set && last_modified_set) {
MgmtFloat f = s->txn_conf->cache_heuristic_lm_factor;
ink_assert((f >= 0.0) && (f <= 1.0));
ink_time_t time_since_last_modify = date_value - last_modified_value;
int h_freshness = (int)(time_since_last_modify * f);
freshness_limit = max(h_freshness, 0);
DebugTxn("http_match", "calculate_document_freshness_limit --- heuristic: date=%" PRId64 ", lm=%" PRId64
", time_since_last_modify=%" PRId64 ", f=%g, freshness_limit = %d",
(int64_t)date_value, (int64_t)last_modified_value, (int64_t)time_since_last_modify, f, freshness_limit);
} else {
freshness_limit = s->txn_conf->cache_heuristic_min_lifetime;
DebugTxn("http_match", "calculate_document_freshness_limit --- heuristic: freshness_limit = %d", freshness_limit);
}
}
}
// The freshness limit must always fall within the min and max guaranteed bounds.
min_freshness_bounds = max((MgmtInt)0, s->txn_conf->cache_guaranteed_min_lifetime);
max_freshness_bounds = s->txn_conf->cache_guaranteed_max_lifetime;
// Heuristic freshness can be more strict.
if (*heuristic) {
min_freshness_bounds = max(min_freshness_bounds, s->txn_conf->cache_heuristic_min_lifetime);
max_freshness_bounds = min(max_freshness_bounds, s->txn_conf->cache_heuristic_max_lifetime);
}
// Now clip the freshness limit.
if (freshness_limit > max_freshness_bounds) {
freshness_limit = max_freshness_bounds;
}
if (freshness_limit < min_freshness_bounds) {
freshness_limit = min_freshness_bounds;
}
DebugTxn("http_match", "calculate_document_freshness_limit --- final freshness_limit = %d", freshness_limit);
return (freshness_limit);
}
////////////////////////////////////////////////////////////////////////////////////
// int HttpTransact::calculate_freshness_fuzz()
//
// This function trys to revents many, many simulatenous revalidations in
// reverse proxy situations. Statistically introduce a fuzz factor that
// brings revalidation forward for a small percentage of the requests/
// The hope is that is that the document early by a selected few, and
// the headers are updated in the cache before the regualr freshness
// limit is actually reached
////////////////////////////////////////////////////////////////////////////////////
int
HttpTransact::calculate_freshness_fuzz(State *s, int fresh_limit)
{
static double LOG_YEAR = log10((double)s->txn_conf->cache_guaranteed_max_lifetime);
const uint32_t granularity = 1000;
int result = 0;
uint32_t random_num = this_ethread()->generator.random();
uint32_t index = random_num % granularity;
uint32_t range = (uint32_t)(granularity * s->txn_conf->freshness_fuzz_prob);
if (index < range) {
if (s->txn_conf->freshness_fuzz_min_time > 0) {
// Complicated calculations to try to find a reasonable fuzz time between fuzz_min_time and fuzz_time
int fresh_small = (int)rint((double)s->txn_conf->freshness_fuzz_min_time *
pow(2, min((double)fresh_limit / (double)s->txn_conf->freshness_fuzz_time,
sqrt((double)s->txn_conf->freshness_fuzz_time))));
int fresh_large = max((int)s->txn_conf->freshness_fuzz_min_time,
(int)rint(s->txn_conf->freshness_fuzz_time *
log10((double)(fresh_limit - s->txn_conf->freshness_fuzz_min_time) / LOG_YEAR)));
result = min(fresh_small, fresh_large);
DebugTxn("http_match", "calculate_freshness_fuzz using min/max --- freshness fuzz = %d", result);
} else {
result = s->txn_conf->freshness_fuzz_time;
DebugTxn("http_match", "calculate_freshness_fuzz --- freshness fuzz = %d", result);
}
}
return result;
}
//////////////////////////////////////////////////////////////////////////////
//
//
// This function takes the request and response headers for a cached
// object, and the current HTTP parameters, and decides if the object
// is still "fresh enough" to serve. One of the following values
// is returned:
//
// FRESHNESS_FRESH Fresh enough, serve it
// FRESHNESS_WARNING Stale but client says it's okay
// FRESHNESS_STALE Too stale, don't use
//
//////////////////////////////////////////////////////////////////////////////
HttpTransact::Freshness_t
HttpTransact::what_is_document_freshness(State *s, HTTPHdr *client_request, HTTPHdr *cached_obj_response)
{
bool heuristic, do_revalidate = false;
int age_limit;
int fresh_limit;
ink_time_t current_age, response_date;
uint32_t cc_mask, cooked_cc_mask;
uint32_t os_specifies_revalidate;
if (s->cache_open_write_fail_action & CACHE_WL_FAIL_ACTION_STALE_ON_REVALIDATE) {
if (is_stale_cache_response_returnable(s)) {
DebugTxn("http_match", "[what_is_document_freshness] cache_serve_stale_on_write_lock_fail, return FRESH");
return (FRESHNESS_FRESH);
}
}
//////////////////////////////////////////////////////
// If config file has a ttl-in-cache field set, //
// it has priority over any other http headers and //
// other configuration parameters. //
//////////////////////////////////////////////////////
if (s->cache_control.ttl_in_cache > 0) {
// what matters if ttl is set is not the age of the document
// but for how long it has been stored in the cache (resident time)
int resident_time = s->current.now - s->response_received_time;
DebugTxn("http_match", "[..._document_freshness] ttl-in-cache = %d, resident time = %d", s->cache_control.ttl_in_cache,
resident_time);
if (resident_time > s->cache_control.ttl_in_cache) {
return (FRESHNESS_STALE);
} else {
return (FRESHNESS_FRESH);
}
}
cooked_cc_mask = cached_obj_response->get_cooked_cc_mask();
os_specifies_revalidate = cooked_cc_mask & (MIME_COOKED_MASK_CC_MUST_REVALIDATE | MIME_COOKED_MASK_CC_PROXY_REVALIDATE);
cc_mask = MIME_COOKED_MASK_CC_NEED_REVALIDATE_ONCE;
// Check to see if the server forces revalidation
if ((cooked_cc_mask & cc_mask) && s->cache_control.revalidate_after <= 0) {
DebugTxn("http_match", "[what_is_document_freshness] document stale due to "
"server must-revalidate");
return FRESHNESS_STALE;
}
response_date = cached_obj_response->get_date();
fresh_limit = calculate_document_freshness_limit(s, cached_obj_response, response_date, &heuristic);
ink_assert(fresh_limit >= 0);
// Fuzz the freshness to prevent too many revalidates to popular
// documents at the same time
if (s->txn_conf->freshness_fuzz_time >= 0) {
fresh_limit = fresh_limit - calculate_freshness_fuzz(s, fresh_limit);
fresh_limit = max(0, fresh_limit);
fresh_limit = min((int)s->txn_conf->cache_guaranteed_max_lifetime, fresh_limit);
}
current_age = HttpTransactHeaders::calculate_document_age(s->request_sent_time, s->response_received_time, cached_obj_response,
response_date, s->current.now);
// Overflow ?
if (current_age < 0) {
current_age = s->txn_conf->cache_guaranteed_max_lifetime;
} else {
current_age = min((time_t)s->txn_conf->cache_guaranteed_max_lifetime, current_age);
}
DebugTxn("http_match", "[what_is_document_freshness] fresh_limit: %d current_age: %" PRId64, fresh_limit, (int64_t)current_age);
/////////////////////////////////////////////////////////
// did the admin override the expiration calculations? //
// (used only for http). //
/////////////////////////////////////////////////////////
ink_assert(client_request == &s->hdr_info.client_request);
if (s->txn_conf->cache_when_to_revalidate == 0) {
;
// Compute how fresh below
} else if (client_request->url_get()->scheme_get_wksidx() == URL_WKSIDX_HTTP) {
switch (s->txn_conf->cache_when_to_revalidate) {
case 1: // Stale if heuristic
if (heuristic) {
DebugTxn("http_match", "[what_is_document_freshness] config requires FRESHNESS_STALE because heuristic calculation");
return (FRESHNESS_STALE);
}
break;
case 2: // Always stale
DebugTxn("http_match", "[what_is_document_freshness] config "
"specifies always FRESHNESS_STALE");
return (FRESHNESS_STALE);
case 3: // Never stale
DebugTxn("http_match", "[what_is_document_freshness] config "
"specifies always FRESHNESS_FRESH");
return (FRESHNESS_FRESH);
case 4: // Stale if IMS
if (client_request->presence(MIME_PRESENCE_IF_MODIFIED_SINCE)) {
DebugTxn("http_match", "[what_is_document_freshness] config "
"specifies FRESHNESS_STALE if IMS present");
return (FRESHNESS_STALE);
}
default: // Bad config, ignore
break;
}
}
//////////////////////////////////////////////////////////////////////
// the normal expiration policy allows serving a doc from cache if: //
// basic: (current_age <= fresh_limit) //
// //
// this can be modified by client Cache-Control headers: //
// max-age: (current_age <= max_age) //
// min-fresh: (current_age <= fresh_limit - min_fresh) //
// max-stale: (current_age <= fresh_limit + max_stale) //
//////////////////////////////////////////////////////////////////////
age_limit = fresh_limit; // basic constraint
DebugTxn("http_match", "[..._document_freshness] initial age limit: %d", age_limit);
cooked_cc_mask = client_request->get_cooked_cc_mask();
cc_mask = (MIME_COOKED_MASK_CC_MAX_STALE | MIME_COOKED_MASK_CC_MIN_FRESH | MIME_COOKED_MASK_CC_MAX_AGE);
if (cooked_cc_mask & cc_mask) {
/////////////////////////////////////////////////
// if max-stale set, relax the freshness limit //
/////////////////////////////////////////////////
if (cooked_cc_mask & MIME_COOKED_MASK_CC_MAX_STALE) {
if (os_specifies_revalidate) {
DebugTxn("http_match", "[...document_freshness] OS specifies revalidation; "
"ignoring client's max-stale request...");
} else {
int max_stale_val = client_request->get_cooked_cc_max_stale();
if (max_stale_val != INT_MAX) {
age_limit += max_stale_val;
} else {
age_limit = max_stale_val;
}
DebugTxn("http_match", "[..._document_freshness] max-stale set, age limit: %d", age_limit);
}
}
/////////////////////////////////////////////////////
// if min-fresh set, constrain the freshness limit //
/////////////////////////////////////////////////////
if (cooked_cc_mask & MIME_COOKED_MASK_CC_MIN_FRESH) {
age_limit = min(age_limit, fresh_limit - client_request->get_cooked_cc_min_fresh());
DebugTxn("http_match", "[..._document_freshness] min_fresh set, age limit: %d", age_limit);
}
///////////////////////////////////////////////////
// if max-age set, constrain the freshness limit //
///////////////////////////////////////////////////
if (!s->cache_control.ignore_client_cc_max_age && (cooked_cc_mask & MIME_COOKED_MASK_CC_MAX_AGE)) {
int age_val = client_request->get_cooked_cc_max_age();
if (age_val == 0) {
do_revalidate = true;
}
age_limit = min(age_limit, age_val);
DebugTxn("http_match", "[..._document_freshness] min_fresh set, age limit: %d", age_limit);
}
}
/////////////////////////////////////////////////////////
// config file may have a "revalidate_after" field set //
/////////////////////////////////////////////////////////
// bug fix changed ">0" to ">=0"
if (s->cache_control.revalidate_after >= 0) {
// if we want the minimum of the already-computed age_limit and revalidate_after
// age_limit = mine(age_limit, s->cache_control.revalidate_after);
// if instead the revalidate_after overrides all other variables
age_limit = s->cache_control.revalidate_after;
DebugTxn("http_match", "[..._document_freshness] revalidate_after set, age limit: %d", age_limit);
}
DebugTxn("http_match", "document_freshness --- current_age = %" PRId64, (int64_t)current_age);
DebugTxn("http_match", "document_freshness --- age_limit = %d", age_limit);
DebugTxn("http_match", "document_freshness --- fresh_limit = %d", fresh_limit);
DebugTxn("http_seq", "document_freshness --- current_age = %" PRId64, (int64_t)current_age);
DebugTxn("http_seq", "document_freshness --- age_limit = %d", age_limit);
DebugTxn("http_seq", "document_freshness --- fresh_limit = %d", fresh_limit);
///////////////////////////////////////////
// now, see if the age is "fresh enough" //
///////////////////////////////////////////
if (do_revalidate || current_age > age_limit) { // client-modified limit
DebugTxn("http_match", "[..._document_freshness] document needs revalidate/too old; "
"returning FRESHNESS_STALE");
return (FRESHNESS_STALE);
} else if (current_age > fresh_limit) { // original limit
if (os_specifies_revalidate) {
DebugTxn("http_match", "[..._document_freshness] document is stale and OS specifies revalidation; "
"returning FRESHNESS_STALE");
return (FRESHNESS_STALE);
}
DebugTxn("http_match", "[..._document_freshness] document is stale but no revalidation explicitly required; "
"returning FRESHNESS_WARNING");
return (FRESHNESS_WARNING);
} else {
DebugTxn("http_match", "[..._document_freshness] document is fresh; returning FRESHNESS_FRESH");
return (FRESHNESS_FRESH);
}
}
//////////////////////////////////////////////////////////////////////////////
//
// HttpTransact::Authentication_t HttpTransact::AuthenticationNeeded(
// const OverridableHttpConfigParams *p,
// HTTPHdr *client_request,
// HTTPHdr *obj_response)
//
// This function takes the current client request, and the headers
// from a potential response (e.g. from cache or proxy), and decides
// if the object needs to be authenticated with the origin server,
// before it can be sent to the client.
//
// The return value describes the authentication process needed. In
// this function, three results are possible:
//
// AUTHENTICATION_SUCCESS Can serve object directly
// AUTHENTICATION_MUST_REVALIDATE Must revalidate with server
// AUTHENTICATION_MUST_PROXY Must not serve object
//
//////////////////////////////////////////////////////////////////////////////
HttpTransact::Authentication_t
HttpTransact::AuthenticationNeeded(const OverridableHttpConfigParams *p, HTTPHdr *client_request, HTTPHdr *obj_response)
{
///////////////////////////////////////////////////////////////////////
// from RFC2068, sec 14.8, if a client request has the Authorization //
// header set, we can't serve it unless the response is public, or //
// if it has a Cache-Control revalidate flag, and we do revalidate. //
///////////////////////////////////////////////////////////////////////
if ((p->cache_ignore_auth == 0) && client_request->presence(MIME_PRESENCE_AUTHORIZATION)) {
if (obj_response->is_cache_control_set(HTTP_VALUE_MUST_REVALIDATE) ||
obj_response->is_cache_control_set(HTTP_VALUE_PROXY_REVALIDATE)) {
return AUTHENTICATION_MUST_REVALIDATE;
} else if (obj_response->is_cache_control_set(HTTP_VALUE_PROXY_REVALIDATE)) {
return AUTHENTICATION_MUST_REVALIDATE;
} else if (obj_response->is_cache_control_set(HTTP_VALUE_PUBLIC)) {
return AUTHENTICATION_SUCCESS;
} else {
if (obj_response->field_find("@WWW-Auth", 9) && client_request->method_get_wksidx() == HTTP_WKSIDX_GET) {
return AUTHENTICATION_CACHE_AUTH;
}
return AUTHENTICATION_MUST_PROXY;
}
}
if (obj_response->field_find("@WWW-Auth", 9) && client_request->method_get_wksidx() == HTTP_WKSIDX_GET) {
return AUTHENTICATION_CACHE_AUTH;
}
return (AUTHENTICATION_SUCCESS);
}
void
HttpTransact::handle_parent_died(State *s)
{
ink_assert(s->parent_result.result == PARENT_FAIL);
build_error_response(s, HTTP_STATUS_BAD_GATEWAY, "Next Hop Connection Failed", "connect#failed_connect", NULL);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
void
HttpTransact::handle_server_died(State *s)
{
const char *reason = NULL;
const char *body_type = "UNKNOWN";
HTTPStatus status = HTTP_STATUS_BAD_GATEWAY;
////////////////////////////////////////////////////////
// FIX: all the body types below need to be filled in //
////////////////////////////////////////////////////////
//
// congestion control
//
if (s->pCongestionEntry != NULL) {
s->congestion_congested_or_failed = 1;
if (s->current.state != CONGEST_CONTROL_CONGESTED_ON_F && s->current.state != CONGEST_CONTROL_CONGESTED_ON_M) {
s->pCongestionEntry->failed_at(s->current.now);
}
}
switch (s->current.state) {
case CONNECTION_ALIVE: /* died while alive for unknown reason */
ink_release_assert(s->hdr_info.response_error != NO_RESPONSE_HEADER_ERROR);
status = HTTP_STATUS_BAD_GATEWAY;
reason = "Unknown Error";
body_type = "response#bad_response";
break;
case CONNECTION_ERROR:
status = HTTP_STATUS_BAD_GATEWAY;
reason = (char *)get_error_string(s->cause_of_death_errno);
body_type = "connect#failed_connect";
break;
case OPEN_RAW_ERROR:
status = HTTP_STATUS_BAD_GATEWAY;
reason = "Tunnel Connection Failed";
body_type = "connect#failed_connect";
break;
case CONNECTION_CLOSED:
status = HTTP_STATUS_BAD_GATEWAY;
reason = "Server Hangup";
body_type = "connect#hangup";
break;
case ACTIVE_TIMEOUT:
if (s->api_txn_active_timeout_value != -1) {
DebugTxn("http_timeout", "Maximum active time of %d msec exceeded", s->api_txn_active_timeout_value);
}
status = HTTP_STATUS_GATEWAY_TIMEOUT;
reason = "Maximum Transaction Time Exceeded";
body_type = "timeout#activity";
break;
case INACTIVE_TIMEOUT:
if (s->api_txn_connect_timeout_value != -1) {
DebugTxn("http_timeout", "Maximum connect time of %d msec exceeded", s->api_txn_connect_timeout_value);
}
status = HTTP_STATUS_GATEWAY_TIMEOUT;
reason = "Connection Timed Out";
body_type = "timeout#inactivity";
break;
case PARSE_ERROR:
case BAD_INCOMING_RESPONSE:
status = HTTP_STATUS_BAD_GATEWAY;
reason = "Invalid HTTP Response";
body_type = "response#bad_response";
break;
case CONGEST_CONTROL_CONGESTED_ON_F:
status = HTTP_STATUS_SERVICE_UNAVAILABLE;
reason = "Origin server congested";
if (s->pCongestionEntry) {
body_type = s->pCongestionEntry->getErrorPage();
} else {
body_type = "congestion#retryAfter";
}
s->hdr_info.response_error = TOTAL_RESPONSE_ERROR_TYPES;
break;
case CONGEST_CONTROL_CONGESTED_ON_M:
status = HTTP_STATUS_SERVICE_UNAVAILABLE;
reason = "Too many users";
if (s->pCongestionEntry) {
body_type = s->pCongestionEntry->getErrorPage();
} else {
body_type = "congestion#retryAfter";
}
s->hdr_info.response_error = TOTAL_RESPONSE_ERROR_TYPES;
break;
case STATE_UNDEFINED:
case TRANSACTION_COMPLETE:
default: /* unknown death */
ink_release_assert(!"[handle_server_died] Unreasonable state - not dead, shouldn't be here");
status = HTTP_STATUS_BAD_GATEWAY;
reason = NULL;
body_type = "response#bad_response";
break;
}
if (s->pCongestionEntry && s->pCongestionEntry->F_congested() && status != HTTP_STATUS_SERVICE_UNAVAILABLE) {
s->pCongestionEntry->stat_inc_F();
CONGEST_SUM_GLOBAL_DYN_STAT(congested_on_F_stat, 1);
status = HTTP_STATUS_SERVICE_UNAVAILABLE;
reason = "Service Unavailable";
body_type = s->pCongestionEntry->getErrorPage();
s->hdr_info.response_error = TOTAL_RESPONSE_ERROR_TYPES;
}
////////////////////////////////////////////////////////
// FIX: comment stuff above and below here, not clear //
////////////////////////////////////////////////////////
switch (s->hdr_info.response_error) {
case NON_EXISTANT_RESPONSE_HEADER:
status = HTTP_STATUS_BAD_GATEWAY;
reason = "No Response Header From Server";
body_type = "response#bad_response";
break;
case MISSING_REASON_PHRASE:
case NO_RESPONSE_HEADER_ERROR:
case NOT_A_RESPONSE_HEADER:
#ifdef REALLY_NEED_TO_CHECK_DATE_VALIDITY
case BOGUS_OR_NO_DATE_IN_RESPONSE:
#endif
status = HTTP_STATUS_BAD_GATEWAY;
reason = "Malformed Server Response";
body_type = "response#bad_response";
break;
case MISSING_STATUS_CODE:
status = HTTP_STATUS_BAD_GATEWAY;
reason = "Malformed Server Response Status";
body_type = "response#bad_response";
break;
default:
break;
}
if (reason == NULL) {
status = HTTP_STATUS_BAD_GATEWAY;
reason = "Server Connection Failed";
body_type = "connect#failed_connect";
}
build_error_response(s, status, reason, body_type, NULL);
return;
}
// return true if the response to the given request is likely cacheable
// This function is called by build_request() to determine if the conditional
// headers should be removed from server request.
bool
HttpTransact::is_request_likely_cacheable(State *s, HTTPHdr *request)
{
if ((s->method == HTTP_WKSIDX_GET || s->api_req_cacheable) && !s->api_server_response_no_store &&
!request->presence(MIME_PRESENCE_AUTHORIZATION) &&
(!request->presence(MIME_PRESENCE_RANGE) || s->txn_conf->cache_range_write)) {
return true;
}
return false;
}
void
HttpTransact::build_request(State *s, HTTPHdr *base_request, HTTPHdr *outgoing_request, HTTPVersion outgoing_version)
{
// this part is to restore the original URL in case, multiple cache
// lookups have happened - client request has been changed as the result
//
// notice that currently, based_request IS client_request
if (base_request == &s->hdr_info.client_request) {
if (s->redirect_info.redirect_in_process) {
// this is for auto redirect
URL *r_url = &s->redirect_info.redirect_url;
ink_assert(r_url->valid());
base_request->url_get()->copy(r_url);
} else {
// this is for multiple cache lookup
URL *o_url = &s->cache_info.original_url;
if (o_url->valid()) {
base_request->url_get()->copy(o_url);
}
}
}
HttpTransactHeaders::copy_header_fields(base_request, outgoing_request, s->txn_conf->fwd_proxy_auth_to_parent);
add_client_ip_to_outgoing_request(s, outgoing_request);
HttpTransactHeaders::remove_privacy_headers_from_request(s->http_config_param, s->txn_conf, outgoing_request);
HttpTransactHeaders::add_global_user_agent_header_to_request(s->txn_conf, outgoing_request);
handle_request_keep_alive_headers(s, outgoing_version, outgoing_request);
// handle_conditional_headers appears to be obsolete. Nothing happens
// unelss s->cache_info.action == HttpTransact::CACHE_DO_UPDATE. In that
// case an assert will go off. The functionality of this method
// (e.g., setting the if-modfied-since header occurs in issue_revalidate
// HttpTransactHeaders::handle_conditional_headers(&s->cache_info, outgoing_request);
if (s->next_hop_scheme < 0) {
s->next_hop_scheme = URL_WKSIDX_HTTP;
}
if (s->orig_scheme < 0) {
s->orig_scheme = URL_WKSIDX_HTTP;
}
if (s->txn_conf->insert_request_via_string) {
HttpTransactHeaders::insert_via_header_in_request(s, outgoing_request);
}
// We build 1.1 request header and then convert as necessary to
// the appropriate version in HttpTransact::build_request
outgoing_request->version_set(HTTPVersion(1, 1));
// Make sure our request version is defined
ink_assert(outgoing_version != HTTPVersion(0, 0));
// HttpTransactHeaders::convert_request(outgoing_version, outgoing_request); // commented out this idea
// Check whether a Host header field is missing from a 1.0 or 1.1 request.
if (outgoing_version != HTTPVersion(0, 9) && !outgoing_request->presence(MIME_PRESENCE_HOST)) {
URL *url = outgoing_request->url_get();
int host_len;
const char *host = url->host_get(&host_len);
// Add a ':port' to the HOST header if the request is not going
// to the default port.
int port = url->port_get();
if (port != url_canonicalize_port(URL_TYPE_HTTP, 0)) {
char *buf = (char *)alloca(host_len + 15);
memcpy(buf, host, host_len);
host_len += snprintf(buf + host_len, 15, ":%d", port);
outgoing_request->value_set(MIME_FIELD_HOST, MIME_LEN_HOST, buf, host_len);
} else {
outgoing_request->value_set(MIME_FIELD_HOST, MIME_LEN_HOST, host, host_len);
}
}
if (s->current.server == &s->server_info && (s->next_hop_scheme == URL_WKSIDX_HTTP || s->next_hop_scheme == URL_WKSIDX_HTTPS ||
s->next_hop_scheme == URL_WKSIDX_WS || s->next_hop_scheme == URL_WKSIDX_WSS)) {
DebugTxn("http_trans", "[build_request] removing host name from url");
HttpTransactHeaders::remove_host_name_from_url(outgoing_request);
}
// If we're going to a parent proxy, make sure we pass host and port
// in the URL even if we didn't get them (e.g. transparent proxy)
if (s->current.request_to == PARENT_PROXY) {
if (!outgoing_request->is_target_in_url() && s->parent_result.parent_is_proxy()) {
DebugTxn("http_trans", "[build_request] adding target to URL for parent proxy");
// No worry about HTTP/0.9 because we reject forward proxy requests that
// don't have a host anywhere.
outgoing_request->set_url_target_from_host_field();
} else if (s->current.request_to == PARENT_PROXY && !s->parent_result.parent_is_proxy() &&
outgoing_request->is_target_in_url()) {
// If the parent is an origin server remove the hostname from the url.
DebugTxn("http_trans", "[build_request] removing target from URL for a parent origin.");
HttpTransactHeaders::remove_host_name_from_url(outgoing_request);
}
}
// If the response is most likely not cacheable, eg, request with Authorization,
// do we really want to remove conditional headers to get large 200 response?
// Answer: NO. Since if the response is most likely not cacheable,
// we don't remove conditional headers so that for a non-200 response
// from the O.S., we will save bandwidth between proxy and O.S.
if (s->current.mode == GENERIC_PROXY) {
if (is_request_likely_cacheable(s, base_request)) {
if (s->txn_conf->cache_when_to_revalidate != 4) {
DebugTxn("http_trans", "[build_request] "
"request like cacheable and conditional headers removed");
HttpTransactHeaders::remove_conditional_headers(outgoing_request);
} else
DebugTxn("http_trans", "[build_request] "
"request like cacheable but keep conditional headers");
} else {
// In this case, we send a conditional request
// instead of the normal non-conditional request.
DebugTxn("http_trans", "[build_request] "
"request not like cacheable and conditional headers not removed");
}
}
if (s->http_config_param->send_100_continue_response) {
HttpTransactHeaders::remove_100_continue_headers(s, outgoing_request);
DebugTxn("http_trans", "[build_request] request expect 100-continue headers removed");
}
s->request_sent_time = ink_cluster_time();
s->current.now = s->request_sent_time;
// The assert is backwards in this case because request is being (re)sent.
ink_assert(s->request_sent_time >= s->response_received_time);
DebugTxn("http_trans", "[build_request] request_sent_time: %" PRId64, (int64_t)s->request_sent_time);
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", outgoing_request, s->state_machine_id, "Proxy's Request");
HTTP_INCREMENT_DYN_STAT(http_outgoing_requests_stat);
}
// build a (status_code) response based upon the given info
void
HttpTransact::build_response(State *s, HTTPHdr *base_response, HTTPHdr *outgoing_response, HTTPVersion outgoing_version)
{
build_response(s, base_response, outgoing_response, outgoing_version, HTTP_STATUS_NONE, NULL);
return;
}
void
HttpTransact::build_response(State *s, HTTPHdr *outgoing_response, HTTPVersion outgoing_version, HTTPStatus status_code,
const char *reason_phrase)
{
build_response(s, NULL, outgoing_response, outgoing_version, status_code, reason_phrase);
return;
}
void
HttpTransact::build_response(State *s, HTTPHdr *base_response, HTTPHdr *outgoing_response, HTTPVersion outgoing_version,
HTTPStatus status_code, const char *reason_phrase)
{
if (reason_phrase == NULL) {
reason_phrase = http_hdr_reason_lookup(status_code);
}
if (base_response == NULL) {
HttpTransactHeaders::build_base_response(outgoing_response, status_code, reason_phrase, strlen(reason_phrase), s->current.now);
} else {
if ((status_code == HTTP_STATUS_NONE) || (status_code == base_response->status_get())) {
HttpTransactHeaders::copy_header_fields(base_response, outgoing_response, s->txn_conf->fwd_proxy_auth_to_parent);
if (s->txn_conf->insert_age_in_response) {
HttpTransactHeaders::insert_time_and_age_headers_in_response(s->request_sent_time, s->response_received_time,
s->current.now, base_response, outgoing_response);
}
// Note: We need to handle the "Content-Length" header first here
// since handle_content_length_header()
// determines whether we accept origin server's content-length.
// We need to have made a decision regard the content-length
// before processing the keep_alive headers
//
handle_content_length_header(s, outgoing_response, base_response);
} else {
switch (status_code) {
case HTTP_STATUS_NOT_MODIFIED:
HttpTransactHeaders::build_base_response(outgoing_response, status_code, reason_phrase, strlen(reason_phrase),
s->current.now);
// According to RFC 2616, Section 10.3.5,
// a 304 response MUST contain Date header,
// Etag and/or Content-location header,
// and Expires, Cache-control, and Vary
// (if they might be changed).
// Since a proxy doesn't know if a header differs from
// a user agent's cached document or not, all are sent.
{
static const char *field_name[] = {MIME_FIELD_ETAG, MIME_FIELD_CONTENT_LOCATION, MIME_FIELD_EXPIRES,
MIME_FIELD_CACHE_CONTROL, MIME_FIELD_VARY};
static int field_len[] = {MIME_LEN_ETAG, MIME_LEN_CONTENT_LOCATION, MIME_LEN_EXPIRES, MIME_LEN_CACHE_CONTROL,
MIME_LEN_VARY};
static uint64_t field_presence[] = {MIME_PRESENCE_ETAG, MIME_PRESENCE_CONTENT_LOCATION, MIME_PRESENCE_EXPIRES,
MIME_PRESENCE_CACHE_CONTROL, MIME_PRESENCE_VARY};
MIMEField *field;
int len;
const char *value;
for (size_t i = 0; i < sizeof(field_len) / sizeof(field_len[0]); i++) {
if (base_response->presence(field_presence[i])) {
field = base_response->field_find(field_name[i], field_len[i]);
ink_assert(field != NULL);
value = field->value_get(&len);
outgoing_response->value_append(field_name[i], field_len[i], value, len, 0);
}
}
}
break;
case HTTP_STATUS_PRECONDITION_FAILED:
// fall through
case HTTP_STATUS_RANGE_NOT_SATISFIABLE:
HttpTransactHeaders::build_base_response(outgoing_response, status_code, reason_phrase, strlen(reason_phrase),
s->current.now);
break;
default:
// ink_assert(!"unexpected status code in build_response()");
break;
}
}
}
// the following is done whether base_response == NULL or not
// If the response is prohibited from containing a body,
// we know the content length is trustable for keep-alive
if (is_response_body_precluded(status_code, s->method)) {
s->hdr_info.trust_response_cl = true;
s->hdr_info.response_content_length = 0;
s->client_info.transfer_encoding = HttpTransact::NO_TRANSFER_ENCODING;
s->server_info.transfer_encoding = HttpTransact::NO_TRANSFER_ENCODING;
}
handle_response_keep_alive_headers(s, outgoing_version, outgoing_response);
if (s->next_hop_scheme < 0) {
s->next_hop_scheme = URL_WKSIDX_HTTP;
}
// Add HSTS header (Strict-Transport-Security) if max-age is set and the request was https
if (s->orig_scheme == URL_WKSIDX_HTTPS && s->txn_conf->proxy_response_hsts_max_age >= 0) {
Debug("http_hdrs", "hsts max-age=%" PRId64, s->txn_conf->proxy_response_hsts_max_age);
HttpTransactHeaders::insert_hsts_header_in_response(s, outgoing_response);
}
if (s->txn_conf->insert_response_via_string) {
HttpTransactHeaders::insert_via_header_in_response(s, outgoing_response);
}
HttpTransactHeaders::convert_response(outgoing_version, outgoing_response);
// process reverse mappings on the location header
// TS-1364: do this regardless of response code
response_url_remap(outgoing_response);
if (s->http_config_param->enable_http_stats) {
HttpTransactHeaders::generate_and_set_squid_codes(outgoing_response, s->via_string, &s->squid_codes);
}
HttpTransactHeaders::add_server_header_to_response(s->txn_conf, outgoing_response);
// auth-response update
// if (!s->state_machine->authAdapter.disabled()) {
// s->state_machine->authAdapter.UpdateResponseHeaders(outgoing_response);
// }
if (!s->cop_test_page && is_debug_tag_set("http_hdrs")) {
if (base_response) {
DUMP_HEADER("http_hdrs", base_response, s->state_machine_id, "Base Header for Building Response");
}
DUMP_HEADER("http_hdrs", outgoing_response, s->state_machine_id, "Proxy's Response 2");
}
return;
}
//////////////////////////////////////////////////////////////////////////////
//
// void HttpTransact::build_error_response(
// State *s,
// HTTPStatus status_code,
// char *reason_phrase_or_null,
// char *error_body_type,
// char *format, ...)
//
// This method sets the requires state for an error reply, including
// the error text, status code, reason phrase, and reply headers. The
// caller calls the method with the HttpTransact::State <s>, the
// HTTP status code <status_code>, a user-specified reason phrase
// string (or NULL) <reason_phrase_or_null>, and a printf-like
// text format and arguments which are appended to the error text.
//
// The <error_body_type> is the error message type, as specified by
// the HttpBodyFactory customized error page system.
//
// If the descriptive text <format> is not NULL or "", it is also
// added to the error text body as descriptive text in the error body.
// If <reason_phrase_or_null> is NULL, the default HTTP reason phrase
// is used. This routine DOES NOT check for buffer overflows. The
// caller should keep the messages small to be sure the error text
// fits in the error buffer (ok, it's nasty, but at least I admit it!).
//
//////////////////////////////////////////////////////////////////////////////
void
HttpTransact::build_error_response(State *s, HTTPStatus status_code, const char *reason_phrase_or_null, const char *error_body_type,
const char *format, ...)
{
va_list ap;
const char *reason_phrase;
char *url_string;
char body_language[256], body_type[256];
if (NULL == error_body_type) {
error_body_type = "default";
}
////////////////////////////////////////////////////////////
// get the url --- remember this is dynamically allocated //
////////////////////////////////////////////////////////////
if (s->hdr_info.client_request.valid()) {
url_string = s->hdr_info.client_request.url_string_get(&s->arena);
} else {
url_string = NULL;
}
// Make sure that if this error occured before we initailzied the state variables that we do now.
initialize_state_variables_from_request(s, &s->hdr_info.client_request);
//////////////////////////////////////////////////////
// If there is a request body, we must disable //
// keep-alive to prevent the body being read as //
// the next header (unless we've already drained //
// which we do for NTLM auth) //
//////////////////////////////////////////////////////
if (status_code == HTTP_STATUS_REQUEST_TIMEOUT || s->hdr_info.client_request.get_content_length() != 0 ||
s->client_info.transfer_encoding == HttpTransact::CHUNKED_ENCODING) {
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
} else {
// We don't have a request body. Since we are
// generating the error, we know we can trust
// the content-length
s->hdr_info.trust_response_cl = true;
}
// If transparent and the forward server connection looks unhappy don't
// keep alive the ua connection.
if ((s->state_machine->ua_session && s->state_machine->ua_session->is_outbound_transparent()) &&
(status_code == HTTP_STATUS_INTERNAL_SERVER_ERROR || status_code == HTTP_STATUS_GATEWAY_TIMEOUT ||
status_code == HTTP_STATUS_BAD_GATEWAY || status_code == HTTP_STATUS_SERVICE_UNAVAILABLE)) {
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
}
switch (status_code) {
case HTTP_STATUS_BAD_REQUEST:
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_ERROR);
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_HEADER_SYNTAX);
break;
case HTTP_STATUS_BAD_GATEWAY:
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_CONNECTION);
break;
case HTTP_STATUS_GATEWAY_TIMEOUT:
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_TIMEOUT);
break;
case HTTP_STATUS_NOT_FOUND:
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_SERVER);
break;
case HTTP_STATUS_FORBIDDEN:
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_ERROR);
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_FORBIDDEN);
break;
case HTTP_STATUS_HTTPVER_NOT_SUPPORTED:
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_ERROR);
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_SERVER);
break;
case HTTP_STATUS_INTERNAL_SERVER_ERROR:
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_DNS_FAILURE);
break;
case HTTP_STATUS_MOVED_TEMPORARILY:
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_MOVED_TEMPORARILY);
break;
case HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED:
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_ERROR);
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_AUTHORIZATION);
break;
case HTTP_STATUS_UNAUTHORIZED:
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_ERROR);
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_AUTHORIZATION);
break;
default:
break;
}
reason_phrase = (reason_phrase_or_null ? reason_phrase_or_null : (char *)(http_hdr_reason_lookup(status_code)));
if (unlikely(!reason_phrase)) {
reason_phrase = "Unknown HTTP Status";
// set the source to internal so that chunking is handled correctly
}
s->source = SOURCE_INTERNAL;
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, status_code, reason_phrase);
if (status_code == HTTP_STATUS_SERVICE_UNAVAILABLE) {
if (s->pCongestionEntry != NULL) {
int ret_tmp;
int retry_after = s->pCongestionEntry->client_retry_after();
s->congestion_control_crat = retry_after;
if (s->hdr_info.client_response.value_get(MIME_FIELD_RETRY_AFTER, MIME_LEN_RETRY_AFTER, &ret_tmp) == NULL) {
s->hdr_info.client_response.value_set_int(MIME_FIELD_RETRY_AFTER, MIME_LEN_RETRY_AFTER, retry_after);
}
}
}
if (status_code == HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED && s->method == HTTP_WKSIDX_CONNECT &&
s->hdr_info.client_response.presence(MIME_PRESENCE_PROXY_CONNECTION)) {
int has_ua_msie = 0;
int user_agent_value_len, slen;
const char *user_agent_value, *c, *e;
user_agent_value = s->hdr_info.client_request.value_get(MIME_FIELD_USER_AGENT, MIME_LEN_USER_AGENT, &user_agent_value_len);
if (user_agent_value && user_agent_value_len >= 4) {
c = user_agent_value;
e = c + user_agent_value_len - 4;
while (1) {
slen = (int)(e - c);
c = (const char *)memchr(c, 'M', slen);
if (c == NULL || (e - c) < 3) {
break;
}
if ((c[1] == 'S') && (c[2] == 'I') && (c[3] == 'E')) {
has_ua_msie = 1;
break;
}
c++;
}
}
if (has_ua_msie) {
s->hdr_info.client_response.value_set(MIME_FIELD_PROXY_CONNECTION, MIME_LEN_PROXY_CONNECTION, "close", 5);
}
}
// Add a bunch of headers to make sure that caches between
// the Traffic Server and the client do not cache the error
// page.
s->hdr_info.client_response.value_set(MIME_FIELD_CACHE_CONTROL, MIME_LEN_CACHE_CONTROL, "no-store", 8);
// Make sure there are no Expires and Last-Modified headers.
s->hdr_info.client_response.field_delete(MIME_FIELD_EXPIRES, MIME_LEN_EXPIRES);
s->hdr_info.client_response.field_delete(MIME_FIELD_LAST_MODIFIED, MIME_LEN_LAST_MODIFIED);
if ((status_code == HTTP_STATUS_TEMPORARY_REDIRECT || status_code == HTTP_STATUS_MOVED_TEMPORARILY ||
status_code == HTTP_STATUS_MOVED_PERMANENTLY) &&
s->remap_redirect) {
s->hdr_info.client_response.value_set(MIME_FIELD_LOCATION, MIME_LEN_LOCATION, s->remap_redirect, strlen(s->remap_redirect));
}
////////////////////////////////////////////////////////////////////
// create the error message using the "body factory", which will //
// build a customized error message if available, or generate the //
// old style internal defaults otherwise --- the body factory //
// supports language targeting using the Accept-Language header //
////////////////////////////////////////////////////////////////////
int64_t len;
char *new_msg;
va_start(ap, format);
new_msg = body_factory->fabricate_with_old_api(error_body_type, s, 8192, &len, body_language, sizeof(body_language), body_type,
sizeof(body_type), format, ap);
va_end(ap);
// After the body factory is called, a new "body" is allocated, and we must replace it. It is
// unfortunate that there's no way to avoid this fabrication even when there is no substitutions...
s->free_internal_msg_buffer();
s->internal_msg_buffer = new_msg;
s->internal_msg_buffer_size = len;
s->internal_msg_buffer_fast_allocator_size = -1;
s->hdr_info.client_response.value_set(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, body_type, strlen(body_type));
s->hdr_info.client_response.value_set(MIME_FIELD_CONTENT_LANGUAGE, MIME_LEN_CONTENT_LANGUAGE, body_language,
strlen(body_language));
////////////////////////////////////////
// log a description in the error log //
////////////////////////////////////////
if (s->current.state == CONNECTION_ERROR) {
char *reason_buffer;
int buf_len = sizeof(char) * (strlen(get_error_string(s->cause_of_death_errno)) + 50);
reason_buffer = (char *)alloca(buf_len);
snprintf(reason_buffer, buf_len, "Connect Error <%s/%d>", get_error_string(s->cause_of_death_errno), s->cause_of_death_errno);
reason_phrase = reason_buffer;
}
if (s->http_config_param->errors_log_error_pages && status_code >= HTTP_STATUS_BAD_REQUEST) {
char ip_string[INET6_ADDRSTRLEN];
Log::error("RESPONSE: sent %s status %d (%s) for '%s'", ats_ip_ntop(&s->client_info.src_addr.sa, ip_string, sizeof(ip_string)),
status_code, reason_phrase, (url_string ? url_string : "<none>"));
}
if (url_string) {
s->arena.str_free(url_string);
}
s->next_action = SM_ACTION_SEND_ERROR_CACHE_NOOP;
return;
}
void
HttpTransact::build_redirect_response(State *s)
{
DebugTxn("http_redirect", "[HttpTransact::build_redirect_response]");
URL *u;
const char *old_host;
int old_host_len;
const char *new_url = NULL;
int new_url_len;
char *to_free = NULL;
char body_language[256], body_type[256];
HTTPStatus status_code = HTTP_STATUS_MOVED_TEMPORARILY;
char *reason_phrase = (char *)(http_hdr_reason_lookup(status_code));
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, status_code, reason_phrase);
//////////////////////////////////////////////////////////
// figure out what new url should be. this little hack //
// inserts expanded hostname into old url in order to //
// get scheme information, then puts the old url back. //
//////////////////////////////////////////////////////////
u = s->hdr_info.client_request.url_get();
old_host = u->host_get(&old_host_len);
u->host_set(s->dns_info.lookup_name, strlen(s->dns_info.lookup_name));
new_url = to_free = u->string_get(&s->arena, &new_url_len);
if (new_url == NULL) {
new_url = "";
}
u->host_set(old_host, old_host_len);
//////////////////////////
// set redirect headers //
//////////////////////////
HTTPHdr *h = &s->hdr_info.client_response;
if (s->txn_conf->insert_response_via_string) {
const char pa[] = "Proxy-agent";
h->value_append(pa, sizeof(pa) - 1, s->http_config_param->proxy_response_via_string,
s->http_config_param->proxy_response_via_string_len);
}
h->value_set(MIME_FIELD_LOCATION, MIME_LEN_LOCATION, new_url, new_url_len);
//////////////////////////
// set descriptive text //
//////////////////////////
s->free_internal_msg_buffer();
s->internal_msg_buffer_fast_allocator_size = -1;
s->internal_msg_buffer = body_factory->fabricate_with_old_api_build_va(
"redirect#moved_temporarily", s, 8192, &s->internal_msg_buffer_size, body_language, sizeof(body_language), body_type,
sizeof(body_type), "%s <a href=\"%s\">%s</a>. %s.", "The document you requested is now", new_url, new_url,
"Please update your documents and bookmarks accordingly", NULL);
h->set_content_length(s->internal_msg_buffer_size);
h->value_set(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, "text/html", 9);
s->arena.str_free(to_free);
}
void
HttpTransact::build_upgrade_response(State *s)
{
DebugTxn("http_upgrade", "[HttpTransact::build_upgrade_response]");
// 101 Switching Protocols
HTTPStatus status_code = HTTP_STATUS_SWITCHING_PROTOCOL;
const char *reason_phrase = http_hdr_reason_lookup(status_code);
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, status_code, reason_phrase);
//////////////////////////
// set upgrade headers //
//////////////////////////
HTTPHdr *h = &s->hdr_info.client_response;
h->value_set(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION, "Upgrade", strlen("Upgrade"));
h->value_set(MIME_FIELD_UPGRADE, MIME_LEN_UPGRADE, MIME_UPGRADE_H2C_TOKEN, strlen(MIME_UPGRADE_H2C_TOKEN));
}
const char *
HttpTransact::get_error_string(int erno)
{
if (erno >= 0) {
return (strerror(erno));
} else {
switch (-erno) {
case ENET_THROTTLING:
return ("throttling");
case ESOCK_DENIED:
return ("socks error - denied");
case ESOCK_TIMEOUT:
return ("socks error - timeout");
case ESOCK_NO_SOCK_SERVER_CONN:
return ("socks error - no server connection");
// this assumes that the following case occurs
// when HttpSM.cc::state_origin_server_read_response
// receives an HTTP_EVENT_EOS. (line 1729 in HttpSM.cc,
// version 1.145.2.13.2.57)
case UNKNOWN_INTERNAL_ERROR:
return ("internal error - server connection terminated");
default:
return ("");
}
}
}
ink_time_t
ink_cluster_time(void)
{
int highest_delta;
ink_time_t local_time;
local_time = Thread::get_hrtime() / HRTIME_SECOND;
highest_delta = (int)HttpConfig::m_master.cluster_time_delta;
// highest_delta =
// lmgmt->record_data->readInteger("proxy.process.http.cluster_delta",
// &found);
// if (! found) {
// ink_assert(!"Highest delta config value not found!");
// highest_delta = 0L;
// }
Debug("http_trans", "[ink_cluster_time] local: %" PRId64 ", highest_delta: %d, cluster: %" PRId64, (int64_t)local_time,
highest_delta, (int64_t)(local_time + (ink_time_t)highest_delta));
ink_assert(highest_delta >= 0);
return local_time + (ink_time_t)highest_delta;
}
//
// The stat functions
//
void
HttpTransact::histogram_response_document_size(State *s, int64_t doc_size)
{
if (doc_size >= 0 && doc_size <= 100) {
HTTP_INCREMENT_DYN_STAT(http_response_document_size_100_stat);
} else if (doc_size <= 1024) {
HTTP_INCREMENT_DYN_STAT(http_response_document_size_1K_stat);
} else if (doc_size <= 3072) {
HTTP_INCREMENT_DYN_STAT(http_response_document_size_3K_stat);
} else if (doc_size <= 5120) {
HTTP_INCREMENT_DYN_STAT(http_response_document_size_5K_stat);
} else if (doc_size <= 10240) {
HTTP_INCREMENT_DYN_STAT(http_response_document_size_10K_stat);
} else if (doc_size <= 1048576) {
HTTP_INCREMENT_DYN_STAT(http_response_document_size_1M_stat);
} else {
HTTP_INCREMENT_DYN_STAT(http_response_document_size_inf_stat);
}
return;
}
void
HttpTransact::histogram_request_document_size(State *s, int64_t doc_size)
{
if (doc_size >= 0 && doc_size <= 100) {
HTTP_INCREMENT_DYN_STAT(http_request_document_size_100_stat);
} else if (doc_size <= 1024) {
HTTP_INCREMENT_DYN_STAT(http_request_document_size_1K_stat);
} else if (doc_size <= 3072) {
HTTP_INCREMENT_DYN_STAT(http_request_document_size_3K_stat);
} else if (doc_size <= 5120) {
HTTP_INCREMENT_DYN_STAT(http_request_document_size_5K_stat);
} else if (doc_size <= 10240) {
HTTP_INCREMENT_DYN_STAT(http_request_document_size_10K_stat);
} else if (doc_size <= 1048576) {
HTTP_INCREMENT_DYN_STAT(http_request_document_size_1M_stat);
} else {
HTTP_INCREMENT_DYN_STAT(http_request_document_size_inf_stat);
}
return;
}
void
HttpTransact::user_agent_connection_speed(State *s, ink_hrtime transfer_time, int64_t nbytes)
{
float bytes_per_hrtime = (transfer_time == 0) ? (nbytes) : ((float)nbytes / (float)(int64_t)transfer_time);
int bytes_per_sec = (int)(bytes_per_hrtime * HRTIME_SECOND);
if (bytes_per_sec <= 100) {
HTTP_INCREMENT_DYN_STAT(http_user_agent_speed_bytes_per_sec_100_stat);
} else if (bytes_per_sec <= 1024) {
HTTP_INCREMENT_DYN_STAT(http_user_agent_speed_bytes_per_sec_1K_stat);
} else if (bytes_per_sec <= 10240) {
HTTP_INCREMENT_DYN_STAT(http_user_agent_speed_bytes_per_sec_10K_stat);
} else if (bytes_per_sec <= 102400) {
HTTP_INCREMENT_DYN_STAT(http_user_agent_speed_bytes_per_sec_100K_stat);
} else if (bytes_per_sec <= 1048576) {
HTTP_INCREMENT_DYN_STAT(http_user_agent_speed_bytes_per_sec_1M_stat);
} else if (bytes_per_sec <= 10485760) {
HTTP_INCREMENT_DYN_STAT(http_user_agent_speed_bytes_per_sec_10M_stat);
} else {
HTTP_INCREMENT_DYN_STAT(http_user_agent_speed_bytes_per_sec_100M_stat);
}
return;
}
/*
* added request_process_time stat for loadshedding foo
*/
void
HttpTransact::client_result_stat(State *s, ink_hrtime total_time, ink_hrtime request_process_time)
{
ClientTransactionResult_t client_transaction_result = CLIENT_TRANSACTION_RESULT_UNDEFINED;
///////////////////////////////////////////////////////
// don't count errors we generated as hits or misses //
///////////////////////////////////////////////////////
if ((s->source == SOURCE_INTERNAL) && (s->hdr_info.client_response.status_get() >= 400)) {
client_transaction_result = CLIENT_TRANSACTION_RESULT_ERROR_OTHER;
}
switch (s->squid_codes.log_code) {
case SQUID_LOG_ERR_CONNECT_FAIL:
HTTP_INCREMENT_DYN_STAT(http_cache_miss_cold_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_ERROR_CONNECT_FAIL;
break;
case SQUID_LOG_TCP_MEM_HIT:
HTTP_INCREMENT_DYN_STAT(http_cache_hit_mem_fresh_stat);
case SQUID_LOG_TCP_HIT:
// It's possible to have two stat's instead of one, if needed.
HTTP_INCREMENT_DYN_STAT(http_cache_hit_fresh_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_HIT_FRESH;
break;
case SQUID_LOG_TCP_REFRESH_HIT:
HTTP_INCREMENT_DYN_STAT(http_cache_hit_reval_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_HIT_REVALIDATED;
break;
case SQUID_LOG_TCP_IMS_HIT:
HTTP_INCREMENT_DYN_STAT(http_cache_hit_ims_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_HIT_FRESH;
break;
case SQUID_LOG_TCP_REF_FAIL_HIT:
HTTP_INCREMENT_DYN_STAT(http_cache_hit_stale_served_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_HIT_FRESH;
break;
case SQUID_LOG_TCP_MISS:
if ((GET_VIA_STRING(VIA_CACHE_RESULT) == VIA_IN_CACHE_NOT_ACCEPTABLE) || (GET_VIA_STRING(VIA_CACHE_RESULT) == VIA_CACHE_MISS)) {
HTTP_INCREMENT_DYN_STAT(http_cache_miss_cold_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_MISS_COLD;
} else {
// FIX: what case is this for? can it ever happen?
HTTP_INCREMENT_DYN_STAT(http_cache_miss_uncacheable_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_MISS_UNCACHABLE;
}
break;
case SQUID_LOG_TCP_REFRESH_MISS:
HTTP_INCREMENT_DYN_STAT(http_cache_miss_changed_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_MISS_CHANGED;
break;
case SQUID_LOG_TCP_CLIENT_REFRESH:
HTTP_INCREMENT_DYN_STAT(http_cache_miss_client_no_cache_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_MISS_CLIENT_NO_CACHE;
break;
case SQUID_LOG_TCP_IMS_MISS:
HTTP_INCREMENT_DYN_STAT(http_cache_miss_ims_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_MISS_COLD;
break;
case SQUID_LOG_TCP_SWAPFAIL:
HTTP_INCREMENT_DYN_STAT(http_cache_read_error_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_HIT_FRESH;
break;
case SQUID_LOG_ERR_READ_TIMEOUT:
case SQUID_LOG_TCP_DENIED:
// No cache result due to error
client_transaction_result = CLIENT_TRANSACTION_RESULT_ERROR_OTHER;
break;
default:
// FIX: What is the conditional below doing?
// if (s->local_trans_stats[http_cache_lookups_stat].count == 1L)
// HTTP_INCREMENT_DYN_STAT(http_cache_miss_cold_stat);
// FIX: I suspect the following line should not be set here,
// because it overrides the error classification above.
// Commenting out.
// client_transaction_result = CLIENT_TRANSACTION_RESULT_MISS_COLD;
break;
}
//////////////////////////////////////////
// don't count aborts as hits or misses //
//////////////////////////////////////////
if (s->client_info.abort == ABORTED) {
client_transaction_result = CLIENT_TRANSACTION_RESULT_ERROR_ABORT;
} else if (s->client_info.abort == MAYBE_ABORTED) {
client_transaction_result = CLIENT_TRANSACTION_RESULT_ERROR_POSSIBLE_ABORT;
}
// Count the status codes, assuming the client didn't abort (i.e. there is an m_http)
if ((s->source != SOURCE_NONE) && (s->client_info.abort == DIDNOT_ABORT)) {
int status_code = s->hdr_info.client_response.status_get();
switch (status_code) {
case 100:
HTTP_INCREMENT_DYN_STAT(http_response_status_100_count_stat);
break;
case 101:
HTTP_INCREMENT_DYN_STAT(http_response_status_101_count_stat);
break;
case 200:
HTTP_INCREMENT_DYN_STAT(http_response_status_200_count_stat);
break;
case 201:
HTTP_INCREMENT_DYN_STAT(http_response_status_201_count_stat);
break;
case 202:
HTTP_INCREMENT_DYN_STAT(http_response_status_202_count_stat);
break;
case 203:
HTTP_INCREMENT_DYN_STAT(http_response_status_203_count_stat);
break;
case 204:
HTTP_INCREMENT_DYN_STAT(http_response_status_204_count_stat);
break;
case 205:
HTTP_INCREMENT_DYN_STAT(http_response_status_205_count_stat);
break;
case 206:
HTTP_INCREMENT_DYN_STAT(http_response_status_206_count_stat);
break;
case 300:
HTTP_INCREMENT_DYN_STAT(http_response_status_300_count_stat);
break;
case 301:
HTTP_INCREMENT_DYN_STAT(http_response_status_301_count_stat);
break;
case 302:
HTTP_INCREMENT_DYN_STAT(http_response_status_302_count_stat);
break;
case 303:
HTTP_INCREMENT_DYN_STAT(http_response_status_303_count_stat);
break;
case 304:
HTTP_INCREMENT_DYN_STAT(http_response_status_304_count_stat);
break;
case 305:
HTTP_INCREMENT_DYN_STAT(http_response_status_305_count_stat);
break;
case 307:
HTTP_INCREMENT_DYN_STAT(http_response_status_307_count_stat);
break;
case 400:
HTTP_INCREMENT_DYN_STAT(http_response_status_400_count_stat);
break;
case 401:
HTTP_INCREMENT_DYN_STAT(http_response_status_401_count_stat);
break;
case 402:
HTTP_INCREMENT_DYN_STAT(http_response_status_402_count_stat);
break;
case 403:
HTTP_INCREMENT_DYN_STAT(http_response_status_403_count_stat);
break;
case 404:
HTTP_INCREMENT_DYN_STAT(http_response_status_404_count_stat);
break;
case 405:
HTTP_INCREMENT_DYN_STAT(http_response_status_405_count_stat);
break;
case 406:
HTTP_INCREMENT_DYN_STAT(http_response_status_406_count_stat);
break;
case 407:
HTTP_INCREMENT_DYN_STAT(http_response_status_407_count_stat);
break;
case 408:
HTTP_INCREMENT_DYN_STAT(http_response_status_408_count_stat);
break;
case 409:
HTTP_INCREMENT_DYN_STAT(http_response_status_409_count_stat);
break;
case 410:
HTTP_INCREMENT_DYN_STAT(http_response_status_410_count_stat);
break;
case 411:
HTTP_INCREMENT_DYN_STAT(http_response_status_411_count_stat);
break;
case 412:
HTTP_INCREMENT_DYN_STAT(http_response_status_412_count_stat);
break;
case 413:
HTTP_INCREMENT_DYN_STAT(http_response_status_413_count_stat);
break;
case 414:
HTTP_INCREMENT_DYN_STAT(http_response_status_414_count_stat);
break;
case 415:
HTTP_INCREMENT_DYN_STAT(http_response_status_415_count_stat);
break;
case 416:
HTTP_INCREMENT_DYN_STAT(http_response_status_416_count_stat);
break;
case 500:
HTTP_INCREMENT_DYN_STAT(http_response_status_500_count_stat);
break;
case 501:
HTTP_INCREMENT_DYN_STAT(http_response_status_501_count_stat);
break;
case 502:
HTTP_INCREMENT_DYN_STAT(http_response_status_502_count_stat);
break;
case 503:
HTTP_INCREMENT_DYN_STAT(http_response_status_503_count_stat);
break;
case 504:
HTTP_INCREMENT_DYN_STAT(http_response_status_504_count_stat);
break;
case 505:
HTTP_INCREMENT_DYN_STAT(http_response_status_505_count_stat);
break;
default:
break;
}
switch (status_code / 100) {
case 1:
HTTP_INCREMENT_DYN_STAT(http_response_status_1xx_count_stat);
break;
case 2:
HTTP_INCREMENT_DYN_STAT(http_response_status_2xx_count_stat);
break;
case 3:
HTTP_INCREMENT_DYN_STAT(http_response_status_3xx_count_stat);
break;
case 4:
HTTP_INCREMENT_DYN_STAT(http_response_status_4xx_count_stat);
break;
case 5:
HTTP_INCREMENT_DYN_STAT(http_response_status_5xx_count_stat);
break;
default:
break;
}
}
// Increment the completed connection count
HTTP_INCREMENT_DYN_STAT(http_completed_requests_stat);
// Set the stat now that we know what happend
ink_hrtime total_msec = ink_hrtime_to_msec(total_time);
ink_hrtime process_msec = ink_hrtime_to_msec(request_process_time);
switch (client_transaction_result) {
case CLIENT_TRANSACTION_RESULT_HIT_FRESH:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_hit_fresh_stat, total_msec);
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_hit_fresh_process_stat, process_msec);
break;
case CLIENT_TRANSACTION_RESULT_HIT_REVALIDATED:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_hit_reval_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_MISS_COLD:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_miss_cold_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_MISS_CHANGED:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_miss_changed_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_MISS_CLIENT_NO_CACHE:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_miss_client_no_cache_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_MISS_UNCACHABLE:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_miss_uncacheable_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_ERROR_ABORT:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_errors_aborts_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_ERROR_POSSIBLE_ABORT:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_errors_possible_aborts_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_ERROR_CONNECT_FAIL:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_errors_connect_failed_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_ERROR_OTHER:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_errors_other_stat, total_msec);
break;
default:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_other_unclassified_stat, total_msec);
// This can happen if a plugin manually sets the status code after an error.
DebugTxn("http", "Unclassified statistic");
break;
}
}
void
HttpTransact::origin_server_connection_speed(State *s, ink_hrtime transfer_time, int64_t nbytes)
{
float bytes_per_hrtime = (transfer_time == 0) ? (nbytes) : ((float)nbytes / (float)(int64_t)transfer_time);
int bytes_per_sec = (int)(bytes_per_hrtime * HRTIME_SECOND);
if (bytes_per_sec <= 100) {
HTTP_INCREMENT_DYN_STAT(http_origin_server_speed_bytes_per_sec_100_stat);
} else if (bytes_per_sec <= 1024) {
HTTP_INCREMENT_DYN_STAT(http_origin_server_speed_bytes_per_sec_1K_stat);
} else if (bytes_per_sec <= 10240) {
HTTP_INCREMENT_DYN_STAT(http_origin_server_speed_bytes_per_sec_10K_stat);
} else if (bytes_per_sec <= 102400) {
HTTP_INCREMENT_DYN_STAT(http_origin_server_speed_bytes_per_sec_100K_stat);
} else if (bytes_per_sec <= 1048576) {
HTTP_INCREMENT_DYN_STAT(http_origin_server_speed_bytes_per_sec_1M_stat);
} else if (bytes_per_sec <= 10485760) {
HTTP_INCREMENT_DYN_STAT(http_origin_server_speed_bytes_per_sec_10M_stat);
} else {
HTTP_INCREMENT_DYN_STAT(http_origin_server_speed_bytes_per_sec_100M_stat);
}
return;
}
void
HttpTransact::update_size_and_time_stats(State *s, ink_hrtime total_time, ink_hrtime user_agent_write_time,
ink_hrtime origin_server_read_time, int user_agent_request_header_size,
int64_t user_agent_request_body_size, int user_agent_response_header_size,
int64_t user_agent_response_body_size, int origin_server_request_header_size,
int64_t origin_server_request_body_size, int origin_server_response_header_size,
int64_t origin_server_response_body_size, int pushed_response_header_size,
int64_t pushed_response_body_size, const TransactionMilestones &milestones)
{
int64_t user_agent_request_size = user_agent_request_header_size + user_agent_request_body_size;
int64_t user_agent_response_size = user_agent_response_header_size + user_agent_response_body_size;
int64_t user_agent_bytes = user_agent_request_size + user_agent_response_size;
int64_t origin_server_request_size = origin_server_request_header_size + origin_server_request_body_size;
int64_t origin_server_response_size = origin_server_response_header_size + origin_server_response_body_size;
int64_t origin_server_bytes = origin_server_request_size + origin_server_response_size;
// Background fill stats
switch (s->state_machine->background_fill) {
case BACKGROUND_FILL_COMPLETED: {
int64_t bg_size = origin_server_response_body_size - user_agent_response_body_size;
bg_size = max((int64_t)0, bg_size);
HTTP_SUM_DYN_STAT(http_background_fill_bytes_completed_stat, bg_size);
break;
}
case BACKGROUND_FILL_ABORTED: {
int64_t bg_size = origin_server_response_body_size - user_agent_response_body_size;
if (bg_size < 0) {
bg_size = 0;
}
HTTP_SUM_DYN_STAT(http_background_fill_bytes_aborted_stat, bg_size);
break;
}
case BACKGROUND_FILL_NONE:
break;
case BACKGROUND_FILL_STARTED:
default:
ink_assert(0);
}
// Bandwidth Savings
switch (s->squid_codes.log_code) {
case SQUID_LOG_TCP_HIT:
case SQUID_LOG_TCP_MEM_HIT:
// It's possible to have two stat's instead of one, if needed.
HTTP_INCREMENT_DYN_STAT(http_tcp_hit_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_hit_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_hit_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_TCP_MISS:
HTTP_INCREMENT_DYN_STAT(http_tcp_miss_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_miss_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_miss_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_TCP_EXPIRED_MISS:
HTTP_INCREMENT_DYN_STAT(http_tcp_expired_miss_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_expired_miss_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_expired_miss_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_TCP_REFRESH_HIT:
HTTP_INCREMENT_DYN_STAT(http_tcp_refresh_hit_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_refresh_hit_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_refresh_hit_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_TCP_REFRESH_MISS:
HTTP_INCREMENT_DYN_STAT(http_tcp_refresh_miss_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_refresh_miss_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_refresh_miss_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_TCP_CLIENT_REFRESH:
HTTP_INCREMENT_DYN_STAT(http_tcp_client_refresh_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_client_refresh_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_client_refresh_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_TCP_IMS_HIT:
HTTP_INCREMENT_DYN_STAT(http_tcp_ims_hit_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_ims_hit_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_ims_hit_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_TCP_IMS_MISS:
HTTP_INCREMENT_DYN_STAT(http_tcp_ims_miss_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_ims_miss_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_ims_miss_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_ERR_CLIENT_ABORT:
HTTP_INCREMENT_DYN_STAT(http_err_client_abort_count_stat);
HTTP_SUM_DYN_STAT(http_err_client_abort_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_err_client_abort_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_ERR_CONNECT_FAIL:
HTTP_INCREMENT_DYN_STAT(http_err_connect_fail_count_stat);
HTTP_SUM_DYN_STAT(http_err_connect_fail_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_err_connect_fail_origin_server_bytes_stat, origin_server_bytes);
break;
default:
HTTP_INCREMENT_DYN_STAT(http_misc_count_stat);
HTTP_SUM_DYN_STAT(http_misc_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_misc_origin_server_bytes_stat, origin_server_bytes);
break;
}
// times
HTTP_SUM_DYN_STAT(http_total_transactions_time_stat, total_time);
// sizes
HTTP_SUM_DYN_STAT(http_user_agent_request_header_total_size_stat, user_agent_request_header_size);
HTTP_SUM_DYN_STAT(http_user_agent_response_header_total_size_stat, user_agent_response_header_size);
HTTP_SUM_DYN_STAT(http_user_agent_request_document_total_size_stat, user_agent_request_body_size);
HTTP_SUM_DYN_STAT(http_user_agent_response_document_total_size_stat, user_agent_response_body_size);
// proxy stats
if (s->current.request_to == HttpTransact::PARENT_PROXY) {
HTTP_SUM_DYN_STAT(http_parent_proxy_request_total_bytes_stat,
origin_server_request_header_size + origin_server_request_body_size);
HTTP_SUM_DYN_STAT(http_parent_proxy_response_total_bytes_stat,
origin_server_response_header_size + origin_server_response_body_size);
HTTP_SUM_DYN_STAT(http_parent_proxy_transaction_time_stat, total_time);
}
// request header zero means the document was cached.
// do not add to stats.
if (origin_server_request_header_size > 0) {
HTTP_SUM_DYN_STAT(http_origin_server_request_header_total_size_stat, origin_server_request_header_size);
HTTP_SUM_DYN_STAT(http_origin_server_response_header_total_size_stat, origin_server_response_header_size);
HTTP_SUM_DYN_STAT(http_origin_server_request_document_total_size_stat, origin_server_request_body_size);
HTTP_SUM_DYN_STAT(http_origin_server_response_document_total_size_stat, origin_server_response_body_size);
}
if (s->method == HTTP_WKSIDX_PUSH) {
HTTP_SUM_DYN_STAT(http_pushed_response_header_total_size_stat, pushed_response_header_size);
HTTP_SUM_DYN_STAT(http_pushed_document_total_size_stat, pushed_response_body_size);
}
histogram_request_document_size(s, user_agent_request_body_size);
histogram_response_document_size(s, user_agent_response_body_size);
if (user_agent_write_time >= 0) {
user_agent_connection_speed(s, user_agent_write_time, user_agent_response_size);
}
if (origin_server_request_header_size > 0 && origin_server_read_time > 0) {
origin_server_connection_speed(s, origin_server_read_time, origin_server_response_size);
}
// update milestones stats
if (http_ua_begin_time_stat) {
HTTP_SUM_DYN_STAT(http_ua_begin_time_stat, milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_BEGIN));
}
if (http_ua_first_read_time_stat) {
HTTP_SUM_DYN_STAT(http_ua_first_read_time_stat, milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_FIRST_READ));
}
if (http_ua_read_header_done_time_stat) {
HTTP_SUM_DYN_STAT(http_ua_read_header_done_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_READ_HEADER_DONE));
}
if (http_ua_begin_write_time_stat) {
HTTP_SUM_DYN_STAT(http_ua_begin_write_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_BEGIN_WRITE));
}
if (http_ua_close_time_stat) {
HTTP_SUM_DYN_STAT(http_ua_close_time_stat, milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_CLOSE));
}
if (http_server_first_connect_time_stat) {
HTTP_SUM_DYN_STAT(http_server_first_connect_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_FIRST_CONNECT));
}
if (http_server_connect_time_stat) {
HTTP_SUM_DYN_STAT(http_server_connect_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_CONNECT));
}
if (http_server_connect_end_time_stat) {
HTTP_SUM_DYN_STAT(http_server_connect_end_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_CONNECT_END));
}
if (http_server_begin_write_time_stat) {
HTTP_SUM_DYN_STAT(http_server_begin_write_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_BEGIN_WRITE));
}
if (http_server_first_read_time_stat) {
HTTP_SUM_DYN_STAT(http_server_first_read_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_FIRST_READ));
}
if (http_server_read_header_done_time_stat) {
HTTP_SUM_DYN_STAT(http_server_read_header_done_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_READ_HEADER_DONE));
}
if (http_server_close_time_stat) {
HTTP_SUM_DYN_STAT(http_server_close_time_stat, milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_CLOSE));
}
if (http_cache_open_read_begin_time_stat) {
HTTP_SUM_DYN_STAT(http_cache_open_read_begin_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_CACHE_OPEN_READ_BEGIN));
}
if (http_cache_open_read_end_time_stat) {
HTTP_SUM_DYN_STAT(http_cache_open_read_end_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_CACHE_OPEN_READ_END));
}
if (http_cache_open_write_begin_time_stat) {
HTTP_SUM_DYN_STAT(http_cache_open_write_begin_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_CACHE_OPEN_WRITE_BEGIN));
}
if (http_cache_open_write_end_time_stat) {
HTTP_SUM_DYN_STAT(http_cache_open_write_end_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_CACHE_OPEN_WRITE_END));
}
if (http_dns_lookup_begin_time_stat) {
HTTP_SUM_DYN_STAT(http_dns_lookup_begin_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_DNS_LOOKUP_BEGIN));
}
if (http_dns_lookup_end_time_stat) {
HTTP_SUM_DYN_STAT(http_dns_lookup_end_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_DNS_LOOKUP_END));
}
if (http_sm_start_time_stat) {
HTTP_SUM_DYN_STAT(http_sm_start_time_stat, milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SM_START));
}
if (http_sm_finish_time_stat) {
HTTP_SUM_DYN_STAT(http_sm_finish_time_stat, milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SM_FINISH));
}
}
void
HttpTransact::delete_warning_value(HTTPHdr *to_warn, HTTPWarningCode warning_code)
{
int w_code = (int)warning_code;
MIMEField *field = to_warn->field_find(MIME_FIELD_WARNING, MIME_LEN_WARNING);
;
// Loop over the values to see if we need to do anything
if (field) {
HdrCsvIter iter;
int valid;
int val_code;
const char *value_str;
int value_len;
MIMEField *new_field = NULL;
val_code = iter.get_first_int(field, &valid);
while (valid) {
if (val_code == w_code) {
// Ok, found the value we're look to delete
// Look over and create a new field
// appending all elements that are not this
// value
val_code = iter.get_first_int(field, &valid);
while (valid) {
if (val_code != warning_code) {
value_str = iter.get_current(&value_len);
if (new_field) {
new_field->value_append(to_warn->m_heap, to_warn->m_mime, value_str, value_len, true);
} else {
new_field = to_warn->field_create();
to_warn->field_value_set(new_field, value_str, value_len);
}
}
val_code = iter.get_next_int(&valid);
}
to_warn->field_delete(MIME_FIELD_WARNING, MIME_LEN_WARNING);
if (new_field) {
new_field->name_set(to_warn->m_heap, to_warn->m_mime, MIME_FIELD_WARNING, MIME_LEN_WARNING);
to_warn->field_attach(new_field);
}
return;
}
val_code = iter.get_next_int(&valid);
}
}
}
void
HttpTransact::change_response_header_because_of_range_request(State *s, HTTPHdr *header)
{
MIMEField *field;
char *reason_phrase;
Debug("http_trans", "Partial content requested, re-calculating content-length");
header->status_set(HTTP_STATUS_PARTIAL_CONTENT);
reason_phrase = (char *)(http_hdr_reason_lookup(HTTP_STATUS_PARTIAL_CONTENT));
header->reason_set(reason_phrase, strlen(reason_phrase));
// set the right Content-Type for multiple entry Range
if (s->num_range_fields > 1) {
field = header->field_find(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE);
if (field != NULL) {
header->field_delete(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE);
}
field = header->field_create(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE);
field->value_append(header->m_heap, header->m_mime, range_type, sizeof(range_type) - 1);
header->field_attach(field);
// TODO: There's a known bug here where the Content-Length is not correct for multi-part
// Range: requests.
header->set_content_length(s->range_output_cl);
} else {
if (s->cache_info.object_read && s->cache_info.object_read->valid()) {
// TODO: It's unclear under which conditions we need to update the Content-Range: header,
// many times it's already set correctly before calling this. For now, always try do it
// when we have the information for it available.
// TODO: Also, it's unclear as to why object_read->valid() is not always true here.
char numbers[RANGE_NUMBERS_LENGTH];
header->field_delete(MIME_FIELD_CONTENT_RANGE, MIME_LEN_CONTENT_RANGE);
field = header->field_create(MIME_FIELD_CONTENT_RANGE, MIME_LEN_CONTENT_RANGE);
snprintf(numbers, sizeof(numbers), "bytes %" PRId64 "-%" PRId64 "/%" PRId64, s->ranges[0]._start, s->ranges[0]._end,
s->cache_info.object_read->object_size_get());
field->value_set(header->m_heap, header->m_mime, numbers, strlen(numbers));
header->field_attach(field);
}
// Always update the Content-Length: header.
header->set_content_length(s->range_output_cl);
}
}
#if TS_HAS_TESTS
void forceLinkRegressionHttpTransact();
void
forceLinkRegressionHttpTransactCaller()
{
forceLinkRegressionHttpTransact();
}
#endif
TS-4788: Add state machine ID to HttpTransact debug logs.
/** @file
A brief file description
@section license License
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 "ts/ink_platform.h"
#include <strings.h>
#include <math.h>
#include "HttpTransact.h"
#include "HttpTransactHeaders.h"
#include "HttpSM.h"
#include "HttpCacheSM.h" //Added to get the scope of HttpCacheSM object - YTS Team, yamsat
#include "HttpDebugNames.h"
#include "time.h"
#include "ts/ParseRules.h"
#include "HTTP.h"
#include "HdrUtils.h"
#include "logging/Log.h"
#include "logging/LogUtils.h"
#include "Error.h"
#include "CacheControl.h"
#include "ControlMatcher.h"
#include "ReverseProxy.h"
#include "HttpBodyFactory.h"
#include "StatPages.h"
#include "../IPAllow.h"
#include "I_Machine.h"
static char range_type[] = "multipart/byteranges; boundary=RANGE_SEPARATOR";
#define RANGE_NUMBERS_LENGTH 60
#define TRANSACT_REMEMBER(_s, _e, _d) \
{ \
HttpSM *sm = (_s)->state_machine; \
sm->history[sm->history_pos % HISTORY_SIZE].file = __FILE__; \
sm->history[sm->history_pos % HISTORY_SIZE].line = __LINE__; \
sm->history[sm->history_pos % HISTORY_SIZE].event = _e; \
sm->history[sm->history_pos % HISTORY_SIZE].data = (void *)_d; \
sm->history_pos += 1; \
}
#define DebugTxn(tag, fmt, ...) \
DebugSpecific((s->state_machine->debug_on), tag, "[%" PRId64 "] " fmt, s->state_machine->sm_id, ##__VA_ARGS__)
extern HttpBodyFactory *body_factory;
inline static bool
is_localhost(const char *name, int len)
{
static const char local[] = "127.0.0.1";
return (len == (sizeof(local) - 1)) && (memcmp(name, local, len) == 0);
}
inline static void
simple_or_unavailable_server_retry(HttpTransact::State *s)
{
HTTP_RELEASE_ASSERT(!s->parent_result.parent_is_proxy());
// reponse is from a parent origin server.
HTTPStatus server_response = http_hdr_status_get(s->hdr_info.server_response.m_http);
DebugTxn("http_trans", "[simple_or_unavailabe_server_retry] server_response = %d, simple_retry_attempts: %d, numParents:%d ",
server_response, s->current.simple_retry_attempts, s->parent_params->numParents(&s->parent_result));
// simple retry is enabled, 0x1
if ((s->parent_result.retry_type() & PARENT_RETRY_SIMPLE) &&
s->current.simple_retry_attempts < s->parent_result.max_retries(PARENT_RETRY_SIMPLE) &&
server_response == HTTP_STATUS_NOT_FOUND) {
DebugTxn("parent_select", "RECEIVED A SIMPLE RETRY RESPONSE");
if (s->current.simple_retry_attempts < s->parent_params->numParents(&s->parent_result)) {
s->current.state = HttpTransact::PARENT_ORIGIN_RETRY;
s->current.retry_type = PARENT_RETRY_SIMPLE;
return;
} else {
DebugTxn("http_trans", "PARENT_RETRY_SIMPLE: retried all parents, send response to client.");
return;
}
}
// unavailable server retry is enabled 0x2
else if ((s->parent_result.retry_type() & PARENT_RETRY_UNAVAILABLE_SERVER) &&
s->current.unavailable_server_retry_attempts < s->parent_result.max_retries(PARENT_RETRY_UNAVAILABLE_SERVER) &&
s->parent_result.response_is_retryable(server_response)) {
DebugTxn("parent_select", "RECEIVED A PARENT_RETRY_UNAVAILABLE_SERVER RESPONSE");
if (s->current.unavailable_server_retry_attempts < s->parent_params->numParents(&s->parent_result)) {
s->current.state = HttpTransact::PARENT_ORIGIN_RETRY;
s->current.retry_type = PARENT_RETRY_UNAVAILABLE_SERVER;
return;
} else {
DebugTxn("http_trans", "PARENT_RETRY_UNAVAILABLE_SERVER: retried all parents, send error to client.");
return;
}
}
}
inline static bool
is_request_conditional(HTTPHdr *header)
{
uint64_t mask = (MIME_PRESENCE_IF_UNMODIFIED_SINCE | MIME_PRESENCE_IF_MODIFIED_SINCE | MIME_PRESENCE_IF_RANGE |
MIME_PRESENCE_IF_MATCH | MIME_PRESENCE_IF_NONE_MATCH);
return (header->presence(mask) &&
(header->method_get_wksidx() == HTTP_WKSIDX_GET || header->method_get_wksidx() == HTTP_WKSIDX_HEAD));
}
static inline bool
is_port_in_range(int port, HttpConfigPortRange *pr)
{
while (pr) {
if (pr->low == -1) {
return true;
} else if ((pr->low <= port) && (pr->high >= port)) {
return true;
}
pr = pr->next;
}
return false;
}
inline static void
update_cache_control_information_from_config(HttpTransact::State *s)
{
getCacheControl(&s->cache_control, &s->request_data, s->txn_conf);
s->cache_info.directives.does_config_permit_lookup &= (s->cache_control.never_cache == false);
s->cache_info.directives.does_config_permit_storing &= (s->cache_control.never_cache == false);
s->cache_info.directives.does_client_permit_storing =
HttpTransact::does_client_request_permit_storing(&s->cache_control, &s->hdr_info.client_request);
s->cache_info.directives.does_client_permit_lookup = HttpTransact::does_client_request_permit_cached_response(
s->txn_conf, &s->cache_control, &s->hdr_info.client_request, s->via_string);
s->cache_info.directives.does_client_permit_dns_storing =
HttpTransact::does_client_request_permit_dns_caching(&s->cache_control, &s->hdr_info.client_request);
if (s->client_info.http_version == HTTPVersion(0, 9)) {
s->cache_info.directives.does_client_permit_lookup = false;
s->cache_info.directives.does_client_permit_storing = false;
}
// Less than 0 means it wasn't overridden, so leave it alone.
if (s->cache_control.cache_responses_to_cookies >= 0) {
s->txn_conf->cache_responses_to_cookies = s->cache_control.cache_responses_to_cookies;
}
}
inline bool
HttpTransact::is_server_negative_cached(State *s)
{
if (s->host_db_info.app.http_data.last_failure != 0 &&
s->host_db_info.app.http_data.last_failure + s->txn_conf->down_server_timeout > s->client_request_time) {
return true;
} else {
// Make sure some nasty clock skew has not happened
// Use the server timeout to set an upperbound as to how far in the
// future we should tolerate bogus last failure times. This sets
// the upper bound to the time that we would ever consider a server
// down to 2*down_server_timeout
if (s->client_request_time + s->txn_conf->down_server_timeout < s->host_db_info.app.http_data.last_failure) {
s->host_db_info.app.http_data.last_failure = 0;
ink_assert(!"extreme clock skew");
return true;
}
return false;
}
}
inline static void
update_current_info(HttpTransact::CurrentInfo *into, HttpTransact::ConnectionAttributes *from, HttpTransact::LookingUp_t who,
int attempts)
{
into->request_to = who;
into->server = from;
into->attempts = attempts;
}
inline static void
update_dns_info(HttpTransact::DNSLookupInfo *dns, HttpTransact::CurrentInfo *from, int attempts, Arena * /* arena ATS_UNUSED */)
{
dns->looking_up = from->request_to;
dns->lookup_name = from->server->name;
dns->attempts = attempts;
}
inline static HTTPHdr *
find_appropriate_cached_resp(HttpTransact::State *s)
{
HTTPHdr *c_resp = NULL;
if (s->cache_info.object_store.valid()) {
c_resp = s->cache_info.object_store.response_get();
if (c_resp != NULL && c_resp->valid()) {
return c_resp;
}
}
ink_assert(s->cache_info.object_read != NULL);
return s->cache_info.object_read->response_get();
}
int response_cacheable_indicated_by_cc(HTTPHdr *response);
inline static bool
is_negative_caching_appropriate(HttpTransact::State *s)
{
if (!s->txn_conf->negative_caching_enabled || !s->hdr_info.server_response.valid()) {
return false;
}
switch (s->hdr_info.server_response.status_get()) {
case HTTP_STATUS_NO_CONTENT:
case HTTP_STATUS_USE_PROXY:
case HTTP_STATUS_BAD_REQUEST:
case HTTP_STATUS_FORBIDDEN:
case HTTP_STATUS_NOT_FOUND:
case HTTP_STATUS_METHOD_NOT_ALLOWED:
case HTTP_STATUS_REQUEST_URI_TOO_LONG:
case HTTP_STATUS_INTERNAL_SERVER_ERROR:
case HTTP_STATUS_NOT_IMPLEMENTED:
case HTTP_STATUS_BAD_GATEWAY:
case HTTP_STATUS_SERVICE_UNAVAILABLE:
case HTTP_STATUS_GATEWAY_TIMEOUT:
return true;
default:
break;
}
return false;
}
inline static HttpTransact::LookingUp_t
find_server_and_update_current_info(HttpTransact::State *s)
{
int host_len;
const char *host = s->hdr_info.client_request.host_get(&host_len);
if (is_localhost(host, host_len)) {
// Do not forward requests to local_host onto a parent.
// I just wanted to do this for cop heartbeats, someone else
// wanted it for all requests to local_host.
s->parent_result.result = PARENT_DIRECT;
} else if (s->method == HTTP_WKSIDX_CONNECT && s->http_config_param->disable_ssl_parenting) {
s->parent_params->findParent(&s->request_data, &s->parent_result);
if (!s->parent_result.is_some() || s->parent_result.is_api_result() || s->parent_result.parent_is_proxy()) {
DebugTxn("http_trans", "request not cacheable, so bypass parent");
s->parent_result.result = PARENT_DIRECT;
}
} else if (s->txn_conf->uncacheable_requests_bypass_parent && s->http_config_param->no_dns_forward_to_parent == 0 &&
!HttpTransact::is_request_cache_lookupable(s)) {
// request not lookupable and cacheable, so bypass parent if the parent is not an origin server.
// Note that the configuration of the proxy as well as the request
// itself affects the result of is_request_cache_lookupable();
// we are assuming both child and parent have similar configuration
// with respect to whether a request is cacheable or not.
// For example, the cache_urls_that_look_dynamic variable.
s->parent_params->findParent(&s->request_data, &s->parent_result);
if (!s->parent_result.is_some() || s->parent_result.is_api_result() || s->parent_result.parent_is_proxy()) {
DebugTxn("http_trans", "request not cacheable, so bypass parent");
s->parent_result.result = PARENT_DIRECT;
}
} else {
switch (s->parent_result.result) {
case PARENT_UNDEFINED:
s->parent_params->findParent(&s->request_data, &s->parent_result);
break;
case PARENT_SPECIFIED:
s->parent_params->nextParent(&s->request_data, &s->parent_result);
// Hack!
// We already have a parent that failed, if we are now told
// to go the origin server, we can only obey this if we
// dns'ed the origin server
if (s->parent_result.result == PARENT_DIRECT && s->http_config_param->no_dns_forward_to_parent != 0) {
ink_assert(!s->server_info.dst_addr.isValid());
s->parent_result.result = PARENT_FAIL;
}
break;
case PARENT_FAIL:
// Check to see if should bypass the parent and go direct
// We can only do this if
// 1) the config permitted us to dns the origin server
// 2) the config permits us
// 3) the parent was not set from API
if (s->http_config_param->no_dns_forward_to_parent == 0 && s->parent_result.bypass_ok() &&
s->parent_result.parent_is_proxy() && !s->parent_params->apiParentExists(&s->request_data)) {
s->parent_result.result = PARENT_DIRECT;
}
break;
default:
ink_assert(0);
// FALL THROUGH
case PARENT_DIRECT:
// // if we have already decided to go direct
// // dont bother calling nextParent.
// // do nothing here, guy.
break;
}
}
switch (s->parent_result.result) {
case PARENT_SPECIFIED:
s->parent_info.name = s->arena.str_store(s->parent_result.hostname, strlen(s->parent_result.hostname));
update_current_info(&s->current, &s->parent_info, HttpTransact::PARENT_PROXY, (s->current.attempts)++);
update_dns_info(&s->dns_info, &s->current, 0, &s->arena);
ink_assert(s->dns_info.looking_up == HttpTransact::PARENT_PROXY);
s->next_hop_scheme = URL_WKSIDX_HTTP;
return HttpTransact::PARENT_PROXY;
case PARENT_FAIL:
// No more parents - need to return an error message
s->current.request_to = HttpTransact::HOST_NONE;
return HttpTransact::HOST_NONE;
case PARENT_DIRECT:
/* fall through */
default:
update_current_info(&s->current, &s->server_info, HttpTransact::ORIGIN_SERVER, (s->current.attempts)++);
update_dns_info(&s->dns_info, &s->current, 0, &s->arena);
ink_assert(s->dns_info.looking_up == HttpTransact::ORIGIN_SERVER);
s->next_hop_scheme = s->scheme;
return HttpTransact::ORIGIN_SERVER;
}
}
inline static bool
do_cookies_prevent_caching(int cookies_conf, HTTPHdr *request, HTTPHdr *response, HTTPHdr *cached_request = NULL)
{
enum CookiesConfig {
COOKIES_CACHE_NONE = 0, // do not cache any responses to cookies
COOKIES_CACHE_ALL = 1, // cache for any content-type (ignore cookies)
COOKIES_CACHE_IMAGES = 2, // cache only for image types
COOKIES_CACHE_ALL_BUT_TEXT = 3, // cache for all but text content-types
COOKIES_CACHE_ALL_BUT_TEXT_EXT = 4 // cache for all but text content-types except with OS response
// without "Set-Cookie" or with "Cache-Control: public"
};
const char *content_type = NULL;
int str_len;
#ifdef DEBUG
ink_assert(request->type_get() == HTTP_TYPE_REQUEST);
ink_assert(response->type_get() == HTTP_TYPE_RESPONSE);
if (cached_request) {
ink_assert(cached_request->type_get() == HTTP_TYPE_REQUEST);
}
#endif
// Can cache all regardless of cookie header - just ignore all cookie headers
if ((CookiesConfig)cookies_conf == COOKIES_CACHE_ALL) {
return false;
}
// It is considered that Set-Cookie headers can be safely ignored
// for non text content types if Cache-Control private is not set.
// This enables a bigger hit rate, which currently outweighs the risk of
// breaking origin servers that truly intend to set a cookie with other
// objects such as images.
// At this time, it is believed that only advertisers do this, and that
// customers won't care about it.
// If the response does not have a Set-Cookie header and
// the response does not have a Cookie header and
// the object is not cached or the request does not have a Cookie header
// then cookies do not prevent caching.
if (!response->presence(MIME_PRESENCE_SET_COOKIE) && !request->presence(MIME_PRESENCE_COOKIE) &&
(cached_request == NULL || !cached_request->presence(MIME_PRESENCE_COOKIE))) {
return false;
}
// Do not cache if cookies option is COOKIES_CACHE_NONE
// and a Cookie is detected
if ((CookiesConfig)cookies_conf == COOKIES_CACHE_NONE) {
return true;
}
// All other options depend on the Content-Type
content_type = response->value_get(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, &str_len);
if ((CookiesConfig)cookies_conf == COOKIES_CACHE_IMAGES) {
if (content_type && str_len >= 5 && memcmp(content_type, "image", 5) == 0) {
// Images can be cached
return false;
}
return true; // do not cache if COOKIES_CACHE_IMAGES && content_type != "image"
}
// COOKIES_CACHE_ALL_BUT_TEXT || COOKIES_CACHE_ALL_BUT_TEXT_EXT
// Note: if the configuration is bad, we consider
// COOKIES_CACHE_ALL_BUT_TEXT to be the default
if (content_type && str_len >= 4 && memcmp(content_type, "text", 4) == 0) { // content type - "text"
// Text objects cannot be cached unless the option is
// COOKIES_CACHE_ALL_BUT_TEXT_EXT.
// Furthermore, if there is a Set-Cookie header, then
// Cache-Control must be set.
if ((CookiesConfig)cookies_conf == COOKIES_CACHE_ALL_BUT_TEXT_EXT &&
((!response->presence(MIME_PRESENCE_SET_COOKIE)) || response->is_cache_control_set(HTTP_VALUE_PUBLIC))) {
return false;
}
return true;
}
return false; // Non text objects can be cached
}
inline static bool
does_method_require_cache_copy_deletion(const HttpConfigParams *http_config_param, const int method)
{
return ((method != HTTP_WKSIDX_GET) &&
(method == HTTP_WKSIDX_DELETE || method == HTTP_WKSIDX_PURGE || method == HTTP_WKSIDX_PUT ||
(http_config_param->cache_post_method != 1 && method == HTTP_WKSIDX_POST)));
}
inline static bool
does_method_effect_cache(int method)
{
return ((method == HTTP_WKSIDX_GET || method == HTTP_WKSIDX_DELETE || method == HTTP_WKSIDX_PURGE || method == HTTP_WKSIDX_PUT ||
method == HTTP_WKSIDX_POST));
}
inline static HttpTransact::StateMachineAction_t
how_to_open_connection(HttpTransact::State *s)
{
ink_assert((s->pending_work == NULL) || (s->current.request_to == HttpTransact::PARENT_PROXY));
// Originally we returned which type of server to open
// Now, however, we may want to issue a cache
// operation first in order to lock the cache
// entry to prevent multiple origin server requests
// for the same document.
// The cache operation that we actually issue, of
// course, depends on the specified "cache_action".
// If there is no cache-action to be issued, just
// connect to the server.
switch (s->cache_info.action) {
case HttpTransact::CACHE_PREPARE_TO_DELETE:
case HttpTransact::CACHE_PREPARE_TO_UPDATE:
case HttpTransact::CACHE_PREPARE_TO_WRITE:
s->transact_return_point = HttpTransact::handle_cache_write_lock;
return HttpTransact::SM_ACTION_CACHE_ISSUE_WRITE;
default:
// This covers:
// CACHE_DO_UNDEFINED, CACHE_DO_NO_ACTION, CACHE_DO_DELETE,
// CACHE_DO_LOOKUP, CACHE_DO_REPLACE, CACHE_DO_SERVE,
// CACHE_DO_SERVE_AND_DELETE, CACHE_DO_SERVE_AND_UPDATE,
// CACHE_DO_UPDATE, CACHE_DO_WRITE, TOTAL_CACHE_ACTION_TYPES
break;
}
if (s->method == HTTP_WKSIDX_CONNECT && s->parent_result.result != PARENT_SPECIFIED) {
s->cdn_saved_next_action = HttpTransact::SM_ACTION_ORIGIN_SERVER_RAW_OPEN;
} else {
s->cdn_saved_next_action = HttpTransact::SM_ACTION_ORIGIN_SERVER_OPEN;
}
// In the following, if url_remap_mode == 2 (URL_REMAP_FOR_OS)
// then do remapping for requests to OS's.
// Whether there is CDN remapping or not, goto SM_ACTION_DNS_LOOKUP;
// after that, it'll goto ORIGIN_SERVER_(RAW_)OPEN as needed.
if ((url_remap_mode == HttpTransact::URL_REMAP_FOR_OS) && (s->current.request_to == HttpTransact::ORIGIN_SERVER) &&
!s->cdn_remap_complete) {
DebugTxn("cdn", "*** START CDN Remapping *** CDN mode = %d", url_remap_mode);
char *remap_redirect = NULL;
int host_len;
const char *host;
// We need to copy the client request into the server request. Why? BUGBUG
s->hdr_info.server_request.url_set(s->hdr_info.client_request.url_get());
// TODO yeah, not sure everything here is correct with redirects
// This probably doesn't work properly, since request_url_remap() is broken.
if (request_url_remap(s, &s->hdr_info.server_request, &remap_redirect)) {
ink_assert(!remap_redirect); // should not redirect in this code
HttpTransact::initialize_state_variables_for_origin_server(s, &s->hdr_info.server_request, true);
DebugTxn("cdn", "Converting proxy request to server request");
// Check whether a Host header field is missing from a 1.0 or 1.1 request.
if (/*outgoing_version != HTTPVersion(0,9) && */
!s->hdr_info.server_request.presence(MIME_PRESENCE_HOST)) {
URL *url = s->hdr_info.server_request.url_get();
host = url->host_get(&host_len);
// Add a ':port' to the HOST header if the request is not going
// to the default port.
int port = url->port_get();
if (port != url_canonicalize_port(URL_TYPE_HTTP, 0)) {
char *buf = (char *)alloca(host_len + 15);
memcpy(buf, host, host_len);
host_len += snprintf(buf + host_len, 15, ":%d", port);
s->hdr_info.server_request.value_set(MIME_FIELD_HOST, MIME_LEN_HOST, buf, host_len);
} else {
s->hdr_info.server_request.value_set(MIME_FIELD_HOST, MIME_LEN_HOST, host, host_len);
}
ats_free(remap_redirect); // This apparently shouldn't happen...
}
// Stripping out the host name from the URL
if (s->current.server == &s->server_info && s->next_hop_scheme == URL_WKSIDX_HTTP) {
DebugTxn("cdn", "Removing host name from URL");
HttpTransactHeaders::remove_host_name_from_url(&s->hdr_info.server_request);
}
} // the URL was remapped
if (is_debug_tag_set("cdn")) {
char *d_url = s->hdr_info.server_request.url_get()->string_get(NULL);
if (d_url) {
DebugTxn("cdn", "URL: %s", d_url);
}
char *d_hst = (char *)s->hdr_info.server_request.value_get(MIME_FIELD_HOST, MIME_LEN_HOST, &host_len);
if (d_hst) {
DebugTxn("cdn", "Host Hdr: %s", d_hst);
}
ats_free(d_url);
}
s->cdn_remap_complete = true; // It doesn't matter if there was an actual remap or not
s->transact_return_point = HttpTransact::OSDNSLookup;
ink_assert(s->next_action);
ink_assert(s->cdn_saved_next_action);
return HttpTransact::SM_ACTION_DNS_LOOKUP;
}
if (!s->already_downgraded) { // false unless downgraded previously (possibly due to HTTP 505)
(&s->hdr_info.server_request)->version_set(HTTPVersion(1, 1));
HttpTransactHeaders::convert_request(s->current.server->http_version, &s->hdr_info.server_request);
}
ink_assert(s->cdn_saved_next_action == HttpTransact::SM_ACTION_ORIGIN_SERVER_OPEN ||
s->cdn_saved_next_action == HttpTransact::SM_ACTION_ORIGIN_SERVER_RAW_OPEN);
return s->cdn_saved_next_action;
}
/*****************************************************************************
*****************************************************************************
**** ****
**** HttpTransact State Machine Handlers ****
**** ****
**** What follow from here on are the state machine handlers - the code ****
**** which is called from HttpSM::set_next_state to specify ****
**** what action the state machine needs to execute next. These ftns ****
**** take as input just the state and set the next_action variable. ****
*****************************************************************************
*****************************************************************************/
void
HttpTransact::BadRequest(State *s)
{
DebugTxn("http_trans", "[BadRequest]"
"parser marked request bad");
bootstrap_state_variables_from_request(s, &s->hdr_info.client_request);
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Invalid HTTP Request", "request#syntax_error", NULL);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
void
HttpTransact::HandleBlindTunnel(State *s)
{
bool inbound_transparent_p = s->state_machine->ua_session->get_netvc()->get_is_transparent();
URL u;
// IpEndpoint dest_addr;
// ip_text_buffer new_host;
DebugTxn("http_trans", "[HttpTransact::HandleBlindTunnel]");
// We've received a request on a port which we blind forward
// For logging purposes we create a fake request
s->hdr_info.client_request.create(HTTP_TYPE_REQUEST);
s->hdr_info.client_request.method_set(HTTP_METHOD_CONNECT, HTTP_LEN_CONNECT);
s->hdr_info.client_request.url_create(&u);
u.scheme_set(URL_SCHEME_TUNNEL, URL_LEN_TUNNEL);
s->hdr_info.client_request.url_set(&u);
// We set the version to 0.9 because once we know where we are going
// this blind ssl tunnel is indistinguishable from a "CONNECT 0.9"
// except for the need to suppression error messages
HTTPVersion ver(0, 9);
s->hdr_info.client_request.version_set(ver);
char new_host[INET6_ADDRSTRLEN];
ats_ip_ntop(s->state_machine->ua_session->get_netvc()->get_local_addr(), new_host, sizeof(new_host));
s->hdr_info.client_request.url_get()->host_set(new_host, strlen(new_host));
s->hdr_info.client_request.url_get()->port_set(s->state_machine->ua_session->get_netvc()->get_local_port());
// Initialize the state vars necessary to sending error responses
bootstrap_state_variables_from_request(s, &s->hdr_info.client_request);
if (is_debug_tag_set("http_trans")) {
int host_len;
const char *host = s->hdr_info.client_request.url_get()->host_get(&host_len);
DebugTxn("http_trans", "[HandleBlindTunnel] destination set to %.*s:%d", host_len, host,
s->hdr_info.client_request.url_get()->port_get());
}
// Now we need to run the url remapping engine to find the where
// this request really goes since we were sent was bound for
// machine we are running on
// Do request_url_remap only if url_remap_mode != URL_REMAP_FOR_OS.
bool url_remap_success = false;
char *remap_redirect = NULL;
if (s->transparent_passthrough) {
url_remap_success = true;
} else if (url_remap_mode == URL_REMAP_DEFAULT || url_remap_mode == URL_REMAP_ALL) {
// TODO: take a look at this
// This probably doesn't work properly, since request_url_remap() is broken.
url_remap_success = request_url_remap(s, &s->hdr_info.client_request, &remap_redirect);
}
// We must have mapping or we will self loop since the this
// request was addressed to us to begin with. Remap directs
// are something used in the normal reverse proxy and if we
// get them here they indicate a very bad misconfiguration!
if (!(inbound_transparent_p || url_remap_success) || remap_redirect != NULL) {
// The error message we send back will be suppressed so
// the only important thing in selecting the error is what
// status code it gets logged as
build_error_response(s, HTTP_STATUS_INTERNAL_SERVER_ERROR, "Port Forwarding Error", "default", NULL);
int host_len;
const char *host = s->hdr_info.client_request.url_get()->host_get(&host_len);
Log::error("Forwarded port error: request with destination %.*s:%d "
"does not have a mapping",
host_len, host, s->hdr_info.client_request.url_get()->port_get());
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
// Set the mode to tunnel so that we don't lookup the cache
s->current.mode = TUNNELLING_PROXY;
// Let the request work it's way through the code and
// we grab it again after the raw connection has been opened
HandleRequest(s);
}
bool
HttpTransact::perform_accept_encoding_filtering(State *s)
{
HttpUserAgent_RegxEntry *uae;
HTTPHdr *client_request;
MIMEField *accept_field;
MIMEField *usragent_field;
char tmp_ua_buf[1024], *c;
char const *u_agent = NULL;
int u_agent_len = 0;
bool retcode = false;
bool ua_match = false;
client_request = &s->hdr_info.client_request;
// Make sense to check Accept-Encoding if UserAgent is present (and matches)
if ((usragent_field = client_request->field_find(MIME_FIELD_USER_AGENT, MIME_LEN_USER_AGENT)) != 0 &&
(u_agent = usragent_field->value_get(&u_agent_len)) != 0 && u_agent_len > 0) {
if (u_agent_len >= (int)sizeof(tmp_ua_buf)) {
u_agent_len = (int)(sizeof(tmp_ua_buf) - 1);
}
memcpy(tmp_ua_buf, u_agent, u_agent_len);
tmp_ua_buf[u_agent_len] = '\0';
// TODO: Do we really want to do these hardcoded checks still?
// Check hardcoded case MSIE>6 & Mozilla>4
if ((c = strstr(tmp_ua_buf, "MSIE")) != NULL) {
if (c[5] >= '7' && c[5] <= '9') {
return false; // Don't change anything for IE > 6
}
ua_match = true;
} else if (!strncasecmp(tmp_ua_buf, "mozilla", 7)) {
if (tmp_ua_buf[8] >= '5' && tmp_ua_buf[8] <= '9') {
return false; // Don't change anything for Mozilla > 4
}
ua_match = true;
}
// Check custom filters
if (!ua_match && HttpConfig::user_agent_list) {
for (uae = HttpConfig::user_agent_list; uae && !ua_match; uae = uae->next) {
switch (uae->stype) {
case HttpUserAgent_RegxEntry::STRTYPE_SUBSTR_CASE: /* .substring, .string */
if (u_agent_len >= uae->user_agent_str_size && !memcmp(tmp_ua_buf, uae->user_agent_str, uae->user_agent_str_size)) {
ua_match = true;
}
break;
case HttpUserAgent_RegxEntry::STRTYPE_SUBSTR_NCASE: /* .substring_ncase, .string_ncase */
if (u_agent_len >= uae->user_agent_str_size && !strncasecmp(uae->user_agent_str, tmp_ua_buf, uae->user_agent_str_size)) {
ua_match = true;
}
break;
case HttpUserAgent_RegxEntry::STRTYPE_REGEXP: /* .regexp POSIX regular expression */
if (uae->regx_valid && !pcre_exec(uae->regx, NULL, tmp_ua_buf, u_agent_len, 0, 0, NULL, 0)) {
ua_match = true;
}
break;
default: /* unknown type in the structure - bad initialization - impossible bug! */
/* I can use ink_error() here since we should shutdown TS immediately */
ink_error("[HttpTransact::perform_accept_encoding_filtering] - get unknown User-Agent string type - bad initialization");
};
}
}
/* If we have correct User-Agent header ....
Just set Accept-Encoding: identity or .... do nothing because
"If no Accept-Encoding field is present in a request, the server MAY assume that the client
will accept any content coding. In this case, if "identity" is one of the available content-codings,
then the server SHOULD use the "identity" content-coding, unless it has additional information that
a different content-coding is meaningful to the client." */
if (ua_match) {
DebugTxn("http_trans", "HttpTransact::ModifyRequest, insert identity Accept-Encoding");
accept_field = client_request->field_find(MIME_FIELD_ACCEPT_ENCODING, MIME_LEN_ACCEPT_ENCODING);
if (!accept_field) {
accept_field = client_request->field_create(MIME_FIELD_ACCEPT_ENCODING, MIME_LEN_ACCEPT_ENCODING);
if (accept_field) {
client_request->field_attach(accept_field);
}
}
if (accept_field) {
client_request->field_value_set(accept_field, HTTP_VALUE_IDENTITY, HTTP_LEN_IDENTITY);
}
}
retcode = true;
} // end of 'user-agent'
return retcode;
}
void
HttpTransact::StartRemapRequest(State *s)
{
if (s->api_skip_all_remapping) {
DebugTxn("http_trans", "API request to skip remapping");
s->hdr_info.client_request.set_url_target_from_host_field();
if (s->is_upgrade_request && s->post_remap_upgrade_return_point) {
TRANSACT_RETURN(SM_ACTION_POST_REMAP_SKIP, s->post_remap_upgrade_return_point);
}
TRANSACT_RETURN(SM_ACTION_POST_REMAP_SKIP, HttpTransact::HandleRequest);
}
DebugTxn("http_trans", "START HttpTransact::StartRemapRequest");
/**
* Check for URL remappings before checking request
* validity or initializing state variables since
* the remappings can insert or change the destination
* host, port and protocol.
**/
HTTPHdr *incoming_request = &s->hdr_info.client_request;
URL *url = incoming_request->url_get();
int host_len, path_len;
const char *host = url->host_get(&host_len);
const char *path = url->path_get(&path_len);
const int port = url->port_get();
const char syntxt[] = "synthetic.txt";
s->cop_test_page = is_localhost(host, host_len) && ((path_len == sizeof(syntxt) - 1) && (memcmp(path, syntxt, path_len) == 0)) &&
port == s->http_config_param->synthetic_port && s->method == HTTP_WKSIDX_GET &&
s->orig_scheme == URL_WKSIDX_HTTP && ats_ip4_addr_cast(&s->client_info.dst_addr.sa) == htonl(INADDR_LOOPBACK);
//////////////////////////////////////////////////////////////////
// FIX: this logic seems awfully convoluted and hard to follow; //
// seems like we could come up with a more elegant and //
// comprehensible design that generalized things //
//////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
// run the remap url-rewriting engine: //
// //
// * the variable <url_remap_success> is set true if //
// the url was rewritten //
// //
// * the variable <remap_redirect> is set to non-NULL if there //
// is a URL provided that the proxy is supposed to redirect //
// requesters of a particular URL to. //
/////////////////////////////////////////////////////////////////
if (is_debug_tag_set("http_chdr_describe") || is_debug_tag_set("http_trans")) {
DebugTxn("http_trans", "Before Remapping:");
obj_describe(s->hdr_info.client_request.m_http, 1);
}
if (url_remap_mode == URL_REMAP_DEFAULT || url_remap_mode == URL_REMAP_ALL) {
if (s->http_config_param->referer_filter_enabled) {
s->filter_mask = URL_REMAP_FILTER_REFERER;
if (s->http_config_param->referer_format_redirect) {
s->filter_mask |= URL_REMAP_FILTER_REDIRECT_FMT;
}
}
}
DebugTxn("http_trans", "END HttpTransact::StartRemapRequest");
TRANSACT_RETURN(SM_ACTION_API_PRE_REMAP, HttpTransact::PerformRemap);
}
void
HttpTransact::PerformRemap(State *s)
{
DebugTxn("http_trans", "Inside PerformRemap");
TRANSACT_RETURN(SM_ACTION_REMAP_REQUEST, HttpTransact::EndRemapRequest);
}
void
HttpTransact::EndRemapRequest(State *s)
{
DebugTxn("http_trans", "START HttpTransact::EndRemapRequest");
HTTPHdr *incoming_request = &s->hdr_info.client_request;
int method = incoming_request->method_get_wksidx();
int host_len;
const char *host = incoming_request->host_get(&host_len);
DebugTxn("http_trans", "EndRemapRequest host is %.*s", host_len, host);
////////////////////////////////////////////////////////////////
// if we got back a URL to redirect to, vector the user there //
////////////////////////////////////////////////////////////////
if (s->remap_redirect != NULL) {
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
if (s->http_return_code == HTTP_STATUS_MOVED_PERMANENTLY) {
build_error_response(s, HTTP_STATUS_MOVED_PERMANENTLY, "Redirect", "redirect#moved_permanently", NULL);
} else {
build_error_response(s, HTTP_STATUS_MOVED_TEMPORARILY, "Redirect", "redirect#moved_temporarily", NULL);
}
ats_free(s->remap_redirect);
s->reverse_proxy = false;
goto done;
}
/////////////////////////////////////////////////////
// Quick HTTP filtering (primary key: http method) //
/////////////////////////////////////////////////////
process_quick_http_filter(s, method);
/////////////////////////////////////////////////////////////////////////
// We must close this connection if client_connection_enabled == false //
/////////////////////////////////////////////////////////////////////////
if (!s->client_connection_enabled) {
build_error_response(s, HTTP_STATUS_FORBIDDEN, "Access Denied", "access#denied", NULL);
s->reverse_proxy = false;
goto done;
}
/////////////////////////////////////////////////////////////////
// Check if remap plugin set HTTP return code and return body //
/////////////////////////////////////////////////////////////////
if (s->http_return_code != HTTP_STATUS_NONE) {
build_error_response(s, s->http_return_code, NULL, NULL, s->internal_msg_buffer_size ? s->internal_msg_buffer : NULL);
s->reverse_proxy = false;
goto done;
}
///////////////////////////////////////////////////////////////
// if no mapping was found, handle the cases where: //
// //
// (1) reverse proxy is on, and no URL host (server request) //
// (2) no mappings are found, but mappings strictly required //
///////////////////////////////////////////////////////////////
if (!s->url_remap_success) {
/**
* It's better to test redirect rules just after url_remap failed
* Or those successfully remapped rules might be redirected
**/
if (handleIfRedirect(s)) {
DebugTxn("http_trans", "END HttpTransact::RemapRequest");
TRANSACT_RETURN(SM_ACTION_INTERNAL_CACHE_NOOP, NULL);
}
if (!s->http_config_param->url_remap_required && !incoming_request->is_target_in_url()) {
s->hdr_info.client_request.set_url_target_from_host_field();
}
/////////////////////////////////////////////////////////
// check for: (1) reverse proxy is on, and no URL host //
/////////////////////////////////////////////////////////
if (s->http_config_param->reverse_proxy_enabled && !s->client_info.is_transparent && !incoming_request->is_target_in_url()) {
/////////////////////////////////////////////////////////
// the url mapping failed, reverse proxy was enabled,
// and the request contains no host:
//
// * if there is an explanatory redirect, send there.
// * if there was no host, send "no host" error.
// * if there was a host, say "not found".
/////////////////////////////////////////////////////////
char *redirect_url = s->http_config_param->reverse_proxy_no_host_redirect;
int redirect_url_len = s->http_config_param->reverse_proxy_no_host_redirect_len;
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
if (redirect_url) { /* there is a redirect url */
build_error_response(s, HTTP_STATUS_MOVED_TEMPORARILY, "Redirect For Explanation", "request#no_host", NULL);
s->hdr_info.client_response.value_set(MIME_FIELD_LOCATION, MIME_LEN_LOCATION, redirect_url, redirect_url_len);
// socket when there is no host. Need to handle DNS failure elsewhere.
} else if (host == NULL) { /* no host */
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Host Header Required", "request#no_host", NULL);
s->squid_codes.log_code = SQUID_LOG_ERR_INVALID_URL;
} else {
build_error_response(s, HTTP_STATUS_NOT_FOUND, "Not Found on Accelerator", "urlrouting#no_mapping", NULL);
s->squid_codes.log_code = SQUID_LOG_ERR_INVALID_URL;
}
s->reverse_proxy = false;
goto done;
} else if (s->http_config_param->url_remap_required && !s->cop_test_page) {
///////////////////////////////////////////////////////
// the url mapping failed, but mappings are strictly //
// required (except for synthetic cop accesses), so //
// return an error message. //
///////////////////////////////////////////////////////
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_NOT_FOUND, "Not Found", "urlrouting#no_mapping", NULL);
s->squid_codes.log_code = SQUID_LOG_ERR_INVALID_URL;
s->reverse_proxy = false;
goto done;
}
} else {
if (s->http_config_param->reverse_proxy_enabled) {
s->req_flavor = REQ_FLAVOR_REVPROXY;
}
}
s->reverse_proxy = true;
s->server_info.is_transparent = s->state_machine->ua_session ? s->state_machine->ua_session->is_outbound_transparent() : false;
done:
// We now set the active-timeout again, since it might have been changed as part of the remap rules.
if (s->state_machine->ua_session) {
s->state_machine->ua_session->get_netvc()->set_active_timeout(HRTIME_SECONDS(s->txn_conf->transaction_active_timeout_in));
}
if (is_debug_tag_set("http_chdr_describe") || is_debug_tag_set("http_trans") || is_debug_tag_set("url_rewrite")) {
DebugTxn("http_trans", "After Remapping:");
obj_describe(s->hdr_info.client_request.m_http, 1);
}
/*
if s->reverse_proxy == false, we can assume remapping failed in some way
-however-
If an API setup a tunnel to fake the origin or proxy's response we will
continue to handle the request (as this was likely the plugin author's intent)
otherwise, 502/404 the request right now. /eric
*/
if (!s->reverse_proxy && s->state_machine->plugin_tunnel_type == HTTP_NO_PLUGIN_TUNNEL) {
DebugTxn("http_trans", "END HttpTransact::EndRemapRequest");
HTTP_INCREMENT_DYN_STAT(http_invalid_client_requests_stat);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
} else {
s->hdr_info.client_response.destroy(); // release the underlying memory.
s->hdr_info.client_response.clear(); // clear the pointers.
DebugTxn("http_trans", "END HttpTransact::EndRemapRequest");
if (s->is_upgrade_request && s->post_remap_upgrade_return_point) {
TRANSACT_RETURN(SM_ACTION_API_POST_REMAP, s->post_remap_upgrade_return_point);
}
TRANSACT_RETURN(SM_ACTION_API_POST_REMAP, HttpTransact::HandleRequest);
}
ink_assert(!"not reached");
}
bool
HttpTransact::handle_upgrade_request(State *s)
{
// Quickest way to determine that this is defintely not an upgrade.
/* RFC 6455 The method of the request MUST be GET, and the HTTP version MUST
be at least 1.1. */
if (!s->hdr_info.client_request.presence(MIME_PRESENCE_UPGRADE) ||
!s->hdr_info.client_request.presence(MIME_PRESENCE_CONNECTION) || s->method != HTTP_WKSIDX_GET ||
s->hdr_info.client_request.version_get() < HTTPVersion(1, 1)) {
return false;
}
MIMEField *upgrade_hdr = s->hdr_info.client_request.field_find(MIME_FIELD_UPGRADE, MIME_LEN_UPGRADE);
MIMEField *connection_hdr = s->hdr_info.client_request.field_find(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION);
StrList connection_hdr_vals;
const char *upgrade_hdr_val = NULL;
int upgrade_hdr_val_len = 0;
if (!upgrade_hdr || !connection_hdr || connection_hdr->value_get_comma_list(&connection_hdr_vals) == 0 ||
(upgrade_hdr_val = upgrade_hdr->value_get(&upgrade_hdr_val_len)) == NULL) {
DebugTxn("http_trans_upgrade", "Transaction wasn't a valid upgrade request, proceeding as a normal HTTP request.");
return false;
}
/*
* In order for this request to be treated as a normal upgrade request we must have a Connection: Upgrade header
* and a Upgrade: header, with a non-empty value, otherwise we just assume it's not an Upgrade Request, after
* we've verified that, we will try to match this upgrade to a known upgrade type such as Websockets.
*/
bool connection_contains_upgrade = false;
// Next, let's validate that the Connection header contains an Upgrade key
for (int i = 0; i < connection_hdr_vals.count; ++i) {
Str *val = connection_hdr_vals.get_idx(i);
if (ptr_len_casecmp(val->str, val->len, MIME_FIELD_UPGRADE, MIME_LEN_UPGRADE) == 0) {
connection_contains_upgrade = true;
break;
}
}
if (!connection_contains_upgrade) {
DebugTxn("http_trans_upgrade",
"Transaction wasn't a valid upgrade request, proceeding as a normal HTTP request, missing Connection upgrade header.");
return false;
}
// Mark this request as an upgrade request.
s->is_upgrade_request = true;
/*
RFC 6455
The request MUST contain an |Upgrade| header field whose value
MUST include the "websocket" keyword.
The request MUST contain a |Connection| header field whose value
MUST include the "Upgrade" token. // Checked Above
The request MUST include a header field with the name
|Sec-WebSocket-Key|.
The request MUST include a header field with the name
|Sec-WebSocket-Version|. The value of this header field MUST be
13.
*/
if (hdrtoken_tokenize(upgrade_hdr_val, upgrade_hdr_val_len, &s->upgrade_token_wks) >= 0) {
if (s->upgrade_token_wks == MIME_VALUE_WEBSOCKET) {
MIMEField *sec_websocket_key =
s->hdr_info.client_request.field_find(MIME_FIELD_SEC_WEBSOCKET_KEY, MIME_LEN_SEC_WEBSOCKET_KEY);
MIMEField *sec_websocket_ver =
s->hdr_info.client_request.field_find(MIME_FIELD_SEC_WEBSOCKET_VERSION, MIME_LEN_SEC_WEBSOCKET_VERSION);
if (sec_websocket_key && sec_websocket_ver && sec_websocket_ver->value_get_int() == 13) {
DebugTxn("http_trans_upgrade", "Transaction wants upgrade to websockets");
handle_websocket_upgrade_pre_remap(s);
return true;
} else {
DebugTxn("http_trans_upgrade", "Unable to upgrade connection to websockets, invalid headers (RFC 6455).");
}
}
// TODO accept h2c token to start HTTP/2 session after TS-3498 is fixed
} else {
DebugTxn("http_trans_upgrade", "Transaction requested upgrade for unknown protocol: %s", upgrade_hdr_val);
}
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Invalid Upgrade Request", "request#syntax_error", NULL);
// we want our modify_request method to just return while we fail out from here.
// this seems like the preferred option because the user wanted to do an upgrade but sent a bad protocol.
TRANSACT_RETURN_VAL(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL, true);
}
void
HttpTransact::handle_websocket_upgrade_pre_remap(State *s)
{
DebugTxn("http_trans_websocket_upgrade_pre_remap", "Prepping transaction before remap.");
/*
* We will use this opportunity to set everything up so that during the remap stage we can deal with
* ws:// and wss:// remap rules, and then we will take over again post remap.
*/
s->is_websocket = true;
s->post_remap_upgrade_return_point = HttpTransact::handle_websocket_upgrade_post_remap;
/* let's modify the url scheme to be wss or ws, so remapping will happen as expected */
URL *url = s->hdr_info.client_request.url_get();
if (url->scheme_get_wksidx() == URL_WKSIDX_HTTP) {
DebugTxn("http_trans_websocket_upgrade_pre_remap", "Changing scheme to WS for remapping.");
url->scheme_set(URL_SCHEME_WS, URL_LEN_WS);
} else if (url->scheme_get_wksidx() == URL_WKSIDX_HTTPS) {
DebugTxn("http_trans_websocket_upgrade_pre_remap", "Changing scheme to WSS for remapping.");
url->scheme_set(URL_SCHEME_WSS, URL_LEN_WSS);
} else {
DebugTxn("http_trans_websocket_upgrade_pre_remap", "Invalid scheme for websocket upgrade");
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Invalid Upgrade Request", "request#syntax_error", NULL);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
TRANSACT_RETURN(SM_ACTION_API_READ_REQUEST_HDR, HttpTransact::StartRemapRequest);
}
void
HttpTransact::handle_websocket_upgrade_post_remap(State *s)
{
DebugTxn("http_trans_websocket_upgrade_post_remap", "Remap is complete, start websocket upgrade");
TRANSACT_RETURN(SM_ACTION_API_POST_REMAP, HttpTransact::handle_websocket_connection);
}
void
HttpTransact::handle_websocket_connection(State *s)
{
DebugTxn("http_trans_websocket", "START handle_websocket_connection");
HandleRequest(s);
}
static bool
mimefield_value_equal(MIMEField *field, const char *value, const int value_len)
{
if (field != NULL) {
int field_value_len = 0;
const char *field_value = field->value_get(&field_value_len);
if (field_value != NULL) {
if (field_value_len == value_len) {
return !strncasecmp(field_value, value, value_len);
}
}
}
return false;
}
void
HttpTransact::ModifyRequest(State *s)
{
int scheme, hostname_len;
const char *hostname;
HTTPHdr &request = s->hdr_info.client_request;
DebugTxn("http_trans", "START HttpTransact::ModifyRequest");
// Initialize the state vars necessary to sending error responses
bootstrap_state_variables_from_request(s, &request);
////////////////////////////////////////////////
// If there is no scheme default to http //
////////////////////////////////////////////////
URL *url = request.url_get();
s->orig_scheme = (scheme = url->scheme_get_wksidx());
s->method = request.method_get_wksidx();
if (scheme < 0 && s->method != HTTP_WKSIDX_CONNECT) {
if (s->client_info.port_attribute == HttpProxyPort::TRANSPORT_SSL) {
url->scheme_set(URL_SCHEME_HTTPS, URL_LEN_HTTPS);
s->orig_scheme = URL_WKSIDX_HTTPS;
} else {
url->scheme_set(URL_SCHEME_HTTP, URL_LEN_HTTP);
s->orig_scheme = URL_WKSIDX_HTTP;
}
}
if (s->method == HTTP_WKSIDX_CONNECT && !request.is_port_in_header()) {
url->port_set(80);
}
// Ugly - this must come after the call to url->scheme_set or
// it can't get the scheme properly and the wrong data is cached.
// The solution should be to move the scheme detecting logic in to
// the header class, rather than doing it in a random bit of
// external code.
hostname = request.host_get(&hostname_len);
if (!request.is_target_in_url()) {
s->hdr_info.client_req_is_server_style = true;
}
// If the incoming request is proxy-style make sure the Host: header
// matches the incoming request URL. The exception is if we have
// Max-Forwards set to 0 in the request
int max_forwards = -1; // -1 is a valid value meaning that it didn't find the header
if (request.presence(MIME_PRESENCE_MAX_FORWARDS)) {
max_forwards = request.get_max_forwards();
}
if ((max_forwards != 0) && !s->hdr_info.client_req_is_server_style && s->method != HTTP_WKSIDX_CONNECT) {
MIMEField *host_field = request.field_find(MIME_FIELD_HOST, MIME_LEN_HOST);
int host_val_len = hostname_len;
const char **host_val = &hostname;
int port = url->port_get_raw();
char *buf = NULL;
// Form the host:port string if not a default port (e.g. 80)
if (port > 0) {
buf = (char *)alloca(host_val_len + 15);
memcpy(buf, hostname, host_val_len);
host_val_len += snprintf(buf + host_val_len, 15, ":%d", port);
host_val = (const char **)(&buf);
}
if (mimefield_value_equal(host_field, *host_val, host_val_len) == false) {
if (!host_field) { // Assure we have a Host field, before setting it
host_field = request.field_create(MIME_FIELD_HOST, MIME_LEN_HOST);
request.field_attach(host_field);
}
request.field_value_set(host_field, *host_val, host_val_len);
request.mark_target_dirty();
}
}
if (s->txn_conf->normalize_ae_gzip) {
// if enabled, force Accept-Encoding header to gzip or no header
MIMEField *ae_field = s->hdr_info.client_request.field_find(MIME_FIELD_ACCEPT_ENCODING, MIME_LEN_ACCEPT_ENCODING);
if (ae_field) {
if (HttpTransactCache::match_gzip(ae_field) == GZIP) {
s->hdr_info.client_request.field_value_set(ae_field, "gzip", 4);
DebugTxn("http_trans", "[ModifyRequest] normalized Accept-Encoding to gzip");
} else {
s->hdr_info.client_request.field_delete(ae_field);
DebugTxn("http_trans", "[ModifyRequest] removed non-gzip Accept-Encoding");
}
}
}
/////////////////////////////////////////////////////////
// Modify Accept-Encoding for several specific User-Agent
/////////////////////////////////////////////////////////
if (s->txn_conf->accept_encoding_filter_enabled) {
perform_accept_encoding_filtering(s);
}
DebugTxn("http_trans", "END HttpTransact::ModifyRequest");
DebugTxn("http_trans", "Checking if transaction wants to upgrade");
if (handle_upgrade_request(s)) {
// everything should be handled by the upgrade handler.
DebugTxn("http_trans", "Transaction will be upgraded by the appropriate upgrade handler.");
return;
}
TRANSACT_RETURN(SM_ACTION_API_READ_REQUEST_HDR, HttpTransact::StartRemapRequest);
}
// This function is supposed to figure out if this transaction is
// susceptible to a redirection as specified by remap.config
bool
HttpTransact::handleIfRedirect(State *s)
{
int answer;
URL redirect_url;
answer = request_url_remap_redirect(&s->hdr_info.client_request, &redirect_url);
if ((answer == PERMANENT_REDIRECT) || (answer == TEMPORARY_REDIRECT)) {
int remap_redirect_len;
s->remap_redirect = redirect_url.string_get(&s->arena, &remap_redirect_len);
redirect_url.destroy();
if (answer == TEMPORARY_REDIRECT) {
if ((s->client_info).http_version.m_version == HTTP_VERSION(1, 1)) {
build_error_response(s, HTTP_STATUS_TEMPORARY_REDIRECT, "Redirect", "redirect#moved_temporarily", NULL);
} else {
build_error_response(s, HTTP_STATUS_MOVED_TEMPORARILY, "Redirect", "redirect#moved_temporarily", NULL);
}
} else {
build_error_response(s, HTTP_STATUS_MOVED_PERMANENTLY, "Redirect", "redirect#moved_permanently", NULL);
}
s->arena.str_free(s->remap_redirect);
s->remap_redirect = NULL;
return true;
}
return false;
}
void
HttpTransact::HandleRequest(State *s)
{
DebugTxn("http_trans", "START HttpTransact::HandleRequest");
ink_assert(!s->hdr_info.server_request.valid());
HTTP_INCREMENT_DYN_STAT(http_incoming_requests_stat);
if (s->client_info.port_attribute == HttpProxyPort::TRANSPORT_SSL) {
HTTP_INCREMENT_DYN_STAT(https_incoming_requests_stat);
}
///////////////////////////////////////////////
// if request is bad, return error response //
///////////////////////////////////////////////
if (!(is_request_valid(s, &s->hdr_info.client_request))) {
HTTP_INCREMENT_DYN_STAT(http_invalid_client_requests_stat);
DebugTxn("http_seq", "[HttpTransact::HandleRequest] request invalid.");
s->next_action = SM_ACTION_SEND_ERROR_CACHE_NOOP;
// s->next_action = HttpTransact::PROXY_INTERNAL_CACHE_NOOP;
return;
}
DebugTxn("http_seq", "[HttpTransact::HandleRequest] request valid.");
if (is_debug_tag_set("http_chdr_describe")) {
obj_describe(s->hdr_info.client_request.m_http, 1);
}
// at this point we are guaranteed that the request is good and acceptable.
// initialize some state variables from the request (client version,
// client keep-alive, cache action, etc.
initialize_state_variables_from_request(s, &s->hdr_info.client_request);
// The following chunk of code will limit the maximum number of websocket connections (TS-3659)
if (s->is_upgrade_request && s->is_websocket && s->http_config_param->max_websocket_connections >= 0) {
int64_t val = 0;
HTTP_READ_DYN_SUM(http_websocket_current_active_client_connections_stat, val);
if (val >= s->http_config_param->max_websocket_connections) {
s->is_websocket = false; // unset to avoid screwing up stats.
DebugTxn("http_trans", "Rejecting websocket connection because the limit has been exceeded");
bootstrap_state_variables_from_request(s, &s->hdr_info.client_request);
build_error_response(s, HTTP_STATUS_SERVICE_UNAVAILABLE, "WebSocket Connection Limit Exceeded", NULL, NULL);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
}
// The following code is configurable to allow a user to control the max post size (TS-3631)
if (s->http_config_param->max_post_size > 0 && s->hdr_info.request_content_length > 0 &&
s->hdr_info.request_content_length > s->http_config_param->max_post_size) {
DebugTxn("http_trans", "Max post size %" PRId64 " Client tried to post a body that was too large.",
s->http_config_param->max_post_size);
HTTP_INCREMENT_DYN_STAT(http_post_body_too_large);
bootstrap_state_variables_from_request(s, &s->hdr_info.client_request);
build_error_response(s, HTTP_STATUS_REQUEST_ENTITY_TOO_LARGE, "Request Entity Too Large", "request#entity_too_large", NULL);
s->squid_codes.log_code = SQUID_LOG_ERR_POST_ENTITY_TOO_LARGE;
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
// The following chunk of code allows you to disallow post w/ expect 100-continue (TS-3459)
if (s->hdr_info.request_content_length && s->http_config_param->disallow_post_100_continue) {
MIMEField *expect = s->hdr_info.client_request.field_find(MIME_FIELD_EXPECT, MIME_LEN_EXPECT);
if (expect != NULL) {
const char *expect_hdr_val = NULL;
int expect_hdr_val_len = 0;
expect_hdr_val = expect->value_get(&expect_hdr_val_len);
if (ptr_len_casecmp(expect_hdr_val, expect_hdr_val_len, HTTP_VALUE_100_CONTINUE, HTTP_LEN_100_CONTINUE) == 0) {
// Let's error out this request.
DebugTxn("http_trans", "Client sent a post expect: 100-continue, sending 405.");
HTTP_INCREMENT_DYN_STAT(disallowed_post_100_continue);
build_error_response(s, HTTP_STATUS_METHOD_NOT_ALLOWED, "Method Not Allowed", "request#method_unsupported", NULL);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
}
}
// Cache lookup or not will be decided later at DecideCacheLookup().
// Before it's decided to do a cache lookup,
// assume no cache lookup and using proxy (not tunneling)
s->cache_info.action = CACHE_DO_NO_ACTION;
s->current.mode = GENERIC_PROXY;
// initialize the cache_control structure read from cache.config
update_cache_control_information_from_config(s);
// We still need to decide whether or not to do a cache lookup since
// the scheduled update code depends on this info.
if (is_request_cache_lookupable(s)) {
s->cache_info.action = CACHE_DO_LOOKUP;
}
// If the hostname is "$internal$" then this is a request for
// internal proxy information.
if (handle_internal_request(s, &s->hdr_info.client_request)) {
TRANSACT_RETURN(SM_ACTION_INTERNAL_REQUEST, NULL);
}
// this needs to be called after initializing state variables from request
// it adds the client-ip to the incoming client request.
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", &s->hdr_info.client_request, s->state_machine_id, "Incoming Request");
if (s->state_machine->plugin_tunnel_type == HTTP_PLUGIN_AS_INTERCEPT) {
setup_plugin_request_intercept(s);
return;
}
// if ip in url or cop test page, not do srv lookup.
if (s->txn_conf->srv_enabled) {
if (s->cop_test_page) {
s->txn_conf->srv_enabled = false;
} else {
IpEndpoint addr;
ats_ip_pton(s->server_info.name, &addr);
s->txn_conf->srv_enabled = !ats_is_ip(&addr);
}
}
// if the request is a trace or options request, decrement the
// max-forwards value. if the incoming max-forwards value was 0,
// then we have to return a response to the client with the
// appropriate action for trace/option. in this case this routine
// is responsible for building the response.
if (handle_trace_and_options_requests(s, &s->hdr_info.client_request)) {
TRANSACT_RETURN(SM_ACTION_INTERNAL_CACHE_NOOP, NULL);
}
if (s->http_config_param->no_dns_forward_to_parent && s->scheme != URL_WKSIDX_HTTPS &&
strcmp(s->server_info.name, "127.0.0.1") != 0) {
// for HTTPS requests, we must go directly to the
// origin server. Ignore the no_dns_just_forward_to_parent setting.
// we need to see if the hostname is an
// ip address since the parent selection code result
// could change as a result of this ip address
IpEndpoint addr;
ats_ip_pton(s->server_info.name, &addr);
if (ats_is_ip(&addr)) {
ats_ip_copy(&s->request_data.dest_ip, &addr);
}
if (s->parent_params->parentExists(&s->request_data)) {
// If the proxy is behind and firewall and there is no
// DNS service available, we just want to forward the request
// the parent proxy. In this case, we never find out the
// origin server's ip. So just skip past OSDNS
ats_ip_invalidate(&s->server_info.dst_addr);
StartAccessControl(s);
return;
} else if (s->http_config_param->no_origin_server_dns) {
build_error_response(s, HTTP_STATUS_BAD_GATEWAY, "Next Hop Connection Failed", "connect#failed_connect", NULL);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
}
// Added to skip the dns if the document is in the cache.
// DNS is requested before cache lookup only if there are rules in cache.config , parent.config or
// if the newly added varible doc_in_cache_skip_dns is not enabled
if (s->dns_info.lookup_name[0] <= '9' && s->dns_info.lookup_name[0] >= '0' &&
(!s->state_machine->enable_redirection || !s->redirect_info.redirect_in_process) &&
s->parent_params->parent_table->hostMatch) {
s->force_dns = 1;
}
/* A redirect means we need to check some things again.
If the cache is enabled then we need to check the new (redirected) request against the cache.
If not, then we need to at least do DNS again to guarantee we are using the correct IP address
(if the host changed). Note DNS comes after cache lookup so in both cases we do the DNS.
*/
if (s->redirect_info.redirect_in_process && s->state_machine->enable_redirection) {
if (s->txn_conf->cache_http) {
TRANSACT_RETURN(SM_ACTION_CACHE_LOOKUP, NULL);
} else {
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, OSDNSLookup); // effectively s->force_dns
}
}
if (s->force_dns) {
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, OSDNSLookup); // After handling the request, DNS is done.
} else {
// After the requested is properly handled No need of requesting the DNS directly check the ACLs
// if the request is authorized
StartAccessControl(s);
}
}
void
HttpTransact::setup_plugin_request_intercept(State *s)
{
ink_assert(s->state_machine->plugin_tunnel != NULL);
// Plugin is intercepting the request which means
// that we don't do dns, cache read or cache write
//
// We just want to write the request straight to the plugin
if (s->cache_info.action != HttpTransact::CACHE_DO_NO_ACTION) {
s->cache_info.action = HttpTransact::CACHE_DO_NO_ACTION;
s->current.mode = TUNNELLING_PROXY;
HTTP_INCREMENT_DYN_STAT(http_tunnels_stat);
}
// Regardless of the protocol we're gatewaying to
// we see the scheme as http
s->scheme = s->next_hop_scheme = URL_WKSIDX_HTTP;
// Set up a "fake" server server entry
update_current_info(&s->current, &s->server_info, HttpTransact::ORIGIN_SERVER, 0);
// Also "fake" the info we'd normally get from
// hostDB
s->server_info.http_version.set(1, 0);
s->server_info.keep_alive = HTTP_NO_KEEPALIVE;
s->host_db_info.app.http_data.http_version = HostDBApplicationInfo::HTTP_VERSION_10;
s->host_db_info.app.http_data.pipeline_max = 1;
s->server_info.dst_addr.setToAnyAddr(AF_INET); // must set an address or we can't set the port.
s->server_info.dst_addr.port() = htons(s->hdr_info.client_request.port_get()); // this is the info that matters.
// Build the request to the server
build_request(s, &s->hdr_info.client_request, &s->hdr_info.server_request, s->client_info.http_version);
// We don't do keep alive over these impersonated
// NetVCs so nuke the connection header
s->hdr_info.server_request.field_delete(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION);
TRANSACT_RETURN(SM_ACTION_ORIGIN_SERVER_OPEN, NULL);
}
////////////////////////////////////////////////////////////////////////
// void HttpTransact::HandleApiErrorJump(State* s)
//
// Called after an API function indicates it wished to send an
// error to the user agent
////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleApiErrorJump(State *s)
{
DebugTxn("http_trans", "[HttpTransact::HandleApiErrorJump]");
// since the READ_REQUEST_HDR_HOOK is processed before
// we examine the request, returning TS_EVENT_ERROR will cause
// the protocol in the via string to be "?" Set it here
// since we know it has to be http
// For CONNECT method, next_hop_scheme is NULL
if (s->next_hop_scheme < 0) {
s->next_hop_scheme = URL_WKSIDX_HTTP;
}
// The client response may not be empty in the
// case the txn was reenabled in error by a plugin from hook SEND_RESPONSE_HDR.
// build_response doesn't clean the header. So clean it up before.
// Do fields_clear() instead of clear() to prevent memory leak
if (s->hdr_info.client_response.valid()) {
s->hdr_info.client_response.fields_clear();
}
// Set the source to internal so chunking is handled correctly
s->source = SOURCE_INTERNAL;
/**
The API indicated an error. Lets use a >=400 error from the state (if one's set) or fallback to a
generic HTTP/1.X 500 INKApi Error
**/
if (s->http_return_code && s->http_return_code >= HTTP_STATUS_BAD_REQUEST) {
const char *reason = http_hdr_reason_lookup(s->http_return_code);
;
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, s->http_return_code, reason ? reason : "Error");
} else {
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, HTTP_STATUS_INTERNAL_SERVER_ERROR, "INKApi Error");
}
TRANSACT_RETURN(SM_ACTION_INTERNAL_CACHE_NOOP, NULL);
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : PPDNSLookup
// Description: called after DNS lookup of parent proxy name
//
// Details :
//
// the configuration information gave us the name of the parent proxy
// to send the request to. this function is called after the dns lookup
// for that name. it may fail, in which case we look for the next parent
// proxy to try and if none exist, then go to the origin server.
// if the lookup succeeds, we open a connection to the parent proxy.
//
//
// Possible Next States From Here:
// - HttpTransact::SM_ACTION_DNS_LOOKUP;
// - HttpTransact::ORIGIN_SERVER_RAW_OPEN;
// - HttpTransact::ORIGIN_SERVER_OPEN;
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::PPDNSLookup(State *s)
{
++s->dns_info.attempts;
DebugTxn("http_trans", "[HttpTransact::PPDNSLookup] This was attempt %d", s->dns_info.attempts);
ink_assert(s->dns_info.looking_up == PARENT_PROXY);
if (!s->dns_info.lookup_success) {
// Mark parent as down due to resolving failure
s->parent_params->markParentDown(&s->parent_result);
// DNS lookup of parent failed, find next parent or o.s.
find_server_and_update_current_info(s);
if (!s->current.server->dst_addr.isValid()) {
if (s->current.request_to == PARENT_PROXY) {
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, PPDNSLookup);
} else {
// We could be out of parents here if all the parents failed DNS lookup
ink_assert(s->current.request_to == HOST_NONE);
handle_parent_died(s);
}
return;
}
} else {
// lookup succeeded, open connection to p.p.
ats_ip_copy(&s->parent_info.dst_addr, s->host_db_info.ip());
s->parent_info.dst_addr.port() = htons(s->parent_result.port);
get_ka_info_from_host_db(s, &s->parent_info, &s->client_info, &s->host_db_info);
char addrbuf[INET6_ADDRSTRLEN];
DebugTxn("http_trans", "[PPDNSLookup] DNS lookup for sm_id[%" PRId64 "] successful IP: %s", s->state_machine->sm_id,
ats_ip_ntop(&s->parent_info.dst_addr.sa, addrbuf, sizeof(addrbuf)));
}
// Since this function can be called several times while retrying
// parents, check to see if we've already built our request
if (!s->hdr_info.server_request.valid()) {
build_request(s, &s->hdr_info.client_request, &s->hdr_info.server_request, s->current.server->http_version);
// Take care of deferred (issue revalidate) work in building
// the request
if (s->pending_work != NULL) {
ink_assert(s->pending_work == issue_revalidate);
(*s->pending_work)(s);
s->pending_work = NULL;
}
}
// what kind of a connection (raw, simple)
s->next_action = how_to_open_connection(s);
}
///////////////////////////////////////////////////////////////////////////////
//
// Name : ReDNSRoundRobin
// Description: Called after we fail to contact part of a round-robin
// robin server set and we found a another ip address.
//
// Details :
//
//
//
// Possible Next States From Here:
// - HttpTransact::ORIGIN_SERVER_RAW_OPEN;
// - HttpTransact::ORIGIN_SERVER_OPEN;
// - HttpTransact::PROXY_INTERNAL_CACHE_NOOP;
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::ReDNSRoundRobin(State *s)
{
ink_assert(s->current.server == &s->server_info);
ink_assert(s->current.server->had_connect_fail());
if (s->dns_info.lookup_success) {
// We using a new server now so clear the connection
// failure mark
s->current.server->clear_connect_fail();
// Our ReDNS of the server succeeded so update the necessary
// information and try again. Need to preserve the current port value if possible.
in_port_t server_port = s->current.server->dst_addr.host_order_port();
// Temporary check to make sure the port preservation can be depended upon. That should be the case
// because we get here only after trying a connection. Remove for 6.2.
ink_assert(s->current.server->dst_addr.isValid() && 0 != server_port);
ats_ip_copy(&s->server_info.dst_addr, s->host_db_info.ip());
s->server_info.dst_addr.port() = htons(server_port);
ats_ip_copy(&s->request_data.dest_ip, &s->server_info.dst_addr);
get_ka_info_from_host_db(s, &s->server_info, &s->client_info, &s->host_db_info);
char addrbuf[INET6_ADDRSTRLEN];
DebugTxn("http_trans", "[ReDNSRoundRobin] DNS lookup for O.S. successful IP: %s",
ats_ip_ntop(&s->server_info.dst_addr.sa, addrbuf, sizeof(addrbuf)));
s->next_action = how_to_open_connection(s);
} else {
// Our ReDNS failed so output the DNS failure error message
build_error_response(s, HTTP_STATUS_BAD_GATEWAY, "Cannot find server.", "connect#dns_failed", NULL);
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_SEND_ERROR_CACHE_NOOP;
// s->next_action = PROXY_INTERNAL_CACHE_NOOP;
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : OSDNSLookup
// Description: called after the DNS lookup of origin server name
//
// Details :
//
// normally called after Start. may be called more than once, however,
// if the dns lookup fails. this may be if the client does not specify
// the full hostname (e.g. just cnn, instead of www.cnn.com), or because
// it was not possible to resolve the name after several attempts.
//
// the next action depends. since this function is normally called after
// a request has come in, which is valid and does not require an immediate
// response, the next action may just be to open a connection to the
// origin server, or a parent proxy, or the next action may be to do a
// cache lookup, or in the event of an error, the next action may be to
// send a response back to the client.
//
//
// Possible Next States From Here:
// - HttpTransact::PROXY_INTERNAL_CACHE_NOOP;
// - HttpTransact::CACHE_LOOKUP;
// - HttpTransact::SM_ACTION_DNS_LOOKUP;
// - HttpTransact::ORIGIN_SERVER_RAW_OPEN;
// - HttpTransact::ORIGIN_SERVER_OPEN;
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::OSDNSLookup(State *s)
{
static int max_dns_lookups = 3 + s->http_config_param->num_url_expansions;
++s->dns_info.attempts;
DebugTxn("http_trans", "[HttpTransact::OSDNSLookup] This was attempt %d", s->dns_info.attempts);
ink_assert(s->dns_info.looking_up == ORIGIN_SERVER);
// detect whether we are about to self loop. the client may have
// specified the proxy as the origin server (badness).
// Check if this procedure is already done - YTS Team, yamsat
if (!s->request_will_not_selfloop) {
if (will_this_request_self_loop(s)) {
DebugTxn("http_trans", "[OSDNSLookup] request will selfloop - bailing out");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
}
if (!s->dns_info.lookup_success) {
// maybe the name can be expanded (e.g cnn -> www.cnn.com)
HostNameExpansionError_t host_name_expansion = try_to_expand_host_name(s);
switch (host_name_expansion) {
case RETRY_EXPANDED_NAME:
// expansion successful, do a dns lookup on expanded name
HTTP_RELEASE_ASSERT(s->dns_info.attempts < max_dns_lookups);
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, OSDNSLookup);
break;
case EXPANSION_NOT_ALLOWED:
case EXPANSION_FAILED:
case DNS_ATTEMPTS_EXHAUSTED:
if (DNSLookupInfo::OS_ADDR_TRY_HOSTDB == s->dns_info.os_addr_style) {
/*
* We tried to connect to client target address, failed and tried to use a different addr
* No HostDB data, just keep on with the CTA.
*/
s->dns_info.lookup_success = true;
s->dns_info.os_addr_style = DNSLookupInfo::OS_ADDR_USE_CLIENT;
DebugTxn("http_seq", "[HttpTransact::OSDNSLookup] DNS lookup unsuccessful, using client target address");
} else {
if (host_name_expansion == EXPANSION_NOT_ALLOWED) {
// config file doesn't allow automatic expansion of host names
HTTP_RELEASE_ASSERT(!(s->http_config_param->enable_url_expandomatic));
DebugTxn("http_seq", "[HttpTransact::OSDNSLookup] DNS Lookup unsuccessful");
} else if (host_name_expansion == EXPANSION_FAILED) {
// not able to expand the hostname. dns lookup failed
DebugTxn("http_seq", "[HttpTransact::OSDNSLookup] DNS Lookup unsuccessful");
} else if (host_name_expansion == DNS_ATTEMPTS_EXHAUSTED) {
// retry attempts exhausted --- can't find dns entry for this host name
HTTP_RELEASE_ASSERT(s->dns_info.attempts >= max_dns_lookups);
DebugTxn("http_seq", "[HttpTransact::OSDNSLookup] DNS Lookup unsuccessful");
}
// output the DNS failure error message
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_BAD_GATEWAY, "Cannot find server.", "connect#dns_failed", NULL);
// s->cache_info.action = CACHE_DO_NO_ACTION;
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
break;
default:
ink_assert(!("try_to_expand_hostname returned an unsupported code"));
break;
}
return;
}
// ok, so the dns lookup succeeded
ink_assert(s->dns_info.lookup_success);
DebugTxn("http_seq", "[HttpTransact::OSDNSLookup] DNS Lookup successful");
if (DNSLookupInfo::OS_ADDR_TRY_HOSTDB == s->dns_info.os_addr_style) {
// We've backed off from a client supplied address and found some
// HostDB addresses. We use those if they're different from the CTA.
// In all cases we now commit to client or HostDB for our source.
if (s->host_db_info.round_robin) {
HostDBInfo *cta = s->host_db_info.rr()->select_next(&s->current.server->dst_addr.sa);
if (cta) {
// found another addr, lock in host DB.
s->host_db_info = *cta;
s->dns_info.os_addr_style = DNSLookupInfo::OS_ADDR_USE_HOSTDB;
} else {
// nothing else there, continue with CTA.
s->dns_info.os_addr_style = DNSLookupInfo::OS_ADDR_USE_CLIENT;
}
} else if (ats_ip_addr_eq(s->host_db_info.ip(), &s->server_info.dst_addr.sa)) {
s->dns_info.os_addr_style = DNSLookupInfo::OS_ADDR_USE_CLIENT;
} else {
s->dns_info.os_addr_style = DNSLookupInfo::OS_ADDR_USE_HOSTDB;
}
}
// Check to see if can fullfill expect requests based on the cached
// update some state variables with hostdb information that has
// been provided.
ats_ip_copy(&s->server_info.dst_addr, s->host_db_info.ip());
// If the SRV response has a port number, we should honor it. Otherwise we do the port defined in remap
if (s->dns_info.srv_lookup_success) {
s->server_info.dst_addr.port() = htons(s->dns_info.srv_port);
} else {
s->server_info.dst_addr.port() = htons(s->hdr_info.client_request.port_get()); // now we can set the port.
}
ats_ip_copy(&s->request_data.dest_ip, &s->server_info.dst_addr);
get_ka_info_from_host_db(s, &s->server_info, &s->client_info, &s->host_db_info);
char addrbuf[INET6_ADDRSTRLEN];
DebugTxn("http_trans", "[OSDNSLookup] DNS lookup for O.S. successful "
"IP: %s",
ats_ip_ntop(&s->server_info.dst_addr.sa, addrbuf, sizeof(addrbuf)));
// so the dns lookup was a success, but the lookup succeeded on
// a hostname which was expanded by the traffic server. we should
// not automatically forward the request to this expanded hostname.
// return a response to the client with the expanded host name
// and a tasty little blurb explaining what happened.
// if a DNS lookup succeeded on a user-defined
// hostname expansion, forward the request to the expanded hostname.
// On the other hand, if the lookup succeeded on a www.<hostname>.com
// expansion, return a 302 response.
// [amc] Also don't redirect if we backed off using HostDB instead of CTA.
if (s->dns_info.attempts == max_dns_lookups && s->dns_info.looking_up == ORIGIN_SERVER &&
DNSLookupInfo::OS_ADDR_USE_CLIENT != s->dns_info.os_addr_style) {
DebugTxn("http_trans", "[OSDNSLookup] DNS name resolution on expansion");
DebugTxn("http_seq", "[OSDNSLookup] DNS name resolution on expansion - returning");
build_redirect_response(s);
// s->cache_info.action = CACHE_DO_NO_ACTION;
TRANSACT_RETURN(SM_ACTION_INTERNAL_CACHE_NOOP, NULL);
}
// everything succeeded with the DNS lookup so do an API callout
// that allows for filtering. We'll do traffic_server internal
// filtering after API filtering
// After SM_ACTION_DNS_LOOKUP, goto the saved action/state ORIGIN_SERVER_(RAW_)OPEN.
// Should we skip the StartAccessControl()? why?
if (s->cdn_remap_complete) {
DebugTxn("cdn", "This is a late DNS lookup. We are going to the OS, "
"not to HandleFiltering.");
ink_assert(s->cdn_saved_next_action == SM_ACTION_ORIGIN_SERVER_OPEN ||
s->cdn_saved_next_action == SM_ACTION_ORIGIN_SERVER_RAW_OPEN);
DebugTxn("cdn", "outgoing version -- (pre conversion) %d", s->hdr_info.server_request.m_http->m_version);
(&s->hdr_info.server_request)->version_set(HTTPVersion(1, 1));
HttpTransactHeaders::convert_request(s->current.server->http_version, &s->hdr_info.server_request);
DebugTxn("cdn", "outgoing version -- (post conversion) %d", s->hdr_info.server_request.m_http->m_version);
TRANSACT_RETURN(s->cdn_saved_next_action, NULL);
} else if (DNSLookupInfo::OS_ADDR_USE_CLIENT == s->dns_info.os_addr_style ||
DNSLookupInfo::OS_ADDR_USE_HOSTDB == s->dns_info.os_addr_style) {
// we've come back after already trying the server to get a better address
// and finished with all backtracking - return to trying the server.
TRANSACT_RETURN(how_to_open_connection(s), HttpTransact::HandleResponse);
} else if (s->dns_info.lookup_name[0] <= '9' && s->dns_info.lookup_name[0] >= '0' && s->parent_params->parent_table->hostMatch &&
!s->http_config_param->no_dns_forward_to_parent) {
// note, broken logic: ACC fudges the OR stmt to always be true,
// 'AuthHttpAdapter' should do the rev-dns if needed, not here .
TRANSACT_RETURN(SM_ACTION_DNS_REVERSE_LOOKUP, HttpTransact::StartAccessControl);
} else {
//(s->state_machine->authAdapter).StartLookup (s);
// TRANSACT_RETURN(SM_ACTION_AUTH_LOOKUP, NULL);
if (s->force_dns) {
StartAccessControl(s); // If skip_dns is enabled and no ip based rules in cache.config and parent.config
// Access Control is called after DNS response
} else {
if ((s->cache_info.action == CACHE_DO_NO_ACTION) &&
(((s->hdr_info.client_request.presence(MIME_PRESENCE_RANGE) && !s->txn_conf->cache_range_write) ||
s->range_setup == RANGE_NOT_SATISFIABLE || s->range_setup == RANGE_NOT_HANDLED))) {
TRANSACT_RETURN(SM_ACTION_API_OS_DNS, HandleCacheOpenReadMiss);
} else if (!s->txn_conf->cache_http || s->cache_lookup_result == HttpTransact::CACHE_LOOKUP_SKIPPED) {
TRANSACT_RETURN(SM_ACTION_API_OS_DNS, LookupSkipOpenServer);
// DNS Lookup is done after LOOKUP Skipped and after we get response
// from the DNS we need to call LookupSkipOpenServer
} else if (s->cache_lookup_result == CACHE_LOOKUP_HIT_FRESH || s->cache_lookup_result == CACHE_LOOKUP_HIT_WARNING ||
s->cache_lookup_result == CACHE_LOOKUP_HIT_STALE) {
// DNS lookup is done if the content is state need to call handle cache open read hit
TRANSACT_RETURN(SM_ACTION_API_OS_DNS, HandleCacheOpenReadHit);
} else if (s->cache_lookup_result == CACHE_LOOKUP_MISS || s->cache_info.action == CACHE_DO_NO_ACTION) {
TRANSACT_RETURN(SM_ACTION_API_OS_DNS, HandleCacheOpenReadMiss);
// DNS lookup is done if the lookup failed and need to call Handle Cache Open Read Miss
} else {
build_error_response(s, HTTP_STATUS_INTERNAL_SERVER_ERROR, "Invalid Cache Lookup result", "default", NULL);
Log::error("HTTP: Invalid CACHE LOOKUP RESULT : %d", s->cache_lookup_result);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
}
}
}
void
HttpTransact::StartAccessControl(State *s)
{
// if (s->cop_test_page || (s->state_machine->authAdapter.disabled() == true)) {
// Heartbeats should always be allowed.
// s->content_control.access = ACCESS_ALLOW;
HandleRequestAuthorized(s);
// return;
// }
// ua_session is NULL for scheduled updates.
// Don't use req_flavor to do the test because if updated
// urls are remapped, the req_flavor is changed to REV_PROXY.
// if (s->state_machine->ua_session == NULL) {
// Scheduled updates should always be allowed
// return;
//}
// pass the access control logic to the ACC module.
//(s->state_machine->authAdapter).StartLookup(s);
}
void
HttpTransact::HandleRequestAuthorized(State *s)
{
//(s->state_machine->authAdapter).SetState(s);
//(s->state_machine->authAdapter).UserAuthorized(NULL);
// TRANSACT_RETURN(HTTP_API_OS_DNS, HandleFiltering);
if (s->force_dns) {
TRANSACT_RETURN(SM_ACTION_API_OS_DNS, HttpTransact::DecideCacheLookup);
} else {
HttpTransact::DecideCacheLookup(s);
}
}
void
HttpTransact::HandleFiltering(State *s)
{
ink_release_assert(!"Fix-Me AUTH MERGE");
if (s->method == HTTP_WKSIDX_PUSH && s->http_config_param->push_method_enabled == 0) {
// config file says this request is not authorized.
// send back error response to client.
DebugTxn("http_trans", "[HandleFiltering] access denied.");
DebugTxn("http_seq", "[HttpTransact::HandleFiltering] Access Denied.");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
// adding a comment so that cvs recognizes that I added a space in the text below
build_error_response(s, HTTP_STATUS_FORBIDDEN, "Access Denied", "access#denied", NULL);
// s->cache_info.action = CACHE_DO_NO_ACTION;
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
DebugTxn("http_seq", "[HttpTransact::HandleFiltering] Request Authorized.");
//////////////////////////////////////////////////////////////
// ok, the config file says that the request is authorized. //
//////////////////////////////////////////////////////////////
// request is not black listed so now decided if we ought to
// lookup the cache
DecideCacheLookup(s);
}
void
HttpTransact::DecideCacheLookup(State *s)
{
// Check if a client request is lookupable.
if (s->redirect_info.redirect_in_process || s->cop_test_page) {
// for redirect, we want to skip cache lookup and write into
// the cache directly with the URL before the redirect
s->cache_info.action = CACHE_DO_NO_ACTION;
s->current.mode = GENERIC_PROXY;
} else {
if (is_request_cache_lookupable(s) && !s->is_upgrade_request) {
s->cache_info.action = CACHE_DO_LOOKUP;
s->current.mode = GENERIC_PROXY;
} else {
s->cache_info.action = CACHE_DO_NO_ACTION;
s->current.mode = TUNNELLING_PROXY;
HTTP_INCREMENT_DYN_STAT(http_tunnels_stat);
}
}
if (service_transaction_in_proxy_only_mode(s)) {
s->cache_info.action = CACHE_DO_NO_ACTION;
s->current.mode = TUNNELLING_PROXY;
HTTP_INCREMENT_DYN_STAT(http_throttled_proxy_only_stat);
}
// at this point the request is ready to continue down the
// traffic server path.
// now decide whether the cache can even be looked up.
if (s->cache_info.action == CACHE_DO_LOOKUP) {
DebugTxn("http_trans", "[DecideCacheLookup] Will do cache lookup.");
DebugTxn("http_seq", "[DecideCacheLookup] Will do cache lookup");
ink_assert(s->current.mode != TUNNELLING_PROXY);
if (s->cache_info.lookup_url == NULL) {
HTTPHdr *incoming_request = &s->hdr_info.client_request;
if (s->txn_conf->maintain_pristine_host_hdr) {
s->cache_info.lookup_url_storage.create(NULL);
s->cache_info.lookup_url_storage.copy(incoming_request->url_get());
s->cache_info.lookup_url = &s->cache_info.lookup_url_storage;
// if the target isn't in the URL, put it in the copy for
// cache lookup.
incoming_request->set_url_target_from_host_field(s->cache_info.lookup_url);
} else {
// make sure the target is in the URL.
incoming_request->set_url_target_from_host_field();
s->cache_info.lookup_url = incoming_request->url_get();
}
// *somebody* wants us to not hack the host header in a reverse proxy setup.
// In addition, they want us to reverse proxy for 6000 servers, which vary
// the stupid content on the Host header!!!!
// We could a) have 6000 alts (barf, puke, vomit) or b) use the original
// host header in the url before doing all cache actions (lookups, writes, etc.)
if (s->txn_conf->maintain_pristine_host_hdr) {
char const *host_hdr;
char const *port_hdr;
int host_len, port_len;
// So, the host header will have the original host header.
if (incoming_request->get_host_port_values(&host_hdr, &host_len, &port_hdr, &port_len)) {
int port = 0;
if (port_hdr) {
s->cache_info.lookup_url->host_set(host_hdr, host_len);
port = ink_atoi(port_hdr, port_len);
} else {
s->cache_info.lookup_url->host_set(host_hdr, host_len);
}
s->cache_info.lookup_url->port_set(port);
}
}
ink_assert(s->cache_info.lookup_url->valid() == true);
}
TRANSACT_RETURN(SM_ACTION_CACHE_LOOKUP, NULL);
} else {
ink_assert(s->cache_info.action != CACHE_DO_LOOKUP && s->cache_info.action != CACHE_DO_SERVE);
DebugTxn("http_trans", "[DecideCacheLookup] Will NOT do cache lookup.");
DebugTxn("http_seq", "[DecideCacheLookup] Will NOT do cache lookup");
// If this is a push request, we need send an error because
// since what ever was sent is not cachable
if (s->method == HTTP_WKSIDX_PUSH) {
HandlePushError(s, "Request Not Cachable");
return;
}
// for redirect, we skipped cache lookup to do the automatic redirection
if (s->redirect_info.redirect_in_process) {
// without calling out the CACHE_LOOKUP_COMPLETE_HOOK
if (s->txn_conf->cache_http) {
s->cache_info.action = CACHE_DO_WRITE;
}
LookupSkipOpenServer(s);
} else {
// calling out CACHE_LOOKUP_COMPLETE_HOOK even when the cache
// lookup is skipped
s->cache_lookup_result = HttpTransact::CACHE_LOOKUP_SKIPPED;
if (s->force_dns) {
TRANSACT_RETURN(SM_ACTION_API_CACHE_LOOKUP_COMPLETE, LookupSkipOpenServer);
} else {
// Returning to dns lookup as cache lookup is skipped
TRANSACT_RETURN(SM_ACTION_API_CACHE_LOOKUP_COMPLETE, CallOSDNSLookup);
}
}
}
return;
}
void
HttpTransact::LookupSkipOpenServer(State *s)
{
// cache will not be looked up. open a connection
// to a parent proxy or to the origin server.
find_server_and_update_current_info(s);
if (s->current.request_to == PARENT_PROXY) {
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, PPDNSLookup);
}
ink_assert(s->current.request_to == ORIGIN_SERVER);
// ink_assert(s->current.server->ip != 0);
build_request(s, &s->hdr_info.client_request, &s->hdr_info.server_request, s->current.server->http_version);
StateMachineAction_t next = how_to_open_connection(s);
s->next_action = next;
if (next == SM_ACTION_ORIGIN_SERVER_OPEN || next == SM_ACTION_ORIGIN_SERVER_RAW_OPEN) {
TRANSACT_RETURN(next, HttpTransact::HandleResponse);
}
}
//////////////////////////////////////////////////////////////////////////////
// Name : HandleCacheOpenReadPush
// Description:
//
// Details :
//
// Called on PUSH requests from HandleCacheOpenRead
//////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleCacheOpenReadPush(State *s, bool read_successful)
{
if (read_successful) {
s->cache_info.action = CACHE_PREPARE_TO_UPDATE;
} else {
s->cache_info.action = CACHE_PREPARE_TO_WRITE;
}
TRANSACT_RETURN(SM_ACTION_READ_PUSH_HDR, HandlePushResponseHdr);
}
//////////////////////////////////////////////////////////////////////////////
// Name : HandlePushResponseHdr
// Description:
//
// Details :
//
// Called after reading the response header on PUSH request
//////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandlePushResponseHdr(State *s)
{
// Verify the pushed header wasn't longer than the content length
int64_t body_bytes = s->hdr_info.request_content_length - s->state_machine->pushed_response_hdr_bytes;
if (body_bytes < 0) {
HandlePushError(s, "Bad Content Length");
return;
}
// We need to create the request header storing in the cache
s->hdr_info.server_request.create(HTTP_TYPE_REQUEST);
s->hdr_info.server_request.copy(&s->hdr_info.client_request);
s->hdr_info.server_request.method_set(HTTP_METHOD_GET, HTTP_LEN_GET);
s->hdr_info.server_request.value_set("X-Inktomi-Source", 16, "http PUSH", 9);
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", &s->hdr_info.server_response, s->state_machine_id, "Pushed Response Header");
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", &s->hdr_info.server_request, s->state_machine_id, "Generated Request Header");
s->response_received_time = s->request_sent_time = ink_cluster_time();
if (is_response_cacheable(s, &s->hdr_info.server_request, &s->hdr_info.server_response)) {
ink_assert(s->cache_info.action == CACHE_PREPARE_TO_WRITE || s->cache_info.action == CACHE_PREPARE_TO_UPDATE);
TRANSACT_RETURN(SM_ACTION_CACHE_ISSUE_WRITE, HandlePushCacheWrite);
} else {
HandlePushError(s, "Response Not Cachable");
}
}
//////////////////////////////////////////////////////////////////////////////
// Name : HandlePushCacheWrite
// Description:
//
// Details :
//
// Called after performing the cache write on a push request
//////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandlePushCacheWrite(State *s)
{
switch (s->cache_info.write_lock_state) {
case CACHE_WL_SUCCESS:
// We were able to get the lock for the URL vector in the cache
if (s->cache_info.action == CACHE_PREPARE_TO_WRITE) {
s->cache_info.action = CACHE_DO_WRITE;
} else if (s->cache_info.action == CACHE_PREPARE_TO_UPDATE) {
s->cache_info.action = CACHE_DO_REPLACE;
} else {
ink_release_assert(0);
}
set_headers_for_cache_write(s, &s->cache_info.object_store, &s->hdr_info.server_request, &s->hdr_info.server_response);
TRANSACT_RETURN(SM_ACTION_STORE_PUSH_BODY, NULL);
break;
case CACHE_WL_FAIL:
case CACHE_WL_READ_RETRY:
// No write lock, can not complete request so bail
HandlePushError(s, "Cache Write Failed");
break;
case CACHE_WL_INIT:
default:
ink_release_assert(0);
}
}
void
HttpTransact::HandlePushTunnelSuccess(State *s)
{
ink_assert(s->cache_info.action == CACHE_DO_WRITE || s->cache_info.action == CACHE_DO_REPLACE);
// FIX ME: check PUSH spec for status codes
HTTPStatus resp_status = (s->cache_info.action == CACHE_DO_WRITE) ? HTTP_STATUS_CREATED : HTTP_STATUS_OK;
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, resp_status);
TRANSACT_RETURN(SM_ACTION_INTERNAL_CACHE_NOOP, NULL);
}
void
HttpTransact::HandlePushTunnelFailure(State *s)
{
HandlePushError(s, "Cache Error");
}
void
HttpTransact::HandleBadPushRespHdr(State *s)
{
HandlePushError(s, "Malformed Pushed Response Header");
}
void
HttpTransact::HandlePushError(State *s, const char *reason)
{
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
// Set half close flag to prevent TCP
// reset from the body still being transfered
s->state_machine->set_ua_half_close_flag();
build_error_response(s, HTTP_STATUS_BAD_REQUEST, reason, "default", NULL);
}
///////////////////////////////////////////////////////////////////////////////
// Name : HandleCacheOpenRead
// Description: the cache lookup succeeded - may have been a hit or a miss
//
// Details :
//
// the cache lookup succeeded. first check if the lookup resulted in
// a hit or a miss, if the lookup was for an http request.
// This function just funnels the result into the appropriate
// functions which handle these different cases.
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleCacheOpenRead(State *s)
{
DebugTxn("http_trans", "[HttpTransact::HandleCacheOpenRead]");
SET_VIA_STRING(VIA_DETAIL_CACHE_TYPE, VIA_DETAIL_CACHE);
bool read_successful = true;
if (s->cache_info.object_read == 0) {
read_successful = false;
//
// If somebody else was writing the document, proceed just like it was
// a normal cache miss, except don't try to write to the cache
//
if (s->cache_lookup_result == CACHE_LOOKUP_DOC_BUSY) {
s->cache_lookup_result = CACHE_LOOKUP_MISS;
s->cache_info.action = CACHE_DO_NO_ACTION;
}
} else {
CacheHTTPInfo *obj = s->cache_info.object_read;
if (obj->response_get()->type_get() == HTTP_TYPE_UNKNOWN) {
read_successful = false;
}
if (obj->request_get()->type_get() == HTTP_TYPE_UNKNOWN) {
read_successful = false;
}
}
if (s->method == HTTP_WKSIDX_PUSH) {
HandleCacheOpenReadPush(s, read_successful);
} else if (read_successful == false) {
// cache miss
DebugTxn("http_trans", "CacheOpenRead -- miss");
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_NOT_CACHED);
// StartAccessControl(s);
if (s->force_dns) {
HandleCacheOpenReadMiss(s);
} else {
// Cache Lookup Unsuccessful ..calling dns lookup
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, OSDNSLookup);
}
} else {
// cache hit
DebugTxn("http_trans", "CacheOpenRead -- hit");
TRANSACT_RETURN(SM_ACTION_API_READ_CACHE_HDR, HandleCacheOpenReadHitFreshness);
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : issue_revalidate
// Description: Sets cache action and does various bookkeeping
//
// Details :
//
// The Cache Lookup was hit but the document was stale so after
// calling build_request, we need setup up the cache action,
// set the via code, and possibly conditionalize the request
// The paths that we take to get this code are:
// Directly from HandleOpenReadHit if we are going to the origin server
// After PPDNS if we are going to a parent proxy
//
//
// Possible Next States From Here:
// -
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::issue_revalidate(State *s)
{
HTTPHdr *c_resp = find_appropriate_cached_resp(s);
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_CACHE_STALE);
ink_assert(GET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP) != ' ');
if (s->www_auth_content == CACHE_AUTH_FRESH) {
s->hdr_info.server_request.method_set(HTTP_METHOD_HEAD, HTTP_LEN_HEAD);
// The document is fresh in cache and we just want to see if the
// the client has the right credentials
// this cache action is just to get us into the hcoofsr function
s->cache_info.action = CACHE_DO_UPDATE;
if (!s->cop_test_page) {
DUMP_HEADER("http_hdrs", &s->hdr_info.server_request, s->state_machine_id, "Proxy's Request (Conditionalized)");
}
return;
}
if (s->cache_info.write_lock_state == CACHE_WL_INIT) {
// We do a cache lookup for DELETE, PUT and POST requests as well.
// We must, however, delete the cached copy after forwarding the
// request to the server. is_cache_response_returnable will ensure
// that we forward the request. We now specify what the cache
// action should be when the response is received.
if (does_method_require_cache_copy_deletion(s->http_config_param, s->method)) {
s->cache_info.action = CACHE_PREPARE_TO_DELETE;
DebugTxn("http_seq", "[HttpTransact::issue_revalidate] cache action: DELETE");
} else {
s->cache_info.action = CACHE_PREPARE_TO_UPDATE;
DebugTxn("http_seq", "[HttpTransact::issue_revalidate] cache action: UPDATE");
}
} else {
// We've looped back around due to missing the write lock
// for the cache. At this point we want to forget about the cache
ink_assert(s->cache_info.write_lock_state == CACHE_WL_READ_RETRY);
s->cache_info.action = CACHE_DO_NO_ACTION;
return;
}
// if the document is cached, just send a conditional request to the server
// So the request does not have preconditions. It can, however
// be a simple GET request with a Pragma:no-cache. As on 8/28/98
// we have fixed the whole Reload/Shift-Reload cached copy
// corruption problem. This means that we can issue a conditional
// request to the server only if the incoming request has a conditional
// or the incoming request does NOT have a no-cache header.
// In other words, if the incoming request is not conditional
// but has a no-cache header we can not issue an IMS. check for
// that case here.
bool no_cache_in_request = false;
if (s->hdr_info.client_request.is_pragma_no_cache_set() || s->hdr_info.client_request.is_cache_control_set(HTTP_VALUE_NO_CACHE)) {
DebugTxn("http_trans", "[issue_revalidate] no-cache header directive in request, folks");
no_cache_in_request = true;
}
if ((!(s->hdr_info.client_request.presence(MIME_PRESENCE_IF_MODIFIED_SINCE))) &&
(!(s->hdr_info.client_request.presence(MIME_PRESENCE_IF_NONE_MATCH))) && (no_cache_in_request == true) &&
(!s->txn_conf->cache_ims_on_client_no_cache) && (s->www_auth_content == CACHE_AUTH_NONE)) {
DebugTxn("http_trans",
"[issue_revalidate] Can not make this a conditional request. This is the force update of the cached copy case");
// set cache action to update. response will be a 200 or error,
// causing cached copy to be replaced (if 200).
s->cache_info.action = CACHE_PREPARE_TO_UPDATE;
return;
}
// do not conditionalize if the cached response is not a 200
switch (c_resp->status_get()) {
case HTTP_STATUS_OK: // 200
// don't conditionalize if we are configured to repeat the clients
// conditionals
if (s->txn_conf->cache_when_to_revalidate == 4) {
break;
}
// ok, request is either a conditional or does not have a no-cache.
// (or is method that we don't conditionalize but lookup the
// cache on like DELETE)
if (c_resp->get_last_modified() > 0 && (s->hdr_info.server_request.method_get_wksidx() == HTTP_WKSIDX_GET ||
s->hdr_info.server_request.method_get_wksidx() == HTTP_WKSIDX_HEAD) &&
s->range_setup == RANGE_NONE) {
// make this a conditional request
int length;
const char *str = c_resp->value_get(MIME_FIELD_LAST_MODIFIED, MIME_LEN_LAST_MODIFIED, &length);
s->hdr_info.server_request.value_set(MIME_FIELD_IF_MODIFIED_SINCE, MIME_LEN_IF_MODIFIED_SINCE, str, length);
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", &s->hdr_info.server_request, s->state_machine_id, "Proxy's Request (Conditionalized)");
}
// if Etag exists, also add if-non-match header
if (c_resp->presence(MIME_PRESENCE_ETAG) && (s->hdr_info.server_request.method_get_wksidx() == HTTP_WKSIDX_GET ||
s->hdr_info.server_request.method_get_wksidx() == HTTP_WKSIDX_HEAD)) {
int length;
const char *etag = c_resp->value_get(MIME_FIELD_ETAG, MIME_LEN_ETAG, &length);
if ((length >= 2) && (etag[0] == 'W') && (etag[1] == '/')) {
etag += 2;
length -= 2;
}
s->hdr_info.server_request.value_set(MIME_FIELD_IF_NONE_MATCH, MIME_LEN_IF_NONE_MATCH, etag, length);
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", &s->hdr_info.server_request, s->state_machine_id, "Proxy's Request (Conditionalized)");
}
break;
case HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: // 203
/* fall through */
case HTTP_STATUS_MULTIPLE_CHOICES: // 300
/* fall through */
case HTTP_STATUS_MOVED_PERMANENTLY: // 301
/* fall through */
case HTTP_STATUS_GONE: // 410
/* fall through */
default:
DebugTxn("http_trans", "[issue_revalidate] cached response is"
"not a 200 response so no conditionalization.");
s->cache_info.action = CACHE_PREPARE_TO_UPDATE;
break;
case HTTP_STATUS_PARTIAL_CONTENT:
ink_assert(!"unexpected status code");
break;
}
}
void
HttpTransact::HandleCacheOpenReadHitFreshness(State *s)
{
CacheHTTPInfo *&obj = s->cache_info.object_read;
ink_release_assert((s->request_sent_time == UNDEFINED_TIME) && (s->response_received_time == UNDEFINED_TIME));
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHitFreshness] Hit in cache");
if (delete_all_document_alternates_and_return(s, true)) {
DebugTxn("http_trans", "[HandleCacheOpenReadHitFreshness] Delete and return");
s->cache_info.action = CACHE_DO_DELETE;
s->next_action = HttpTransact::SM_ACTION_INTERNAL_CACHE_DELETE;
return;
}
s->request_sent_time = obj->request_sent_time_get();
s->response_received_time = obj->response_received_time_get();
// There may be clock skew if one of the machines
// went down and we do not have the correct delta
// for it. this is just to deal with the effects
// of the skew by setting minimum and maximum times
// so that ages are not negative, etc.
s->request_sent_time = min(s->client_request_time, s->request_sent_time);
s->response_received_time = min(s->client_request_time, s->response_received_time);
ink_assert(s->request_sent_time <= s->response_received_time);
DebugTxn("http_trans", "[HandleCacheOpenReadHitFreshness] request_sent_time : %" PRId64, (int64_t)s->request_sent_time);
DebugTxn("http_trans", "[HandleCacheOpenReadHitFreshness] response_received_time : %" PRId64, (int64_t)s->response_received_time);
// if the plugin has already decided the freshness, we don't need to
// do it again
if (s->cache_lookup_result == HttpTransact::CACHE_LOOKUP_NONE) {
// is the document still fresh enough to be served back to
// the client without revalidation?
Freshness_t freshness = what_is_document_freshness(s, &s->hdr_info.client_request, obj->response_get());
switch (freshness) {
case FRESHNESS_FRESH:
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHitFreshness] "
"Fresh copy");
s->cache_lookup_result = HttpTransact::CACHE_LOOKUP_HIT_FRESH;
break;
case FRESHNESS_WARNING:
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHitFreshness] "
"Heuristic-based Fresh copy");
s->cache_lookup_result = HttpTransact::CACHE_LOOKUP_HIT_WARNING;
break;
case FRESHNESS_STALE:
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHitFreshness] "
"Stale in cache");
s->cache_lookup_result = HttpTransact::CACHE_LOOKUP_HIT_STALE;
s->is_revalidation_necessary = true; // to identify a revalidation occurrence
break;
default:
ink_assert(!("what_is_document_freshness has returned unsupported code."));
break;
}
}
ink_assert(s->cache_lookup_result != HttpTransact::CACHE_LOOKUP_MISS);
if (s->cache_lookup_result == HttpTransact::CACHE_LOOKUP_HIT_STALE)
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_EXPIRED);
if (!s->force_dns) { // If DNS is not performed before
if (need_to_revalidate(s)) {
TRANSACT_RETURN(SM_ACTION_API_CACHE_LOOKUP_COMPLETE,
CallOSDNSLookup); // content needs to be revalidated and we did not perform a dns ....calling DNS lookup
} else { // document can be served can cache
TRANSACT_RETURN(SM_ACTION_API_CACHE_LOOKUP_COMPLETE, HttpTransact::HandleCacheOpenReadHit);
}
} else { // we have done dns . Its up to HandleCacheOpenReadHit to decide to go OS or serve from cache
TRANSACT_RETURN(SM_ACTION_API_CACHE_LOOKUP_COMPLETE, HttpTransact::HandleCacheOpenReadHit);
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : CallOSDNSLookup
// Description: Moves in SM_ACTION_DNS_LOOKUP state and sets the transact return to OSDNSLookup
//
// Details :
/////////////////////////////////////////////////////////////////////////////
void
HttpTransact::CallOSDNSLookup(State *s)
{
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, OSDNSLookup);
}
///////////////////////////////////////////////////////////////////////////////
// Name : need_to_revalidate
// Description: Checks if a document which is in the cache needs to be revalidates
//
// Details : Function calls AuthenticationNeeded and is_cache_response_returnable to determine
// if the cached document can be served
/////////////////////////////////////////////////////////////////////////////
bool
HttpTransact::need_to_revalidate(State *s)
{
bool needs_revalidate, needs_authenticate = false;
bool needs_cache_auth = false;
CacheHTTPInfo *obj;
if (s->api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE) {
obj = &s->cache_info.object_store;
ink_assert(obj->valid());
if (!obj->valid()) {
return true;
}
} else {
obj = s->cache_info.object_read;
}
// do we have to authenticate with the server before
// sending back the cached response to the client?
Authentication_t authentication_needed = AuthenticationNeeded(s->txn_conf, &s->hdr_info.client_request, obj->response_get());
switch (authentication_needed) {
case AUTHENTICATION_SUCCESS:
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHit] "
"Authentication not needed");
needs_authenticate = false;
break;
case AUTHENTICATION_MUST_REVALIDATE:
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_METHOD);
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHit] "
"Authentication needed");
needs_authenticate = true;
break;
case AUTHENTICATION_MUST_PROXY:
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHit] "
"Authentication needed");
needs_authenticate = true;
break;
case AUTHENTICATION_CACHE_AUTH:
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHit] "
"Authentication needed for cache_auth_content");
needs_authenticate = false;
needs_cache_auth = true;
break;
default:
ink_assert(!("AuthenticationNeeded has returned unsupported code."));
return true;
break;
}
ink_assert(s->cache_lookup_result == CACHE_LOOKUP_HIT_FRESH || s->cache_lookup_result == CACHE_LOOKUP_HIT_WARNING ||
s->cache_lookup_result == CACHE_LOOKUP_HIT_STALE);
if (s->cache_lookup_result == CACHE_LOOKUP_HIT_STALE &&
s->api_update_cached_object != HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE) {
needs_revalidate = true;
} else {
needs_revalidate = false;
}
bool send_revalidate = ((needs_authenticate == true) || (needs_revalidate == true) || (is_cache_response_returnable(s) == false));
if (needs_cache_auth == true) {
s->www_auth_content = send_revalidate ? CACHE_AUTH_STALE : CACHE_AUTH_FRESH;
send_revalidate = true;
}
return send_revalidate;
}
///////////////////////////////////////////////////////////////////////////////
// Name : HandleCacheOpenReadHit
// Description: handle result of a cache hit
//
// Details :
//
// Cache lookup succeeded and resulted in a cache hit. This means
// that the Accept* and Etags fields also matched. The cache lookup
// may have resulted in a vector of alternates (since lookup may
// be based on a url). A different function (SelectFromAlternates)
// goes through the alternates and finds the best match. That is
// then returned to this function. The result may not be sent back
// to the client, still, if the document is not fresh enough, or
// does not have enough authorization, or if the client wants a
// reload, etc. that decision will be made in this routine.
//
//
// Possible Next States From Here:
// - HttpTransact::PROXY_INTERNAL_CACHE_DELETE;
// - HttpTransact::SM_ACTION_DNS_LOOKUP;
// - HttpTransact::ORIGIN_SERVER_OPEN;
// - HttpTransact::PROXY_INTERNAL_CACHE_NOOP;
// - HttpTransact::SERVE_FROM_CACHE;
// - result of how_to_open_connection()
//
//
// For Range requests, we will decide to do simple tunneling if one of the
// following conditions hold:
// - document stale
// - cached response doesn't have Accept-Ranges and Content-Length
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleCacheOpenReadHit(State *s)
{
bool needs_revalidate, needs_authenticate = false;
bool needs_cache_auth = false;
bool server_up = true;
CacheHTTPInfo *obj;
if (s->api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE) {
obj = &s->cache_info.object_store;
ink_assert(obj->valid());
} else {
obj = s->cache_info.object_read;
}
// do we have to authenticate with the server before
// sending back the cached response to the client?
Authentication_t authentication_needed = AuthenticationNeeded(s->txn_conf, &s->hdr_info.client_request, obj->response_get());
switch (authentication_needed) {
case AUTHENTICATION_SUCCESS:
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHit] "
"Authentication not needed");
needs_authenticate = false;
break;
case AUTHENTICATION_MUST_REVALIDATE:
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_METHOD);
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHit] "
"Authentication needed");
needs_authenticate = true;
break;
case AUTHENTICATION_MUST_PROXY:
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHit] "
"Authentication needed");
HandleCacheOpenReadMiss(s);
return;
case AUTHENTICATION_CACHE_AUTH:
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHit] "
"Authentication needed for cache_auth_content");
needs_authenticate = false;
needs_cache_auth = true;
break;
default:
ink_assert(!("AuthenticationNeeded has returned unsupported code."));
break;
}
ink_assert(s->cache_lookup_result == CACHE_LOOKUP_HIT_FRESH || s->cache_lookup_result == CACHE_LOOKUP_HIT_WARNING ||
s->cache_lookup_result == CACHE_LOOKUP_HIT_STALE);
if (s->cache_lookup_result == CACHE_LOOKUP_HIT_STALE &&
s->api_update_cached_object != HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE) {
needs_revalidate = true;
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_EXPIRED);
} else {
needs_revalidate = false;
}
// the response may not be directly returnable to the client. there
// are several reasons for this: config may force revalidation or
// client may have forced a refresh by sending a Pragma:no-cache
// or a Cache-Control:no-cache, or the client may have sent a
// non-GET/HEAD request for a document that is cached. an example
// of a situation for this is when a client sends a DELETE, PUT
// or POST request for a url that is cached. except for DELETE,
// we may actually want to update the cached copy with the contents
// of the PUT/POST, but the easiest, safest and most robust solution
// is to simply delete the cached copy (in order to maintain cache
// consistency). this is particularly true if the server does not
// accept or conditionally accepts the PUT/POST requests.
// anyhow, this is an overloaded function and will return false
// if the origin server still has to be looked up.
bool response_returnable = is_cache_response_returnable(s);
// do we need to revalidate. in other words if the response
// has to be authorized, is stale or can not be returned, do
// a revalidate.
bool send_revalidate = ((needs_authenticate == true) || (needs_revalidate == true) || (response_returnable == false));
if (needs_cache_auth == true) {
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_EXPIRED);
s->www_auth_content = send_revalidate ? CACHE_AUTH_STALE : CACHE_AUTH_FRESH;
send_revalidate = true;
}
DebugTxn("http_trans", "CacheOpenRead --- needs_auth = %d", needs_authenticate);
DebugTxn("http_trans", "CacheOpenRead --- needs_revalidate = %d", needs_revalidate);
DebugTxn("http_trans", "CacheOpenRead --- response_returnable = %d", response_returnable);
DebugTxn("http_trans", "CacheOpenRead --- needs_cache_auth = %d", needs_cache_auth);
DebugTxn("http_trans", "CacheOpenRead --- send_revalidate = %d", send_revalidate);
if (send_revalidate) {
DebugTxn("http_trans", "CacheOpenRead --- HIT-STALE");
s->dns_info.attempts = 0;
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHit] "
"Revalidate document with server");
if (s->http_config_param->icp_enabled && icp_dynamic_enabled && s->http_config_param->stale_icp_enabled &&
needs_authenticate == false && needs_cache_auth == false && !s->hdr_info.client_request.is_pragma_no_cache_set() &&
!s->hdr_info.client_request.is_cache_control_set(HTTP_VALUE_NO_CACHE)) {
DebugTxn("http_trans", "[HandleCacheOpenReadHit] ICP is configured"
" and no no-cache in request; checking ICP for a STALE hit");
s->stale_icp_lookup = true;
// we haven't done the ICP lookup yet. The following is to
// fake an icp_info to cater for build_request's needs
s->icp_info.http_version.set(1, 0);
if (!s->txn_conf->keep_alive_enabled_out) {
s->icp_info.keep_alive = HTTP_NO_KEEPALIVE;
} else {
s->icp_info.keep_alive = HTTP_KEEPALIVE;
}
update_current_info(&s->current, &s->icp_info, HttpTransact::ICP_SUGGESTED_HOST, 1);
}
if (s->stale_icp_lookup == false) {
find_server_and_update_current_info(s);
// We do not want to try to revalidate documents if we think
// the server is down due to the something report problem
//
// Note: we only want to skip origin servers because 1)
// parent proxies have their own negative caching
// scheme & 2) If we skip down parents, every page
// we serve is potentially stale
//
if (s->current.request_to == ORIGIN_SERVER && is_server_negative_cached(s) && response_returnable == true &&
is_stale_cache_response_returnable(s) == true) {
server_up = false;
update_current_info(&s->current, NULL, UNDEFINED_LOOKUP, 0);
DebugTxn("http_trans", "CacheOpenReadHit - server_down, returning stale document");
}
// a parent lookup could come back as PARENT_FAIL if in parent.config, go_direct == false and
// there are no available parents (all down).
else if (s->current.request_to == HOST_NONE && s->parent_result.result == PARENT_FAIL) {
if (is_server_negative_cached(s) && response_returnable == true && is_stale_cache_response_returnable(s) == true) {
server_up = false;
update_current_info(&s->current, NULL, UNDEFINED_LOOKUP, 0);
DebugTxn("http_trans", "CacheOpenReadHit - server_down, returning stale document");
} else {
handle_parent_died(s);
return;
}
}
}
if (server_up || s->stale_icp_lookup) {
bool check_hostdb = get_ka_info_from_config(s, s->current.server);
DebugTxn("http_trans", "CacheOpenReadHit - check_hostdb %d", check_hostdb);
if (!s->stale_icp_lookup && (check_hostdb || !s->current.server->dst_addr.isValid())) {
// ink_release_assert(s->current.request_to == PARENT_PROXY ||
// s->http_config_param->no_dns_forward_to_parent != 0);
// We must be going a PARENT PROXY since so did
// origin server DNS lookup right after state Start
//
// If we end up here in the release case just fall
// through. The request will fail because of the
// missing ip but we won't take down the system
//
if (s->current.request_to == PARENT_PROXY) {
// Set ourselves up to handle pending revalidate issues
// after the PP DNS lookup
ink_assert(s->pending_work == NULL);
s->pending_work = issue_revalidate;
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, PPDNSLookup);
} else if (s->current.request_to == ORIGIN_SERVER) {
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, OSDNSLookup);
} else {
handle_parent_died(s);
return;
}
}
DebugTxn("http_trans", "CacheOpenReadHit - version %d", s->current.server->http_version.m_version);
build_request(s, &s->hdr_info.client_request, &s->hdr_info.server_request, s->current.server->http_version);
issue_revalidate(s);
// this can not be anything but a simple origin server connection.
// in other words, we would not have looked up the cache for a
// connect request, so the next action can not be origin_server_raw_open.
s->next_action = how_to_open_connection(s);
if (s->stale_icp_lookup && s->next_action == SM_ACTION_ORIGIN_SERVER_OPEN) {
s->next_action = SM_ACTION_ICP_QUERY;
}
ink_release_assert(s->next_action != SM_ACTION_ORIGIN_SERVER_RAW_OPEN);
return;
} else { // server is down but stale response is returnable
SET_VIA_STRING(VIA_DETAIL_CACHE_TYPE, VIA_DETAIL_CACHE);
}
}
// cache hit, document is fresh, does not authorization,
// is valid, etc. etc. send it back to the client.
//
// the important thing to keep in mind is that if we are
// here then we found a match in the cache and the document
// is fresh and we have enough authorization for it to send
// it back to the client without revalidating first with the
// origin server. we are, therefore, allowed to behave as the
// origin server. we can, therefore, make the claim that the
// document has not been modified since or has not been unmodified
// since the time requested by the client. this may not be
// the case in reality, but since the document is fresh in
// the cache, we can make the claim that this is the truth.
//
// so, any decision we make at this point can be made with authority.
// realistically, if we can not make this claim, then there
// is no reason to cache anything.
//
ink_assert((send_revalidate == true && server_up == false) || (send_revalidate == false && server_up == true));
DebugTxn("http_trans", "CacheOpenRead --- HIT-FRESH");
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHit] "
"Serve from cache");
// ToDo: Should support other levels of cache hits here, but the cache does not support it (yet)
if (SQUID_HIT_RAM == s->cache_info.hit_miss_code) {
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_RAM_CACHE_FRESH);
} else {
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_CACHE_FRESH);
}
if (s->cache_lookup_result == CACHE_LOOKUP_HIT_WARNING) {
build_response_from_cache(s, HTTP_WARNING_CODE_HERUISTIC_EXPIRATION);
} else if (s->cache_lookup_result == CACHE_LOOKUP_HIT_STALE) {
ink_assert(server_up == false);
build_response_from_cache(s, HTTP_WARNING_CODE_REVALIDATION_FAILED);
} else {
build_response_from_cache(s, HTTP_WARNING_CODE_NONE);
}
if (s->api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE) {
s->saved_update_next_action = s->next_action;
s->saved_update_cache_action = s->cache_info.action;
s->next_action = SM_ACTION_CACHE_PREPARE_UPDATE;
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : build_response_from_cache()
// Description: build a client response from cached response and client request
//
// Input : State, warning code to be inserted into the response header
// Output :
//
// Details : This function is called if we decided to serve a client request
// using a cached response.
// It is called by handle_server_connection_not_open()
// and HandleCacheOpenReadHit().
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::build_response_from_cache(State *s, HTTPWarningCode warning_code)
{
HTTPHdr *client_request = &s->hdr_info.client_request;
HTTPHdr *cached_response = NULL;
HTTPHdr *to_warn = &s->hdr_info.client_response;
CacheHTTPInfo *obj;
if (s->api_update_cached_object == HttpTransact::UPDATE_CACHED_OBJECT_CONTINUE) {
obj = &s->cache_info.object_store;
ink_assert(obj->valid());
} else {
obj = s->cache_info.object_read;
}
cached_response = obj->response_get();
// If the client request is conditional, and the cached copy meets
// the conditions, do not need to send back the full document,
// just a NOT_MODIFIED response.
// If the request is not conditional,
// the function match_response_to_request_conditionals() returns
// the code of the cached response, which means that we should send
// back the full document.
HTTPStatus client_response_code =
HttpTransactCache::match_response_to_request_conditionals(client_request, cached_response, s->response_received_time);
switch (client_response_code) {
case HTTP_STATUS_NOT_MODIFIED:
// A IMS or INM GET client request with conditions being met
// by the cached response. Send back a NOT MODIFIED response.
DebugTxn("http_trans", "[build_response_from_cache] Not modified");
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_HIT_CONDITIONAL);
build_response(s, cached_response, &s->hdr_info.client_response, s->client_info.http_version, client_response_code);
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
break;
case HTTP_STATUS_PRECONDITION_FAILED:
// A conditional request with conditions not being met by the cached
// response. Send back a PRECONDITION FAILED response.
DebugTxn("http_trans", "[build_response_from_cache] Precondition Failed");
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_CONDITIONAL);
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, client_response_code);
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
break;
case HTTP_STATUS_RANGE_NOT_SATISFIABLE:
// Check if cached response supports Range. If it does, append
// Range transformation plugin
// A little misnomer. HTTP_STATUS_RANGE_NOT_SATISFIABLE
// acutally means If-Range match fails here.
// fall through
default:
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_HIT_SERVED);
if (s->method == HTTP_WKSIDX_GET || s->api_resp_cacheable == true) {
// send back the full document to the client.
DebugTxn("http_trans", "[build_response_from_cache] Match! Serving full document.");
s->cache_info.action = CACHE_DO_SERVE;
// Check if cached response supports Range. If it does, append
// Range transformation plugin
// only if the cached response is a 200 OK
if (client_response_code == HTTP_STATUS_OK && client_request->presence(MIME_PRESENCE_RANGE)) {
s->state_machine->do_range_setup_if_necessary();
if (s->range_setup == RANGE_NOT_SATISFIABLE) {
build_error_response(s, HTTP_STATUS_RANGE_NOT_SATISFIABLE, "Requested Range Not Satisfiable", "default", NULL);
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
break;
} else if ((s->range_setup == RANGE_NOT_HANDLED) || !s->range_in_cache) {
// we switch to tunneling for Range requests if it is out of order.
// or if the range can't be satisfied from the cache
// In that case we fetch the entire source so it's OK to switch
// this late.
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadHit] Out-of-order Range request - tunneling");
s->cache_info.action = CACHE_DO_NO_ACTION;
if (s->force_dns) {
HandleCacheOpenReadMiss(s); // DNS is already completed no need of doing DNS
} else {
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP,
OSDNSLookup); // DNS not done before need to be done now as we are connecting to OS
}
return;
}
}
if (s->state_machine->do_transform_open()) {
set_header_for_transform(s, cached_response);
to_warn = &s->hdr_info.transform_response;
} else {
build_response(s, cached_response, &s->hdr_info.client_response, s->client_info.http_version);
}
s->next_action = SM_ACTION_SERVE_FROM_CACHE;
}
// If the client request is a HEAD, then serve the header from cache.
else if (s->method == HTTP_WKSIDX_HEAD) {
DebugTxn("http_trans", "[build_response_from_cache] Match! Serving header only.");
build_response(s, cached_response, &s->hdr_info.client_response, s->client_info.http_version);
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
} else {
// We handled the request but it's not GET or HEAD (eg. DELETE),
// and server is not reacheable: 502
//
DebugTxn("http_trans", "[build_response_from_cache] No match! Connection failed.");
build_error_response(s, HTTP_STATUS_BAD_GATEWAY, "Connection Failed", "connect#failed_connect", NULL);
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
warning_code = HTTP_WARNING_CODE_NONE;
}
break;
}
// After building the client response, add the given warning if provided.
if (warning_code != HTTP_WARNING_CODE_NONE) {
delete_warning_value(to_warn, warning_code);
HttpTransactHeaders::insert_warning_header(s->http_config_param, to_warn, warning_code);
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : handle_cache_write_lock
// Description:
//
// Details :
//
//
//
// Possible Next States From Here:
// - result of how_to_open_connection
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_cache_write_lock(State *s)
{
bool remove_ims = false;
ink_assert(s->cache_info.action == CACHE_PREPARE_TO_DELETE || s->cache_info.action == CACHE_PREPARE_TO_UPDATE ||
s->cache_info.action == CACHE_PREPARE_TO_WRITE);
switch (s->cache_info.write_lock_state) {
case CACHE_WL_SUCCESS:
// We were able to get the lock for the URL vector in the cache
SET_UNPREPARE_CACHE_ACTION(s->cache_info);
break;
case CACHE_WL_FAIL:
// No write lock, ignore the cache and proxy only;
// FIX: Should just serve from cache if this is a revalidate
s->cache_info.action = CACHE_DO_NO_ACTION;
switch (s->cache_open_write_fail_action) {
case CACHE_WL_FAIL_ACTION_ERROR_ON_MISS:
case CACHE_WL_FAIL_ACTION_ERROR_ON_MISS_STALE_ON_REVALIDATE:
case CACHE_WL_FAIL_ACTION_ERROR_ON_MISS_OR_REVALIDATE:
DebugTxn("http_error", "cache_open_write_fail_action %d, cache miss, return error", s->cache_open_write_fail_action);
s->cache_info.write_status = CACHE_WRITE_ERROR;
build_error_response(s, HTTP_STATUS_BAD_GATEWAY, "Connection Failed", "connect#failed_connect", NULL);
MIMEField *ats_field;
HTTPHdr *header;
header = &(s->hdr_info.client_response);
if ((ats_field = header->field_find(MIME_FIELD_ATS_INTERNAL, MIME_LEN_ATS_INTERNAL)) == NULL) {
if (likely((ats_field = header->field_create(MIME_FIELD_ATS_INTERNAL, MIME_LEN_ATS_INTERNAL)) != NULL)) {
header->field_attach(ats_field);
}
}
if (likely(ats_field)) {
int value = (s->cache_info.object_read) ? 1 : 0;
DebugTxn("http_error", "Adding Ats-Internal-Messages: %d", value);
header->field_value_set_int(ats_field, value);
} else {
DebugTxn("http_error", "failed to add Ats-Internal-Messages");
}
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
return;
default:
s->cache_info.write_status = CACHE_WRITE_LOCK_MISS;
remove_ims = true;
break;
}
break;
case CACHE_WL_READ_RETRY:
// Write failed but retried and got a vector to read
// We need to clean up our state so that transact does
// not assert later on. Then handle the open read hit
//
s->request_sent_time = UNDEFINED_TIME;
s->response_received_time = UNDEFINED_TIME;
s->cache_info.action = CACHE_DO_LOOKUP;
remove_ims = true;
SET_VIA_STRING(VIA_DETAIL_CACHE_TYPE, VIA_DETAIL_CACHE);
break;
case CACHE_WL_INIT:
default:
ink_release_assert(0);
break;
}
// Since we've already built the server request and we can't get the write
// lock we need to remove the ims field from the request since we're
// ignoring the cache. If their is a client ims field, copy that since
// we're tunneling response anyway
if (remove_ims) {
s->hdr_info.server_request.field_delete(MIME_FIELD_IF_MODIFIED_SINCE, MIME_LEN_IF_MODIFIED_SINCE);
s->hdr_info.server_request.field_delete(MIME_FIELD_IF_NONE_MATCH, MIME_LEN_IF_NONE_MATCH);
MIMEField *c_ims = s->hdr_info.client_request.field_find(MIME_FIELD_IF_MODIFIED_SINCE, MIME_LEN_IF_MODIFIED_SINCE);
MIMEField *c_inm = s->hdr_info.client_request.field_find(MIME_FIELD_IF_NONE_MATCH, MIME_LEN_IF_NONE_MATCH);
if (c_ims) {
int len;
const char *value = c_ims->value_get(&len);
s->hdr_info.server_request.value_set(MIME_FIELD_IF_MODIFIED_SINCE, MIME_LEN_IF_MODIFIED_SINCE, value, len);
}
if (c_inm) {
int len;
const char *value = c_inm->value_get(&len);
s->hdr_info.server_request.value_set(MIME_FIELD_IF_NONE_MATCH, MIME_LEN_IF_NONE_MATCH, value, len);
}
}
if (s->cache_info.write_lock_state == CACHE_WL_READ_RETRY) {
DebugTxn("http_error", "calling hdr_info.server_request.destroy");
s->hdr_info.server_request.destroy();
HandleCacheOpenReadHitFreshness(s);
} else {
StateMachineAction_t next;
if (s->stale_icp_lookup == false) {
next = how_to_open_connection(s);
if (next == SM_ACTION_ORIGIN_SERVER_OPEN || next == SM_ACTION_ORIGIN_SERVER_RAW_OPEN) {
s->next_action = next;
TRANSACT_RETURN(next, NULL);
} else {
// hehe!
s->next_action = next;
ink_assert(s->next_action == SM_ACTION_DNS_LOOKUP);
return;
}
} else {
next = SM_ACTION_ICP_QUERY;
}
TRANSACT_RETURN(next, NULL);
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : HandleCacheOpenReadMiss
// Description: cache looked up, miss or hit, but needs authorization
//
// Details :
//
//
//
// Possible Next States From Here:
// - HttpTransact::ICP_QUERY;
// - HttpTransact::SM_ACTION_DNS_LOOKUP;
// - HttpTransact::ORIGIN_SERVER_OPEN;
// - HttpTransact::PROXY_INTERNAL_CACHE_NOOP;
// - result of how_to_open_connection()
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleCacheOpenReadMiss(State *s)
{
DebugTxn("http_trans", "[HandleCacheOpenReadMiss] --- MISS");
DebugTxn("http_seq", "[HttpTransact::HandleCacheOpenReadMiss] "
"Miss in cache");
if (delete_all_document_alternates_and_return(s, false)) {
DebugTxn("http_trans", "[HandleCacheOpenReadMiss] Delete and return");
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
return;
}
// reinitialize some variables to reflect cache miss state.
s->cache_info.object_read = NULL;
s->request_sent_time = UNDEFINED_TIME;
s->response_received_time = UNDEFINED_TIME;
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_CACHE_MISS);
if (GET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP) == ' ') {
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_NOT_CACHED);
}
// We do a cache lookup for DELETE and PUT requests as well.
// We must, however, not cache the responses to these requests.
if (does_method_require_cache_copy_deletion(s->http_config_param, s->method) && s->api_req_cacheable == false) {
s->cache_info.action = CACHE_DO_NO_ACTION;
} else if ((s->hdr_info.client_request.presence(MIME_PRESENCE_RANGE) && !s->txn_conf->cache_range_write) ||
does_method_effect_cache(s->method) == false || s->range_setup == RANGE_NOT_SATISFIABLE ||
s->range_setup == RANGE_NOT_HANDLED) {
s->cache_info.action = CACHE_DO_NO_ACTION;
} else {
s->cache_info.action = CACHE_PREPARE_TO_WRITE;
}
// We should not issue an ICP lookup if the request has a
// no-cache header. First check if the request has a no
// cache header. Then, if icp is enabled and the request
// does not have a no-cache header, issue an icp lookup.
// does the request have a no-cache?
bool no_cache_in_request = false;
if (s->hdr_info.client_request.is_pragma_no_cache_set() || s->hdr_info.client_request.is_cache_control_set(HTTP_VALUE_NO_CACHE)) {
no_cache_in_request = true;
}
// if ICP is enabled and above test indicates that request
// does not have a no-cache, issue icp query to sibling cache.
if (s->http_config_param->icp_enabled && icp_dynamic_enabled != 0 && (no_cache_in_request == false)) {
DebugTxn("http_trans", "[HandleCacheOpenReadMiss] "
"ICP is configured and no no-cache in request; checking ICP");
s->next_action = SM_ACTION_ICP_QUERY;
return;
}
///////////////////////////////////////////////////////////////
// a normal miss would try to fetch the document from the //
// origin server, unless the origin server isn't resolvable, //
// but if "CacheControl: only-if-cached" is set, then we are //
// supposed to send a 504 (GATEWAY TIMEOUT) response. //
///////////////////////////////////////////////////////////////
HTTPHdr *h = &s->hdr_info.client_request;
if (!h->is_cache_control_set(HTTP_VALUE_ONLY_IF_CACHED)) {
find_server_and_update_current_info(s);
// a parent lookup could come back as PARENT_FAIL if in parent.config go_direct == false and
// there are no available parents (all down).
if (s->parent_result.result == PARENT_FAIL) {
handle_parent_died(s);
return;
}
if (!s->current.server->dst_addr.isValid()) {
ink_release_assert(s->current.request_to == PARENT_PROXY || s->http_config_param->no_dns_forward_to_parent != 0);
if (s->current.request_to == PARENT_PROXY) {
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, HttpTransact::PPDNSLookup);
} else {
handle_parent_died(s);
return;
}
}
build_request(s, &s->hdr_info.client_request, &s->hdr_info.server_request, s->current.server->http_version);
s->next_action = how_to_open_connection(s);
} else { // miss, but only-if-cached is set
build_error_response(s, HTTP_STATUS_GATEWAY_TIMEOUT, "Not Cached", "cache#not_in_cache", NULL);
s->next_action = SM_ACTION_SEND_ERROR_CACHE_NOOP;
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : HandleICPLookup
// Description:
//
// Details :
//
//
//
// Possible Next States From Here:
// - HttpTransact::SM_ACTION_DNS_LOOKUP;
// - HttpTransact::PROXY_INTERNAL_CACHE_NOOP;
// - result of how_to_open_connection()
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleICPLookup(State *s)
{
SET_VIA_STRING(VIA_DETAIL_CACHE_TYPE, VIA_DETAIL_ICP);
if (s->icp_lookup_success == true) {
HTTP_INCREMENT_DYN_STAT(http_icp_suggested_lookups_stat);
DebugTxn("http_trans", "[HandleICPLookup] Success, sending request to icp suggested host.");
ats_ip4_set(&s->icp_info.dst_addr, s->icp_ip_result.sin_addr.s_addr);
s->icp_info.dst_addr.port() = ntohs(s->icp_ip_result.sin_port);
// TODO in this case we should go to the miss case
// just a little shy about using goto's, that's all.
ink_release_assert((s->icp_info.dst_addr.port() != s->client_info.dst_addr.port()) ||
(ats_ip_addr_cmp(&s->icp_info.dst_addr.sa, &Machine::instance()->ip.sa) != 0));
// Since the ICPDNSLookup is not called, these two
// values are not initialized.
// Force them to be initialized
s->icp_info.http_version.set(1, 0);
if (!s->txn_conf->keep_alive_enabled_out) {
s->icp_info.keep_alive = HTTP_NO_KEEPALIVE;
} else {
s->icp_info.keep_alive = HTTP_KEEPALIVE;
}
s->icp_info.name = (char *)s->arena.alloc(17);
unsigned char *p = (unsigned char *)&s->icp_ip_result.sin_addr.s_addr;
snprintf(s->icp_info.name, 17, "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
update_current_info(&s->current, &s->icp_info, ICP_SUGGESTED_HOST, 1);
s->next_hop_scheme = URL_WKSIDX_HTTP;
} else {
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_NOT_CACHED);
DebugTxn("http_trans", "[HandleICPLookup] Failure, sending request to forward server.");
s->parent_info.name = NULL;
ink_zero(s->parent_info.dst_addr);
find_server_and_update_current_info(s);
if (!ats_is_ip(&s->current.server->dst_addr)) {
if (s->current.request_to == PARENT_PROXY) {
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, PPDNSLookup);
} else {
ink_release_assert(0);
}
return;
}
}
if (!s->stale_icp_lookup) {
build_request(s, &s->hdr_info.client_request, &s->hdr_info.server_request, s->current.server->http_version);
} else {
ink_assert(s->hdr_info.server_request.valid());
s->stale_icp_lookup = false;
}
s->next_action = how_to_open_connection(s);
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : OriginServerRawOpen
// Description: called for ssl tunneling
//
// Details :
//
// when the method is CONNECT, we open a raw connection to the origin
// server. if the open succeeds, then do ssl tunneling from the client
// to the host.
//
//
// Possible Next States From Here:
// - HttpTransact::PROXY_INTERNAL_CACHE_NOOP;
// - HttpTransact::SSL_TUNNEL;
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::OriginServerRawOpen(State *s)
{
DebugTxn("http_trans", "[HttpTransact::OriginServerRawOpen]");
switch (s->current.state) {
case STATE_UNDEFINED:
/* fall through */
case OPEN_RAW_ERROR:
/* fall through */
case CONNECTION_ERROR:
/* fall through */
case CONNECTION_CLOSED:
/* fall through */
case CONGEST_CONTROL_CONGESTED_ON_F:
/* fall through */
case CONGEST_CONTROL_CONGESTED_ON_M:
handle_server_died(s);
ink_assert(s->cache_info.action == CACHE_DO_NO_ACTION);
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
break;
case CONNECTION_ALIVE:
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, HTTP_STATUS_OK);
DebugTxn("http_trans", "[OriginServerRawOpen] connection alive. next action is ssl_tunnel");
s->next_action = SM_ACTION_SSL_TUNNEL;
break;
default:
ink_assert(!("s->current.state is set to something unsupported"));
break;
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : HandleResponse
// Description: called from the state machine when a response is received
//
// Details :
//
// This is the entry into a coin-sorting machine. There are many different
// bins that the response can fall into. First, the response can be invalid
// if for example it is not a response, or not complete, or the connection
// was closed, etc. Then, the response can be from an icp-suggested-host,
// from a parent proxy or from the origin server. The next action to take
// differs for all three of these cases. Finally, good responses can either
// require a cache action, be it deletion, update, or writing or may just
// need to be tunnelled to the client. This latter case should be handled
// with as little processing as possible, since it should represent a fast
// path.
//
//
// Possible Next States From Here:
//
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleResponse(State *s)
{
DebugTxn("http_trans", "[HttpTransact::HandleResponse]");
DebugTxn("http_seq", "[HttpTransact::HandleResponse] Response received");
s->source = SOURCE_HTTP_ORIGIN_SERVER;
s->response_received_time = ink_cluster_time();
ink_assert(s->response_received_time >= s->request_sent_time);
s->current.now = s->response_received_time;
DebugTxn("http_trans", "[HandleResponse] response_received_time: %" PRId64, (int64_t)s->response_received_time);
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", &s->hdr_info.server_response, s->state_machine_id, "Incoming O.S. Response");
HTTP_INCREMENT_DYN_STAT(http_incoming_responses_stat);
ink_release_assert(s->current.request_to != UNDEFINED_LOOKUP);
if (s->cache_info.action != CACHE_DO_WRITE) {
ink_release_assert(s->cache_info.action != CACHE_DO_LOOKUP);
ink_release_assert(s->cache_info.action != CACHE_DO_SERVE);
ink_release_assert(s->cache_info.action != CACHE_PREPARE_TO_DELETE);
ink_release_assert(s->cache_info.action != CACHE_PREPARE_TO_UPDATE);
ink_release_assert(s->cache_info.action != CACHE_PREPARE_TO_WRITE);
}
if (!is_response_valid(s, &s->hdr_info.server_response)) {
DebugTxn("http_seq", "[HttpTransact::HandleResponse] Response not valid");
} else {
DebugTxn("http_seq", "[HttpTransact::HandleResponse] Response valid");
initialize_state_variables_from_response(s, &s->hdr_info.server_response);
}
switch (s->current.request_to) {
case ICP_SUGGESTED_HOST:
handle_response_from_icp_suggested_host(s);
break;
case PARENT_PROXY:
handle_response_from_parent(s);
break;
case ORIGIN_SERVER:
handle_response_from_server(s);
break;
default:
ink_assert(!("s->current.request_to is not ICP, P.P. or O.S. - hmmm."));
break;
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : HandleUpdateCachedObject
// Description: called from the state machine when we are going to modify
// headers without any server contact.
//
// Details : this function does very little. mainly to satisfy
// the call_transact_and_set_next format and not affect
// the performance of the non-invalidate operations, which
// are the majority
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleUpdateCachedObject(State *s)
{
if (s->cache_info.write_lock_state == HttpTransact::CACHE_WL_SUCCESS) {
ink_assert(s->cache_info.object_store.valid());
ink_assert(s->cache_info.object_store.response_get() != NULL);
ink_assert(s->cache_info.object_read != NULL);
ink_assert(s->cache_info.object_read->valid());
if (!s->cache_info.object_store.request_get()) {
s->cache_info.object_store.request_set(s->cache_info.object_read->request_get());
}
s->request_sent_time = s->cache_info.object_read->request_sent_time_get();
s->response_received_time = s->cache_info.object_read->response_received_time_get();
if (s->api_update_cached_object == UPDATE_CACHED_OBJECT_CONTINUE) {
TRANSACT_RETURN(SM_ACTION_CACHE_ISSUE_UPDATE, HttpTransact::HandleUpdateCachedObjectContinue);
} else {
TRANSACT_RETURN(SM_ACTION_CACHE_ISSUE_UPDATE, HttpTransact::HandleApiErrorJump);
}
} else if (s->api_update_cached_object == UPDATE_CACHED_OBJECT_CONTINUE) {
// even failed to update, continue to serve from cache
HandleUpdateCachedObjectContinue(s);
} else {
s->api_update_cached_object = UPDATE_CACHED_OBJECT_FAIL;
HandleApiErrorJump(s);
}
}
void
HttpTransact::HandleUpdateCachedObjectContinue(State *s)
{
ink_assert(s->api_update_cached_object == UPDATE_CACHED_OBJECT_CONTINUE);
s->cache_info.action = s->saved_update_cache_action;
s->next_action = s->saved_update_next_action;
}
///////////////////////////////////////////////////////////////////////////////
// Name : HandleStatPage
// Description: called from the state machine when a response is received
//
// Details :
//
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::HandleStatPage(State *s)
{
HTTPStatus status;
if (s->internal_msg_buffer) {
status = HTTP_STATUS_OK;
} else {
status = HTTP_STATUS_NOT_FOUND;
}
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, status);
///////////////////////////
// insert content-length //
///////////////////////////
s->hdr_info.client_response.set_content_length(s->internal_msg_buffer_size);
if (s->internal_msg_buffer_type) {
int len = strlen(s->internal_msg_buffer_type);
if (len > 0) {
s->hdr_info.client_response.value_set(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, s->internal_msg_buffer_type, len);
}
} else {
s->hdr_info.client_response.value_set(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, "text/plain", 10);
}
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
}
///////////////////////////////////////////////////////////////////////////////
// Name : handle_response_from_icp_suggested_host
// Description: response came from the host suggested by the icp lookup
//
// Details :
//
// If the response was bad (for whatever reason), may try to open a
// connection with a parent proxy, if there are any, else the request
// should be sent to the client.
// If the response is good, handle_forward_server_connection_open is
// called.
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_response_from_icp_suggested_host(State *s)
{
DebugTxn("http_trans", "[handle_response_from_icp_suggested_host] (hrfish)");
HTTP_RELEASE_ASSERT(s->current.server == &s->icp_info);
s->icp_info.state = s->current.state;
switch (s->current.state) {
case CONNECTION_ALIVE:
DebugTxn("http_trans", "[hrfish] connection alive");
SET_VIA_STRING(VIA_DETAIL_ICP_CONNECT, VIA_DETAIL_ICP_SUCCESS);
handle_forward_server_connection_open(s);
break;
default:
DebugTxn("http_trans", "[hrfish] connection not alive");
SET_VIA_STRING(VIA_DETAIL_ICP_CONNECT, VIA_DETAIL_ICP_FAILURE);
// If the request is not retryable, bail
if (is_request_retryable(s) == false) {
handle_server_died(s);
return;
}
// send request to parent proxy now if there is
// one or else directly to the origin server.
find_server_and_update_current_info(s);
if (!ats_is_ip(&s->current.server->dst_addr)) {
if (s->current.request_to == PARENT_PROXY) {
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, PPDNSLookup);
} else {
ink_release_assert(0);
}
return;
}
ink_assert(s->hdr_info.server_request.valid());
s->next_action = how_to_open_connection(s);
if (s->current.server == &s->server_info && s->next_hop_scheme == URL_WKSIDX_HTTP) {
HttpTransactHeaders::remove_host_name_from_url(&s->hdr_info.server_request);
}
break;
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : handle_response_from_parent
// Description: response came from a parent proxy
//
// Details :
//
// The configuration file can be used to specify more than one parent
// proxy. If a connection to one fails, another can be looked up. This
// function handles responses from parent proxies. If the response is
// bad the next parent proxy (if any) is looked up. If there are no more
// parent proxies that can be looked up, the response is sent to the
// origin server. If the response is good handle_forward_server_connection_open
// is called, as with handle_response_from_icp_suggested_host.
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_response_from_parent(State *s)
{
DebugTxn("http_trans", "[handle_response_from_parent] (hrfp)");
HTTP_RELEASE_ASSERT(s->current.server == &s->parent_info);
// response is from a parent origin server.
if (is_response_valid(s, &s->hdr_info.server_response) && s->current.request_to == HttpTransact::PARENT_PROXY &&
!s->parent_result.parent_is_proxy()) {
// check for a retryable response if simple or unavailable server retry are enabled.
if (s->parent_result.retry_type() & (PARENT_RETRY_SIMPLE | PARENT_RETRY_UNAVAILABLE_SERVER)) {
simple_or_unavailable_server_retry(s);
}
}
s->parent_info.state = s->current.state;
switch (s->current.state) {
case CONNECTION_ALIVE:
DebugTxn("http_trans", "[hrfp] connection alive");
s->current.server->connect_result = 0;
SET_VIA_STRING(VIA_DETAIL_PP_CONNECT, VIA_DETAIL_PP_SUCCESS);
if (s->parent_result.retry) {
s->parent_params->markParentUp(&s->parent_result);
}
handle_forward_server_connection_open(s);
break;
default: {
LookingUp_t next_lookup = UNDEFINED_LOOKUP;
DebugTxn("http_trans", "[hrfp] connection not alive");
SET_VIA_STRING(VIA_DETAIL_PP_CONNECT, VIA_DETAIL_PP_FAILURE);
ink_assert(s->hdr_info.server_request.valid());
s->current.server->connect_result = ENOTCONN;
char addrbuf[INET6_ADDRSTRLEN];
DebugTxn("http_trans", "[%d] failed to connect to parent %s", s->current.attempts,
ats_ip_ntop(&s->current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)));
// If the request is not retryable, just give up!
if (!is_request_retryable(s)) {
s->parent_params->markParentDown(&s->parent_result);
s->parent_result.result = PARENT_FAIL;
handle_parent_died(s);
return;
}
// try a simple retry if we received a simple retryable response from the parent.
if (s->current.retry_type == PARENT_RETRY_SIMPLE || s->current.retry_type == PARENT_RETRY_UNAVAILABLE_SERVER) {
if (s->current.retry_type == PARENT_RETRY_SIMPLE) {
if (s->current.simple_retry_attempts >= s->parent_result.max_retries(PARENT_RETRY_SIMPLE)) {
DebugTxn("http_trans", "PARENT_RETRY_SIMPLE: retried all parents, send error to client.");
s->current.retry_type = PARENT_RETRY_NONE;
} else {
s->current.simple_retry_attempts++;
DebugTxn("http_trans", "PARENT_RETRY_SIMPLE: try another parent.");
s->current.retry_type = PARENT_RETRY_NONE;
next_lookup = find_server_and_update_current_info(s);
}
} else { // try unavailable server retry if we have a unavailable server retry response from the parent.
if (s->current.unavailable_server_retry_attempts >= s->parent_result.max_retries(PARENT_RETRY_UNAVAILABLE_SERVER)) {
DebugTxn("http_trans", "PARENT_RETRY_UNAVAILABLE_SERVER: retried all parents, send error to client.");
s->current.retry_type = PARENT_RETRY_NONE;
} else {
s->current.unavailable_server_retry_attempts++;
DebugTxn("http_trans", "PARENT_RETRY_UNAVAILABLE_SERVER: marking parent down and trying another.");
s->current.retry_type = PARENT_RETRY_NONE;
s->parent_params->markParentDown(&s->parent_result);
next_lookup = find_server_and_update_current_info(s);
}
}
} else if (s->current.attempts < s->txn_conf->parent_connect_attempts) {
s->current.attempts++;
// Are we done with this particular parent?
if ((s->current.attempts - 1) % s->http_config_param->per_parent_connect_attempts != 0) {
// No we are not done with this parent so retry
s->next_action = how_to_open_connection(s);
DebugTxn("http_trans", "%s Retrying parent for attempt %d, max %" PRId64, "[handle_response_from_parent]",
s->current.attempts, s->http_config_param->per_parent_connect_attempts);
return;
} else {
DebugTxn("http_trans", "%s %d per parent attempts exhausted", "[handle_response_from_parent]", s->current.attempts);
// Only mark the parent down if we failed to connect
// to the parent otherwise slow origin servers cause
// us to mark the parent down
if (s->current.state == CONNECTION_ERROR) {
s->parent_params->markParentDown(&s->parent_result);
}
// We are done so look for another parent if any
next_lookup = find_server_and_update_current_info(s);
}
} else {
// Done trying parents... fail over to origin server if that is
// appropriate
DebugTxn("http_trans", "[handle_response_from_parent] Error. No more retries.");
s->parent_params->markParentDown(&s->parent_result);
s->parent_result.result = PARENT_FAIL;
next_lookup = find_server_and_update_current_info(s);
}
// We have either tried to find a new parent or failed over to the
// origin server
switch (next_lookup) {
case PARENT_PROXY:
ink_assert(s->current.request_to == PARENT_PROXY);
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, PPDNSLookup);
break;
case ORIGIN_SERVER:
s->current.attempts = 0;
s->next_action = how_to_open_connection(s);
if (s->current.server == &s->server_info && s->next_hop_scheme == URL_WKSIDX_HTTP) {
HttpTransactHeaders::remove_host_name_from_url(&s->hdr_info.server_request);
}
break;
case HOST_NONE:
handle_parent_died(s);
break;
default:
// This handles:
// UNDEFINED_LOOKUP, ICP_SUGGESTED_HOST,
// INCOMING_ROUTER
break;
}
break;
}
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : handle_response_from_server
// Description: response is from the origin server
//
// Details :
//
// response from the origin server. one of three things can happen now.
// if the response is bad, then we can either retry (by first downgrading
// the request, maybe making it non-keepalive, etc.), or we can give up.
// the latter case is handled by handle_server_connection_not_open and
// sends an error response back to the client. if the response is good
// handle_forward_server_connection_open is called.
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_response_from_server(State *s)
{
DebugTxn("http_trans", "[handle_response_from_server] (hrfs)");
HTTP_RELEASE_ASSERT(s->current.server == &s->server_info);
unsigned max_connect_retries = 0;
// plugin call
s->server_info.state = s->current.state;
if (s->fp_tsremap_os_response) {
s->fp_tsremap_os_response(s->remap_plugin_instance, reinterpret_cast<TSHttpTxn>(s->state_machine), s->current.state);
}
switch (s->current.state) {
case CONNECTION_ALIVE:
DebugTxn("http_trans", "[hrfs] connection alive");
SET_VIA_STRING(VIA_DETAIL_SERVER_CONNECT, VIA_DETAIL_SERVER_SUCCESS);
s->current.server->clear_connect_fail();
handle_forward_server_connection_open(s);
break;
case CONGEST_CONTROL_CONGESTED_ON_F:
case CONGEST_CONTROL_CONGESTED_ON_M:
DebugTxn("http_trans", "[handle_response_from_server] Error. congestion control -- congested.");
SET_VIA_STRING(VIA_DETAIL_SERVER_CONNECT, VIA_DETAIL_SERVER_FAILURE);
s->current.server->set_connect_fail(EUSERS); // too many users
handle_server_connection_not_open(s);
break;
case OPEN_RAW_ERROR:
/* fall through */
case CONNECTION_ERROR:
/* fall through */
case STATE_UNDEFINED:
/* fall through */
case INACTIVE_TIMEOUT:
/* fall through */
case PARSE_ERROR:
/* fall through */
case CONNECTION_CLOSED:
/* fall through */
case BAD_INCOMING_RESPONSE:
// Set to generic I/O error if not already set specifically.
if (!s->current.server->had_connect_fail()) {
s->current.server->set_connect_fail(EIO);
}
if (is_server_negative_cached(s)) {
max_connect_retries = s->txn_conf->connect_attempts_max_retries_dead_server;
} else {
// server not yet negative cached - use default number of retries
max_connect_retries = s->txn_conf->connect_attempts_max_retries;
}
if (s->pCongestionEntry != NULL) {
max_connect_retries = s->pCongestionEntry->connect_retries();
}
if (is_request_retryable(s) && s->current.attempts < max_connect_retries) {
// If this is a round robin DNS entry & we're tried configured
// number of times, we should try another node
if (DNSLookupInfo::OS_ADDR_TRY_CLIENT == s->dns_info.os_addr_style) {
// attempt was based on client supplied server address. Try again
// using HostDB.
// Allow DNS attempt
s->dns_info.lookup_success = false;
// See if we can get data from HostDB for this.
s->dns_info.os_addr_style = DNSLookupInfo::OS_ADDR_TRY_HOSTDB;
// Force host resolution to have the same family as the client.
// Because this is a transparent connection, we can't switch address
// families - that is locked in by the client source address.
s->state_machine->ua_session->set_host_res_style(ats_host_res_match(&s->current.server->dst_addr.sa));
TRANSACT_RETURN(SM_ACTION_DNS_LOOKUP, OSDNSLookup);
} else if ((s->dns_info.srv_lookup_success || s->host_db_info.is_rr_elt()) &&
(s->txn_conf->connect_attempts_rr_retries > 0) &&
(s->current.attempts % s->txn_conf->connect_attempts_rr_retries == 0)) {
delete_server_rr_entry(s, max_connect_retries);
return;
} else {
retry_server_connection_not_open(s, s->current.state, max_connect_retries);
DebugTxn("http_trans", "[handle_response_from_server] Error. Retrying...");
s->next_action = how_to_open_connection(s);
if (s->api_server_addr_set) {
// If the plugin set a server address, back up to the OS_DNS hook
// to let it try another one. Force OS_ADDR_USE_CLIENT so that
// in OSDNSLoopkup, we back up to how_to_open_connections which
// will tell HttpSM to connect the origin server.
s->dns_info.os_addr_style = DNSLookupInfo::OS_ADDR_USE_CLIENT;
TRANSACT_RETURN(SM_ACTION_API_OS_DNS, OSDNSLookup);
}
return;
}
} else {
DebugTxn("http_trans", "[handle_response_from_server] Error. No more retries.");
SET_VIA_STRING(VIA_DETAIL_SERVER_CONNECT, VIA_DETAIL_SERVER_FAILURE);
handle_server_connection_not_open(s);
}
break;
case ACTIVE_TIMEOUT:
DebugTxn("http_trans", "[hrfs] connection not alive");
SET_VIA_STRING(VIA_DETAIL_SERVER_CONNECT, VIA_DETAIL_SERVER_FAILURE);
s->current.server->set_connect_fail(ETIMEDOUT);
handle_server_connection_not_open(s);
break;
default:
ink_assert(!("s->current.state is set to something unsupported"));
break;
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : delete_server_rr_entry
// Description:
//
// Details :
//
// connection to server failed mark down the server round robin entry
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::delete_server_rr_entry(State *s, int max_retries)
{
char addrbuf[INET6_ADDRSTRLEN];
DebugTxn("http_trans", "[%d] failed to connect to %s", s->current.attempts,
ats_ip_ntop(&s->current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)));
DebugTxn("http_trans", "[delete_server_rr_entry] marking rr entry "
"down and finding next one");
ink_assert(s->current.server->had_connect_fail());
ink_assert(s->current.request_to == ORIGIN_SERVER);
ink_assert(s->current.server == &s->server_info);
update_dns_info(&s->dns_info, &s->current, 0, &s->arena);
s->current.attempts++;
DebugTxn("http_trans", "[delete_server_rr_entry] attempts now: %d, max: %d", s->current.attempts, max_retries);
TRANSACT_RETURN(SM_ACTION_ORIGIN_SERVER_RR_MARK_DOWN, ReDNSRoundRobin);
}
///////////////////////////////////////////////////////////////////////////////
// Name : retry_server_connection_not_open
// Description:
//
// Details :
//
// connection to server failed. retry.
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::retry_server_connection_not_open(State *s, ServerState_t conn_state, unsigned max_retries)
{
ink_assert(s->current.state != CONNECTION_ALIVE);
ink_assert(s->current.state != ACTIVE_TIMEOUT);
ink_assert(s->current.attempts <= max_retries);
ink_assert(s->current.server->had_connect_fail());
char addrbuf[INET6_ADDRSTRLEN];
char *url_string = s->hdr_info.client_request.url_string_get(&s->arena);
DebugTxn("http_trans", "[%d] failed to connect [%d] to %s", s->current.attempts, conn_state,
ats_ip_ntop(&s->current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)));
//////////////////////////////////////////
// on the first connect attempt failure //
// record the failue //
//////////////////////////////////////////
if (0 == s->current.attempts) {
Log::error("CONNECT:[%d] could not connect [%s] to %s for '%s'", s->current.attempts,
HttpDebugNames::get_server_state_name(conn_state),
ats_ip_ntop(&s->current.server->dst_addr.sa, addrbuf, sizeof(addrbuf)), url_string ? url_string : "<none>");
}
if (url_string) {
s->arena.str_free(url_string);
}
//////////////////////////////////////////////
// disable keep-alive for request and retry //
//////////////////////////////////////////////
s->current.server->keep_alive = HTTP_NO_KEEPALIVE;
s->current.attempts++;
DebugTxn("http_trans", "[retry_server_connection_not_open] attempts now: %d, max: %d", s->current.attempts, max_retries);
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : handle_server_connection_not_open
// Description:
//
// Details :
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_server_connection_not_open(State *s)
{
bool serve_from_cache = false;
DebugTxn("http_trans", "[handle_server_connection_not_open] (hscno)");
DebugTxn("http_seq", "[HttpTransact::handle_server_connection_not_open] ");
ink_assert(s->current.state != CONNECTION_ALIVE);
SET_VIA_STRING(VIA_SERVER_RESULT, VIA_SERVER_ERROR);
HTTP_INCREMENT_DYN_STAT(http_broken_server_connections_stat);
// Fire off a hostdb update to mark the server as down
s->state_machine->do_hostdb_update_if_necessary();
switch (s->cache_info.action) {
case CACHE_DO_UPDATE:
serve_from_cache = is_stale_cache_response_returnable(s);
break;
case CACHE_PREPARE_TO_DELETE:
/* fall through */
case CACHE_PREPARE_TO_UPDATE:
/* fall through */
case CACHE_PREPARE_TO_WRITE:
ink_release_assert(!"Why still preparing for cache action - "
"we skipped a step somehow.");
break;
case CACHE_DO_LOOKUP:
/* fall through */
case CACHE_DO_SERVE:
ink_assert(!("Why server response? Should have been a cache operation"));
break;
case CACHE_DO_DELETE:
// decisions, decisions. what should we do here?
// we could theoretically still delete the cached
// copy or serve it back with a warning, or easier
// just punt and biff the user. i say: biff the user.
/* fall through */
case CACHE_DO_UNDEFINED:
/* fall through */
case CACHE_DO_NO_ACTION:
/* fall through */
case CACHE_DO_WRITE:
/* fall through */
default:
serve_from_cache = false;
break;
}
if (serve_from_cache) {
ink_assert(s->cache_info.object_read != NULL);
ink_assert(s->cache_info.action == CACHE_DO_UPDATE);
ink_assert(s->internal_msg_buffer == NULL);
DebugTxn("http_trans", "[hscno] serving stale doc to client");
build_response_from_cache(s, HTTP_WARNING_CODE_REVALIDATION_FAILED);
} else {
handle_server_died(s);
s->next_action = SM_ACTION_SEND_ERROR_CACHE_NOOP;
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : handle_forward_server_connection_open
// Description: connection to a forward server is open and good
//
// Details :
//
// "Forward server" includes the icp-suggested-host or the parent proxy
// or the origin server. This function first determines if the forward
// server uses HTTP 0.9, in which case it simply tunnels the response
// to the client. Else, it updates
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_forward_server_connection_open(State *s)
{
DebugTxn("http_trans", "[handle_forward_server_connection_open] (hfsco)");
DebugTxn("http_seq", "[HttpTransact::handle_server_connection_open] ");
ink_release_assert(s->current.state == CONNECTION_ALIVE);
if (s->hdr_info.server_response.version_get() == HTTPVersion(0, 9)) {
DebugTxn("http_trans", "[hfsco] server sent 0.9 response, reading...");
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, HTTP_STATUS_OK, "Connection Established");
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_SERVER_READ;
return;
} else if (s->hdr_info.server_response.version_get() == HTTPVersion(1, 0)) {
if (s->current.server->http_version == HTTPVersion(0, 9)) {
// update_hostdb_to_indicate_server_version_is_1_0
s->updated_server_version = HostDBApplicationInfo::HTTP_VERSION_10;
} else if (s->current.server->http_version == HTTPVersion(1, 1)) {
// update_hostdb_to_indicate_server_version_is_1_0
s->updated_server_version = HostDBApplicationInfo::HTTP_VERSION_10;
} else {
// dont update the hostdb. let us try again with what we currently think.
}
} else if (s->hdr_info.server_response.version_get() == HTTPVersion(1, 1)) {
if (s->current.server->http_version == HTTPVersion(0, 9)) {
// update_hostdb_to_indicate_server_version_is_1_1
s->updated_server_version = HostDBApplicationInfo::HTTP_VERSION_11;
} else if (s->current.server->http_version == HTTPVersion(1, 0)) {
// update_hostdb_to_indicate_server_version_is_1_1
s->updated_server_version = HostDBApplicationInfo::HTTP_VERSION_11;
} else {
// dont update the hostdb. let us try again with what we currently think.
}
} else {
// dont update the hostdb. let us try again with what we currently think.
}
if (s->hdr_info.server_response.status_get() == HTTP_STATUS_CONTINUE) {
handle_100_continue_response(s);
return;
}
s->state_machine->do_hostdb_update_if_necessary();
if (s->www_auth_content == CACHE_AUTH_FRESH) {
// no update is needed - either to serve from cache if authorized,
// or tunnnel the server response
if (s->hdr_info.server_response.status_get() == HTTP_STATUS_OK) {
// borrow a state variable used by the API function
// this enable us to serve from cache without doing any updating
s->api_server_response_ignore = true;
}
// s->cache_info.action = CACHE_PREPARE_TO_SERVE;
// xing xing in the tunneling case, need to check when the cache_read_vc is closed, make sure the cache_read_vc is closed
// right
// away
}
CacheVConnection *cw_vc = s->state_machine->get_cache_sm().cache_write_vc;
if (s->redirect_info.redirect_in_process && s->state_machine->enable_redirection) {
if (s->cache_info.action == CACHE_DO_NO_ACTION) {
switch (s->hdr_info.server_response.status_get()) {
case HTTP_STATUS_MULTIPLE_CHOICES: // 300
case HTTP_STATUS_MOVED_PERMANENTLY: // 301
case HTTP_STATUS_MOVED_TEMPORARILY: // 302
case HTTP_STATUS_SEE_OTHER: // 303
case HTTP_STATUS_USE_PROXY: // 305
case HTTP_STATUS_TEMPORARY_REDIRECT: // 307
break;
default:
DebugTxn("http_trans", "[hfsco] redirect in progress, non-3xx response, setting cache_do_write");
if (cw_vc && s->txn_conf->cache_http) {
s->cache_info.action = CACHE_DO_WRITE;
}
break;
}
}
}
switch (s->cache_info.action) {
case CACHE_DO_WRITE:
/* fall through */
case CACHE_DO_UPDATE:
/* fall through */
case CACHE_DO_DELETE:
DebugTxn("http_trans", "[hfsco] cache action: %s", HttpDebugNames::get_cache_action_name(s->cache_info.action));
handle_cache_operation_on_forward_server_response(s);
break;
case CACHE_PREPARE_TO_DELETE:
/* fall through */
case CACHE_PREPARE_TO_UPDATE:
/* fall through */
case CACHE_PREPARE_TO_WRITE:
ink_release_assert(!"Why still preparing for cache action - we skipped a step somehow.");
break;
case CACHE_DO_LOOKUP:
/* fall through */
case CACHE_DO_SERVE:
ink_assert(!("Why server response? Should have been a cache operation"));
break;
case CACHE_DO_UNDEFINED:
/* fall through */
case CACHE_DO_NO_ACTION:
/* fall through */
default:
// Just tunnel?
DebugTxn("http_trans", "[hfsco] cache action: %s", HttpDebugNames::get_cache_action_name(s->cache_info.action));
handle_no_cache_operation_on_forward_server_response(s);
break;
}
return;
}
// void HttpTransact::handle_100_continue_response(State* s)
//
// We've received a 100 continue response. Determine if
// we should just swallow the response 100 or forward it
// the client. http-1.1-spec-rev-06 section 8.2.3
//
void
HttpTransact::handle_100_continue_response(State *s)
{
bool forward_100 = false;
HTTPVersion ver = s->hdr_info.client_request.version_get();
if (ver == HTTPVersion(1, 1)) {
forward_100 = true;
} else if (ver == HTTPVersion(1, 0)) {
if (s->hdr_info.client_request.value_get_int(MIME_FIELD_EXPECT, MIME_LEN_EXPECT) == 100) {
forward_100 = true;
}
}
if (forward_100) {
// We just want to copy the server's response. All
// the other build response functions insist on
// adding stuff
build_response_copy(s, &s->hdr_info.server_response, &s->hdr_info.client_response, s->client_info.http_version);
TRANSACT_RETURN(SM_ACTION_INTERNAL_100_RESPONSE, HandleResponse);
} else {
TRANSACT_RETURN(SM_ACTION_SERVER_PARSE_NEXT_HDR, HandleResponse);
}
}
// void HttpTransact::build_response_copy
//
// Build a response with minimal changes from the base response
//
void
HttpTransact::build_response_copy(State *s, HTTPHdr *base_response, HTTPHdr *outgoing_response, HTTPVersion outgoing_version)
{
HttpTransactHeaders::copy_header_fields(base_response, outgoing_response, s->txn_conf->fwd_proxy_auth_to_parent, s->current.now);
HttpTransactHeaders::convert_response(outgoing_version, outgoing_response); // http version conversion
HttpTransactHeaders::add_server_header_to_response(s->txn_conf, outgoing_response);
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", outgoing_response, s->state_machine_id, "Proxy's Response");
}
//////////////////////////////////////////////////////////////////////////
// IMS handling table //
// OS = Origin Server //
// IMS = A GET request w/ an If-Modified-Since header //
// LMs = Last modified state returned by server //
// D, D' are Last modified dates returned by the origin server //
// and are later used for IMS //
// D < D' //
// //
// +------------------------------------------------------------+ //
// | Client's | Cached | Proxy's | Response to client | //
// | Request | State | Request | OS 200 | OS 304 | //
// |------------------------------------------------------------| //
// | GET | Fresh | N/A | N/A | N/A | //
// |------------------------------------------------------------| //
// | GET | Stale, D' | IMS D' | 200, new | 200, cached | //
// |------------------------------------------------------------| //
// | IMS D | None | GET | 200, new *| N/A | //
// |------------------------------------------------------------| //
// | IMS D | Stale, D' | IMS D' | 200, new | Compare | //
// |---------------------------------------------| LMs & D' | //
// | IMS D' | Stale, D' | IMS D' | 200, new | If match, 304| //
// |---------------------------------------------| If no match, | //
// | IMS D' | Stale D | IMS D | 200, new *| 200, cached | //
// +------------------------------------------------------------+ //
// //
// Note: * indicates a case that could be optimized to return //
// 304 to the client but currently is not //
// //
//////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Name : handle_cache_operation_on_forward_server_response
// Description:
//
// Details :
//
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_cache_operation_on_forward_server_response(State *s)
{
DebugTxn("http_trans", "[handle_cache_operation_on_forward_server_response] (hcoofsr)");
DebugTxn("http_seq", "[handle_cache_operation_on_forward_server_response]");
HTTPHdr *base_response = NULL;
HTTPStatus server_response_code = HTTP_STATUS_NONE;
HTTPStatus client_response_code = HTTP_STATUS_NONE;
const char *warn_text = NULL;
bool cacheable = false;
cacheable = is_response_cacheable(s, &s->hdr_info.client_request, &s->hdr_info.server_response);
DebugTxn("http_trans", "[hcoofsr] response %s cacheable", cacheable ? "is" : "is not");
// set the correct next action, cache action, response code, and base response
server_response_code = s->hdr_info.server_response.status_get();
switch (server_response_code) {
case HTTP_STATUS_NOT_MODIFIED: // 304
SET_VIA_STRING(VIA_SERVER_RESULT, VIA_SERVER_NOT_MODIFIED);
// determine the correct cache action, next state, and response
// precondition: s->cache_info.action should be one of the following
// CACHE_DO_DELETE, or CACHE_DO_UPDATE; otherwise, it's an error.
if (s->api_server_response_ignore && s->cache_info.action == CACHE_DO_UPDATE) {
s->api_server_response_ignore = false;
ink_assert(s->cache_info.object_read);
base_response = s->cache_info.object_read->response_get();
s->cache_info.action = CACHE_DO_SERVE;
DebugTxn("http_trans", "[hcoofsr] not merging, cache action changed to: %s",
HttpDebugNames::get_cache_action_name(s->cache_info.action));
s->next_action = SM_ACTION_SERVE_FROM_CACHE;
client_response_code = base_response->status_get();
} else if ((s->cache_info.action == CACHE_DO_DELETE) || ((s->cache_info.action == CACHE_DO_UPDATE) && !cacheable)) {
if (is_request_conditional(&s->hdr_info.client_request)) {
client_response_code = HttpTransactCache::match_response_to_request_conditionals(
&s->hdr_info.client_request, s->cache_info.object_read->response_get(), s->response_received_time);
} else {
client_response_code = HTTP_STATUS_OK;
}
if (client_response_code != HTTP_STATUS_OK) {
// we can just forward the not modified response
// from the server and delete the cached copy
base_response = &s->hdr_info.server_response;
client_response_code = base_response->status_get();
s->cache_info.action = CACHE_DO_DELETE;
s->next_action = SM_ACTION_INTERNAL_CACHE_DELETE;
} else {
// We got screwed. The client did not send a conditional request,
// but we had a cached copy which we revalidated. The server has
// now told us to delete the cached copy and sent back a 304.
// We need to send the cached copy to the client, then delete it.
if (s->method == HTTP_WKSIDX_HEAD) {
s->cache_info.action = CACHE_DO_DELETE;
s->next_action = SM_ACTION_SERVER_READ;
} else {
s->cache_info.action = CACHE_DO_SERVE_AND_DELETE;
s->next_action = SM_ACTION_SERVE_FROM_CACHE;
}
base_response = s->cache_info.object_read->response_get();
client_response_code = base_response->status_get();
}
} else if (s->cache_info.action == CACHE_DO_UPDATE && is_request_conditional(&s->hdr_info.server_request)) {
// CACHE_DO_UPDATE and server response is cacheable
if (is_request_conditional(&s->hdr_info.client_request)) {
if (s->txn_conf->cache_when_to_revalidate != 4) {
client_response_code = HttpTransactCache::match_response_to_request_conditionals(
&s->hdr_info.client_request, s->cache_info.object_read->response_get(), s->response_received_time);
} else {
client_response_code = server_response_code;
}
} else {
client_response_code = HTTP_STATUS_OK;
}
if (client_response_code != HTTP_STATUS_OK) {
// delete the cached copy unless configured to always verify IMS
if (s->txn_conf->cache_when_to_revalidate != 4) {
s->cache_info.action = CACHE_DO_UPDATE;
s->next_action = SM_ACTION_INTERNAL_CACHE_UPDATE_HEADERS;
/* base_response will be set after updating headers below */
} else {
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
base_response = &s->hdr_info.server_response;
}
} else {
if (s->method == HTTP_WKSIDX_HEAD) {
s->cache_info.action = CACHE_DO_UPDATE;
s->next_action = SM_ACTION_SERVER_READ;
} else {
if (s->hdr_info.client_request.presence(MIME_PRESENCE_RANGE)) {
s->state_machine->do_range_setup_if_necessary();
// Note that even if the Range request is not satisfiable, we
// update and serve this cache. This will give a 200 response to
// a bad client, but allows us to avoid pegging the origin (e.g. abuse).
}
s->cache_info.action = CACHE_DO_SERVE_AND_UPDATE;
s->next_action = SM_ACTION_SERVE_FROM_CACHE;
}
/* base_response will be set after updating headers below */
}
} else { // cache action != CACHE_DO_DELETE and != CACHE_DO_UPDATE
// bogus response from server. deal by tunnelling to client.
// server should not have sent back a 304 because our request
// should not have been an conditional.
DebugTxn("http_trans", "[hcoofsr] 304 for non-conditional request");
s->cache_info.action = CACHE_DO_NO_ACTION;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
client_response_code = s->hdr_info.server_response.status_get();
base_response = &s->hdr_info.server_response;
// since this is bad, insert warning header into client response
// The only exception case is conditional client request,
// cache miss, and client request being unlikely cacheable.
// In this case, the server request is given the same
// conditional headers as client request (see build_request()).
// So an unexpected 304 might be received.
// FIXME: check this case
if (is_request_likely_cacheable(s, &s->hdr_info.client_request)) {
warn_text = "Proxy received unexpected 304 response; "
"content may be stale";
}
}
break;
case HTTP_STATUS_HTTPVER_NOT_SUPPORTED: // 505
{
bool keep_alive = (s->current.server->keep_alive == HTTP_KEEPALIVE);
s->next_action = how_to_open_connection(s);
/* Downgrade the request level and retry */
if (!HttpTransactHeaders::downgrade_request(&keep_alive, &s->hdr_info.server_request)) {
build_error_response(s, HTTP_STATUS_HTTPVER_NOT_SUPPORTED, "HTTP Version Not Supported", "response#bad_version", NULL);
s->next_action = SM_ACTION_SEND_ERROR_CACHE_NOOP;
s->already_downgraded = true;
} else {
if (!keep_alive) {
/* START Hack */
(s->hdr_info.server_request).field_delete(MIME_FIELD_PROXY_CONNECTION, MIME_LEN_PROXY_CONNECTION);
/* END Hack */
}
s->already_downgraded = true;
s->next_action = how_to_open_connection(s);
}
}
return;
default:
DebugTxn("http_trans", "[hcoofsr] response code: %d", server_response_code);
SET_VIA_STRING(VIA_SERVER_RESULT, VIA_SERVER_SERVED);
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_SERVED);
/* if we receive a 500, 502, 503 or 504 while revalidating
a document, treat the response as a 304 and in effect revalidate the document for
negative_revalidating_lifetime. (negative revalidating)
*/
if ((server_response_code == HTTP_STATUS_INTERNAL_SERVER_ERROR || server_response_code == HTTP_STATUS_GATEWAY_TIMEOUT ||
server_response_code == HTTP_STATUS_BAD_GATEWAY || server_response_code == HTTP_STATUS_SERVICE_UNAVAILABLE) &&
s->cache_info.action == CACHE_DO_UPDATE && s->txn_conf->negative_revalidating_enabled &&
is_stale_cache_response_returnable(s)) {
DebugTxn("http_trans", "[hcoofsr] negative revalidating: revalidate stale object and serve from cache");
s->cache_info.object_store.create();
s->cache_info.object_store.request_set(&s->hdr_info.client_request);
s->cache_info.object_store.response_set(s->cache_info.object_read->response_get());
base_response = s->cache_info.object_store.response_get();
time_t exp_time = s->txn_conf->negative_revalidating_lifetime + ink_cluster_time();
base_response->set_expires(exp_time);
SET_VIA_STRING(VIA_CACHE_FILL_ACTION, VIA_CACHE_UPDATED);
HTTP_INCREMENT_DYN_STAT(http_cache_updates_stat);
// unset Cache-control: "need-revalidate-once" (if it's set)
// This directive is used internally by T.S. to invalidate
// documents so that an invalidated document needs to be
// revalidated again.
base_response->unset_cooked_cc_need_revalidate_once();
if (is_request_conditional(&s->hdr_info.client_request) &&
HttpTransactCache::match_response_to_request_conditionals(&s->hdr_info.client_request,
s->cache_info.object_read->response_get(),
s->response_received_time) == HTTP_STATUS_NOT_MODIFIED) {
s->next_action = SM_ACTION_INTERNAL_CACHE_UPDATE_HEADERS;
client_response_code = HTTP_STATUS_NOT_MODIFIED;
} else {
if (s->method == HTTP_WKSIDX_HEAD) {
s->cache_info.action = CACHE_DO_UPDATE;
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
} else {
s->cache_info.action = CACHE_DO_SERVE_AND_UPDATE;
s->next_action = SM_ACTION_SERVE_FROM_CACHE;
}
client_response_code = s->cache_info.object_read->response_get()->status_get();
}
ink_assert(base_response->valid());
if (client_response_code == HTTP_STATUS_NOT_MODIFIED) {
ink_assert(GET_VIA_STRING(VIA_CLIENT_REQUEST) != VIA_CLIENT_SIMPLE);
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_IMS);
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_NOT_MODIFIED);
} else {
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_SERVED);
}
ink_assert(client_response_code != HTTP_STATUS_NONE);
if (s->next_action == SM_ACTION_SERVE_FROM_CACHE && s->state_machine->do_transform_open()) {
set_header_for_transform(s, base_response);
} else {
build_response(s, base_response, &s->hdr_info.client_response, s->client_info.http_version, client_response_code);
}
return;
}
s->next_action = SM_ACTION_SERVER_READ;
client_response_code = server_response_code;
base_response = &s->hdr_info.server_response;
s->negative_caching = is_negative_caching_appropriate(s) && cacheable;
// determine the correct cache action given the original cache action,
// cacheability of server response, and request method
// precondition: s->cache_info.action is one of the following
// CACHE_DO_UPDATE, CACHE_DO_WRITE, or CACHE_DO_DELETE
if (s->api_server_response_no_store) {
s->cache_info.action = CACHE_DO_NO_ACTION;
} else if (s->api_server_response_ignore && server_response_code == HTTP_STATUS_OK &&
s->hdr_info.server_request.method_get_wksidx() == HTTP_WKSIDX_HEAD) {
s->api_server_response_ignore = false;
ink_assert(s->cache_info.object_read);
base_response = s->cache_info.object_read->response_get();
s->cache_info.action = CACHE_DO_SERVE;
DebugTxn("http_trans", "[hcoofsr] ignoring server response, "
"cache action changed to: %s",
HttpDebugNames::get_cache_action_name(s->cache_info.action));
s->next_action = SM_ACTION_SERVE_FROM_CACHE;
client_response_code = base_response->status_get();
} else if (s->cache_info.action == CACHE_DO_UPDATE) {
if (s->www_auth_content == CACHE_AUTH_FRESH || s->api_server_response_ignore) {
s->cache_info.action = CACHE_DO_NO_ACTION;
} else if (s->www_auth_content == CACHE_AUTH_STALE && server_response_code == HTTP_STATUS_UNAUTHORIZED) {
s->cache_info.action = CACHE_DO_NO_ACTION;
} else if (!cacheable) {
s->cache_info.action = CACHE_DO_DELETE;
} else if (s->method == HTTP_WKSIDX_HEAD) {
s->cache_info.action = CACHE_DO_DELETE;
} else {
ink_assert(s->cache_info.object_read != 0);
s->cache_info.action = CACHE_DO_REPLACE;
}
} else if (s->cache_info.action == CACHE_DO_WRITE) {
if (!cacheable && !s->negative_caching) {
s->cache_info.action = CACHE_DO_NO_ACTION;
} else if (s->method == HTTP_WKSIDX_HEAD) {
s->cache_info.action = CACHE_DO_NO_ACTION;
} else {
s->cache_info.action = CACHE_DO_WRITE;
}
} else if (s->cache_info.action == CACHE_DO_DELETE) {
// do nothing
} else {
ink_assert(!("cache action inconsistent with current state"));
}
// postcondition: s->cache_info.action is one of the following
// CACHE_DO_REPLACE, CACHE_DO_WRITE, CACHE_DO_DELETE, or
// CACHE_DO_NO_ACTION
// Check see if we ought to serve the client a 304 based on
// it's IMS date. We may gotten a 200 back from the origin
// server if our (the proxies's) cached copy was out of date
// but the client's wasn't. However, if the response is
// not cacheable we ought not issue a 304 to the client so
// make sure we are writing the document to the cache if
// before issuing a 304
if (s->cache_info.action == CACHE_DO_WRITE || s->cache_info.action == CACHE_DO_NO_ACTION ||
s->cache_info.action == CACHE_DO_REPLACE) {
if (s->negative_caching) {
HTTPHdr *resp;
s->cache_info.object_store.create();
s->cache_info.object_store.request_set(&s->hdr_info.client_request);
s->cache_info.object_store.response_set(&s->hdr_info.server_response);
resp = s->cache_info.object_store.response_get();
if (!resp->presence(MIME_PRESENCE_EXPIRES)) {
time_t exp_time = s->txn_conf->negative_caching_lifetime + ink_cluster_time();
resp->set_expires(exp_time);
}
} else if (is_request_conditional(&s->hdr_info.client_request) && server_response_code == HTTP_STATUS_OK) {
client_response_code = HttpTransactCache::match_response_to_request_conditionals(
&s->hdr_info.client_request, &s->hdr_info.server_response, s->response_received_time);
DebugTxn("http_trans", "[hcoofsr] conditional request, 200 "
"response, send back 304 if possible [crc=%d]",
client_response_code);
if ((client_response_code == HTTP_STATUS_NOT_MODIFIED) || (client_response_code == HTTP_STATUS_PRECONDITION_FAILED)) {
switch (s->cache_info.action) {
case CACHE_DO_WRITE:
case CACHE_DO_REPLACE:
s->next_action = SM_ACTION_INTERNAL_CACHE_WRITE;
break;
case CACHE_DO_DELETE:
s->next_action = SM_ACTION_INTERNAL_CACHE_DELETE;
break;
default:
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
break;
}
} else {
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_SERVER_REVALIDATED);
}
}
} else if (s->negative_caching) {
s->negative_caching = false;
}
break;
}
// update stat, set via string, etc
switch (s->cache_info.action) {
case CACHE_DO_SERVE_AND_DELETE:
// fall through
case CACHE_DO_DELETE:
DebugTxn("http_trans", "[hcoofsr] delete cached copy");
SET_VIA_STRING(VIA_CACHE_FILL_ACTION, VIA_CACHE_DELETED);
HTTP_INCREMENT_DYN_STAT(http_cache_deletes_stat);
break;
case CACHE_DO_WRITE:
DebugTxn("http_trans", "[hcoofsr] cache write");
SET_VIA_STRING(VIA_CACHE_FILL_ACTION, VIA_CACHE_WRITTEN);
HTTP_INCREMENT_DYN_STAT(http_cache_writes_stat);
break;
case CACHE_DO_SERVE_AND_UPDATE:
// fall through
case CACHE_DO_UPDATE:
// fall through
case CACHE_DO_REPLACE:
DebugTxn("http_trans", "[hcoofsr] cache update/replace");
SET_VIA_STRING(VIA_CACHE_FILL_ACTION, VIA_CACHE_UPDATED);
HTTP_INCREMENT_DYN_STAT(http_cache_updates_stat);
break;
default:
break;
}
if ((client_response_code == HTTP_STATUS_NOT_MODIFIED) && (s->cache_info.action != CACHE_DO_NO_ACTION)) {
/* ink_assert(GET_VIA_STRING(VIA_CLIENT_REQUEST)
!= VIA_CLIENT_SIMPLE); */
DebugTxn("http_trans", "[hcoofsr] Client request was conditional");
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_IMS);
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_NOT_MODIFIED);
} else {
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_SERVED);
}
ink_assert(client_response_code != HTTP_STATUS_NONE);
// The correct cache action, next action, and response code are set.
// Do the real work below.
// first update the cached object
if ((s->cache_info.action == CACHE_DO_UPDATE) || (s->cache_info.action == CACHE_DO_SERVE_AND_UPDATE)) {
DebugTxn("http_trans", "[hcoofsr] merge and update cached copy");
merge_and_update_headers_for_cache_update(s);
base_response = s->cache_info.object_store.response_get();
// unset Cache-control: "need-revalidate-once" (if it's set)
// This directive is used internally by T.S. to invalidate documents
// so that an invalidated document needs to be revalidated again.
base_response->unset_cooked_cc_need_revalidate_once();
// unset warning revalidation failed header if it set
// (potentially added by negative revalidating)
delete_warning_value(base_response, HTTP_WARNING_CODE_REVALIDATION_FAILED);
}
ink_assert(base_response->valid());
if ((s->cache_info.action == CACHE_DO_WRITE) || (s->cache_info.action == CACHE_DO_REPLACE)) {
set_headers_for_cache_write(s, &s->cache_info.object_store, &s->hdr_info.server_request, &s->hdr_info.server_response);
}
// 304, 412, and 416 responses are handled here
if ((client_response_code == HTTP_STATUS_NOT_MODIFIED) || (client_response_code == HTTP_STATUS_PRECONDITION_FAILED)) {
// Because we are decoupling User-Agent validation from
// Traffic Server validation just build a regular 304
// if the exception of adding prepending the VIA
// header to show the revalidation path
build_response(s, base_response, &s->hdr_info.client_response, s->client_info.http_version, client_response_code);
// Copy over the response via field (if any) preserving
// the order of the fields
MIMEField *resp_via = s->hdr_info.server_response.field_find(MIME_FIELD_VIA, MIME_LEN_VIA);
if (resp_via) {
MIMEField *our_via;
our_via = s->hdr_info.client_response.field_find(MIME_FIELD_VIA, MIME_LEN_VIA);
if (our_via == NULL) {
our_via = s->hdr_info.client_response.field_create(MIME_FIELD_VIA, MIME_LEN_VIA);
s->hdr_info.client_response.field_attach(our_via);
}
// HDR FIX ME - Mulitple appends are VERY slow
while (resp_via) {
int clen;
const char *cfield = resp_via->value_get(&clen);
s->hdr_info.client_response.field_value_append(our_via, cfield, clen, true);
resp_via = resp_via->m_next_dup;
}
}
// a warning text is added only in the case of a NOT MODIFIED response
if (warn_text) {
HttpTransactHeaders::insert_warning_header(s->http_config_param, &s->hdr_info.client_response, HTTP_WARNING_CODE_MISC_WARNING,
warn_text, strlen(warn_text));
}
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", &s->hdr_info.client_response, s->state_machine_id, "Proxy's Response (Client Conditionals)");
return;
}
// all other responses (not 304, 412, 416) are handled here
else {
if (((s->next_action == SM_ACTION_SERVE_FROM_CACHE) || (s->next_action == SM_ACTION_SERVER_READ)) &&
s->state_machine->do_transform_open()) {
set_header_for_transform(s, base_response);
} else {
build_response(s, base_response, &s->hdr_info.client_response, s->client_info.http_version, client_response_code);
}
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// Name : handle_no_cache_operation_on_forward_server_response
// Description:
//
// Details :
//
//
//
// Possible Next States From Here:
//
///////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_no_cache_operation_on_forward_server_response(State *s)
{
DebugTxn("http_trans", "[handle_no_cache_operation_on_forward_server_response] (hncoofsr)");
DebugTxn("http_seq", "[handle_no_cache_operation_on_forward_server_response]");
bool keep_alive = s->current.server->keep_alive == HTTP_KEEPALIVE;
const char *warn_text = NULL;
switch (s->hdr_info.server_response.status_get()) {
case HTTP_STATUS_OK:
DebugTxn("http_trans", "[hncoofsr] server sent back 200");
SET_VIA_STRING(VIA_SERVER_RESULT, VIA_SERVER_SERVED);
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_SERVED);
if (s->method == HTTP_WKSIDX_CONNECT) {
DebugTxn("http_trans", "[hncoofsr] next action is SSL_TUNNEL");
s->next_action = SM_ACTION_SSL_TUNNEL;
} else {
DebugTxn("http_trans", "[hncoofsr] next action will be OS_READ_CACHE_NOOP");
ink_assert(s->cache_info.action == CACHE_DO_NO_ACTION);
s->next_action = SM_ACTION_SERVER_READ;
}
if (s->state_machine->redirect_url == NULL) {
s->state_machine->enable_redirection = false;
}
break;
case HTTP_STATUS_NOT_MODIFIED:
DebugTxn("http_trans", "[hncoofsr] server sent back 304. IMS from client?");
SET_VIA_STRING(VIA_SERVER_RESULT, VIA_SERVER_NOT_MODIFIED);
SET_VIA_STRING(VIA_PROXY_RESULT, VIA_PROXY_NOT_MODIFIED);
if (!is_request_conditional(&s->hdr_info.client_request)) {
// bogus server response. not a conditional request
// from the client and probably not a conditional
// request from the proxy.
// since this is bad, insert warning header into client response
warn_text = "Proxy received unexpected 304 response; content may be stale";
}
ink_assert(s->cache_info.action == CACHE_DO_NO_ACTION);
s->next_action = SM_ACTION_INTERNAL_CACHE_NOOP;
break;
case HTTP_STATUS_HTTPVER_NOT_SUPPORTED:
s->next_action = how_to_open_connection(s);
/* Downgrade the request level and retry */
if (!HttpTransactHeaders::downgrade_request(&keep_alive, &s->hdr_info.server_request)) {
s->already_downgraded = true;
build_error_response(s, HTTP_STATUS_HTTPVER_NOT_SUPPORTED, "HTTP Version Not Supported", "response#bad_version", NULL);
s->next_action = SM_ACTION_SEND_ERROR_CACHE_NOOP;
} else {
s->already_downgraded = true;
s->next_action = how_to_open_connection(s);
}
return;
case HTTP_STATUS_PARTIAL_CONTENT:
// If we get this back we should be just passing it through.
ink_assert(s->cache_info.action == CACHE_DO_NO_ACTION);
s->next_action = SM_ACTION_SERVER_READ;
break;
default:
DebugTxn("http_trans", "[hncoofsr] server sent back something other than 100,304,200");
/* Default behavior is to pass-through response to the client */
ink_assert(s->cache_info.action == CACHE_DO_NO_ACTION);
s->next_action = SM_ACTION_SERVER_READ;
break;
}
HTTPHdr *to_warn;
if (s->next_action == SM_ACTION_SERVER_READ && s->state_machine->do_transform_open()) {
set_header_for_transform(s, &s->hdr_info.server_response);
to_warn = &s->hdr_info.transform_response;
} else {
build_response(s, &s->hdr_info.server_response, &s->hdr_info.client_response, s->client_info.http_version);
to_warn = &s->hdr_info.server_response;
}
if (warn_text) {
HttpTransactHeaders::insert_warning_header(s->http_config_param, to_warn, HTTP_WARNING_CODE_MISC_WARNING, warn_text,
strlen(warn_text));
}
return;
}
void
HttpTransact::merge_and_update_headers_for_cache_update(State *s)
{
URL *s_url = NULL;
HTTPHdr *cached_hdr = NULL;
if (!s->cache_info.object_store.valid()) {
s->cache_info.object_store.create();
}
s->cache_info.object_store.request_set(&s->hdr_info.server_request);
cached_hdr = s->cache_info.object_store.response_get();
if (s->redirect_info.redirect_in_process) {
s_url = &s->redirect_info.original_url;
} else {
s_url = &s->cache_info.original_url;
}
ink_assert(s_url != NULL);
s->cache_info.object_store.request_get()->url_set(s_url->valid() ? s_url : s->hdr_info.client_request.url_get());
if (s->cache_info.object_store.request_get()->method_get_wksidx() == HTTP_WKSIDX_HEAD) {
s->cache_info.object_store.request_get()->method_set(HTTP_METHOD_GET, HTTP_LEN_GET);
}
if (s->api_modifiable_cached_resp) {
ink_assert(cached_hdr != NULL && cached_hdr->valid());
s->api_modifiable_cached_resp = false;
} else {
s->cache_info.object_store.response_set(s->cache_info.object_read->response_get());
}
// Delete caching headers from the cached response. If these are
// still being served by the origin we will copy new versions in
// from the server response. RFC 2616 says that a 304 response may
// omit some headers if they were sent in a 200 response (see section
// 10.3.5), but RFC 7232) is clear that the 304 and 200 responses
// must be identical (see section 4.1). This code attempts to strike
// a balance between the two.
cached_hdr->field_delete(MIME_FIELD_AGE, MIME_LEN_AGE);
cached_hdr->field_delete(MIME_FIELD_ETAG, MIME_LEN_ETAG);
cached_hdr->field_delete(MIME_FIELD_EXPIRES, MIME_LEN_EXPIRES);
merge_response_header_with_cached_header(cached_hdr, &s->hdr_info.server_response);
// Some special processing for 304
if (s->hdr_info.server_response.status_get() == HTTP_STATUS_NOT_MODIFIED) {
// Hack fix. If the server sends back
// a 304 without a Date Header, use the current time
// as the new Date value in the header to be cached.
time_t date_value = s->hdr_info.server_response.get_date();
if (date_value <= 0) {
cached_hdr->set_date(s->request_sent_time);
date_value = s->request_sent_time;
}
// If the cached response has an Age: we should update it
// We could use calculate_document_age but my guess is it's overkill
// Just use 'now' - 304's Date: + Age: (response's Age: if there)
date_value = max(s->current.now - date_value, (ink_time_t)0);
if (s->hdr_info.server_response.presence(MIME_PRESENCE_AGE)) {
time_t new_age = s->hdr_info.server_response.get_age();
if (new_age >= 0) {
cached_hdr->set_age(date_value + new_age);
} else {
cached_hdr->set_age(-1); // Overflow
}
}
delete_warning_value(cached_hdr, HTTP_WARNING_CODE_REVALIDATION_FAILED);
}
s->cache_info.object_store.request_get()->field_delete(MIME_FIELD_VIA, MIME_LEN_VIA);
}
void
HttpTransact::handle_transform_cache_write(State *s)
{
ink_assert(s->cache_info.transform_action == CACHE_PREPARE_TO_WRITE);
switch (s->cache_info.write_lock_state) {
case CACHE_WL_SUCCESS:
// We were able to get the lock for the URL vector in the cache
s->cache_info.transform_action = CACHE_DO_WRITE;
break;
case CACHE_WL_FAIL:
// No write lock, ignore the cache
s->cache_info.transform_action = CACHE_DO_NO_ACTION;
s->cache_info.transform_write_status = CACHE_WRITE_LOCK_MISS;
break;
default:
ink_release_assert(0);
}
TRANSACT_RETURN(SM_ACTION_TRANSFORM_READ, NULL);
}
void
HttpTransact::handle_transform_ready(State *s)
{
ink_assert(s->hdr_info.transform_response.valid() == true);
s->pre_transform_source = s->source;
s->source = SOURCE_TRANSFORM;
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", &s->hdr_info.transform_response, s->state_machine_id, "Header From Transform");
build_response(s, &s->hdr_info.transform_response, &s->hdr_info.client_response, s->client_info.http_version);
if (s->cache_info.action != CACHE_DO_NO_ACTION && s->cache_info.action != CACHE_DO_DELETE && s->api_info.cache_transformed &&
!s->range_setup) {
HTTPHdr *transform_store_request = 0;
switch (s->pre_transform_source) {
case SOURCE_CACHE:
// If we are transforming from the cache, treat
// the transform as if it were virtual server
// use in the incoming request
transform_store_request = &s->hdr_info.client_request;
break;
case SOURCE_HTTP_ORIGIN_SERVER:
transform_store_request = &s->hdr_info.server_request;
break;
default:
ink_release_assert(0);
}
ink_assert(transform_store_request->valid() == true);
set_headers_for_cache_write(s, &s->cache_info.transform_store, transform_store_request, &s->hdr_info.transform_response);
// For debugging
if (is_action_tag_set("http_nullt")) {
s->cache_info.transform_store.request_get()->value_set("InkXform", 8, "nullt", 5);
s->cache_info.transform_store.response_get()->value_set("InkXform", 8, "nullt", 5);
}
s->cache_info.transform_action = CACHE_PREPARE_TO_WRITE;
TRANSACT_RETURN(SM_ACTION_CACHE_ISSUE_WRITE_TRANSFORM, handle_transform_cache_write);
} else {
s->cache_info.transform_action = CACHE_DO_NO_ACTION;
TRANSACT_RETURN(SM_ACTION_TRANSFORM_READ, NULL);
}
}
void
HttpTransact::set_header_for_transform(State *s, HTTPHdr *base_header)
{
s->hdr_info.transform_response.create(HTTP_TYPE_RESPONSE);
s->hdr_info.transform_response.copy(base_header);
// Nuke the content length since 1) the transform will probably
// change it. 2) it would only be valid for the first transform
// in the chain
s->hdr_info.transform_response.field_delete(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH);
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", &s->hdr_info.transform_response, s->state_machine_id, "Header To Transform");
}
void
HttpTransact::set_headers_for_cache_write(State *s, HTTPInfo *cache_info, HTTPHdr *request, HTTPHdr *response)
{
URL *temp_url;
ink_assert(request->type_get() == HTTP_TYPE_REQUEST);
ink_assert(response->type_get() == HTTP_TYPE_RESPONSE);
if (!cache_info->valid()) {
cache_info->create();
}
/* Store the requested URI */
// Nasty hack. The set calls for
// marshalled types current do handle something being
// set to itself. Make the check here for that case.
// Why the request url is set before a copy made is
// quite beyond me. Seems like a unsafe practice so
// FIX ME!
// Logic added to restore the orignal URL for multiple cache lookup
// and automatic redirection
if (s->redirect_info.redirect_in_process) {
temp_url = &s->redirect_info.original_url;
ink_assert(temp_url->valid());
request->url_set(temp_url);
} else if ((temp_url = &(s->cache_info.original_url))->valid()) {
request->url_set(temp_url);
} else if (request != &s->hdr_info.client_request) {
request->url_set(s->hdr_info.client_request.url_get());
}
cache_info->request_set(request);
/* Why do we check the negative caching case? No one knows. This used to assert if the cache_info
response wasn't already valid, which broke negative caching when a transform is active. Why it
wasn't OK to pull in the @a response explicitly passed in isn't clear and looking at the call
sites yields no insight. So the assert is removed and we keep the behavior that if the response
in @a cache_info is already set, we don't override it.
*/
if (!s->negative_caching || !cache_info->response_get()->valid()) {
cache_info->response_set(response);
}
if (s->api_server_request_body_set) {
cache_info->request_get()->method_set(HTTP_METHOD_GET, HTTP_LEN_GET);
}
// Set-Cookie should not be put in the cache to prevent
// sending person A's cookie to person B
cache_info->response_get()->field_delete(MIME_FIELD_SET_COOKIE, MIME_LEN_SET_COOKIE);
cache_info->request_get()->field_delete(MIME_FIELD_VIA, MIME_LEN_VIA);
// server 200 Ok for Range request
cache_info->request_get()->field_delete(MIME_FIELD_RANGE, MIME_LEN_RANGE);
// If we're ignoring auth, then we don't want to cache WWW-Auth
// headers
if (s->txn_conf->cache_ignore_auth) {
cache_info->response_get()->field_delete(MIME_FIELD_WWW_AUTHENTICATE, MIME_LEN_WWW_AUTHENTICATE);
}
// if (s->cache_control.cache_auth_content && s->www_auth_content != CACHE_AUTH_NONE) {
// decided to cache authenticated content because of cache.config
// add one marker to the content in cache
// cache_info->response_get()->value_set("@WWW-Auth", 9, "true", 4);
//}
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", cache_info->request_get(), s->state_machine_id, "Cached Request Hdr");
}
void
HttpTransact::merge_response_header_with_cached_header(HTTPHdr *cached_header, HTTPHdr *response_header)
{
MIMEField *field;
MIMEField *new_field;
MIMEFieldIter fiter;
const char *name;
bool dups_seen = false;
field = response_header->iter_get_first(&fiter);
for (; field != NULL; field = response_header->iter_get_next(&fiter)) {
int name_len;
name = field->name_get(&name_len);
///////////////////////////
// is hop-by-hop header? //
///////////////////////////
if (HttpTransactHeaders::is_this_a_hop_by_hop_header(name)) {
continue;
}
/////////////////////////////////////
// dont cache content-length field //
/////////////////////////////////////
if (name == MIME_FIELD_CONTENT_LENGTH) {
continue;
}
/////////////////////////////////////
// dont cache Set-Cookie headers //
/////////////////////////////////////
if (name == MIME_FIELD_SET_COOKIE) {
continue;
}
/////////////////////////////////////////
// dont overwrite the cached content //
// type as this wreaks havoc with //
// transformed content //
/////////////////////////////////////////
if (name == MIME_FIELD_CONTENT_TYPE) {
continue;
}
/////////////////////////////////////
// dont delete warning. a separate//
// functions merges the two in a //
// complex manner //
/////////////////////////////////////
if (name == MIME_FIELD_WARNING) {
continue;
}
// Copy all remaining headers with replacement
// Duplicate header fields cause a bug problem
// since we need to duplicate with replacement.
// Without dups, we can just nuke what is already
// there in the cached header. With dups, we
// can't do this because what is already there
// may be a dup we've already copied in. If
// dups show up we look through the remaining
// header fields in the new reponse, nuke
// them in the cached response and then add in
// the remaining fields one by one from the
// response header
//
if (field->m_next_dup) {
if (dups_seen == false) {
MIMEField *dfield;
// use a second iterator to delete the
// remaining response headers in the cached response,
// so that they will be added in the next iterations.
MIMEFieldIter fiter2 = fiter;
const char *dname = name;
int dlen = name_len;
while (dname) {
cached_header->field_delete(dname, dlen);
dfield = response_header->iter_get_next(&fiter2);
if (dfield) {
dname = dfield->name_get(&dlen);
} else {
dname = NULL;
}
}
dups_seen = true;
}
}
int value_len;
const char *value = field->value_get(&value_len);
if (dups_seen == false) {
cached_header->value_set(name, name_len, value, value_len);
} else {
new_field = cached_header->field_create(name, name_len);
cached_header->field_attach(new_field);
cached_header->field_value_set(new_field, value, value_len);
}
}
merge_warning_header(cached_header, response_header);
Debug("http_hdr_space", "Merged response header with %d dead bytes", cached_header->m_heap->m_lost_string_space);
}
void
HttpTransact::merge_warning_header(HTTPHdr *cached_header, HTTPHdr *response_header)
{
// The plan:
//
// 1) The cached header has it's warning codes untouched
// since merge_response_header_with_cached_header()
// doesn't deal with warning headers.
// 2) If there are 1xx warning codes in the cached
// header, they need to be removed. Removal
// is difficult since the hdrs don't comma
// separate values, so build up a new header
// piecemal. Very slow but shouldn't happen
// very often
// 3) Since we keep the all the warning codes from
// the response header, append if to
// the cached header
//
MIMEField *c_warn = cached_header->field_find(MIME_FIELD_WARNING, MIME_LEN_WARNING);
MIMEField *r_warn = response_header->field_find(MIME_FIELD_WARNING, MIME_LEN_WARNING);
MIMEField *new_cwarn = NULL;
int move_warn_len;
const char *move_warn;
// Loop over the cached warning header and transfer all non 1xx
// warning values to a new header
if (c_warn) {
HdrCsvIter csv;
move_warn = csv.get_first(c_warn, &move_warn_len);
while (move_warn) {
int code = ink_atoi(move_warn, move_warn_len);
if (code < 100 || code > 199) {
bool first_move;
if (!new_cwarn) {
new_cwarn = cached_header->field_create();
first_move = true;
} else {
first_move = false;
}
cached_header->field_value_append(new_cwarn, move_warn, move_warn_len, !first_move);
}
move_warn = csv.get_next(&move_warn_len);
}
// At this point we can nuke the old warning headers
cached_header->field_delete(MIME_FIELD_WARNING, MIME_LEN_WARNING);
// Add in the new header if it has anything in it
if (new_cwarn) {
new_cwarn->name_set(cached_header->m_heap, cached_header->m_mime, MIME_FIELD_WARNING, MIME_LEN_WARNING);
cached_header->field_attach(new_cwarn);
}
}
// Loop over all the dups in the response warning header and append
// them one by one on to the cached warning header
while (r_warn) {
move_warn = r_warn->value_get(&move_warn_len);
if (new_cwarn) {
cached_header->field_value_append(new_cwarn, move_warn, move_warn_len, true);
} else {
new_cwarn = cached_header->field_create(MIME_FIELD_WARNING, MIME_LEN_WARNING);
cached_header->field_attach(new_cwarn);
cached_header->field_value_set(new_cwarn, move_warn, move_warn_len);
}
r_warn = r_warn->m_next_dup;
}
}
////////////////////////////////////////////////////////
// Set the keep-alive and version flags for later use //
// in request construction //
// this is also used when opening a connection to //
// the origin server, and search_keepalive_to(). //
////////////////////////////////////////////////////////
bool
HttpTransact::get_ka_info_from_config(State *s, ConnectionAttributes *server_info)
{
bool check_hostdb = false;
if (server_info->http_version > HTTPVersion(0, 9)) {
DebugTxn("http_trans", "get_ka_info_from_config, version already set server_info->http_version %d",
server_info->http_version.m_version);
return false;
}
switch (s->txn_conf->send_http11_requests) {
case HttpConfigParams::SEND_HTTP11_NEVER:
server_info->http_version = HTTPVersion(1, 0);
break;
case HttpConfigParams::SEND_HTTP11_UPGRADE_HOSTDB:
server_info->http_version = HTTPVersion(1, 0);
check_hostdb = true;
break;
case HttpConfigParams::SEND_HTTP11_IF_REQUEST_11_AND_HOSTDB:
server_info->http_version = HTTPVersion(1, 0);
if (s->hdr_info.client_request.version_get() == HTTPVersion(1, 1)) {
// check hostdb only if client req is http/1.1
check_hostdb = true;
}
break;
default:
// The default is the "1" config, SEND_HTTP11_ALWAYS, but assert in debug builds since we shouldn't be here
ink_assert(0);
// FALL THROUGH in a release build
case HttpConfigParams::SEND_HTTP11_ALWAYS:
server_info->http_version = HTTPVersion(1, 1);
break;
}
DebugTxn("http_trans", "get_ka_info_from_config, server_info->http_version %d, check_hostdb %d",
server_info->http_version.m_version, check_hostdb);
// Set keep_alive info based on the records.config setting
server_info->keep_alive = s->txn_conf->keep_alive_enabled_out ? HTTP_KEEPALIVE : HTTP_NO_KEEPALIVE;
return check_hostdb;
}
////////////////////////////////////////////////////////
// Set the keep-alive and version flags for later use //
// in request construction //
// this is also used when opening a connection to //
// the origin server, and search_keepalive_to(). //
////////////////////////////////////////////////////////
void
HttpTransact::get_ka_info_from_host_db(State *s, ConnectionAttributes *server_info,
ConnectionAttributes * /* client_info ATS_UNUSED */, HostDBInfo *host_db_info)
{
bool force_http11 = false;
bool http11_if_hostdb = false;
switch (s->txn_conf->send_http11_requests) {
case HttpConfigParams::SEND_HTTP11_NEVER:
// No need to do anything since above vars
// are defaulted false
break;
case HttpConfigParams::SEND_HTTP11_UPGRADE_HOSTDB:
http11_if_hostdb = true;
break;
case HttpConfigParams::SEND_HTTP11_IF_REQUEST_11_AND_HOSTDB:
if (s->hdr_info.client_request.version_get() == HTTPVersion(1, 1)) {
http11_if_hostdb = true;
}
break;
default:
// The default is the "1" config, SEND_HTTP11_ALWAYS, but assert in debug builds since we shouldn't be here
ink_assert(0);
// FALL THROUGH in a release build
case HttpConfigParams::SEND_HTTP11_ALWAYS:
force_http11 = true;
break;
}
if (force_http11 == true ||
(http11_if_hostdb == true && host_db_info->app.http_data.http_version == HostDBApplicationInfo::HTTP_VERSION_11)) {
server_info->http_version.set(1, 1);
server_info->keep_alive = HTTP_KEEPALIVE;
} else if (host_db_info->app.http_data.http_version == HostDBApplicationInfo::HTTP_VERSION_10) {
server_info->http_version.set(1, 0);
server_info->keep_alive = HTTP_KEEPALIVE;
} else if (host_db_info->app.http_data.http_version == HostDBApplicationInfo::HTTP_VERSION_09) {
server_info->http_version.set(0, 9);
server_info->keep_alive = HTTP_NO_KEEPALIVE;
} else {
//////////////////////////////////////////////
// not set yet for this host. set defaults. //
//////////////////////////////////////////////
server_info->http_version.set(1, 0);
server_info->keep_alive = HTTP_KEEPALIVE;
host_db_info->app.http_data.http_version = HostDBApplicationInfo::HTTP_VERSION_10;
}
/////////////////////////////
// origin server keep_alive //
/////////////////////////////
if (!s->txn_conf->keep_alive_enabled_out) {
server_info->keep_alive = HTTP_NO_KEEPALIVE;
}
return;
}
void
HttpTransact::add_client_ip_to_outgoing_request(State *s, HTTPHdr *request)
{
char ip_string[INET6_ADDRSTRLEN + 1] = {'\0'};
size_t ip_string_size = 0;
if (!ats_is_ip(&s->client_info.src_addr.sa)) {
return;
}
// Always prepare the IP string.
if (ats_ip_ntop(&s->client_info.src_addr.sa, ip_string, sizeof(ip_string)) != NULL) {
ip_string_size += strlen(ip_string);
} else {
// Failure, omg
ip_string_size = 0;
ip_string[0] = 0;
}
////////////////////////////////////////////////////////////////
// if we want client-ip headers, and there isn't one, add one //
////////////////////////////////////////////////////////////////
if ((s->txn_conf->anonymize_insert_client_ip) && (!s->txn_conf->anonymize_remove_client_ip)) {
bool client_ip_set = request->presence(MIME_PRESENCE_CLIENT_IP);
DebugTxn("http_trans", "client_ip_set = %d", client_ip_set);
if (!client_ip_set && ip_string_size > 0) {
request->value_set(MIME_FIELD_CLIENT_IP, MIME_LEN_CLIENT_IP, ip_string, ip_string_size);
DebugTxn("http_trans", "inserted request header 'Client-ip: %s'", ip_string);
}
}
if (s->txn_conf->insert_squid_x_forwarded_for) {
if (ip_string_size > 0) {
MIMEField *x_for;
if ((x_for = request->field_find(MIME_FIELD_X_FORWARDED_FOR, MIME_LEN_X_FORWARDED_FOR)) != 0) {
// http://en.wikipedia.org/wiki/X-Forwarded-For
// The X-Forwarded-For (XFF) HTTP header field is a de facto standard
// for identifying the originating IP address of a client connecting
// to a web server through an HTTP proxy or load balancer. This is a
// non-RFC-standard request field which was introduced by the Squid
// caching proxy server's developers.
// X-Forwarded-For: client1, proxy1, proxy2
request->field_value_append(x_for, ip_string, ip_string_size, true); // true => comma must be inserted
} else {
request->value_set(MIME_FIELD_X_FORWARDED_FOR, MIME_LEN_X_FORWARDED_FOR, ip_string, ip_string_size);
}
DebugTxn("http_trans", "[add_client_ip_to_outgoing_request] Appended connecting client's "
"(%s) to the X-Forwards header",
ip_string);
}
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : check_request_validity()
// Description: checks to see if incoming request has necessary fields
//
// Input : State, header (can we do this without the state?)
// Output : enum RequestError_t of the error type, if any
//
// Details :
//
//
///////////////////////////////////////////////////////////////////////////////
HttpTransact::RequestError_t
HttpTransact::check_request_validity(State *s, HTTPHdr *incoming_hdr)
{
if (incoming_hdr == 0) {
return NON_EXISTANT_REQUEST_HEADER;
}
if (!(HttpTransactHeaders::is_request_proxy_authorized(incoming_hdr))) {
return FAILED_PROXY_AUTHORIZATION;
}
URL *incoming_url = incoming_hdr->url_get();
int hostname_len;
const char *hostname = incoming_hdr->host_get(&hostname_len);
if (hostname == NULL) {
return MISSING_HOST_FIELD;
}
if (hostname_len >= MAXDNAME || hostname_len <= 0 || memchr(hostname, '\0', hostname_len)) {
return BAD_HTTP_HEADER_SYNTAX;
}
int scheme = incoming_url->scheme_get_wksidx();
int method = incoming_hdr->method_get_wksidx();
// Check for chunked encoding
if (incoming_hdr->presence(MIME_PRESENCE_TRANSFER_ENCODING)) {
MIMEField *field = incoming_hdr->field_find(MIME_FIELD_TRANSFER_ENCODING, MIME_LEN_TRANSFER_ENCODING);
HdrCsvIter enc_val_iter;
int enc_val_len;
const char *enc_value = enc_val_iter.get_first(field, &enc_val_len);
while (enc_value) {
const char *wks_value = hdrtoken_string_to_wks(enc_value, enc_val_len);
if (wks_value == HTTP_VALUE_CHUNKED) {
s->client_info.transfer_encoding = CHUNKED_ENCODING;
break;
}
enc_value = enc_val_iter.get_next(&enc_val_len);
}
}
/////////////////////////////////////////////////////
// get request content length //
// To avoid parsing content-length twice, we set //
// s->hdr_info.request_content_length here rather //
// than in initialize_state_variables_from_request //
/////////////////////////////////////////////////////
if (method != HTTP_WKSIDX_TRACE) {
int64_t length = incoming_hdr->get_content_length();
s->hdr_info.request_content_length = (length >= 0) ? length : HTTP_UNDEFINED_CL; // content length less than zero is invalid
DebugTxn("http_trans", "[init_stat_vars_from_req] set req cont length to %" PRId64, s->hdr_info.request_content_length);
} else {
s->hdr_info.request_content_length = 0;
}
if (!((scheme == URL_WKSIDX_HTTP) && (method == HTTP_WKSIDX_GET))) {
if (scheme != URL_WKSIDX_HTTP && scheme != URL_WKSIDX_HTTPS && method != HTTP_WKSIDX_CONNECT &&
!((scheme == URL_WKSIDX_WS || scheme == URL_WKSIDX_WSS) && s->is_websocket)) {
if (scheme < 0) {
return NO_REQUEST_SCHEME;
} else {
return SCHEME_NOT_SUPPORTED;
}
}
if (!HttpTransactHeaders::is_this_method_supported(scheme, method)) {
return METHOD_NOT_SUPPORTED;
}
if ((method == HTTP_WKSIDX_CONNECT) && !s->transparent_passthrough &&
(!is_port_in_range(incoming_hdr->url_get()->port_get(), s->http_config_param->connect_ports))) {
return BAD_CONNECT_PORT;
}
// Require Content-Length/Transfer-Encoding for POST/PUSH/PUT
if ((scheme == URL_WKSIDX_HTTP || scheme == URL_WKSIDX_HTTPS) &&
(method == HTTP_WKSIDX_POST || method == HTTP_WKSIDX_PUSH || method == HTTP_WKSIDX_PUT) &&
s->client_info.transfer_encoding != CHUNKED_ENCODING) {
if ((s->txn_conf->post_check_content_length_enabled) && !incoming_hdr->presence(MIME_PRESENCE_CONTENT_LENGTH)) {
return NO_POST_CONTENT_LENGTH;
}
if (HTTP_UNDEFINED_CL == s->hdr_info.request_content_length) {
return INVALID_POST_CONTENT_LENGTH;
}
}
}
// Check whether a Host header field is missing in the request.
if (!incoming_hdr->presence(MIME_PRESENCE_HOST) && incoming_hdr->version_get() != HTTPVersion(0, 9)) {
// Update the number of incoming 1.0 or 1.1 requests that do
// not contain Host header fields.
HTTP_INCREMENT_DYN_STAT(http_missing_host_hdr_stat);
}
// Did the client send a "TE: identity;q=0"? We have to respond
// with an error message because we only support identity
// Transfer Encoding.
if (incoming_hdr->presence(MIME_PRESENCE_TE)) {
MIMEField *te_field = incoming_hdr->field_find(MIME_FIELD_TE, MIME_LEN_TE);
HTTPValTE *te_val;
if (te_field) {
HdrCsvIter csv_iter;
int te_raw_len;
const char *te_raw = csv_iter.get_first(te_field, &te_raw_len);
while (te_raw) {
te_val = http_parse_te(te_raw, te_raw_len, &s->arena);
if (te_val->encoding == HTTP_VALUE_IDENTITY) {
if (te_val->qvalue <= 0.0) {
s->arena.free(te_val, sizeof(HTTPValTE));
return UNACCEPTABLE_TE_REQUIRED;
}
}
s->arena.free(te_val, sizeof(HTTPValTE));
te_raw = csv_iter.get_next(&te_raw_len);
}
}
}
return NO_REQUEST_HEADER_ERROR;
}
HttpTransact::ResponseError_t
HttpTransact::check_response_validity(State *s, HTTPHdr *incoming_hdr)
{
ink_assert(s->next_hop_scheme == URL_WKSIDX_HTTP || s->next_hop_scheme == URL_WKSIDX_HTTPS);
if (incoming_hdr == 0) {
return NON_EXISTANT_RESPONSE_HEADER;
}
if (incoming_hdr->type_get() != HTTP_TYPE_RESPONSE) {
return NOT_A_RESPONSE_HEADER;
}
// If the response is 0.9 then there is no status
// code or date
if (did_forward_server_send_0_9_response(s) == true) {
return NO_RESPONSE_HEADER_ERROR;
}
HTTPStatus incoming_status = incoming_hdr->status_get();
if (!incoming_status) {
return MISSING_STATUS_CODE;
}
if (incoming_status == HTTP_STATUS_INTERNAL_SERVER_ERROR) {
return STATUS_CODE_SERVER_ERROR;
}
if (!incoming_hdr->presence(MIME_PRESENCE_DATE)) {
incoming_hdr->set_date(s->current.now);
}
// if (! incoming_hdr->get_reason_phrase()) {
// return MISSING_REASON_PHRASE;
// }
#ifdef REALLY_NEED_TO_CHECK_DATE_VALIDITY
if (incoming_hdr->presence(MIME_PRESENCE_DATE)) {
time_t date_value = incoming_hdr->get_date();
if (date_value <= 0) {
// following lines commented out because of performance
// concerns
// if (s->http_config_param->errors_log_error_pages) {
// const char *date_string =
// incoming_hdr->value_get(MIME_FIELD_DATE);
// Log::error ("Incoming response has bogus date value: %d: %s",
// date_value, date_string ? date_string : "(null)");
// }
DebugTxn("http_trans", "[check_response_validity] Bogus date in response");
return BOGUS_OR_NO_DATE_IN_RESPONSE;
}
} else {
DebugTxn("http_trans", "[check_response_validity] No date in response");
return BOGUS_OR_NO_DATE_IN_RESPONSE;
}
#endif
return NO_RESPONSE_HEADER_ERROR;
}
bool
HttpTransact::did_forward_server_send_0_9_response(State *s)
{
if (s->hdr_info.server_response.version_get() == HTTPVersion(0, 9)) {
s->current.server->http_version.set(0, 9);
return true;
}
return false;
}
bool
HttpTransact::handle_internal_request(State * /* s ATS_UNUSED */, HTTPHdr *incoming_hdr)
{
URL *url;
ink_assert(incoming_hdr->type_get() == HTTP_TYPE_REQUEST);
if (incoming_hdr->method_get_wksidx() != HTTP_WKSIDX_GET) {
return false;
}
url = incoming_hdr->url_get();
int scheme = url->scheme_get_wksidx();
if (scheme != URL_WKSIDX_HTTP && scheme != URL_WKSIDX_HTTPS) {
return false;
}
if (!statPagesManager.is_stat_page(url)) {
return false;
}
return true;
}
bool
HttpTransact::handle_trace_and_options_requests(State *s, HTTPHdr *incoming_hdr)
{
ink_assert(incoming_hdr->type_get() == HTTP_TYPE_REQUEST);
// This only applies to TRACE and OPTIONS
if ((s->method != HTTP_WKSIDX_TRACE) && (s->method != HTTP_WKSIDX_OPTIONS)) {
return false;
}
// If there is no Max-Forwards request header, just return false.
if (!incoming_hdr->presence(MIME_PRESENCE_MAX_FORWARDS)) {
// Trace and Options requests should not be looked up in cache.
// s->cache_info.action = CACHE_DO_NO_ACTION;
s->current.mode = TUNNELLING_PROXY;
HTTP_INCREMENT_DYN_STAT(http_tunnels_stat);
return false;
}
int max_forwards = incoming_hdr->get_max_forwards();
if (max_forwards <= 0) {
//////////////////////////////////////////////
// if max-forward is 0 the request must not //
// be forwarded to the origin server. //
//////////////////////////////////////////////
DebugTxn("http_trans", "[handle_trace] max-forwards: 0, building response...");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, HTTP_STATUS_OK);
////////////////////////////////////////
// if method is trace we should write //
// the request header as the body. //
////////////////////////////////////////
if (s->method == HTTP_WKSIDX_TRACE) {
DebugTxn("http_trans", "[handle_trace] inserting request in body.");
int req_length = incoming_hdr->length_get();
HTTP_RELEASE_ASSERT(req_length > 0);
s->free_internal_msg_buffer();
s->internal_msg_buffer_size = req_length * 2;
if (s->internal_msg_buffer_size <= max_iobuffer_size) {
s->internal_msg_buffer_fast_allocator_size = buffer_size_to_index(s->internal_msg_buffer_size);
s->internal_msg_buffer = (char *)ioBufAllocator[s->internal_msg_buffer_fast_allocator_size].alloc_void();
} else {
s->internal_msg_buffer_fast_allocator_size = -1;
s->internal_msg_buffer = (char *)ats_malloc(s->internal_msg_buffer_size);
}
// clear the stupid buffer
memset(s->internal_msg_buffer, '\0', s->internal_msg_buffer_size);
int offset = 0;
int used = 0;
int done;
done = incoming_hdr->print(s->internal_msg_buffer, s->internal_msg_buffer_size, &used, &offset);
HTTP_RELEASE_ASSERT(done);
s->internal_msg_buffer_size = used;
s->hdr_info.client_response.set_content_length(used);
} else {
// For OPTIONS request insert supported methods in ALLOW field
DebugTxn("http_trans", "[handle_options] inserting methods in Allow.");
HttpTransactHeaders::insert_supported_methods_in_response(&s->hdr_info.client_response, s->scheme);
}
return true;
} else { /* max-forwards != 0 */
if ((max_forwards <= 0) || (max_forwards > INT_MAX)) {
Log::error("HTTP: snapping invalid max-forwards value %d to %d", max_forwards, INT_MAX);
max_forwards = INT_MAX;
}
--max_forwards;
DebugTxn("http_trans", "[handle_trace_options] Decrementing max_forwards to %d", max_forwards);
incoming_hdr->set_max_forwards(max_forwards);
// Trace and Options requests should not be looked up in cache.
// s->cache_info.action = CACHE_DO_NO_ACTION;
s->current.mode = TUNNELLING_PROXY;
HTTP_INCREMENT_DYN_STAT(http_tunnels_stat);
}
return false;
}
void
HttpTransact::initialize_state_variables_for_origin_server(State *s, HTTPHdr *incoming_request, bool second_time)
{
if (s->server_info.name && !second_time) {
ink_assert(s->server_info.dst_addr.port() != 0);
}
int host_len;
const char *host = incoming_request->host_get(&host_len);
s->server_info.name = s->arena.str_store(host, host_len);
if (second_time) {
s->dns_info.attempts = 0;
s->dns_info.lookup_name = s->server_info.name;
}
}
void
HttpTransact::bootstrap_state_variables_from_request(State *s, HTTPHdr *incoming_request)
{
s->current.now = s->client_request_time = ink_cluster_time();
s->client_info.http_version = incoming_request->version_get();
}
void
HttpTransact::initialize_state_variables_from_request(State *s, HTTPHdr *obsolete_incoming_request)
{
HTTPHdr *incoming_request = &s->hdr_info.client_request;
// Temporary, until we're confident that the second argument is redundant.
ink_assert(incoming_request == obsolete_incoming_request);
int host_len;
const char *host_name = incoming_request->host_get(&host_len);
// check if the request is conditional (IMS or INM)
if (incoming_request->presence(MIME_PRESENCE_IF_MODIFIED_SINCE | MIME_PRESENCE_IF_NONE_MATCH)) {
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_IMS);
} else {
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_SIMPLE);
}
// Is the user agent Keep-Alive?
// If we are transparent or if the user-agent is following
// the 1.1 spec, we will see a "Connection" header to
// indicate a keep-alive. However most user-agents including
// MSIE3.0, Netscape4.04 and Netscape3.01 send Proxy-Connection
// when they are configured to use a proxy. Proxy-Connection
// is not in the spec but was added to prevent problems
// with a dumb proxy forwarding all headers (including "Connection")
// to the origin server and confusing it. In cases of transparent
// deployments we use the Proxy-Connect hdr (to be as transparent
// as possible).
MIMEField *pc = incoming_request->field_find(MIME_FIELD_PROXY_CONNECTION, MIME_LEN_PROXY_CONNECTION);
// If we need to send a close header later check to see if it should be "Proxy-Connection"
if (pc != NULL) {
s->client_info.proxy_connect_hdr = true;
}
if (s->state_machine->ua_session) {
s->request_data.incoming_port = s->state_machine->ua_session->get_netvc()->get_local_port();
s->request_data.internal_txn = s->state_machine->ua_session->get_netvc()->get_is_internal_request();
}
NetVConnection *vc = NULL;
if (s->state_machine->ua_session) {
vc = s->state_machine->ua_session->get_netvc();
}
// If this is an internal request, never keep alive
if (!s->txn_conf->keep_alive_enabled_in || (vc && vc->get_is_internal_request()) ||
(s->state_machine->ua_session && s->state_machine->ua_session->ignore_keep_alive())) {
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
} else {
s->client_info.keep_alive = incoming_request->keep_alive_get();
}
if (s->client_info.keep_alive == HTTP_KEEPALIVE && s->client_info.http_version == HTTPVersion(1, 1)) {
s->client_info.pipeline_possible = true;
}
if (!s->server_info.name || s->redirect_info.redirect_in_process) {
s->server_info.name = s->arena.str_store(host_name, host_len);
}
s->next_hop_scheme = s->scheme = incoming_request->url_get()->scheme_get_wksidx();
// With websockets we need to make an outgoing request
// as http or https.
// We switch back to HTTP or HTTPS for the next hop
// I think this is required to properly establish outbound WSS connections,
// you'll need to force the next hop to be https.
if (s->is_websocket) {
if (s->next_hop_scheme == URL_WKSIDX_WS) {
DebugTxn("http_trans", "Switching WS next hop scheme to http.");
s->next_hop_scheme = URL_WKSIDX_HTTP;
s->scheme = URL_WKSIDX_HTTP;
// s->request_data.hdr->url_get()->scheme_set(URL_SCHEME_HTTP, URL_LEN_HTTP);
} else if (s->next_hop_scheme == URL_WKSIDX_WSS) {
DebugTxn("http_trans", "Switching WSS next hop scheme to https.");
s->next_hop_scheme = URL_WKSIDX_HTTPS;
s->scheme = URL_WKSIDX_HTTPS;
// s->request_data.hdr->url_get()->scheme_set(URL_SCHEME_HTTPS, URL_LEN_HTTPS);
} else {
Error("Scheme doesn't match websocket...!");
}
s->current.mode = GENERIC_PROXY;
s->cache_info.action = CACHE_DO_NO_ACTION;
}
s->method = incoming_request->method_get_wksidx();
if (s->method == HTTP_WKSIDX_GET) {
HTTP_INCREMENT_DYN_STAT(http_get_requests_stat);
} else if (s->method == HTTP_WKSIDX_HEAD) {
HTTP_INCREMENT_DYN_STAT(http_head_requests_stat);
} else if (s->method == HTTP_WKSIDX_POST) {
HTTP_INCREMENT_DYN_STAT(http_post_requests_stat);
} else if (s->method == HTTP_WKSIDX_PUT) {
HTTP_INCREMENT_DYN_STAT(http_put_requests_stat);
} else if (s->method == HTTP_WKSIDX_CONNECT) {
HTTP_INCREMENT_DYN_STAT(http_connect_requests_stat);
} else if (s->method == HTTP_WKSIDX_DELETE) {
HTTP_INCREMENT_DYN_STAT(http_delete_requests_stat);
} else if (s->method == HTTP_WKSIDX_PURGE) {
HTTP_INCREMENT_DYN_STAT(http_purge_requests_stat);
} else if (s->method == HTTP_WKSIDX_TRACE) {
HTTP_INCREMENT_DYN_STAT(http_trace_requests_stat);
} else if (s->method == HTTP_WKSIDX_PUSH) {
HTTP_INCREMENT_DYN_STAT(http_push_requests_stat);
} else if (s->method == HTTP_WKSIDX_OPTIONS) {
HTTP_INCREMENT_DYN_STAT(http_options_requests_stat);
} else if (s->method == HTTP_WKSIDX_TRACE) {
HTTP_INCREMENT_DYN_STAT(http_trace_requests_stat);
} else {
HTTP_INCREMENT_DYN_STAT(http_extension_method_requests_stat);
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_METHOD);
s->squid_codes.log_code = SQUID_LOG_TCP_MISS;
s->hdr_info.extension_method = true;
}
// if transfer encoding is chunked content length is undefined
if (s->client_info.transfer_encoding == CHUNKED_ENCODING) {
s->hdr_info.request_content_length = HTTP_UNDEFINED_CL;
}
s->request_data.hdr = &s->hdr_info.client_request;
s->request_data.hostname_str = s->arena.str_store(host_name, host_len);
ats_ip_copy(&s->request_data.src_ip, &s->client_info.src_addr);
memset(&s->request_data.dest_ip, 0, sizeof(s->request_data.dest_ip));
if (s->state_machine->ua_session) {
NetVConnection *netvc = s->state_machine->ua_session->get_netvc();
if (netvc) {
s->request_data.incoming_port = netvc->get_local_port();
}
}
s->request_data.xact_start = s->client_request_time;
s->request_data.api_info = &s->api_info;
/////////////////////////////////////////////
// Do dns lookup for the host. We need //
// the expanded host for cache lookup, and //
// the host ip for reverse proxy. //
/////////////////////////////////////////////
s->dns_info.looking_up = ORIGIN_SERVER;
s->dns_info.attempts = 0;
s->dns_info.lookup_name = s->server_info.name;
}
void
HttpTransact::initialize_state_variables_from_response(State *s, HTTPHdr *incoming_response)
{
/* check if the server permits caching */
s->cache_info.directives.does_server_permit_storing =
HttpTransactHeaders::does_server_allow_response_to_be_stored(&s->hdr_info.server_response);
/*
* A stupid moronic broken pathetic excuse
* for a server may send us a keep alive response even
* if we sent "Connection: close" We need check the response
* header regardless of what we sent to the server
*/
s->current.server->keep_alive = s->hdr_info.server_response.keep_alive_get();
// Don't allow an upgrade request to Keep Alive
if (s->is_upgrade_request) {
s->current.server->keep_alive = HTTP_NO_KEEPALIVE;
}
if (s->current.server->keep_alive == HTTP_KEEPALIVE) {
if (!s->cop_test_page) {
DebugTxn("http_hdrs", "[initialize_state_variables_from_response]"
"Server is keep-alive.");
}
} else if (s->state_machine->ua_session && s->state_machine->ua_session->is_outbound_transparent() &&
s->state_machine->t_state.http_config_param->use_client_source_port) {
/* If we are reusing the client<->ATS 4-tuple for ATS<->server then if the server side is closed, we can't
re-open it because the 4-tuple may still be in the processing of shutting down. So if the server isn't
keep alive we must turn that off for the client as well.
*/
s->state_machine->t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE;
}
HTTPStatus status_code = incoming_response->status_get();
if (is_response_body_precluded(status_code, s->method)) {
s->hdr_info.response_content_length = 0;
s->hdr_info.trust_response_cl = true;
} else {
// This code used to discriminate CL: headers when the origin disabled keep-alive.
if (incoming_response->presence(MIME_PRESENCE_CONTENT_LENGTH)) {
int64_t cl = incoming_response->get_content_length();
s->hdr_info.response_content_length = (cl >= 0) ? cl : HTTP_UNDEFINED_CL;
s->hdr_info.trust_response_cl = true;
} else {
s->hdr_info.response_content_length = HTTP_UNDEFINED_CL;
s->hdr_info.trust_response_cl = false;
}
}
if (incoming_response->presence(MIME_PRESENCE_TRANSFER_ENCODING)) {
MIMEField *field = incoming_response->field_find(MIME_FIELD_TRANSFER_ENCODING, MIME_LEN_TRANSFER_ENCODING);
ink_assert(field != NULL);
HdrCsvIter enc_val_iter;
int enc_val_len;
const char *enc_value = enc_val_iter.get_first(field, &enc_val_len);
while (enc_value) {
const char *wks_value = hdrtoken_string_to_wks(enc_value, enc_val_len);
if (wks_value == HTTP_VALUE_CHUNKED) {
if (!s->cop_test_page) {
DebugTxn("http_hdrs", "[init_state_vars_from_resp] transfer encoding: chunked!");
}
s->current.server->transfer_encoding = CHUNKED_ENCODING;
s->hdr_info.response_content_length = HTTP_UNDEFINED_CL;
s->hdr_info.trust_response_cl = false;
// OBJECTIVE: Since we are dechunking the request remove the
// chunked value If this is the only value, we need to remove
// the whole field.
MIMEField *new_enc_field = NULL;
HdrCsvIter new_enc_iter;
int new_enc_len;
const char *new_enc_val = new_enc_iter.get_first(field, &new_enc_len);
// Loop over the all the values in existing Trans-enc header and
// copy the ones that aren't our chunked value to a new field
while (new_enc_val) {
const char *new_wks_value = hdrtoken_string_to_wks(new_enc_val, new_enc_len);
if (new_wks_value != wks_value) {
if (new_enc_field) {
new_enc_field->value_append(incoming_response->m_heap, incoming_response->m_mime, new_enc_val, new_enc_len, true);
} else {
new_enc_field = incoming_response->field_create();
incoming_response->field_value_set(new_enc_field, new_enc_val, new_enc_len);
}
}
new_enc_val = new_enc_iter.get_next(&new_enc_len);
}
// We're done with the old field since we copied out everything
// we needed
incoming_response->field_delete(field);
// If there is a new field (ie: there was more than one
// transfer-encoding), insert it to the list
if (new_enc_field) {
new_enc_field->name_set(incoming_response->m_heap, incoming_response->m_mime, MIME_FIELD_TRANSFER_ENCODING,
MIME_LEN_TRANSFER_ENCODING);
incoming_response->field_attach(new_enc_field);
}
return;
} // if (enc_value == CHUNKED)
enc_value = enc_val_iter.get_next(&enc_val_len);
}
}
s->current.server->transfer_encoding = NO_TRANSFER_ENCODING;
}
bool
HttpTransact::is_cache_response_returnable(State *s)
{
if (s->cache_control.never_cache) {
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_CONFIG);
return false;
}
if (!s->cache_info.directives.does_client_permit_lookup) {
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_CLIENT);
return false;
}
if (!HttpTransactHeaders::is_method_cacheable(s->http_config_param, s->method) && s->api_resp_cacheable == false) {
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_CACHE_NOT_ACCEPTABLE);
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_METHOD);
return false;
}
// If cookies in response and no TTL set, we do not cache the doc
if ((s->cache_control.ttl_in_cache <= 0) &&
do_cookies_prevent_caching((int)s->txn_conf->cache_responses_to_cookies, &s->hdr_info.client_request,
s->cache_info.object_read->response_get(), s->cache_info.object_read->request_get())) {
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_CACHE_NOT_ACCEPTABLE);
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_COOKIE);
return false;
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
// Name : is_stale_cache_response_returnable()
// Description: check if a stale cached response is returnable to a client
//
// Input : State
// Output : true or false
//
// Details :
//
///////////////////////////////////////////////////////////////////////////////
bool
HttpTransact::is_stale_cache_response_returnable(State *s)
{
HTTPHdr *cached_response = s->cache_info.object_read->response_get();
// First check if client allows cached response
// Note does_client_permit_lookup was set to
// does_client_Request_permit_cached_response()
// in update_cache_control_information_from_config().
if (!s->cache_info.directives.does_client_permit_lookup) {
return false;
}
// Spec says that we can not serve a stale document with a
// "must-revalidate header"
// How about "s-maxage" and "no-cache" directives?
uint32_t cc_mask;
cc_mask = (MIME_COOKED_MASK_CC_MUST_REVALIDATE | MIME_COOKED_MASK_CC_PROXY_REVALIDATE | MIME_COOKED_MASK_CC_NEED_REVALIDATE_ONCE |
MIME_COOKED_MASK_CC_NO_CACHE | MIME_COOKED_MASK_CC_NO_STORE | MIME_COOKED_MASK_CC_S_MAXAGE);
if ((cached_response->get_cooked_cc_mask() & cc_mask) || cached_response->is_pragma_no_cache_set()) {
DebugTxn("http_trans", "[is_stale_cache_response_returnable] "
"document headers prevent serving stale");
return false;
}
// See how old the document really is. We don't want create a
// stale content museum of documents that are no longer available
time_t current_age = HttpTransactHeaders::calculate_document_age(s->cache_info.object_read->request_sent_time_get(),
s->cache_info.object_read->response_received_time_get(),
cached_response, cached_response->get_date(), s->current.now);
// Negative age is overflow
if ((current_age < 0) || (current_age > s->txn_conf->cache_max_stale_age)) {
DebugTxn("http_trans", "[is_stale_cache_response_returnable] "
"document age is too large %" PRId64,
(int64_t)current_age);
return false;
}
// If the stale document requires authorization, we can't return it either.
Authentication_t auth_needed = AuthenticationNeeded(s->txn_conf, &s->hdr_info.client_request, cached_response);
if (auth_needed != AUTHENTICATION_SUCCESS) {
DebugTxn("http_trans", "[is_stale_cache_response_returnable] "
"authorization prevent serving stale");
return false;
}
DebugTxn("http_trans", "[is_stale_cache_response_returnable] can serve stale");
return true;
}
bool
HttpTransact::url_looks_dynamic(URL *url)
{
const char *p_start, *p, *t;
static const char *asp = ".asp";
const char *part;
int part_length;
if (url->scheme_get_wksidx() != URL_WKSIDX_HTTP && url->scheme_get_wksidx() != URL_WKSIDX_HTTPS) {
return false;
}
////////////////////////////////////////////////////////////
// (1) If URL contains query stuff in it, call it dynamic //
////////////////////////////////////////////////////////////
part = url->params_get(&part_length);
if (part != NULL) {
return true;
}
part = url->query_get(&part_length);
if (part != NULL) {
return true;
}
///////////////////////////////////////////////
// (2) If path ends in "asp" call it dynamic //
///////////////////////////////////////////////
part = url->path_get(&part_length);
if (part) {
p = &part[part_length - 1];
t = &asp[3];
while (p != part) {
if (ParseRules::ink_tolower(*p) == ParseRules::ink_tolower(*t)) {
p -= 1;
t -= 1;
if (t == asp) {
return true;
}
} else {
break;
}
}
}
/////////////////////////////////////////////////////////////////
// (3) If the path of the url contains "cgi", call it dynamic. //
/////////////////////////////////////////////////////////////////
if (part && part_length >= 3) {
for (p_start = part; p_start <= &part[part_length - 3]; p_start++) {
if (((p_start[0] == 'c') || (p_start[0] == 'C')) && ((p_start[1] == 'g') || (p_start[1] == 'G')) &&
((p_start[2] == 'i') || (p_start[2] == 'I'))) {
return (true);
}
}
}
return (false);
}
///////////////////////////////////////////////////////////////////////////////
// Name : is_request_cache_lookupable()
// Description: check if a request should be looked up in cache
//
// Input : State, request header
// Output : true or false
//
// Details :
//
//
///////////////////////////////////////////////////////////////////////////////
bool
HttpTransact::is_request_cache_lookupable(State *s)
{
// ummm, someone has already decided that proxy should tunnel
if (s->current.mode == TUNNELLING_PROXY) {
return false;
}
// don't bother with remaining checks if we already did a cache lookup
if (s->cache_info.lookup_count > 0) {
return true;
}
// is cache turned on?
if (!s->txn_conf->cache_http) {
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_CACHE_OFF);
return false;
}
// GET, HEAD, POST, DELETE, and PUT are all cache lookupable
if (!HttpTransactHeaders::is_method_cache_lookupable(s->method) && s->api_req_cacheable == false) {
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_METHOD);
return false;
}
// don't cache page if URL "looks dynamic" and this filter is enabled
// We can do the check in is_response_cacheable() or here.
// It may be more efficient if we are not going to cache dynamic looking urls
// (the default config?) since we don't even need to do cache lookup.
// So for the time being, it'll be left here.
// If url looks dynamic but a ttl is set, request is cache lookupable
if ((!s->txn_conf->cache_urls_that_look_dynamic) && url_looks_dynamic(s->hdr_info.client_request.url_get()) &&
(s->cache_control.ttl_in_cache <= 0)) {
// We do not want to forward the request for a dynamic URL onto the
// origin server if the value of the Max-Forwards header is zero.
int max_forwards = -1;
if (s->hdr_info.client_request.presence(MIME_PRESENCE_MAX_FORWARDS)) {
MIMEField *max_forwards_f = s->hdr_info.client_request.field_find(MIME_FIELD_MAX_FORWARDS, MIME_LEN_MAX_FORWARDS);
if (max_forwards_f) {
max_forwards = max_forwards_f->value_get_int();
}
}
if (max_forwards != 0) {
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_URL);
return false;
}
}
// Don't look in cache if it's a RANGE request but the cache is not enabled for RANGE.
if (!s->txn_conf->cache_range_lookup && s->hdr_info.client_request.presence(MIME_PRESENCE_RANGE)) {
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_HEADER_FIELD);
return false;
}
// Even with "no-cache" directive, we want to do a cache lookup
// because we need to update our cached copy.
// Client request "no-cache" directive is handle elsewhere:
// update_cache_control_information_from_config()
return true;
}
///////////////////////////////////////////////////////////////////////////////
// Name : response_cacheable_indicated_by_cc()
// Description: check if a response is cacheable as indicated by Cache-Control
//
// Input : Response header
// Output : -1, 0, or +1
//
// Details :
// (1) return -1 if cache control indicates response not cacheable,
// ie, with no-store, or private directives;
// (2) return +1 if cache control indicates response cacheable
// ie, with public, max-age, s-maxage, must-revalidate, or proxy-revalidate;
// (3) otherwise, return 0 if cache control does not indicate.
//
///////////////////////////////////////////////////////////////////////////////
int
response_cacheable_indicated_by_cc(HTTPHdr *response)
{
uint32_t cc_mask;
// the following directives imply not cacheable
cc_mask = (MIME_COOKED_MASK_CC_NO_STORE | MIME_COOKED_MASK_CC_PRIVATE);
if (response->get_cooked_cc_mask() & cc_mask) {
return -1;
}
// the following directives imply cacheable
cc_mask = (MIME_COOKED_MASK_CC_PUBLIC | MIME_COOKED_MASK_CC_MAX_AGE | MIME_COOKED_MASK_CC_S_MAXAGE |
MIME_COOKED_MASK_CC_MUST_REVALIDATE | MIME_COOKED_MASK_CC_PROXY_REVALIDATE);
if (response->get_cooked_cc_mask() & cc_mask) {
return 1;
}
// otherwise, no indication
return 0;
}
///////////////////////////////////////////////////////////////////////////////
// Name : is_response_cacheable()
// Description: check if a response is cacheable
//
// Input : State, request header, response header
// Output : true or false
//
// Details :
//
///////////////////////////////////////////////////////////////////////////////
bool
HttpTransact::is_response_cacheable(State *s, HTTPHdr *request, HTTPHdr *response)
{
// If the use_client_target_addr is specified but the client
// specified OS addr does not match any of trafficserver's looked up
// host addresses, do not allow cache. This may cause DNS cache poisoning
// of other trafficserver clients. The flag is set in the
// process_host_db_info method
if (!s->dns_info.lookup_validated && s->client_info.is_transparent) {
DebugTxn("http_trans", "[is_response_cacheable] "
"Lookup not validated. Possible DNS cache poison. Don't cache");
return false;
}
// the plugin may decide we don't want to cache the response
if (s->api_server_response_no_store) {
return false;
}
// if method is not GET or HEAD, do not cache.
// Note: POST is also cacheable with Expires or Cache-control.
// but due to INKqa11567, we are not caching POST responses.
// Basically, the problem is the resp for POST url1 req should not
// be served to a GET url1 request, but we just match URL not method.
int req_method = request->method_get_wksidx();
if (!(HttpTransactHeaders::is_method_cacheable(s->http_config_param, req_method)) && s->api_req_cacheable == false) {
DebugTxn("http_trans", "[is_response_cacheable] "
"only GET, and some HEAD and POST are cachable");
return false;
}
// DebugTxn("http_trans", "[is_response_cacheable] method is cacheable");
// If the request was not looked up in the cache, the response
// should not be cached (same subsequent requests will not be
// looked up, either, so why cache this).
if (!(is_request_cache_lookupable(s))) {
DebugTxn("http_trans", "[is_response_cacheable] "
"request is not cache lookupable, response is not cachable");
return false;
}
// already has a fresh copy in the cache
if (s->range_setup == RANGE_NOT_HANDLED) {
return false;
}
// Check whether the response is cachable based on its cookie
// If there are cookies in response but a ttl is set, allow caching
if ((s->cache_control.ttl_in_cache <= 0) &&
do_cookies_prevent_caching((int)s->txn_conf->cache_responses_to_cookies, request, response)) {
DebugTxn("http_trans", "[is_response_cacheable] "
"response has uncachable cookies, response is not cachable");
return false;
}
// if server spits back a WWW-Authenticate
if ((s->txn_conf->cache_ignore_auth) == 0 && response->presence(MIME_PRESENCE_WWW_AUTHENTICATE)) {
DebugTxn("http_trans", "[is_response_cacheable] "
"response has WWW-Authenticate, response is not cachable");
return false;
}
// does server explicitly forbid storing?
// If OS forbids storing but a ttl is set, allow caching
if (!s->cache_info.directives.does_server_permit_storing && !s->cache_control.ignore_server_no_cache &&
(s->cache_control.ttl_in_cache <= 0)) {
DebugTxn("http_trans", "[is_response_cacheable] server does not permit storing and config file does not "
"indicate that server directive should be ignored");
return false;
}
// DebugTxn("http_trans", "[is_response_cacheable] server permits storing");
// does config explicitly forbid storing?
// ttl overides other config parameters
if ((!s->cache_info.directives.does_config_permit_storing && !s->cache_control.ignore_server_no_cache &&
(s->cache_control.ttl_in_cache <= 0)) ||
(s->cache_control.never_cache)) {
DebugTxn("http_trans", "[is_response_cacheable] config doesn't allow storing, and cache control does not "
"say to ignore no-cache and does not specify never-cache or a ttl");
return false;
}
// DebugTxn("http_trans", "[is_response_cacheable] config permits storing");
// does client explicitly forbid storing?
if (!s->cache_info.directives.does_client_permit_storing && !s->cache_control.ignore_client_no_cache) {
DebugTxn("http_trans", "[is_response_cacheable] client does not permit storing, "
"and cache control does not say to ignore client no-cache");
return false;
}
DebugTxn("http_trans", "[is_response_cacheable] client permits storing");
HTTPStatus response_code = response->status_get();
// caching/not-caching based on required headers
// only makes sense when the server sends back a
// 200 and a document.
if (response_code == HTTP_STATUS_OK) {
// If a ttl is set: no header required for caching
// otherwise: follow parameter http.cache.required_headers
if (s->cache_control.ttl_in_cache <= 0) {
uint32_t cc_mask = (MIME_COOKED_MASK_CC_MAX_AGE | MIME_COOKED_MASK_CC_S_MAXAGE);
// server did not send expires header or last modified
// and we are configured to not cache without them.
switch (s->txn_conf->cache_required_headers) {
case HttpConfigParams::CACHE_REQUIRED_HEADERS_NONE:
DebugTxn("http_trans", "[is_response_cacheable] "
"no response headers required");
break;
case HttpConfigParams::CACHE_REQUIRED_HEADERS_AT_LEAST_LAST_MODIFIED:
if (!response->presence(MIME_PRESENCE_EXPIRES) && !(response->get_cooked_cc_mask() & cc_mask) &&
!response->get_last_modified()) {
DebugTxn("http_trans", "[is_response_cacheable] "
"last_modified, expires, or max-age is required");
s->squid_codes.hit_miss_code = ((response->get_date() == 0) ? (SQUID_MISS_HTTP_NO_DLE) : (SQUID_MISS_HTTP_NO_LE));
return false;
}
break;
case HttpConfigParams::CACHE_REQUIRED_HEADERS_CACHE_CONTROL:
if (!response->presence(MIME_PRESENCE_EXPIRES) && !(response->get_cooked_cc_mask() & cc_mask)) {
DebugTxn("http_trans", "[is_response_cacheable] "
"expires header or max-age is required");
return false;
}
break;
default:
break;
}
}
}
// do not cache partial content - Range response
if (response_code == HTTP_STATUS_PARTIAL_CONTENT || response_code == HTTP_STATUS_RANGE_NOT_SATISFIABLE) {
DebugTxn("http_trans", "[is_response_cacheable] "
"response code %d - don't cache",
response_code);
return false;
}
// check if cache control overrides default cacheability
int indicator;
indicator = response_cacheable_indicated_by_cc(response);
if (indicator > 0) { // cacheable indicated by cache control header
DebugTxn("http_trans", "[is_response_cacheable] YES by response cache control");
// even if it is authenticated, this is cacheable based on regular rules
s->www_auth_content = CACHE_AUTH_NONE;
return true;
} else if (indicator < 0) { // not cacheable indicated by cache control header
// If a ttl is set, allow caching even if response contains
// Cache-Control headers to prevent caching
if (s->cache_control.ttl_in_cache > 0) {
DebugTxn("http_trans",
"[is_response_cacheable] Cache-control header directives in response overridden by ttl in cache.config");
} else if (!s->cache_control.ignore_server_no_cache) {
DebugTxn("http_trans", "[is_response_cacheable] NO by response cache control");
return false;
}
}
// else no indication by cache control header
// continue to determine cacheability
// if client contains Authorization header,
// only cache if response has proper Cache-Control
// if (s->www_auth_content == CACHE_AUTH_FRESH) {
// response to the HEAD request
// return false;
//} else if (s->www_auth_content == CACHE_AUTH_TRUE ||
// (s->www_auth_content == CACHE_AUTH_NONE && request->presence(MIME_PRESENCE_AUTHORIZATION))) {
// if (!s->cache_control.cache_auth_content || response_code != HTTP_STATUS_OK || req_method != HTTP_WKSIDX_GET)
// return false;
//}
// s->www_auth_content == CACHE_AUTH_STALE silently continues
if (response->presence(MIME_PRESENCE_EXPIRES)) {
DebugTxn("http_trans", "[is_response_cacheable] YES response w/ Expires");
return true;
}
// if it's a 302 or 307 and no positive indicator from cache-control, reject
if (response_code == HTTP_STATUS_MOVED_TEMPORARILY || response_code == HTTP_STATUS_TEMPORARY_REDIRECT) {
DebugTxn("http_trans", "[is_response_cacheable] cache-control or expires header is required for 302");
return false;
}
// if it's a POST request and no positive indicator from cache-control
if (req_method == HTTP_WKSIDX_POST) {
// allow caching for a POST requests w/o Expires but with a ttl
if (s->cache_control.ttl_in_cache > 0) {
DebugTxn("http_trans", "[is_response_cacheable] POST method with a TTL");
} else {
DebugTxn("http_trans", "[is_response_cacheable] NO POST w/o Expires or CC");
return false;
}
}
// default cacheability
if (!s->txn_conf->negative_caching_enabled) {
if ((response_code == HTTP_STATUS_OK) || (response_code == HTTP_STATUS_NOT_MODIFIED) ||
(response_code == HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION) || (response_code == HTTP_STATUS_MOVED_PERMANENTLY) ||
(response_code == HTTP_STATUS_MULTIPLE_CHOICES) || (response_code == HTTP_STATUS_GONE)) {
DebugTxn("http_trans", "[is_response_cacheable] YES by default ");
return true;
} else {
DebugTxn("http_trans", "[is_response_cacheable] NO by default");
return false;
}
}
if (response_code == HTTP_STATUS_SEE_OTHER || response_code == HTTP_STATUS_UNAUTHORIZED ||
response_code == HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
return false;
}
// let is_negative_caching_approriate decide what to do
return true;
/* Since we weren't caching response obtained with
Authorization (the cache control stuff was commented out previously)
I've moved this check to is_request_cache_lookupable().
We should consider this matter further. It is unclear
how many sites actually add Cache-Control headers for Authorized content.
// if client contains Authorization header, only cache if response
// has proper Cache-Control flags, as in RFC2068, section 14.8.
if (request->field_presence(MIME_PRESENCE_AUTHORIZATION)) {
// if (! (response->is_cache_control_set(HTTP_VALUE_MUST_REVALIDATE)) &&
// ! (response->is_cache_control_set(HTTP_VALUE_PROXY_REVALIDATE)) &&
// ! (response->is_cache_control_set(HTTP_VALUE_PUBLIC))) {
DebugTxn("http_trans", "[is_response_cacheable] request has AUTHORIZATION - not cacheable");
return(false);
// }
// else {
// DebugTxn("http_trans","[is_response_cacheable] request has AUTHORIZATION, "
// "but response has a cache-control that allows caching");
// }
}
*/
}
bool
HttpTransact::is_request_valid(State *s, HTTPHdr *incoming_request)
{
RequestError_t incoming_error;
URL *url = NULL;
if (incoming_request) {
url = incoming_request->url_get();
}
incoming_error = check_request_validity(s, incoming_request);
switch (incoming_error) {
case NO_REQUEST_HEADER_ERROR:
DebugTxn("http_trans", "[is_request_valid] no request header errors");
break;
case FAILED_PROXY_AUTHORIZATION:
DebugTxn("http_trans", "[is_request_valid] failed proxy authorization");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED, "Proxy Authentication Required",
"access#proxy_auth_required", NULL);
return false;
case NON_EXISTANT_REQUEST_HEADER:
/* fall through */
case BAD_HTTP_HEADER_SYNTAX: {
DebugTxn("http_trans", "[is_request_valid] non-existant/bad header");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Invalid HTTP Request", "request#syntax_error", NULL);
return false;
}
case MISSING_HOST_FIELD:
////////////////////////////////////////////////////////////////////
// FIX: are we sure the following logic is right? it seems that //
// we shouldn't complain about the missing host header until //
// we know we really need one --- are we sure we need a host //
// header at this point? //
// //
// FIX: also, let's clean up the transparency code to remove the //
// SunOS conditionals --- we will be transparent on all //
// platforms soon! in fact, I really want a method that i //
// can call for each transaction to say if the transaction //
// is a forward proxy request, a transparent request, a //
// reverse proxy request, etc --- the detail of how we //
// determine the cases should be hidden behind the method. //
////////////////////////////////////////////////////////////////////
DebugTxn("http_trans", "[is_request_valid] missing host field");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
if (s->http_config_param->reverse_proxy_enabled) { // host header missing and reverse proxy on
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Host Header Required", "request#no_host", NULL);
} else {
// host header missing and reverse proxy off
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Host Required In Request", "request#no_host", NULL);
}
return false;
case SCHEME_NOT_SUPPORTED:
case NO_REQUEST_SCHEME: {
DebugTxn("http_trans", "[is_request_valid] unsupported or missing request scheme");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Unsupported URL Scheme", "request#scheme_unsupported", NULL);
return false;
}
/* fall through */
case METHOD_NOT_SUPPORTED:
DebugTxn("http_trans", "[is_request_valid] unsupported method");
s->current.mode = TUNNELLING_PROXY;
return true;
case BAD_CONNECT_PORT:
int port;
port = url ? url->port_get() : 0;
DebugTxn("http_trans", "[is_request_valid] %d is an invalid connect port", port);
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_FORBIDDEN, "Tunnel Forbidden", "access#connect_forbidden", NULL);
return false;
case NO_POST_CONTENT_LENGTH: {
DebugTxn("http_trans", "[is_request_valid] post request without content length");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_LENGTH_REQUIRED, "Content Length Required", "request#no_content_length", NULL);
return false;
}
case UNACCEPTABLE_TE_REQUIRED: {
DebugTxn("http_trans", "[is_request_valid] TE required is unacceptable.");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_NOT_ACCEPTABLE, "Transcoding Not Available", "transcoding#unsupported", NULL);
return false;
}
case INVALID_POST_CONTENT_LENGTH: {
DebugTxn("http_trans", "[is_request_valid] post request with negative content length value");
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Invalid Content Length", "request#invalid_content_length", NULL);
return false;
}
default:
return true;
}
return true;
}
// bool HttpTransact::is_request_retryable
//
// In the general case once bytes have been sent on the wire the request cannot be retried.
// The reason we cannot retry is that the rfc2616 does not make any gaurantees about the
// retry-ability of a request. In fact in the reverse proxy case it is quite common for GET
// requests on the origin to fire tracking events etc. So, as a proxy once we have sent bytes
// on the wire to the server we cannot gaurantee that the request is safe to redispatch to another server.
//
bool
HttpTransact::is_request_retryable(State *s)
{
// If there was no error establishing the connection (and we sent bytes)-- we cannot retry
if (s->current.state != CONNECTION_ERROR && s->state_machine->server_request_hdr_bytes > 0) {
return false;
}
if (s->state_machine->plugin_tunnel_type != HTTP_NO_PLUGIN_TUNNEL) {
// API can override
if (s->state_machine->plugin_tunnel_type == HTTP_PLUGIN_AS_SERVER && s->api_info.retry_intercept_failures == true) {
// This used to be an == comparison, which made no sense. Changed
// to be an assignment, hoping the state is correct.
s->state_machine->plugin_tunnel_type = HTTP_NO_PLUGIN_TUNNEL;
} else {
return false;
}
}
return true;
}
bool
HttpTransact::is_response_valid(State *s, HTTPHdr *incoming_response)
{
if (s->current.state != CONNECTION_ALIVE) {
ink_assert((s->current.state == CONNECTION_ERROR) || (s->current.state == OPEN_RAW_ERROR) ||
(s->current.state == PARSE_ERROR) || (s->current.state == CONNECTION_CLOSED) ||
(s->current.state == INACTIVE_TIMEOUT) || (s->current.state == ACTIVE_TIMEOUT) ||
(s->current.state == CONGEST_CONTROL_CONGESTED_ON_M) || (s->current.state == CONGEST_CONTROL_CONGESTED_ON_F));
s->hdr_info.response_error = CONNECTION_OPEN_FAILED;
return false;
}
s->hdr_info.response_error = check_response_validity(s, incoming_response);
switch (s->hdr_info.response_error) {
#ifdef REALLY_NEED_TO_CHECK_DATE_VALIDITY
case BOGUS_OR_NO_DATE_IN_RESPONSE:
// We could modify the response to add the date, if need be.
// incoming_response->set_date(s->request_sent_time);
return true;
#endif
case NO_RESPONSE_HEADER_ERROR:
DebugTxn("http_trans", "[is_response_valid] No errors in response");
return true;
case MISSING_REASON_PHRASE:
DebugTxn("http_trans", "[is_response_valid] Response Error: Missing reason phrase - allowing");
return true;
case STATUS_CODE_SERVER_ERROR:
DebugTxn("http_trans", "[is_response_valid] Response Error: Origin Server returned 500 - allowing");
return true;
case CONNECTION_OPEN_FAILED:
DebugTxn("http_trans", "[is_response_valid] Response Error: connection open failed");
s->current.state = CONNECTION_ERROR;
return false;
case NON_EXISTANT_RESPONSE_HEADER:
DebugTxn("http_trans", "[is_response_valid] Response Error: No response header");
s->current.state = BAD_INCOMING_RESPONSE;
return false;
case NOT_A_RESPONSE_HEADER:
DebugTxn("http_trans", "[is_response_valid] Response Error: Not a response header");
s->current.state = BAD_INCOMING_RESPONSE;
return false;
case MISSING_STATUS_CODE:
DebugTxn("http_trans", "[is_response_valid] Response Error: Missing status code");
s->current.state = BAD_INCOMING_RESPONSE;
return false;
default:
DebugTxn("http_trans", "[is_response_valid] Errors in response");
s->current.state = BAD_INCOMING_RESPONSE;
return false;
}
}
///////////////////////////////////////////////////////////////////////////////
// Name : service_transaction_in_proxy_only_mode
// Description: uses some metric to force this transaction to be proxy-only
//
// Details :
//
// Some metric may be employed to force the traffic server to enter
// a proxy-only mode temporarily. This function is called to determine
// if the current transaction should be proxy-only. The function is
// called from initialize_state_variables_from_request and is used to
// set s->current.mode to TUNNELLING_PROXY and just for safety to set
// s->cache_info.action to CACHE_DO_NO_ACTION.
//
// Currently the function is just a placeholder and always returns false.
//
///////////////////////////////////////////////////////////////////////////////
bool
HttpTransact::service_transaction_in_proxy_only_mode(State * /* s ATS_UNUSED */)
{
return false;
}
void
HttpTransact::process_quick_http_filter(State *s, int method)
{
// connection already disabled by previous ACL filtering, don't modify it.
if (!s->client_connection_enabled) {
return;
}
if (s->state_machine->ua_session) {
const AclRecord *acl_record = s->state_machine->ua_session->get_acl_record();
bool deny_request = (acl_record == NULL);
if (acl_record && (acl_record->_method_mask != AclRecord::ALL_METHOD_MASK)) {
if (method != -1) {
deny_request = !acl_record->isMethodAllowed(method);
} else {
int method_str_len;
const char *method_str = s->hdr_info.client_request.method_get(&method_str_len);
deny_request = !acl_record->isNonstandardMethodAllowed(std::string(method_str, method_str_len));
}
}
if (deny_request) {
if (is_debug_tag_set("ip-allow")) {
ip_text_buffer ipb;
DebugTxn("ip-allow", "Quick filter denial on %s:%s with mask %x",
ats_ip_ntop(&s->client_info.src_addr.sa, ipb, sizeof(ipb)), hdrtoken_index_to_wks(method),
acl_record ? acl_record->_method_mask : 0x0);
}
s->client_connection_enabled = false;
}
}
}
HttpTransact::HostNameExpansionError_t
HttpTransact::try_to_expand_host_name(State *s)
{
static int max_dns_lookups = 2 + s->http_config_param->num_url_expansions;
static int last_expansion = max_dns_lookups - 2;
HTTP_RELEASE_ASSERT(!s->dns_info.lookup_success);
if (s->dns_info.looking_up == ORIGIN_SERVER) {
///////////////////////////////////////////////////
// if resolving dns of the origin server failed, //
// we try to expand hostname. //
///////////////////////////////////////////////////
if (s->http_config_param->enable_url_expandomatic) {
int attempts = s->dns_info.attempts;
ink_assert(attempts >= 1 && attempts <= max_dns_lookups);
if (attempts < max_dns_lookups) {
// Try a URL expansion
if (attempts <= last_expansion) {
char *expansion = s->http_config_param->url_expansions[attempts - 1];
int length = strlen(s->server_info.name) + strlen(expansion) + 1;
s->dns_info.lookup_name = s->arena.str_alloc(length);
ink_string_concatenate_strings_n(s->dns_info.lookup_name, length + 1, s->server_info.name, ".", expansion, NULL);
} else {
if (ParseRules::strchr(s->server_info.name, '.')) {
// don't expand if contains '.'
return (EXPANSION_FAILED);
}
// Try www.<server_name>.com
int length = strlen(s->server_info.name) + 8;
s->dns_info.lookup_name = s->arena.str_alloc(length);
ink_string_concatenate_strings_n(s->dns_info.lookup_name, length + 1, "www.", s->server_info.name, ".com", NULL);
}
return RETRY_EXPANDED_NAME;
} else {
return DNS_ATTEMPTS_EXHAUSTED;
}
} else {
return EXPANSION_NOT_ALLOWED;
}
} else {
//////////////////////////////////////////////////////
// we looked up dns of parent proxy, but it failed, //
// try lookup of origin server name. //
//////////////////////////////////////////////////////
ink_assert(s->dns_info.looking_up == PARENT_PROXY);
s->dns_info.lookup_name = s->server_info.name;
s->dns_info.looking_up = ORIGIN_SERVER;
s->dns_info.attempts = 0;
return RETRY_EXPANDED_NAME;
}
}
bool
HttpTransact::will_this_request_self_loop(State *s)
{
////////////////////////////////////////
// check if we are about to self loop //
////////////////////////////////////////
if (s->dns_info.lookup_success) {
if (ats_ip_addr_eq(s->host_db_info.ip(), &Machine::instance()->ip.sa)) {
in_port_t host_port = s->hdr_info.client_request.url_get()->port_get();
in_port_t local_port = s->client_info.src_addr.host_order_port();
if (host_port == local_port) {
switch (s->dns_info.looking_up) {
case ORIGIN_SERVER:
DebugTxn("http_transact", "[will_this_request_self_loop] host ip and port same as local ip and port - bailing");
break;
case PARENT_PROXY:
DebugTxn("http_transact", "[will_this_request_self_loop] "
"parent proxy ip and port same as local ip and port - bailing");
break;
default:
DebugTxn("http_transact", "[will_this_request_self_loop] "
"unknown's ip and port same as local ip and port - bailing");
break;
}
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Cycle Detected", "request#cycle_detected", NULL);
return true;
}
}
// Now check for a loop using the Via string.
const char *uuid = Machine::instance()->uuid.getString();
MIMEField *via_field = s->hdr_info.client_request.field_find(MIME_FIELD_VIA, MIME_LEN_VIA);
while (via_field) {
// No need to waste cycles comma separating the via values since we want to do a match anywhere in the
// in the string. We can just loop over the dup hdr fields
int via_len;
const char *via_string = via_field->value_get(&via_len);
if (via_string && ptr_len_str(via_string, via_len, uuid)) {
DebugTxn("http_transact", "[will_this_request_self_loop] Incoming via: %.*s has (%s[%s] (%s))", via_len, via_string,
s->http_config_param->proxy_hostname, uuid, s->http_config_param->proxy_request_via_string);
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Multi-Hop Cycle Detected", "request#cycle_detected", NULL);
return true;
}
via_field = via_field->m_next_dup;
}
}
s->request_will_not_selfloop = true;
return false;
}
/*
* handle_content_length_header(...)
* Function handles the insertion of content length headers into
* header. header CAN equal base.
*/
void
HttpTransact::handle_content_length_header(State *s, HTTPHdr *header, HTTPHdr *base)
{
int64_t cl = HTTP_UNDEFINED_CL;
ink_assert(header->type_get() == HTTP_TYPE_RESPONSE);
if (base->presence(MIME_PRESENCE_CONTENT_LENGTH)) {
cl = base->get_content_length();
if (cl >= 0) {
// header->set_content_length(cl);
ink_assert(header->get_content_length() == cl);
switch (s->source) {
case SOURCE_HTTP_ORIGIN_SERVER:
// We made our decision about whether to trust the
// response content length in init_state_vars_from_response()
if (s->range_setup != HttpTransact::RANGE_NOT_TRANSFORM_REQUESTED) {
break;
}
case SOURCE_CACHE:
// if we are doing a single Range: request, calculate the new
// C-L: header
if (s->range_setup == HttpTransact::RANGE_NOT_TRANSFORM_REQUESTED) {
change_response_header_because_of_range_request(s, header);
s->hdr_info.trust_response_cl = true;
}
////////////////////////////////////////////////
// Make sure that the cache's object size //
// agrees with the Content-Length //
// Otherwise, set the state's machine view //
// of c-l to undefined to turn off K-A //
////////////////////////////////////////////////
else if ((int64_t)s->cache_info.object_read->object_size_get() == cl) {
s->hdr_info.trust_response_cl = true;
} else {
DebugTxn("http_trans", "Content Length header and cache object size mismatch."
"Disabling keep-alive");
s->hdr_info.trust_response_cl = false;
}
break;
case SOURCE_TRANSFORM:
if (s->range_setup == HttpTransact::RANGE_REQUESTED) {
header->set_content_length(s->range_output_cl);
s->hdr_info.trust_response_cl = true;
} else if (s->hdr_info.transform_response_cl == HTTP_UNDEFINED_CL) {
s->hdr_info.trust_response_cl = false;
} else {
s->hdr_info.trust_response_cl = true;
}
break;
default:
ink_release_assert(0);
break;
}
} else {
header->field_delete(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH);
s->hdr_info.trust_response_cl = false;
}
DebugTxn("http_trans", "[handle_content_length_header] RESPONSE cont len in hdr is %" PRId64, header->get_content_length());
} else {
// No content length header
if (s->source == SOURCE_CACHE) {
// If there is no content-length header, we can
// insert one since the cache knows definately
// how long the object is unless we're in a
// read-while-write mode and object hasn't been
// written into a cache completely.
cl = s->cache_info.object_read->object_size_get();
if (cl == INT64_MAX) { // INT64_MAX cl in cache indicates rww in progress
header->field_delete(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH);
s->hdr_info.trust_response_cl = false;
s->hdr_info.request_content_length = HTTP_UNDEFINED_CL;
ink_assert(s->range_setup == RANGE_NONE);
} else if (s->range_setup == RANGE_NOT_TRANSFORM_REQUESTED) {
// if we are doing a single Range: request, calculate the new
// C-L: header
change_response_header_because_of_range_request(s, header);
s->hdr_info.trust_response_cl = true;
} else {
header->set_content_length(cl);
s->hdr_info.trust_response_cl = true;
}
} else {
// Check to see if there is no content length
// header because the response precludes a
// body
if (is_response_body_precluded(header->status_get(), s->method)) {
// We want to be able to do keep-alive here since
// there can't be body so we don't have any
// issues about trusting the body length
s->hdr_info.trust_response_cl = true;
} else {
s->hdr_info.trust_response_cl = false;
}
header->field_delete(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH);
ink_assert(s->range_setup != RANGE_NOT_TRANSFORM_REQUESTED);
}
}
return;
} /* End HttpTransact::handle_content_length_header */
//////////////////////////////////////////////////////////////////////////////
//
// void HttpTransact::handle_request_keep_alive_headers(
// State* s, bool ka_on, HTTPVersion ver, HTTPHdr *heads)
//
// Removes keep alive headers from user-agent from <heads>
//
// Adds the appropriate keep alive headers (if any) to <heads>
// for keep-alive state <ka_on>, and HTTP version <ver>.
//
//////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_request_keep_alive_headers(State *s, HTTPVersion ver, HTTPHdr *heads)
{
enum KA_Action_t {
KA_UNKNOWN,
KA_DISABLED,
KA_CLOSE,
KA_CONNECTION,
};
KA_Action_t ka_action = KA_UNKNOWN;
bool upstream_ka = (s->current.server->keep_alive == HTTP_KEEPALIVE);
ink_assert(heads->type_get() == HTTP_TYPE_REQUEST);
// Check preconditions for Keep-Alive
if (!upstream_ka) {
ka_action = KA_DISABLED;
} else if (HTTP_MAJOR(ver.m_version) == 0) { /* No K-A for 0.9 apps */
ka_action = KA_DISABLED;
}
// If preconditions are met, figure out what action to take
if (ka_action == KA_UNKNOWN) {
int method = heads->method_get_wksidx();
if (method == HTTP_WKSIDX_GET || method == HTTP_WKSIDX_HEAD || method == HTTP_WKSIDX_OPTIONS || method == HTTP_WKSIDX_PURGE ||
method == HTTP_WKSIDX_DELETE || method == HTTP_WKSIDX_TRACE) {
// These methods do not need a content-length header
ka_action = KA_CONNECTION;
} else {
// All remaining methods require a content length header
if (heads->get_content_length() == -1) {
ka_action = KA_CLOSE;
} else {
ka_action = KA_CONNECTION;
}
}
}
ink_assert(ka_action != KA_UNKNOWN);
// Since connection headers are hop-to-hop, strip the
// the ones we received from the user-agent
heads->field_delete(MIME_FIELD_PROXY_CONNECTION, MIME_LEN_PROXY_CONNECTION);
heads->field_delete(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION);
if (!s->is_upgrade_request) {
// Insert K-A headers as necessary
switch (ka_action) {
case KA_CONNECTION:
ink_assert(s->current.server->keep_alive != HTTP_NO_KEEPALIVE);
if (ver == HTTPVersion(1, 0)) {
if (s->current.request_to == PARENT_PROXY || s->current.request_to == ICP_SUGGESTED_HOST) {
heads->value_set(MIME_FIELD_PROXY_CONNECTION, MIME_LEN_PROXY_CONNECTION, "keep-alive", 10);
} else {
heads->value_set(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION, "keep-alive", 10);
}
}
// NOTE: if the version is 1.1 we don't need to do
// anything since keep-alive is assumed
break;
case KA_DISABLED:
case KA_CLOSE:
if (s->current.server->keep_alive != HTTP_NO_KEEPALIVE || (ver == HTTPVersion(1, 1))) {
/* Had keep-alive */
s->current.server->keep_alive = HTTP_NO_KEEPALIVE;
if (s->current.request_to == PARENT_PROXY || s->current.request_to == ICP_SUGGESTED_HOST) {
heads->value_set(MIME_FIELD_PROXY_CONNECTION, MIME_LEN_PROXY_CONNECTION, "close", 5);
} else {
heads->value_set(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION, "close", 5);
}
}
// Note: if we are 1.1, we always need to send the close
// header since persistant connnections are the default
break;
case KA_UNKNOWN:
default:
ink_assert(0);
break;
}
} else { /* websocket connection */
s->current.server->keep_alive = HTTP_NO_KEEPALIVE;
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
heads->value_set(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION, MIME_FIELD_UPGRADE, MIME_LEN_UPGRADE);
if (s->is_websocket) {
heads->value_set(MIME_FIELD_UPGRADE, MIME_LEN_UPGRADE, "websocket", 9);
}
}
} /* End HttpTransact::handle_request_keep_alive_headers */
//////////////////////////////////////////////////////////////////////////////
//
// void HttpTransact::handle_response_keep_alive_headers(
// State* s, bool ka_on, HTTPVersion ver, HTTPHdr *heads)
//
// Removes keep alive headers from origin server from <heads>
//
// Adds the appropriate Transfer-Encoding: chunked header.
//
// Adds the appropriate keep alive headers (if any) to <heads>
// for keep-alive state <ka_on>, and HTTP version <ver>.
//
//////////////////////////////////////////////////////////////////////////////
void
HttpTransact::handle_response_keep_alive_headers(State *s, HTTPVersion ver, HTTPHdr *heads)
{
enum KA_Action_t {
KA_UNKNOWN,
KA_DISABLED,
KA_CLOSE,
KA_CONNECTION,
};
KA_Action_t ka_action = KA_UNKNOWN;
ink_assert(heads->type_get() == HTTP_TYPE_RESPONSE);
// Since connection headers are hop-to-hop, strip the
// the ones we received from upstream
heads->field_delete(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION);
heads->field_delete(MIME_FIELD_PROXY_CONNECTION, MIME_LEN_PROXY_CONNECTION);
// Handle the upgrade cases
if (s->is_upgrade_request && heads->status_get() == HTTP_STATUS_SWITCHING_PROTOCOL && s->source == SOURCE_HTTP_ORIGIN_SERVER) {
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
if (s->is_websocket) {
DebugTxn("http_trans", "transaction successfully upgraded to websockets.");
// s->transparent_passthrough = true;
heads->value_set(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION, MIME_FIELD_UPGRADE, MIME_LEN_UPGRADE);
heads->value_set(MIME_FIELD_UPGRADE, MIME_LEN_UPGRADE, "websocket", 9);
}
// We set this state so that we can jump to our blind forwarding state once
// the response is sent to the client.
s->did_upgrade_succeed = true;
return;
}
int c_hdr_field_len;
const char *c_hdr_field_str;
if (s->client_info.proxy_connect_hdr) {
c_hdr_field_str = MIME_FIELD_PROXY_CONNECTION;
c_hdr_field_len = MIME_LEN_PROXY_CONNECTION;
} else {
c_hdr_field_str = MIME_FIELD_CONNECTION;
c_hdr_field_len = MIME_LEN_CONNECTION;
}
// Check pre-conditions for keep-alive
if (HTTP_MAJOR(ver.m_version) == 0) { /* No K-A for 0.9 apps */
ka_action = KA_DISABLED;
} else if (heads->status_get() == HTTP_STATUS_NO_CONTENT &&
((s->source == SOURCE_HTTP_ORIGIN_SERVER && s->current.server->transfer_encoding != NO_TRANSFER_ENCODING) ||
heads->get_content_length() != 0)) {
// some systems hang until the connection closes when receiving a 204 regardless of the K-A headers
// close if there is any body response from the origin
ka_action = KA_CLOSE;
} else {
// Determine if we are going to send either a server-generated or
// proxy-generated chunked response to the client. If we cannot
// trust the content-length, we may be able to chunk the response
// to the client to keep the connection alive.
// Insert a Transfer-Encoding header in the response if necessary.
// check that the client is HTTP 1.1 and the conf allows chunking or the client
// protocol unchunks before returning to the user agent (i.e. is http/2)
if (s->client_info.http_version == HTTPVersion(1, 1) &&
(s->txn_conf->chunking_enabled == 1 ||
(s->state_machine->plugin_tag && (!strncmp(s->state_machine->plugin_tag, "http/2", 6)))) &&
// if we're not sending a body, don't set a chunked header regardless of server response
!is_response_body_precluded(s->hdr_info.client_response.status_get(), s->method) &&
// we do not need chunked encoding for internal error messages
// that are sent to the client if the server response is not valid.
(((s->source == SOURCE_HTTP_ORIGIN_SERVER || s->source == SOURCE_TRANSFORM) && s->hdr_info.server_response.valid() &&
// if we receive a 304, we will serve the client from the
// cache and thus do not need chunked encoding.
s->hdr_info.server_response.status_get() != HTTP_STATUS_NOT_MODIFIED &&
(s->current.server->transfer_encoding == HttpTransact::CHUNKED_ENCODING ||
// we can use chunked encoding if we cannot trust the content
// length (e.g. no Content-Length and Connection:close in HTTP/1.1 responses)
s->hdr_info.trust_response_cl == false)) ||
// handle serve from cache (read-while-write) case
(s->source == SOURCE_CACHE && s->hdr_info.trust_response_cl == false) ||
// any transform will potentially alter the content length. try chunking if possible
(s->source == SOURCE_TRANSFORM && s->hdr_info.trust_response_cl == false))) {
s->client_info.receive_chunked_response = true;
heads->value_append(MIME_FIELD_TRANSFER_ENCODING, MIME_LEN_TRANSFER_ENCODING, HTTP_VALUE_CHUNKED, HTTP_LEN_CHUNKED, true);
} else {
s->client_info.receive_chunked_response = false;
}
// make sure no content length header is send when transfer encoding is chunked
if (s->client_info.receive_chunked_response) {
s->hdr_info.trust_response_cl = false;
// And delete the header if it's already been added...
heads->field_delete(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH);
}
// Close the connection if client_info is not keep-alive.
// Otherwise, if we cannot trust the content length, we will close the connection
// unless we are going to use chunked encoding or the client issued
// a PUSH request
if (s->client_info.keep_alive != HTTP_KEEPALIVE) {
ka_action = KA_DISABLED;
} else if (s->hdr_info.trust_response_cl == false &&
!(s->client_info.receive_chunked_response == true ||
(s->method == HTTP_WKSIDX_PUSH && s->client_info.keep_alive == HTTP_KEEPALIVE))) {
ka_action = KA_CLOSE;
} else {
ka_action = KA_CONNECTION;
}
}
// Insert K-A headers as necessary
switch (ka_action) {
case KA_CONNECTION:
ink_assert(s->client_info.keep_alive != HTTP_NO_KEEPALIVE);
// This is a hack, we send the keep-alive header for both 1.0
// and 1.1, to be "compatible" with Akamai.
// if (ver == HTTPVersion (1, 0)) {
heads->value_set(c_hdr_field_str, c_hdr_field_len, "keep-alive", 10);
// NOTE: if the version is 1.1 we don't need to do
// anything since keep-alive is assumed
break;
case KA_CLOSE:
case KA_DISABLED:
if (s->client_info.keep_alive != HTTP_NO_KEEPALIVE || (ver == HTTPVersion(1, 1))) {
heads->value_set(c_hdr_field_str, c_hdr_field_len, "close", 5);
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
}
// Note: if we are 1.1, we always need to send the close
// header since persistant connnections are the default
break;
case KA_UNKNOWN:
default:
ink_assert(0);
break;
}
} /* End HttpTransact::handle_response_keep_alive_headers */
bool
HttpTransact::delete_all_document_alternates_and_return(State *s, bool cache_hit)
{
if (cache_hit == true) {
// ToDo: Should support other levels of cache hits here, but the cache does not support it (yet)
if (SQUID_HIT_RAM == s->cache_info.hit_miss_code) {
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_RAM_CACHE_FRESH);
} else {
SET_VIA_STRING(VIA_CACHE_RESULT, VIA_IN_CACHE_FRESH);
}
} else {
SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_NOT_CACHED);
}
if ((s->method != HTTP_WKSIDX_GET) && (s->method == HTTP_WKSIDX_DELETE || s->method == HTTP_WKSIDX_PURGE)) {
bool valid_max_forwards;
int max_forwards = -1;
MIMEField *max_forwards_f = s->hdr_info.client_request.field_find(MIME_FIELD_MAX_FORWARDS, MIME_LEN_MAX_FORWARDS);
// Check the max forwards value for DELETE
if (max_forwards_f) {
valid_max_forwards = true;
max_forwards = max_forwards_f->value_get_int();
} else {
valid_max_forwards = false;
}
if (s->method == HTTP_WKSIDX_PURGE || (valid_max_forwards && max_forwards <= 0)) {
DebugTxn("http_trans", "[delete_all_document_alternates_and_return] "
"DELETE with Max-Forwards: %d",
max_forwards);
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
// allow deletes to be pipelined
// We want to allow keep-alive so trust the response content
// length. There really isn't one and the SM will add the
// zero content length when setting up the transfer
s->hdr_info.trust_response_cl = true;
build_response(s, &s->hdr_info.client_response, s->client_info.http_version,
(cache_hit == true) ? HTTP_STATUS_OK : HTTP_STATUS_NOT_FOUND);
return true;
} else {
if (valid_max_forwards) {
--max_forwards;
DebugTxn("http_trans", "[delete_all_document_alternates_and_return] "
"Decrementing max_forwards to %d",
max_forwards);
s->hdr_info.client_request.value_set_int(MIME_FIELD_MAX_FORWARDS, MIME_LEN_MAX_FORWARDS, max_forwards);
}
}
}
return false;
}
bool
HttpTransact::does_client_request_permit_cached_response(const OverridableHttpConfigParams *p, CacheControlResult *c, HTTPHdr *h,
char *via_string)
{
////////////////////////////////////////////////////////////////////////
// If aren't ignoring client's cache directives, meet client's wishes //
////////////////////////////////////////////////////////////////////////
if (!c->ignore_client_no_cache) {
if (h->is_cache_control_set(HTTP_VALUE_NO_CACHE)) {
return (false);
}
if (h->is_pragma_no_cache_set()) {
// if we are going to send out an ims anyway,
// no need to flag this as a no-cache.
if (!p->cache_ims_on_client_no_cache) {
via_string[VIA_CLIENT_REQUEST] = VIA_CLIENT_NO_CACHE;
}
return (false);
}
}
return (true);
}
bool
HttpTransact::does_client_request_permit_dns_caching(CacheControlResult *c, HTTPHdr *h)
{
if (h->is_pragma_no_cache_set() && h->is_cache_control_set(HTTP_VALUE_NO_CACHE) && (!c->ignore_client_no_cache)) {
return (false);
}
return (true);
}
bool
HttpTransact::does_client_request_permit_storing(CacheControlResult *c, HTTPHdr *h)
{
////////////////////////////////////////////////////////////////////////
// If aren't ignoring client's cache directives, meet client's wishes //
////////////////////////////////////////////////////////////////////////
if (!c->ignore_client_no_cache) {
if (h->is_cache_control_set(HTTP_VALUE_NO_STORE)) {
return (false);
}
}
return (true);
}
int
HttpTransact::calculate_document_freshness_limit(State *s, HTTPHdr *response, time_t response_date, bool *heuristic)
{
bool expires_set, date_set, last_modified_set;
time_t date_value, expires_value, last_modified_value;
MgmtInt min_freshness_bounds, max_freshness_bounds;
int freshness_limit = 0;
uint32_t cc_mask = response->get_cooked_cc_mask();
*heuristic = false;
if (cc_mask & (MIME_COOKED_MASK_CC_S_MAXAGE | MIME_COOKED_MASK_CC_MAX_AGE)) {
if (cc_mask & MIME_COOKED_MASK_CC_S_MAXAGE) {
freshness_limit = (int)response->get_cooked_cc_s_maxage();
DebugTxn("http_match", "calculate_document_freshness_limit --- s_max_age set, freshness_limit = %d", freshness_limit);
} else if (cc_mask & MIME_COOKED_MASK_CC_MAX_AGE) {
freshness_limit = (int)response->get_cooked_cc_max_age();
DebugTxn("http_match", "calculate_document_freshness_limit --- max_age set, freshness_limit = %d", freshness_limit);
}
freshness_limit = min(max(0, freshness_limit), (int)s->txn_conf->cache_guaranteed_max_lifetime);
} else {
date_set = last_modified_set = false;
if (s->plugin_set_expire_time != UNDEFINED_TIME) {
expires_set = true;
expires_value = s->plugin_set_expire_time;
} else {
expires_set = (response->presence(MIME_PRESENCE_EXPIRES) != 0);
expires_value = response->get_expires();
}
date_value = response_date;
if (date_value > 0) {
date_set = true;
} else {
date_value = s->request_sent_time;
DebugTxn("http_match",
"calculate_document_freshness_limit --- Expires header = %" PRId64 " no date, using sent time %" PRId64,
(int64_t)expires_value, (int64_t)date_value);
}
ink_assert(date_value > 0);
// Getting the cache_sm object
HttpCacheSM &cache_sm = s->state_machine->get_cache_sm();
// Bypassing if loop to set freshness_limit to heuristic value
if (expires_set && !cache_sm.is_readwhilewrite_inprogress()) {
if (expires_value == UNDEFINED_TIME || expires_value <= date_value) {
expires_value = date_value;
DebugTxn("http_match", "calculate_document_freshness_limit --- no expires, using date %" PRId64, (int64_t)expires_value);
}
freshness_limit = (int)(expires_value - date_value);
DebugTxn("http_match", "calculate_document_freshness_limit --- Expires: %" PRId64 ", Date: %" PRId64 ", freshness_limit = %d",
(int64_t)expires_value, (int64_t)date_value, freshness_limit);
freshness_limit = min(max(0, freshness_limit), (int)s->txn_conf->cache_guaranteed_max_lifetime);
} else {
last_modified_value = 0;
if (response->presence(MIME_PRESENCE_LAST_MODIFIED)) {
last_modified_set = true;
last_modified_value = response->get_last_modified();
DebugTxn("http_match", "calculate_document_freshness_limit --- Last Modified header = %" PRId64,
(int64_t)last_modified_value);
if (last_modified_value == UNDEFINED_TIME) {
last_modified_set = false;
} else if (last_modified_value > date_value) {
last_modified_value = date_value;
DebugTxn("http_match", "calculate_document_freshness_limit --- no last-modified, using sent time %" PRId64,
(int64_t)last_modified_value);
}
}
*heuristic = true;
if (date_set && last_modified_set) {
MgmtFloat f = s->txn_conf->cache_heuristic_lm_factor;
ink_assert((f >= 0.0) && (f <= 1.0));
ink_time_t time_since_last_modify = date_value - last_modified_value;
int h_freshness = (int)(time_since_last_modify * f);
freshness_limit = max(h_freshness, 0);
DebugTxn("http_match", "calculate_document_freshness_limit --- heuristic: date=%" PRId64 ", lm=%" PRId64
", time_since_last_modify=%" PRId64 ", f=%g, freshness_limit = %d",
(int64_t)date_value, (int64_t)last_modified_value, (int64_t)time_since_last_modify, f, freshness_limit);
} else {
freshness_limit = s->txn_conf->cache_heuristic_min_lifetime;
DebugTxn("http_match", "calculate_document_freshness_limit --- heuristic: freshness_limit = %d", freshness_limit);
}
}
}
// The freshness limit must always fall within the min and max guaranteed bounds.
min_freshness_bounds = max((MgmtInt)0, s->txn_conf->cache_guaranteed_min_lifetime);
max_freshness_bounds = s->txn_conf->cache_guaranteed_max_lifetime;
// Heuristic freshness can be more strict.
if (*heuristic) {
min_freshness_bounds = max(min_freshness_bounds, s->txn_conf->cache_heuristic_min_lifetime);
max_freshness_bounds = min(max_freshness_bounds, s->txn_conf->cache_heuristic_max_lifetime);
}
// Now clip the freshness limit.
if (freshness_limit > max_freshness_bounds) {
freshness_limit = max_freshness_bounds;
}
if (freshness_limit < min_freshness_bounds) {
freshness_limit = min_freshness_bounds;
}
DebugTxn("http_match", "calculate_document_freshness_limit --- final freshness_limit = %d", freshness_limit);
return (freshness_limit);
}
////////////////////////////////////////////////////////////////////////////////////
// int HttpTransact::calculate_freshness_fuzz()
//
// This function trys to revents many, many simulatenous revalidations in
// reverse proxy situations. Statistically introduce a fuzz factor that
// brings revalidation forward for a small percentage of the requests/
// The hope is that is that the document early by a selected few, and
// the headers are updated in the cache before the regualr freshness
// limit is actually reached
////////////////////////////////////////////////////////////////////////////////////
int
HttpTransact::calculate_freshness_fuzz(State *s, int fresh_limit)
{
static double LOG_YEAR = log10((double)s->txn_conf->cache_guaranteed_max_lifetime);
const uint32_t granularity = 1000;
int result = 0;
uint32_t random_num = this_ethread()->generator.random();
uint32_t index = random_num % granularity;
uint32_t range = (uint32_t)(granularity * s->txn_conf->freshness_fuzz_prob);
if (index < range) {
if (s->txn_conf->freshness_fuzz_min_time > 0) {
// Complicated calculations to try to find a reasonable fuzz time between fuzz_min_time and fuzz_time
int fresh_small = (int)rint((double)s->txn_conf->freshness_fuzz_min_time *
pow(2, min((double)fresh_limit / (double)s->txn_conf->freshness_fuzz_time,
sqrt((double)s->txn_conf->freshness_fuzz_time))));
int fresh_large = max((int)s->txn_conf->freshness_fuzz_min_time,
(int)rint(s->txn_conf->freshness_fuzz_time *
log10((double)(fresh_limit - s->txn_conf->freshness_fuzz_min_time) / LOG_YEAR)));
result = min(fresh_small, fresh_large);
DebugTxn("http_match", "calculate_freshness_fuzz using min/max --- freshness fuzz = %d", result);
} else {
result = s->txn_conf->freshness_fuzz_time;
DebugTxn("http_match", "calculate_freshness_fuzz --- freshness fuzz = %d", result);
}
}
return result;
}
//////////////////////////////////////////////////////////////////////////////
//
//
// This function takes the request and response headers for a cached
// object, and the current HTTP parameters, and decides if the object
// is still "fresh enough" to serve. One of the following values
// is returned:
//
// FRESHNESS_FRESH Fresh enough, serve it
// FRESHNESS_WARNING Stale but client says it's okay
// FRESHNESS_STALE Too stale, don't use
//
//////////////////////////////////////////////////////////////////////////////
HttpTransact::Freshness_t
HttpTransact::what_is_document_freshness(State *s, HTTPHdr *client_request, HTTPHdr *cached_obj_response)
{
bool heuristic, do_revalidate = false;
int age_limit;
int fresh_limit;
ink_time_t current_age, response_date;
uint32_t cc_mask, cooked_cc_mask;
uint32_t os_specifies_revalidate;
if (s->cache_open_write_fail_action & CACHE_WL_FAIL_ACTION_STALE_ON_REVALIDATE) {
if (is_stale_cache_response_returnable(s)) {
DebugTxn("http_match", "[what_is_document_freshness] cache_serve_stale_on_write_lock_fail, return FRESH");
return (FRESHNESS_FRESH);
}
}
//////////////////////////////////////////////////////
// If config file has a ttl-in-cache field set, //
// it has priority over any other http headers and //
// other configuration parameters. //
//////////////////////////////////////////////////////
if (s->cache_control.ttl_in_cache > 0) {
// what matters if ttl is set is not the age of the document
// but for how long it has been stored in the cache (resident time)
int resident_time = s->current.now - s->response_received_time;
DebugTxn("http_match", "[..._document_freshness] ttl-in-cache = %d, resident time = %d", s->cache_control.ttl_in_cache,
resident_time);
if (resident_time > s->cache_control.ttl_in_cache) {
return (FRESHNESS_STALE);
} else {
return (FRESHNESS_FRESH);
}
}
cooked_cc_mask = cached_obj_response->get_cooked_cc_mask();
os_specifies_revalidate = cooked_cc_mask & (MIME_COOKED_MASK_CC_MUST_REVALIDATE | MIME_COOKED_MASK_CC_PROXY_REVALIDATE);
cc_mask = MIME_COOKED_MASK_CC_NEED_REVALIDATE_ONCE;
// Check to see if the server forces revalidation
if ((cooked_cc_mask & cc_mask) && s->cache_control.revalidate_after <= 0) {
DebugTxn("http_match", "[what_is_document_freshness] document stale due to "
"server must-revalidate");
return FRESHNESS_STALE;
}
response_date = cached_obj_response->get_date();
fresh_limit = calculate_document_freshness_limit(s, cached_obj_response, response_date, &heuristic);
ink_assert(fresh_limit >= 0);
// Fuzz the freshness to prevent too many revalidates to popular
// documents at the same time
if (s->txn_conf->freshness_fuzz_time >= 0) {
fresh_limit = fresh_limit - calculate_freshness_fuzz(s, fresh_limit);
fresh_limit = max(0, fresh_limit);
fresh_limit = min((int)s->txn_conf->cache_guaranteed_max_lifetime, fresh_limit);
}
current_age = HttpTransactHeaders::calculate_document_age(s->request_sent_time, s->response_received_time, cached_obj_response,
response_date, s->current.now);
// Overflow ?
if (current_age < 0) {
current_age = s->txn_conf->cache_guaranteed_max_lifetime;
} else {
current_age = min((time_t)s->txn_conf->cache_guaranteed_max_lifetime, current_age);
}
DebugTxn("http_match", "[what_is_document_freshness] fresh_limit: %d current_age: %" PRId64, fresh_limit, (int64_t)current_age);
/////////////////////////////////////////////////////////
// did the admin override the expiration calculations? //
// (used only for http). //
/////////////////////////////////////////////////////////
ink_assert(client_request == &s->hdr_info.client_request);
if (s->txn_conf->cache_when_to_revalidate == 0) {
;
// Compute how fresh below
} else if (client_request->url_get()->scheme_get_wksidx() == URL_WKSIDX_HTTP) {
switch (s->txn_conf->cache_when_to_revalidate) {
case 1: // Stale if heuristic
if (heuristic) {
DebugTxn("http_match", "[what_is_document_freshness] config requires FRESHNESS_STALE because heuristic calculation");
return (FRESHNESS_STALE);
}
break;
case 2: // Always stale
DebugTxn("http_match", "[what_is_document_freshness] config "
"specifies always FRESHNESS_STALE");
return (FRESHNESS_STALE);
case 3: // Never stale
DebugTxn("http_match", "[what_is_document_freshness] config "
"specifies always FRESHNESS_FRESH");
return (FRESHNESS_FRESH);
case 4: // Stale if IMS
if (client_request->presence(MIME_PRESENCE_IF_MODIFIED_SINCE)) {
DebugTxn("http_match", "[what_is_document_freshness] config "
"specifies FRESHNESS_STALE if IMS present");
return (FRESHNESS_STALE);
}
default: // Bad config, ignore
break;
}
}
//////////////////////////////////////////////////////////////////////
// the normal expiration policy allows serving a doc from cache if: //
// basic: (current_age <= fresh_limit) //
// //
// this can be modified by client Cache-Control headers: //
// max-age: (current_age <= max_age) //
// min-fresh: (current_age <= fresh_limit - min_fresh) //
// max-stale: (current_age <= fresh_limit + max_stale) //
//////////////////////////////////////////////////////////////////////
age_limit = fresh_limit; // basic constraint
DebugTxn("http_match", "[..._document_freshness] initial age limit: %d", age_limit);
cooked_cc_mask = client_request->get_cooked_cc_mask();
cc_mask = (MIME_COOKED_MASK_CC_MAX_STALE | MIME_COOKED_MASK_CC_MIN_FRESH | MIME_COOKED_MASK_CC_MAX_AGE);
if (cooked_cc_mask & cc_mask) {
/////////////////////////////////////////////////
// if max-stale set, relax the freshness limit //
/////////////////////////////////////////////////
if (cooked_cc_mask & MIME_COOKED_MASK_CC_MAX_STALE) {
if (os_specifies_revalidate) {
DebugTxn("http_match", "[...document_freshness] OS specifies revalidation; "
"ignoring client's max-stale request...");
} else {
int max_stale_val = client_request->get_cooked_cc_max_stale();
if (max_stale_val != INT_MAX) {
age_limit += max_stale_val;
} else {
age_limit = max_stale_val;
}
DebugTxn("http_match", "[..._document_freshness] max-stale set, age limit: %d", age_limit);
}
}
/////////////////////////////////////////////////////
// if min-fresh set, constrain the freshness limit //
/////////////////////////////////////////////////////
if (cooked_cc_mask & MIME_COOKED_MASK_CC_MIN_FRESH) {
age_limit = min(age_limit, fresh_limit - client_request->get_cooked_cc_min_fresh());
DebugTxn("http_match", "[..._document_freshness] min_fresh set, age limit: %d", age_limit);
}
///////////////////////////////////////////////////
// if max-age set, constrain the freshness limit //
///////////////////////////////////////////////////
if (!s->cache_control.ignore_client_cc_max_age && (cooked_cc_mask & MIME_COOKED_MASK_CC_MAX_AGE)) {
int age_val = client_request->get_cooked_cc_max_age();
if (age_val == 0) {
do_revalidate = true;
}
age_limit = min(age_limit, age_val);
DebugTxn("http_match", "[..._document_freshness] min_fresh set, age limit: %d", age_limit);
}
}
/////////////////////////////////////////////////////////
// config file may have a "revalidate_after" field set //
/////////////////////////////////////////////////////////
// bug fix changed ">0" to ">=0"
if (s->cache_control.revalidate_after >= 0) {
// if we want the minimum of the already-computed age_limit and revalidate_after
// age_limit = mine(age_limit, s->cache_control.revalidate_after);
// if instead the revalidate_after overrides all other variables
age_limit = s->cache_control.revalidate_after;
DebugTxn("http_match", "[..._document_freshness] revalidate_after set, age limit: %d", age_limit);
}
DebugTxn("http_match", "document_freshness --- current_age = %" PRId64, (int64_t)current_age);
DebugTxn("http_match", "document_freshness --- age_limit = %d", age_limit);
DebugTxn("http_match", "document_freshness --- fresh_limit = %d", fresh_limit);
DebugTxn("http_seq", "document_freshness --- current_age = %" PRId64, (int64_t)current_age);
DebugTxn("http_seq", "document_freshness --- age_limit = %d", age_limit);
DebugTxn("http_seq", "document_freshness --- fresh_limit = %d", fresh_limit);
///////////////////////////////////////////
// now, see if the age is "fresh enough" //
///////////////////////////////////////////
if (do_revalidate || current_age > age_limit) { // client-modified limit
DebugTxn("http_match", "[..._document_freshness] document needs revalidate/too old; "
"returning FRESHNESS_STALE");
return (FRESHNESS_STALE);
} else if (current_age > fresh_limit) { // original limit
if (os_specifies_revalidate) {
DebugTxn("http_match", "[..._document_freshness] document is stale and OS specifies revalidation; "
"returning FRESHNESS_STALE");
return (FRESHNESS_STALE);
}
DebugTxn("http_match", "[..._document_freshness] document is stale but no revalidation explicitly required; "
"returning FRESHNESS_WARNING");
return (FRESHNESS_WARNING);
} else {
DebugTxn("http_match", "[..._document_freshness] document is fresh; returning FRESHNESS_FRESH");
return (FRESHNESS_FRESH);
}
}
//////////////////////////////////////////////////////////////////////////////
//
// HttpTransact::Authentication_t HttpTransact::AuthenticationNeeded(
// const OverridableHttpConfigParams *p,
// HTTPHdr *client_request,
// HTTPHdr *obj_response)
//
// This function takes the current client request, and the headers
// from a potential response (e.g. from cache or proxy), and decides
// if the object needs to be authenticated with the origin server,
// before it can be sent to the client.
//
// The return value describes the authentication process needed. In
// this function, three results are possible:
//
// AUTHENTICATION_SUCCESS Can serve object directly
// AUTHENTICATION_MUST_REVALIDATE Must revalidate with server
// AUTHENTICATION_MUST_PROXY Must not serve object
//
//////////////////////////////////////////////////////////////////////////////
HttpTransact::Authentication_t
HttpTransact::AuthenticationNeeded(const OverridableHttpConfigParams *p, HTTPHdr *client_request, HTTPHdr *obj_response)
{
///////////////////////////////////////////////////////////////////////
// from RFC2068, sec 14.8, if a client request has the Authorization //
// header set, we can't serve it unless the response is public, or //
// if it has a Cache-Control revalidate flag, and we do revalidate. //
///////////////////////////////////////////////////////////////////////
if ((p->cache_ignore_auth == 0) && client_request->presence(MIME_PRESENCE_AUTHORIZATION)) {
if (obj_response->is_cache_control_set(HTTP_VALUE_MUST_REVALIDATE) ||
obj_response->is_cache_control_set(HTTP_VALUE_PROXY_REVALIDATE)) {
return AUTHENTICATION_MUST_REVALIDATE;
} else if (obj_response->is_cache_control_set(HTTP_VALUE_PROXY_REVALIDATE)) {
return AUTHENTICATION_MUST_REVALIDATE;
} else if (obj_response->is_cache_control_set(HTTP_VALUE_PUBLIC)) {
return AUTHENTICATION_SUCCESS;
} else {
if (obj_response->field_find("@WWW-Auth", 9) && client_request->method_get_wksidx() == HTTP_WKSIDX_GET) {
return AUTHENTICATION_CACHE_AUTH;
}
return AUTHENTICATION_MUST_PROXY;
}
}
if (obj_response->field_find("@WWW-Auth", 9) && client_request->method_get_wksidx() == HTTP_WKSIDX_GET) {
return AUTHENTICATION_CACHE_AUTH;
}
return (AUTHENTICATION_SUCCESS);
}
void
HttpTransact::handle_parent_died(State *s)
{
ink_assert(s->parent_result.result == PARENT_FAIL);
build_error_response(s, HTTP_STATUS_BAD_GATEWAY, "Next Hop Connection Failed", "connect#failed_connect", NULL);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
void
HttpTransact::handle_server_died(State *s)
{
const char *reason = NULL;
const char *body_type = "UNKNOWN";
HTTPStatus status = HTTP_STATUS_BAD_GATEWAY;
////////////////////////////////////////////////////////
// FIX: all the body types below need to be filled in //
////////////////////////////////////////////////////////
//
// congestion control
//
if (s->pCongestionEntry != NULL) {
s->congestion_congested_or_failed = 1;
if (s->current.state != CONGEST_CONTROL_CONGESTED_ON_F && s->current.state != CONGEST_CONTROL_CONGESTED_ON_M) {
s->pCongestionEntry->failed_at(s->current.now);
}
}
switch (s->current.state) {
case CONNECTION_ALIVE: /* died while alive for unknown reason */
ink_release_assert(s->hdr_info.response_error != NO_RESPONSE_HEADER_ERROR);
status = HTTP_STATUS_BAD_GATEWAY;
reason = "Unknown Error";
body_type = "response#bad_response";
break;
case CONNECTION_ERROR:
status = HTTP_STATUS_BAD_GATEWAY;
reason = (char *)get_error_string(s->cause_of_death_errno);
body_type = "connect#failed_connect";
break;
case OPEN_RAW_ERROR:
status = HTTP_STATUS_BAD_GATEWAY;
reason = "Tunnel Connection Failed";
body_type = "connect#failed_connect";
break;
case CONNECTION_CLOSED:
status = HTTP_STATUS_BAD_GATEWAY;
reason = "Server Hangup";
body_type = "connect#hangup";
break;
case ACTIVE_TIMEOUT:
if (s->api_txn_active_timeout_value != -1) {
DebugTxn("http_timeout", "Maximum active time of %d msec exceeded", s->api_txn_active_timeout_value);
}
status = HTTP_STATUS_GATEWAY_TIMEOUT;
reason = "Maximum Transaction Time Exceeded";
body_type = "timeout#activity";
break;
case INACTIVE_TIMEOUT:
if (s->api_txn_connect_timeout_value != -1) {
DebugTxn("http_timeout", "Maximum connect time of %d msec exceeded", s->api_txn_connect_timeout_value);
}
status = HTTP_STATUS_GATEWAY_TIMEOUT;
reason = "Connection Timed Out";
body_type = "timeout#inactivity";
break;
case PARSE_ERROR:
case BAD_INCOMING_RESPONSE:
status = HTTP_STATUS_BAD_GATEWAY;
reason = "Invalid HTTP Response";
body_type = "response#bad_response";
break;
case CONGEST_CONTROL_CONGESTED_ON_F:
status = HTTP_STATUS_SERVICE_UNAVAILABLE;
reason = "Origin server congested";
if (s->pCongestionEntry) {
body_type = s->pCongestionEntry->getErrorPage();
} else {
body_type = "congestion#retryAfter";
}
s->hdr_info.response_error = TOTAL_RESPONSE_ERROR_TYPES;
break;
case CONGEST_CONTROL_CONGESTED_ON_M:
status = HTTP_STATUS_SERVICE_UNAVAILABLE;
reason = "Too many users";
if (s->pCongestionEntry) {
body_type = s->pCongestionEntry->getErrorPage();
} else {
body_type = "congestion#retryAfter";
}
s->hdr_info.response_error = TOTAL_RESPONSE_ERROR_TYPES;
break;
case STATE_UNDEFINED:
case TRANSACTION_COMPLETE:
default: /* unknown death */
ink_release_assert(!"[handle_server_died] Unreasonable state - not dead, shouldn't be here");
status = HTTP_STATUS_BAD_GATEWAY;
reason = NULL;
body_type = "response#bad_response";
break;
}
if (s->pCongestionEntry && s->pCongestionEntry->F_congested() && status != HTTP_STATUS_SERVICE_UNAVAILABLE) {
s->pCongestionEntry->stat_inc_F();
CONGEST_SUM_GLOBAL_DYN_STAT(congested_on_F_stat, 1);
status = HTTP_STATUS_SERVICE_UNAVAILABLE;
reason = "Service Unavailable";
body_type = s->pCongestionEntry->getErrorPage();
s->hdr_info.response_error = TOTAL_RESPONSE_ERROR_TYPES;
}
////////////////////////////////////////////////////////
// FIX: comment stuff above and below here, not clear //
////////////////////////////////////////////////////////
switch (s->hdr_info.response_error) {
case NON_EXISTANT_RESPONSE_HEADER:
status = HTTP_STATUS_BAD_GATEWAY;
reason = "No Response Header From Server";
body_type = "response#bad_response";
break;
case MISSING_REASON_PHRASE:
case NO_RESPONSE_HEADER_ERROR:
case NOT_A_RESPONSE_HEADER:
#ifdef REALLY_NEED_TO_CHECK_DATE_VALIDITY
case BOGUS_OR_NO_DATE_IN_RESPONSE:
#endif
status = HTTP_STATUS_BAD_GATEWAY;
reason = "Malformed Server Response";
body_type = "response#bad_response";
break;
case MISSING_STATUS_CODE:
status = HTTP_STATUS_BAD_GATEWAY;
reason = "Malformed Server Response Status";
body_type = "response#bad_response";
break;
default:
break;
}
if (reason == NULL) {
status = HTTP_STATUS_BAD_GATEWAY;
reason = "Server Connection Failed";
body_type = "connect#failed_connect";
}
build_error_response(s, status, reason, body_type, NULL);
return;
}
// return true if the response to the given request is likely cacheable
// This function is called by build_request() to determine if the conditional
// headers should be removed from server request.
bool
HttpTransact::is_request_likely_cacheable(State *s, HTTPHdr *request)
{
if ((s->method == HTTP_WKSIDX_GET || s->api_req_cacheable) && !s->api_server_response_no_store &&
!request->presence(MIME_PRESENCE_AUTHORIZATION) &&
(!request->presence(MIME_PRESENCE_RANGE) || s->txn_conf->cache_range_write)) {
return true;
}
return false;
}
void
HttpTransact::build_request(State *s, HTTPHdr *base_request, HTTPHdr *outgoing_request, HTTPVersion outgoing_version)
{
// this part is to restore the original URL in case, multiple cache
// lookups have happened - client request has been changed as the result
//
// notice that currently, based_request IS client_request
if (base_request == &s->hdr_info.client_request) {
if (s->redirect_info.redirect_in_process) {
// this is for auto redirect
URL *r_url = &s->redirect_info.redirect_url;
ink_assert(r_url->valid());
base_request->url_get()->copy(r_url);
} else {
// this is for multiple cache lookup
URL *o_url = &s->cache_info.original_url;
if (o_url->valid()) {
base_request->url_get()->copy(o_url);
}
}
}
HttpTransactHeaders::copy_header_fields(base_request, outgoing_request, s->txn_conf->fwd_proxy_auth_to_parent);
add_client_ip_to_outgoing_request(s, outgoing_request);
HttpTransactHeaders::remove_privacy_headers_from_request(s->http_config_param, s->txn_conf, outgoing_request);
HttpTransactHeaders::add_global_user_agent_header_to_request(s->txn_conf, outgoing_request);
handle_request_keep_alive_headers(s, outgoing_version, outgoing_request);
// handle_conditional_headers appears to be obsolete. Nothing happens
// unelss s->cache_info.action == HttpTransact::CACHE_DO_UPDATE. In that
// case an assert will go off. The functionality of this method
// (e.g., setting the if-modfied-since header occurs in issue_revalidate
// HttpTransactHeaders::handle_conditional_headers(&s->cache_info, outgoing_request);
if (s->next_hop_scheme < 0) {
s->next_hop_scheme = URL_WKSIDX_HTTP;
}
if (s->orig_scheme < 0) {
s->orig_scheme = URL_WKSIDX_HTTP;
}
if (s->txn_conf->insert_request_via_string) {
HttpTransactHeaders::insert_via_header_in_request(s, outgoing_request);
}
// We build 1.1 request header and then convert as necessary to
// the appropriate version in HttpTransact::build_request
outgoing_request->version_set(HTTPVersion(1, 1));
// Make sure our request version is defined
ink_assert(outgoing_version != HTTPVersion(0, 0));
// HttpTransactHeaders::convert_request(outgoing_version, outgoing_request); // commented out this idea
// Check whether a Host header field is missing from a 1.0 or 1.1 request.
if (outgoing_version != HTTPVersion(0, 9) && !outgoing_request->presence(MIME_PRESENCE_HOST)) {
URL *url = outgoing_request->url_get();
int host_len;
const char *host = url->host_get(&host_len);
// Add a ':port' to the HOST header if the request is not going
// to the default port.
int port = url->port_get();
if (port != url_canonicalize_port(URL_TYPE_HTTP, 0)) {
char *buf = (char *)alloca(host_len + 15);
memcpy(buf, host, host_len);
host_len += snprintf(buf + host_len, 15, ":%d", port);
outgoing_request->value_set(MIME_FIELD_HOST, MIME_LEN_HOST, buf, host_len);
} else {
outgoing_request->value_set(MIME_FIELD_HOST, MIME_LEN_HOST, host, host_len);
}
}
if (s->current.server == &s->server_info && (s->next_hop_scheme == URL_WKSIDX_HTTP || s->next_hop_scheme == URL_WKSIDX_HTTPS ||
s->next_hop_scheme == URL_WKSIDX_WS || s->next_hop_scheme == URL_WKSIDX_WSS)) {
DebugTxn("http_trans", "[build_request] removing host name from url");
HttpTransactHeaders::remove_host_name_from_url(outgoing_request);
}
// If we're going to a parent proxy, make sure we pass host and port
// in the URL even if we didn't get them (e.g. transparent proxy)
if (s->current.request_to == PARENT_PROXY) {
if (!outgoing_request->is_target_in_url() && s->parent_result.parent_is_proxy()) {
DebugTxn("http_trans", "[build_request] adding target to URL for parent proxy");
// No worry about HTTP/0.9 because we reject forward proxy requests that
// don't have a host anywhere.
outgoing_request->set_url_target_from_host_field();
} else if (s->current.request_to == PARENT_PROXY && !s->parent_result.parent_is_proxy() &&
outgoing_request->is_target_in_url()) {
// If the parent is an origin server remove the hostname from the url.
DebugTxn("http_trans", "[build_request] removing target from URL for a parent origin.");
HttpTransactHeaders::remove_host_name_from_url(outgoing_request);
}
}
// If the response is most likely not cacheable, eg, request with Authorization,
// do we really want to remove conditional headers to get large 200 response?
// Answer: NO. Since if the response is most likely not cacheable,
// we don't remove conditional headers so that for a non-200 response
// from the O.S., we will save bandwidth between proxy and O.S.
if (s->current.mode == GENERIC_PROXY) {
if (is_request_likely_cacheable(s, base_request)) {
if (s->txn_conf->cache_when_to_revalidate != 4) {
DebugTxn("http_trans", "[build_request] "
"request like cacheable and conditional headers removed");
HttpTransactHeaders::remove_conditional_headers(outgoing_request);
} else
DebugTxn("http_trans", "[build_request] "
"request like cacheable but keep conditional headers");
} else {
// In this case, we send a conditional request
// instead of the normal non-conditional request.
DebugTxn("http_trans", "[build_request] "
"request not like cacheable and conditional headers not removed");
}
}
if (s->http_config_param->send_100_continue_response) {
HttpTransactHeaders::remove_100_continue_headers(s, outgoing_request);
DebugTxn("http_trans", "[build_request] request expect 100-continue headers removed");
}
s->request_sent_time = ink_cluster_time();
s->current.now = s->request_sent_time;
// The assert is backwards in this case because request is being (re)sent.
ink_assert(s->request_sent_time >= s->response_received_time);
DebugTxn("http_trans", "[build_request] request_sent_time: %" PRId64, (int64_t)s->request_sent_time);
if (!s->cop_test_page)
DUMP_HEADER("http_hdrs", outgoing_request, s->state_machine_id, "Proxy's Request");
HTTP_INCREMENT_DYN_STAT(http_outgoing_requests_stat);
}
// build a (status_code) response based upon the given info
void
HttpTransact::build_response(State *s, HTTPHdr *base_response, HTTPHdr *outgoing_response, HTTPVersion outgoing_version)
{
build_response(s, base_response, outgoing_response, outgoing_version, HTTP_STATUS_NONE, NULL);
return;
}
void
HttpTransact::build_response(State *s, HTTPHdr *outgoing_response, HTTPVersion outgoing_version, HTTPStatus status_code,
const char *reason_phrase)
{
build_response(s, NULL, outgoing_response, outgoing_version, status_code, reason_phrase);
return;
}
void
HttpTransact::build_response(State *s, HTTPHdr *base_response, HTTPHdr *outgoing_response, HTTPVersion outgoing_version,
HTTPStatus status_code, const char *reason_phrase)
{
if (reason_phrase == NULL) {
reason_phrase = http_hdr_reason_lookup(status_code);
}
if (base_response == NULL) {
HttpTransactHeaders::build_base_response(outgoing_response, status_code, reason_phrase, strlen(reason_phrase), s->current.now);
} else {
if ((status_code == HTTP_STATUS_NONE) || (status_code == base_response->status_get())) {
HttpTransactHeaders::copy_header_fields(base_response, outgoing_response, s->txn_conf->fwd_proxy_auth_to_parent);
if (s->txn_conf->insert_age_in_response) {
HttpTransactHeaders::insert_time_and_age_headers_in_response(s->request_sent_time, s->response_received_time,
s->current.now, base_response, outgoing_response);
}
// Note: We need to handle the "Content-Length" header first here
// since handle_content_length_header()
// determines whether we accept origin server's content-length.
// We need to have made a decision regard the content-length
// before processing the keep_alive headers
//
handle_content_length_header(s, outgoing_response, base_response);
} else {
switch (status_code) {
case HTTP_STATUS_NOT_MODIFIED:
HttpTransactHeaders::build_base_response(outgoing_response, status_code, reason_phrase, strlen(reason_phrase),
s->current.now);
// According to RFC 2616, Section 10.3.5,
// a 304 response MUST contain Date header,
// Etag and/or Content-location header,
// and Expires, Cache-control, and Vary
// (if they might be changed).
// Since a proxy doesn't know if a header differs from
// a user agent's cached document or not, all are sent.
{
static const char *field_name[] = {MIME_FIELD_ETAG, MIME_FIELD_CONTENT_LOCATION, MIME_FIELD_EXPIRES,
MIME_FIELD_CACHE_CONTROL, MIME_FIELD_VARY};
static int field_len[] = {MIME_LEN_ETAG, MIME_LEN_CONTENT_LOCATION, MIME_LEN_EXPIRES, MIME_LEN_CACHE_CONTROL,
MIME_LEN_VARY};
static uint64_t field_presence[] = {MIME_PRESENCE_ETAG, MIME_PRESENCE_CONTENT_LOCATION, MIME_PRESENCE_EXPIRES,
MIME_PRESENCE_CACHE_CONTROL, MIME_PRESENCE_VARY};
MIMEField *field;
int len;
const char *value;
for (size_t i = 0; i < sizeof(field_len) / sizeof(field_len[0]); i++) {
if (base_response->presence(field_presence[i])) {
field = base_response->field_find(field_name[i], field_len[i]);
ink_assert(field != NULL);
value = field->value_get(&len);
outgoing_response->value_append(field_name[i], field_len[i], value, len, 0);
}
}
}
break;
case HTTP_STATUS_PRECONDITION_FAILED:
// fall through
case HTTP_STATUS_RANGE_NOT_SATISFIABLE:
HttpTransactHeaders::build_base_response(outgoing_response, status_code, reason_phrase, strlen(reason_phrase),
s->current.now);
break;
default:
// ink_assert(!"unexpected status code in build_response()");
break;
}
}
}
// the following is done whether base_response == NULL or not
// If the response is prohibited from containing a body,
// we know the content length is trustable for keep-alive
if (is_response_body_precluded(status_code, s->method)) {
s->hdr_info.trust_response_cl = true;
s->hdr_info.response_content_length = 0;
s->client_info.transfer_encoding = HttpTransact::NO_TRANSFER_ENCODING;
s->server_info.transfer_encoding = HttpTransact::NO_TRANSFER_ENCODING;
}
handle_response_keep_alive_headers(s, outgoing_version, outgoing_response);
if (s->next_hop_scheme < 0) {
s->next_hop_scheme = URL_WKSIDX_HTTP;
}
// Add HSTS header (Strict-Transport-Security) if max-age is set and the request was https
if (s->orig_scheme == URL_WKSIDX_HTTPS && s->txn_conf->proxy_response_hsts_max_age >= 0) {
DebugTxn("http_hdrs", "hsts max-age=%" PRId64, s->txn_conf->proxy_response_hsts_max_age);
HttpTransactHeaders::insert_hsts_header_in_response(s, outgoing_response);
}
if (s->txn_conf->insert_response_via_string) {
HttpTransactHeaders::insert_via_header_in_response(s, outgoing_response);
}
HttpTransactHeaders::convert_response(outgoing_version, outgoing_response);
// process reverse mappings on the location header
// TS-1364: do this regardless of response code
response_url_remap(outgoing_response);
if (s->http_config_param->enable_http_stats) {
HttpTransactHeaders::generate_and_set_squid_codes(outgoing_response, s->via_string, &s->squid_codes);
}
HttpTransactHeaders::add_server_header_to_response(s->txn_conf, outgoing_response);
// auth-response update
// if (!s->state_machine->authAdapter.disabled()) {
// s->state_machine->authAdapter.UpdateResponseHeaders(outgoing_response);
// }
if (!s->cop_test_page && is_debug_tag_set("http_hdrs")) {
if (base_response) {
DUMP_HEADER("http_hdrs", base_response, s->state_machine_id, "Base Header for Building Response");
}
DUMP_HEADER("http_hdrs", outgoing_response, s->state_machine_id, "Proxy's Response 2");
}
return;
}
//////////////////////////////////////////////////////////////////////////////
//
// void HttpTransact::build_error_response(
// State *s,
// HTTPStatus status_code,
// char *reason_phrase_or_null,
// char *error_body_type,
// char *format, ...)
//
// This method sets the requires state for an error reply, including
// the error text, status code, reason phrase, and reply headers. The
// caller calls the method with the HttpTransact::State <s>, the
// HTTP status code <status_code>, a user-specified reason phrase
// string (or NULL) <reason_phrase_or_null>, and a printf-like
// text format and arguments which are appended to the error text.
//
// The <error_body_type> is the error message type, as specified by
// the HttpBodyFactory customized error page system.
//
// If the descriptive text <format> is not NULL or "", it is also
// added to the error text body as descriptive text in the error body.
// If <reason_phrase_or_null> is NULL, the default HTTP reason phrase
// is used. This routine DOES NOT check for buffer overflows. The
// caller should keep the messages small to be sure the error text
// fits in the error buffer (ok, it's nasty, but at least I admit it!).
//
//////////////////////////////////////////////////////////////////////////////
void
HttpTransact::build_error_response(State *s, HTTPStatus status_code, const char *reason_phrase_or_null, const char *error_body_type,
const char *format, ...)
{
va_list ap;
const char *reason_phrase;
char *url_string;
char body_language[256], body_type[256];
if (NULL == error_body_type) {
error_body_type = "default";
}
////////////////////////////////////////////////////////////
// get the url --- remember this is dynamically allocated //
////////////////////////////////////////////////////////////
if (s->hdr_info.client_request.valid()) {
url_string = s->hdr_info.client_request.url_string_get(&s->arena);
} else {
url_string = NULL;
}
// Make sure that if this error occured before we initailzied the state variables that we do now.
initialize_state_variables_from_request(s, &s->hdr_info.client_request);
//////////////////////////////////////////////////////
// If there is a request body, we must disable //
// keep-alive to prevent the body being read as //
// the next header (unless we've already drained //
// which we do for NTLM auth) //
//////////////////////////////////////////////////////
if (status_code == HTTP_STATUS_REQUEST_TIMEOUT || s->hdr_info.client_request.get_content_length() != 0 ||
s->client_info.transfer_encoding == HttpTransact::CHUNKED_ENCODING) {
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
} else {
// We don't have a request body. Since we are
// generating the error, we know we can trust
// the content-length
s->hdr_info.trust_response_cl = true;
}
// If transparent and the forward server connection looks unhappy don't
// keep alive the ua connection.
if ((s->state_machine->ua_session && s->state_machine->ua_session->is_outbound_transparent()) &&
(status_code == HTTP_STATUS_INTERNAL_SERVER_ERROR || status_code == HTTP_STATUS_GATEWAY_TIMEOUT ||
status_code == HTTP_STATUS_BAD_GATEWAY || status_code == HTTP_STATUS_SERVICE_UNAVAILABLE)) {
s->client_info.keep_alive = HTTP_NO_KEEPALIVE;
}
switch (status_code) {
case HTTP_STATUS_BAD_REQUEST:
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_ERROR);
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_HEADER_SYNTAX);
break;
case HTTP_STATUS_BAD_GATEWAY:
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_CONNECTION);
break;
case HTTP_STATUS_GATEWAY_TIMEOUT:
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_TIMEOUT);
break;
case HTTP_STATUS_NOT_FOUND:
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_SERVER);
break;
case HTTP_STATUS_FORBIDDEN:
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_ERROR);
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_FORBIDDEN);
break;
case HTTP_STATUS_HTTPVER_NOT_SUPPORTED:
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_ERROR);
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_SERVER);
break;
case HTTP_STATUS_INTERNAL_SERVER_ERROR:
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_DNS_FAILURE);
break;
case HTTP_STATUS_MOVED_TEMPORARILY:
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_MOVED_TEMPORARILY);
break;
case HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED:
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_ERROR);
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_AUTHORIZATION);
break;
case HTTP_STATUS_UNAUTHORIZED:
SET_VIA_STRING(VIA_CLIENT_REQUEST, VIA_CLIENT_ERROR);
SET_VIA_STRING(VIA_ERROR_TYPE, VIA_ERROR_AUTHORIZATION);
break;
default:
break;
}
reason_phrase = (reason_phrase_or_null ? reason_phrase_or_null : (char *)(http_hdr_reason_lookup(status_code)));
if (unlikely(!reason_phrase)) {
reason_phrase = "Unknown HTTP Status";
// set the source to internal so that chunking is handled correctly
}
s->source = SOURCE_INTERNAL;
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, status_code, reason_phrase);
if (status_code == HTTP_STATUS_SERVICE_UNAVAILABLE) {
if (s->pCongestionEntry != NULL) {
int ret_tmp;
int retry_after = s->pCongestionEntry->client_retry_after();
s->congestion_control_crat = retry_after;
if (s->hdr_info.client_response.value_get(MIME_FIELD_RETRY_AFTER, MIME_LEN_RETRY_AFTER, &ret_tmp) == NULL) {
s->hdr_info.client_response.value_set_int(MIME_FIELD_RETRY_AFTER, MIME_LEN_RETRY_AFTER, retry_after);
}
}
}
if (status_code == HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED && s->method == HTTP_WKSIDX_CONNECT &&
s->hdr_info.client_response.presence(MIME_PRESENCE_PROXY_CONNECTION)) {
int has_ua_msie = 0;
int user_agent_value_len, slen;
const char *user_agent_value, *c, *e;
user_agent_value = s->hdr_info.client_request.value_get(MIME_FIELD_USER_AGENT, MIME_LEN_USER_AGENT, &user_agent_value_len);
if (user_agent_value && user_agent_value_len >= 4) {
c = user_agent_value;
e = c + user_agent_value_len - 4;
while (1) {
slen = (int)(e - c);
c = (const char *)memchr(c, 'M', slen);
if (c == NULL || (e - c) < 3) {
break;
}
if ((c[1] == 'S') && (c[2] == 'I') && (c[3] == 'E')) {
has_ua_msie = 1;
break;
}
c++;
}
}
if (has_ua_msie) {
s->hdr_info.client_response.value_set(MIME_FIELD_PROXY_CONNECTION, MIME_LEN_PROXY_CONNECTION, "close", 5);
}
}
// Add a bunch of headers to make sure that caches between
// the Traffic Server and the client do not cache the error
// page.
s->hdr_info.client_response.value_set(MIME_FIELD_CACHE_CONTROL, MIME_LEN_CACHE_CONTROL, "no-store", 8);
// Make sure there are no Expires and Last-Modified headers.
s->hdr_info.client_response.field_delete(MIME_FIELD_EXPIRES, MIME_LEN_EXPIRES);
s->hdr_info.client_response.field_delete(MIME_FIELD_LAST_MODIFIED, MIME_LEN_LAST_MODIFIED);
if ((status_code == HTTP_STATUS_TEMPORARY_REDIRECT || status_code == HTTP_STATUS_MOVED_TEMPORARILY ||
status_code == HTTP_STATUS_MOVED_PERMANENTLY) &&
s->remap_redirect) {
s->hdr_info.client_response.value_set(MIME_FIELD_LOCATION, MIME_LEN_LOCATION, s->remap_redirect, strlen(s->remap_redirect));
}
////////////////////////////////////////////////////////////////////
// create the error message using the "body factory", which will //
// build a customized error message if available, or generate the //
// old style internal defaults otherwise --- the body factory //
// supports language targeting using the Accept-Language header //
////////////////////////////////////////////////////////////////////
int64_t len;
char *new_msg;
va_start(ap, format);
new_msg = body_factory->fabricate_with_old_api(error_body_type, s, 8192, &len, body_language, sizeof(body_language), body_type,
sizeof(body_type), format, ap);
va_end(ap);
// After the body factory is called, a new "body" is allocated, and we must replace it. It is
// unfortunate that there's no way to avoid this fabrication even when there is no substitutions...
s->free_internal_msg_buffer();
s->internal_msg_buffer = new_msg;
s->internal_msg_buffer_size = len;
s->internal_msg_buffer_fast_allocator_size = -1;
s->hdr_info.client_response.value_set(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, body_type, strlen(body_type));
s->hdr_info.client_response.value_set(MIME_FIELD_CONTENT_LANGUAGE, MIME_LEN_CONTENT_LANGUAGE, body_language,
strlen(body_language));
////////////////////////////////////////
// log a description in the error log //
////////////////////////////////////////
if (s->current.state == CONNECTION_ERROR) {
char *reason_buffer;
int buf_len = sizeof(char) * (strlen(get_error_string(s->cause_of_death_errno)) + 50);
reason_buffer = (char *)alloca(buf_len);
snprintf(reason_buffer, buf_len, "Connect Error <%s/%d>", get_error_string(s->cause_of_death_errno), s->cause_of_death_errno);
reason_phrase = reason_buffer;
}
if (s->http_config_param->errors_log_error_pages && status_code >= HTTP_STATUS_BAD_REQUEST) {
char ip_string[INET6_ADDRSTRLEN];
Log::error("RESPONSE: sent %s status %d (%s) for '%s'", ats_ip_ntop(&s->client_info.src_addr.sa, ip_string, sizeof(ip_string)),
status_code, reason_phrase, (url_string ? url_string : "<none>"));
}
if (url_string) {
s->arena.str_free(url_string);
}
s->next_action = SM_ACTION_SEND_ERROR_CACHE_NOOP;
return;
}
void
HttpTransact::build_redirect_response(State *s)
{
DebugTxn("http_redirect", "[HttpTransact::build_redirect_response]");
URL *u;
const char *old_host;
int old_host_len;
const char *new_url = NULL;
int new_url_len;
char *to_free = NULL;
char body_language[256], body_type[256];
HTTPStatus status_code = HTTP_STATUS_MOVED_TEMPORARILY;
char *reason_phrase = (char *)(http_hdr_reason_lookup(status_code));
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, status_code, reason_phrase);
//////////////////////////////////////////////////////////
// figure out what new url should be. this little hack //
// inserts expanded hostname into old url in order to //
// get scheme information, then puts the old url back. //
//////////////////////////////////////////////////////////
u = s->hdr_info.client_request.url_get();
old_host = u->host_get(&old_host_len);
u->host_set(s->dns_info.lookup_name, strlen(s->dns_info.lookup_name));
new_url = to_free = u->string_get(&s->arena, &new_url_len);
if (new_url == NULL) {
new_url = "";
}
u->host_set(old_host, old_host_len);
//////////////////////////
// set redirect headers //
//////////////////////////
HTTPHdr *h = &s->hdr_info.client_response;
if (s->txn_conf->insert_response_via_string) {
const char pa[] = "Proxy-agent";
h->value_append(pa, sizeof(pa) - 1, s->http_config_param->proxy_response_via_string,
s->http_config_param->proxy_response_via_string_len);
}
h->value_set(MIME_FIELD_LOCATION, MIME_LEN_LOCATION, new_url, new_url_len);
//////////////////////////
// set descriptive text //
//////////////////////////
s->free_internal_msg_buffer();
s->internal_msg_buffer_fast_allocator_size = -1;
s->internal_msg_buffer = body_factory->fabricate_with_old_api_build_va(
"redirect#moved_temporarily", s, 8192, &s->internal_msg_buffer_size, body_language, sizeof(body_language), body_type,
sizeof(body_type), "%s <a href=\"%s\">%s</a>. %s.", "The document you requested is now", new_url, new_url,
"Please update your documents and bookmarks accordingly", NULL);
h->set_content_length(s->internal_msg_buffer_size);
h->value_set(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, "text/html", 9);
s->arena.str_free(to_free);
}
void
HttpTransact::build_upgrade_response(State *s)
{
DebugTxn("http_upgrade", "[HttpTransact::build_upgrade_response]");
// 101 Switching Protocols
HTTPStatus status_code = HTTP_STATUS_SWITCHING_PROTOCOL;
const char *reason_phrase = http_hdr_reason_lookup(status_code);
build_response(s, &s->hdr_info.client_response, s->client_info.http_version, status_code, reason_phrase);
//////////////////////////
// set upgrade headers //
//////////////////////////
HTTPHdr *h = &s->hdr_info.client_response;
h->value_set(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION, "Upgrade", strlen("Upgrade"));
h->value_set(MIME_FIELD_UPGRADE, MIME_LEN_UPGRADE, MIME_UPGRADE_H2C_TOKEN, strlen(MIME_UPGRADE_H2C_TOKEN));
}
const char *
HttpTransact::get_error_string(int erno)
{
if (erno >= 0) {
return (strerror(erno));
} else {
switch (-erno) {
case ENET_THROTTLING:
return ("throttling");
case ESOCK_DENIED:
return ("socks error - denied");
case ESOCK_TIMEOUT:
return ("socks error - timeout");
case ESOCK_NO_SOCK_SERVER_CONN:
return ("socks error - no server connection");
// this assumes that the following case occurs
// when HttpSM.cc::state_origin_server_read_response
// receives an HTTP_EVENT_EOS. (line 1729 in HttpSM.cc,
// version 1.145.2.13.2.57)
case UNKNOWN_INTERNAL_ERROR:
return ("internal error - server connection terminated");
default:
return ("");
}
}
}
ink_time_t
ink_cluster_time(void)
{
int highest_delta;
ink_time_t local_time;
local_time = Thread::get_hrtime() / HRTIME_SECOND;
highest_delta = (int)HttpConfig::m_master.cluster_time_delta;
// highest_delta =
// lmgmt->record_data->readInteger("proxy.process.http.cluster_delta",
// &found);
// if (! found) {
// ink_assert(!"Highest delta config value not found!");
// highest_delta = 0L;
// }
Debug("http_trans", "[ink_cluster_time] local: %" PRId64 ", highest_delta: %d, cluster: %" PRId64, (int64_t)local_time,
highest_delta, (int64_t)(local_time + (ink_time_t)highest_delta));
ink_assert(highest_delta >= 0);
return local_time + (ink_time_t)highest_delta;
}
//
// The stat functions
//
void
HttpTransact::histogram_response_document_size(State *s, int64_t doc_size)
{
if (doc_size >= 0 && doc_size <= 100) {
HTTP_INCREMENT_DYN_STAT(http_response_document_size_100_stat);
} else if (doc_size <= 1024) {
HTTP_INCREMENT_DYN_STAT(http_response_document_size_1K_stat);
} else if (doc_size <= 3072) {
HTTP_INCREMENT_DYN_STAT(http_response_document_size_3K_stat);
} else if (doc_size <= 5120) {
HTTP_INCREMENT_DYN_STAT(http_response_document_size_5K_stat);
} else if (doc_size <= 10240) {
HTTP_INCREMENT_DYN_STAT(http_response_document_size_10K_stat);
} else if (doc_size <= 1048576) {
HTTP_INCREMENT_DYN_STAT(http_response_document_size_1M_stat);
} else {
HTTP_INCREMENT_DYN_STAT(http_response_document_size_inf_stat);
}
return;
}
void
HttpTransact::histogram_request_document_size(State *s, int64_t doc_size)
{
if (doc_size >= 0 && doc_size <= 100) {
HTTP_INCREMENT_DYN_STAT(http_request_document_size_100_stat);
} else if (doc_size <= 1024) {
HTTP_INCREMENT_DYN_STAT(http_request_document_size_1K_stat);
} else if (doc_size <= 3072) {
HTTP_INCREMENT_DYN_STAT(http_request_document_size_3K_stat);
} else if (doc_size <= 5120) {
HTTP_INCREMENT_DYN_STAT(http_request_document_size_5K_stat);
} else if (doc_size <= 10240) {
HTTP_INCREMENT_DYN_STAT(http_request_document_size_10K_stat);
} else if (doc_size <= 1048576) {
HTTP_INCREMENT_DYN_STAT(http_request_document_size_1M_stat);
} else {
HTTP_INCREMENT_DYN_STAT(http_request_document_size_inf_stat);
}
return;
}
void
HttpTransact::user_agent_connection_speed(State *s, ink_hrtime transfer_time, int64_t nbytes)
{
float bytes_per_hrtime = (transfer_time == 0) ? (nbytes) : ((float)nbytes / (float)(int64_t)transfer_time);
int bytes_per_sec = (int)(bytes_per_hrtime * HRTIME_SECOND);
if (bytes_per_sec <= 100) {
HTTP_INCREMENT_DYN_STAT(http_user_agent_speed_bytes_per_sec_100_stat);
} else if (bytes_per_sec <= 1024) {
HTTP_INCREMENT_DYN_STAT(http_user_agent_speed_bytes_per_sec_1K_stat);
} else if (bytes_per_sec <= 10240) {
HTTP_INCREMENT_DYN_STAT(http_user_agent_speed_bytes_per_sec_10K_stat);
} else if (bytes_per_sec <= 102400) {
HTTP_INCREMENT_DYN_STAT(http_user_agent_speed_bytes_per_sec_100K_stat);
} else if (bytes_per_sec <= 1048576) {
HTTP_INCREMENT_DYN_STAT(http_user_agent_speed_bytes_per_sec_1M_stat);
} else if (bytes_per_sec <= 10485760) {
HTTP_INCREMENT_DYN_STAT(http_user_agent_speed_bytes_per_sec_10M_stat);
} else {
HTTP_INCREMENT_DYN_STAT(http_user_agent_speed_bytes_per_sec_100M_stat);
}
return;
}
/*
* added request_process_time stat for loadshedding foo
*/
void
HttpTransact::client_result_stat(State *s, ink_hrtime total_time, ink_hrtime request_process_time)
{
ClientTransactionResult_t client_transaction_result = CLIENT_TRANSACTION_RESULT_UNDEFINED;
///////////////////////////////////////////////////////
// don't count errors we generated as hits or misses //
///////////////////////////////////////////////////////
if ((s->source == SOURCE_INTERNAL) && (s->hdr_info.client_response.status_get() >= 400)) {
client_transaction_result = CLIENT_TRANSACTION_RESULT_ERROR_OTHER;
}
switch (s->squid_codes.log_code) {
case SQUID_LOG_ERR_CONNECT_FAIL:
HTTP_INCREMENT_DYN_STAT(http_cache_miss_cold_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_ERROR_CONNECT_FAIL;
break;
case SQUID_LOG_TCP_MEM_HIT:
HTTP_INCREMENT_DYN_STAT(http_cache_hit_mem_fresh_stat);
case SQUID_LOG_TCP_HIT:
// It's possible to have two stat's instead of one, if needed.
HTTP_INCREMENT_DYN_STAT(http_cache_hit_fresh_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_HIT_FRESH;
break;
case SQUID_LOG_TCP_REFRESH_HIT:
HTTP_INCREMENT_DYN_STAT(http_cache_hit_reval_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_HIT_REVALIDATED;
break;
case SQUID_LOG_TCP_IMS_HIT:
HTTP_INCREMENT_DYN_STAT(http_cache_hit_ims_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_HIT_FRESH;
break;
case SQUID_LOG_TCP_REF_FAIL_HIT:
HTTP_INCREMENT_DYN_STAT(http_cache_hit_stale_served_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_HIT_FRESH;
break;
case SQUID_LOG_TCP_MISS:
if ((GET_VIA_STRING(VIA_CACHE_RESULT) == VIA_IN_CACHE_NOT_ACCEPTABLE) || (GET_VIA_STRING(VIA_CACHE_RESULT) == VIA_CACHE_MISS)) {
HTTP_INCREMENT_DYN_STAT(http_cache_miss_cold_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_MISS_COLD;
} else {
// FIX: what case is this for? can it ever happen?
HTTP_INCREMENT_DYN_STAT(http_cache_miss_uncacheable_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_MISS_UNCACHABLE;
}
break;
case SQUID_LOG_TCP_REFRESH_MISS:
HTTP_INCREMENT_DYN_STAT(http_cache_miss_changed_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_MISS_CHANGED;
break;
case SQUID_LOG_TCP_CLIENT_REFRESH:
HTTP_INCREMENT_DYN_STAT(http_cache_miss_client_no_cache_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_MISS_CLIENT_NO_CACHE;
break;
case SQUID_LOG_TCP_IMS_MISS:
HTTP_INCREMENT_DYN_STAT(http_cache_miss_ims_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_MISS_COLD;
break;
case SQUID_LOG_TCP_SWAPFAIL:
HTTP_INCREMENT_DYN_STAT(http_cache_read_error_stat);
client_transaction_result = CLIENT_TRANSACTION_RESULT_HIT_FRESH;
break;
case SQUID_LOG_ERR_READ_TIMEOUT:
case SQUID_LOG_TCP_DENIED:
// No cache result due to error
client_transaction_result = CLIENT_TRANSACTION_RESULT_ERROR_OTHER;
break;
default:
// FIX: What is the conditional below doing?
// if (s->local_trans_stats[http_cache_lookups_stat].count == 1L)
// HTTP_INCREMENT_DYN_STAT(http_cache_miss_cold_stat);
// FIX: I suspect the following line should not be set here,
// because it overrides the error classification above.
// Commenting out.
// client_transaction_result = CLIENT_TRANSACTION_RESULT_MISS_COLD;
break;
}
//////////////////////////////////////////
// don't count aborts as hits or misses //
//////////////////////////////////////////
if (s->client_info.abort == ABORTED) {
client_transaction_result = CLIENT_TRANSACTION_RESULT_ERROR_ABORT;
} else if (s->client_info.abort == MAYBE_ABORTED) {
client_transaction_result = CLIENT_TRANSACTION_RESULT_ERROR_POSSIBLE_ABORT;
}
// Count the status codes, assuming the client didn't abort (i.e. there is an m_http)
if ((s->source != SOURCE_NONE) && (s->client_info.abort == DIDNOT_ABORT)) {
int status_code = s->hdr_info.client_response.status_get();
switch (status_code) {
case 100:
HTTP_INCREMENT_DYN_STAT(http_response_status_100_count_stat);
break;
case 101:
HTTP_INCREMENT_DYN_STAT(http_response_status_101_count_stat);
break;
case 200:
HTTP_INCREMENT_DYN_STAT(http_response_status_200_count_stat);
break;
case 201:
HTTP_INCREMENT_DYN_STAT(http_response_status_201_count_stat);
break;
case 202:
HTTP_INCREMENT_DYN_STAT(http_response_status_202_count_stat);
break;
case 203:
HTTP_INCREMENT_DYN_STAT(http_response_status_203_count_stat);
break;
case 204:
HTTP_INCREMENT_DYN_STAT(http_response_status_204_count_stat);
break;
case 205:
HTTP_INCREMENT_DYN_STAT(http_response_status_205_count_stat);
break;
case 206:
HTTP_INCREMENT_DYN_STAT(http_response_status_206_count_stat);
break;
case 300:
HTTP_INCREMENT_DYN_STAT(http_response_status_300_count_stat);
break;
case 301:
HTTP_INCREMENT_DYN_STAT(http_response_status_301_count_stat);
break;
case 302:
HTTP_INCREMENT_DYN_STAT(http_response_status_302_count_stat);
break;
case 303:
HTTP_INCREMENT_DYN_STAT(http_response_status_303_count_stat);
break;
case 304:
HTTP_INCREMENT_DYN_STAT(http_response_status_304_count_stat);
break;
case 305:
HTTP_INCREMENT_DYN_STAT(http_response_status_305_count_stat);
break;
case 307:
HTTP_INCREMENT_DYN_STAT(http_response_status_307_count_stat);
break;
case 400:
HTTP_INCREMENT_DYN_STAT(http_response_status_400_count_stat);
break;
case 401:
HTTP_INCREMENT_DYN_STAT(http_response_status_401_count_stat);
break;
case 402:
HTTP_INCREMENT_DYN_STAT(http_response_status_402_count_stat);
break;
case 403:
HTTP_INCREMENT_DYN_STAT(http_response_status_403_count_stat);
break;
case 404:
HTTP_INCREMENT_DYN_STAT(http_response_status_404_count_stat);
break;
case 405:
HTTP_INCREMENT_DYN_STAT(http_response_status_405_count_stat);
break;
case 406:
HTTP_INCREMENT_DYN_STAT(http_response_status_406_count_stat);
break;
case 407:
HTTP_INCREMENT_DYN_STAT(http_response_status_407_count_stat);
break;
case 408:
HTTP_INCREMENT_DYN_STAT(http_response_status_408_count_stat);
break;
case 409:
HTTP_INCREMENT_DYN_STAT(http_response_status_409_count_stat);
break;
case 410:
HTTP_INCREMENT_DYN_STAT(http_response_status_410_count_stat);
break;
case 411:
HTTP_INCREMENT_DYN_STAT(http_response_status_411_count_stat);
break;
case 412:
HTTP_INCREMENT_DYN_STAT(http_response_status_412_count_stat);
break;
case 413:
HTTP_INCREMENT_DYN_STAT(http_response_status_413_count_stat);
break;
case 414:
HTTP_INCREMENT_DYN_STAT(http_response_status_414_count_stat);
break;
case 415:
HTTP_INCREMENT_DYN_STAT(http_response_status_415_count_stat);
break;
case 416:
HTTP_INCREMENT_DYN_STAT(http_response_status_416_count_stat);
break;
case 500:
HTTP_INCREMENT_DYN_STAT(http_response_status_500_count_stat);
break;
case 501:
HTTP_INCREMENT_DYN_STAT(http_response_status_501_count_stat);
break;
case 502:
HTTP_INCREMENT_DYN_STAT(http_response_status_502_count_stat);
break;
case 503:
HTTP_INCREMENT_DYN_STAT(http_response_status_503_count_stat);
break;
case 504:
HTTP_INCREMENT_DYN_STAT(http_response_status_504_count_stat);
break;
case 505:
HTTP_INCREMENT_DYN_STAT(http_response_status_505_count_stat);
break;
default:
break;
}
switch (status_code / 100) {
case 1:
HTTP_INCREMENT_DYN_STAT(http_response_status_1xx_count_stat);
break;
case 2:
HTTP_INCREMENT_DYN_STAT(http_response_status_2xx_count_stat);
break;
case 3:
HTTP_INCREMENT_DYN_STAT(http_response_status_3xx_count_stat);
break;
case 4:
HTTP_INCREMENT_DYN_STAT(http_response_status_4xx_count_stat);
break;
case 5:
HTTP_INCREMENT_DYN_STAT(http_response_status_5xx_count_stat);
break;
default:
break;
}
}
// Increment the completed connection count
HTTP_INCREMENT_DYN_STAT(http_completed_requests_stat);
// Set the stat now that we know what happend
ink_hrtime total_msec = ink_hrtime_to_msec(total_time);
ink_hrtime process_msec = ink_hrtime_to_msec(request_process_time);
switch (client_transaction_result) {
case CLIENT_TRANSACTION_RESULT_HIT_FRESH:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_hit_fresh_stat, total_msec);
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_hit_fresh_process_stat, process_msec);
break;
case CLIENT_TRANSACTION_RESULT_HIT_REVALIDATED:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_hit_reval_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_MISS_COLD:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_miss_cold_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_MISS_CHANGED:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_miss_changed_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_MISS_CLIENT_NO_CACHE:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_miss_client_no_cache_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_MISS_UNCACHABLE:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_miss_uncacheable_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_ERROR_ABORT:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_errors_aborts_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_ERROR_POSSIBLE_ABORT:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_errors_possible_aborts_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_ERROR_CONNECT_FAIL:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_errors_connect_failed_stat, total_msec);
break;
case CLIENT_TRANSACTION_RESULT_ERROR_OTHER:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_errors_other_stat, total_msec);
break;
default:
HTTP_SUM_DYN_STAT(http_ua_msecs_counts_other_unclassified_stat, total_msec);
// This can happen if a plugin manually sets the status code after an error.
DebugTxn("http", "Unclassified statistic");
break;
}
}
void
HttpTransact::origin_server_connection_speed(State *s, ink_hrtime transfer_time, int64_t nbytes)
{
float bytes_per_hrtime = (transfer_time == 0) ? (nbytes) : ((float)nbytes / (float)(int64_t)transfer_time);
int bytes_per_sec = (int)(bytes_per_hrtime * HRTIME_SECOND);
if (bytes_per_sec <= 100) {
HTTP_INCREMENT_DYN_STAT(http_origin_server_speed_bytes_per_sec_100_stat);
} else if (bytes_per_sec <= 1024) {
HTTP_INCREMENT_DYN_STAT(http_origin_server_speed_bytes_per_sec_1K_stat);
} else if (bytes_per_sec <= 10240) {
HTTP_INCREMENT_DYN_STAT(http_origin_server_speed_bytes_per_sec_10K_stat);
} else if (bytes_per_sec <= 102400) {
HTTP_INCREMENT_DYN_STAT(http_origin_server_speed_bytes_per_sec_100K_stat);
} else if (bytes_per_sec <= 1048576) {
HTTP_INCREMENT_DYN_STAT(http_origin_server_speed_bytes_per_sec_1M_stat);
} else if (bytes_per_sec <= 10485760) {
HTTP_INCREMENT_DYN_STAT(http_origin_server_speed_bytes_per_sec_10M_stat);
} else {
HTTP_INCREMENT_DYN_STAT(http_origin_server_speed_bytes_per_sec_100M_stat);
}
return;
}
void
HttpTransact::update_size_and_time_stats(State *s, ink_hrtime total_time, ink_hrtime user_agent_write_time,
ink_hrtime origin_server_read_time, int user_agent_request_header_size,
int64_t user_agent_request_body_size, int user_agent_response_header_size,
int64_t user_agent_response_body_size, int origin_server_request_header_size,
int64_t origin_server_request_body_size, int origin_server_response_header_size,
int64_t origin_server_response_body_size, int pushed_response_header_size,
int64_t pushed_response_body_size, const TransactionMilestones &milestones)
{
int64_t user_agent_request_size = user_agent_request_header_size + user_agent_request_body_size;
int64_t user_agent_response_size = user_agent_response_header_size + user_agent_response_body_size;
int64_t user_agent_bytes = user_agent_request_size + user_agent_response_size;
int64_t origin_server_request_size = origin_server_request_header_size + origin_server_request_body_size;
int64_t origin_server_response_size = origin_server_response_header_size + origin_server_response_body_size;
int64_t origin_server_bytes = origin_server_request_size + origin_server_response_size;
// Background fill stats
switch (s->state_machine->background_fill) {
case BACKGROUND_FILL_COMPLETED: {
int64_t bg_size = origin_server_response_body_size - user_agent_response_body_size;
bg_size = max((int64_t)0, bg_size);
HTTP_SUM_DYN_STAT(http_background_fill_bytes_completed_stat, bg_size);
break;
}
case BACKGROUND_FILL_ABORTED: {
int64_t bg_size = origin_server_response_body_size - user_agent_response_body_size;
if (bg_size < 0) {
bg_size = 0;
}
HTTP_SUM_DYN_STAT(http_background_fill_bytes_aborted_stat, bg_size);
break;
}
case BACKGROUND_FILL_NONE:
break;
case BACKGROUND_FILL_STARTED:
default:
ink_assert(0);
}
// Bandwidth Savings
switch (s->squid_codes.log_code) {
case SQUID_LOG_TCP_HIT:
case SQUID_LOG_TCP_MEM_HIT:
// It's possible to have two stat's instead of one, if needed.
HTTP_INCREMENT_DYN_STAT(http_tcp_hit_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_hit_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_hit_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_TCP_MISS:
HTTP_INCREMENT_DYN_STAT(http_tcp_miss_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_miss_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_miss_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_TCP_EXPIRED_MISS:
HTTP_INCREMENT_DYN_STAT(http_tcp_expired_miss_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_expired_miss_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_expired_miss_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_TCP_REFRESH_HIT:
HTTP_INCREMENT_DYN_STAT(http_tcp_refresh_hit_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_refresh_hit_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_refresh_hit_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_TCP_REFRESH_MISS:
HTTP_INCREMENT_DYN_STAT(http_tcp_refresh_miss_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_refresh_miss_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_refresh_miss_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_TCP_CLIENT_REFRESH:
HTTP_INCREMENT_DYN_STAT(http_tcp_client_refresh_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_client_refresh_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_client_refresh_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_TCP_IMS_HIT:
HTTP_INCREMENT_DYN_STAT(http_tcp_ims_hit_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_ims_hit_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_ims_hit_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_TCP_IMS_MISS:
HTTP_INCREMENT_DYN_STAT(http_tcp_ims_miss_count_stat);
HTTP_SUM_DYN_STAT(http_tcp_ims_miss_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_tcp_ims_miss_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_ERR_CLIENT_ABORT:
HTTP_INCREMENT_DYN_STAT(http_err_client_abort_count_stat);
HTTP_SUM_DYN_STAT(http_err_client_abort_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_err_client_abort_origin_server_bytes_stat, origin_server_bytes);
break;
case SQUID_LOG_ERR_CONNECT_FAIL:
HTTP_INCREMENT_DYN_STAT(http_err_connect_fail_count_stat);
HTTP_SUM_DYN_STAT(http_err_connect_fail_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_err_connect_fail_origin_server_bytes_stat, origin_server_bytes);
break;
default:
HTTP_INCREMENT_DYN_STAT(http_misc_count_stat);
HTTP_SUM_DYN_STAT(http_misc_user_agent_bytes_stat, user_agent_bytes);
HTTP_SUM_DYN_STAT(http_misc_origin_server_bytes_stat, origin_server_bytes);
break;
}
// times
HTTP_SUM_DYN_STAT(http_total_transactions_time_stat, total_time);
// sizes
HTTP_SUM_DYN_STAT(http_user_agent_request_header_total_size_stat, user_agent_request_header_size);
HTTP_SUM_DYN_STAT(http_user_agent_response_header_total_size_stat, user_agent_response_header_size);
HTTP_SUM_DYN_STAT(http_user_agent_request_document_total_size_stat, user_agent_request_body_size);
HTTP_SUM_DYN_STAT(http_user_agent_response_document_total_size_stat, user_agent_response_body_size);
// proxy stats
if (s->current.request_to == HttpTransact::PARENT_PROXY) {
HTTP_SUM_DYN_STAT(http_parent_proxy_request_total_bytes_stat,
origin_server_request_header_size + origin_server_request_body_size);
HTTP_SUM_DYN_STAT(http_parent_proxy_response_total_bytes_stat,
origin_server_response_header_size + origin_server_response_body_size);
HTTP_SUM_DYN_STAT(http_parent_proxy_transaction_time_stat, total_time);
}
// request header zero means the document was cached.
// do not add to stats.
if (origin_server_request_header_size > 0) {
HTTP_SUM_DYN_STAT(http_origin_server_request_header_total_size_stat, origin_server_request_header_size);
HTTP_SUM_DYN_STAT(http_origin_server_response_header_total_size_stat, origin_server_response_header_size);
HTTP_SUM_DYN_STAT(http_origin_server_request_document_total_size_stat, origin_server_request_body_size);
HTTP_SUM_DYN_STAT(http_origin_server_response_document_total_size_stat, origin_server_response_body_size);
}
if (s->method == HTTP_WKSIDX_PUSH) {
HTTP_SUM_DYN_STAT(http_pushed_response_header_total_size_stat, pushed_response_header_size);
HTTP_SUM_DYN_STAT(http_pushed_document_total_size_stat, pushed_response_body_size);
}
histogram_request_document_size(s, user_agent_request_body_size);
histogram_response_document_size(s, user_agent_response_body_size);
if (user_agent_write_time >= 0) {
user_agent_connection_speed(s, user_agent_write_time, user_agent_response_size);
}
if (origin_server_request_header_size > 0 && origin_server_read_time > 0) {
origin_server_connection_speed(s, origin_server_read_time, origin_server_response_size);
}
// update milestones stats
if (http_ua_begin_time_stat) {
HTTP_SUM_DYN_STAT(http_ua_begin_time_stat, milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_BEGIN));
}
if (http_ua_first_read_time_stat) {
HTTP_SUM_DYN_STAT(http_ua_first_read_time_stat, milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_FIRST_READ));
}
if (http_ua_read_header_done_time_stat) {
HTTP_SUM_DYN_STAT(http_ua_read_header_done_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_READ_HEADER_DONE));
}
if (http_ua_begin_write_time_stat) {
HTTP_SUM_DYN_STAT(http_ua_begin_write_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_BEGIN_WRITE));
}
if (http_ua_close_time_stat) {
HTTP_SUM_DYN_STAT(http_ua_close_time_stat, milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_UA_CLOSE));
}
if (http_server_first_connect_time_stat) {
HTTP_SUM_DYN_STAT(http_server_first_connect_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_FIRST_CONNECT));
}
if (http_server_connect_time_stat) {
HTTP_SUM_DYN_STAT(http_server_connect_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_CONNECT));
}
if (http_server_connect_end_time_stat) {
HTTP_SUM_DYN_STAT(http_server_connect_end_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_CONNECT_END));
}
if (http_server_begin_write_time_stat) {
HTTP_SUM_DYN_STAT(http_server_begin_write_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_BEGIN_WRITE));
}
if (http_server_first_read_time_stat) {
HTTP_SUM_DYN_STAT(http_server_first_read_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_FIRST_READ));
}
if (http_server_read_header_done_time_stat) {
HTTP_SUM_DYN_STAT(http_server_read_header_done_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_READ_HEADER_DONE));
}
if (http_server_close_time_stat) {
HTTP_SUM_DYN_STAT(http_server_close_time_stat, milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SERVER_CLOSE));
}
if (http_cache_open_read_begin_time_stat) {
HTTP_SUM_DYN_STAT(http_cache_open_read_begin_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_CACHE_OPEN_READ_BEGIN));
}
if (http_cache_open_read_end_time_stat) {
HTTP_SUM_DYN_STAT(http_cache_open_read_end_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_CACHE_OPEN_READ_END));
}
if (http_cache_open_write_begin_time_stat) {
HTTP_SUM_DYN_STAT(http_cache_open_write_begin_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_CACHE_OPEN_WRITE_BEGIN));
}
if (http_cache_open_write_end_time_stat) {
HTTP_SUM_DYN_STAT(http_cache_open_write_end_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_CACHE_OPEN_WRITE_END));
}
if (http_dns_lookup_begin_time_stat) {
HTTP_SUM_DYN_STAT(http_dns_lookup_begin_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_DNS_LOOKUP_BEGIN));
}
if (http_dns_lookup_end_time_stat) {
HTTP_SUM_DYN_STAT(http_dns_lookup_end_time_stat,
milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_DNS_LOOKUP_END));
}
if (http_sm_start_time_stat) {
HTTP_SUM_DYN_STAT(http_sm_start_time_stat, milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SM_START));
}
if (http_sm_finish_time_stat) {
HTTP_SUM_DYN_STAT(http_sm_finish_time_stat, milestones.difference_msec(TS_MILESTONE_SM_START, TS_MILESTONE_SM_FINISH));
}
}
void
HttpTransact::delete_warning_value(HTTPHdr *to_warn, HTTPWarningCode warning_code)
{
int w_code = (int)warning_code;
MIMEField *field = to_warn->field_find(MIME_FIELD_WARNING, MIME_LEN_WARNING);
;
// Loop over the values to see if we need to do anything
if (field) {
HdrCsvIter iter;
int valid;
int val_code;
const char *value_str;
int value_len;
MIMEField *new_field = NULL;
val_code = iter.get_first_int(field, &valid);
while (valid) {
if (val_code == w_code) {
// Ok, found the value we're look to delete
// Look over and create a new field
// appending all elements that are not this
// value
val_code = iter.get_first_int(field, &valid);
while (valid) {
if (val_code != warning_code) {
value_str = iter.get_current(&value_len);
if (new_field) {
new_field->value_append(to_warn->m_heap, to_warn->m_mime, value_str, value_len, true);
} else {
new_field = to_warn->field_create();
to_warn->field_value_set(new_field, value_str, value_len);
}
}
val_code = iter.get_next_int(&valid);
}
to_warn->field_delete(MIME_FIELD_WARNING, MIME_LEN_WARNING);
if (new_field) {
new_field->name_set(to_warn->m_heap, to_warn->m_mime, MIME_FIELD_WARNING, MIME_LEN_WARNING);
to_warn->field_attach(new_field);
}
return;
}
val_code = iter.get_next_int(&valid);
}
}
}
void
HttpTransact::change_response_header_because_of_range_request(State *s, HTTPHdr *header)
{
MIMEField *field;
char *reason_phrase;
DebugTxn("http_trans", "Partial content requested, re-calculating content-length");
header->status_set(HTTP_STATUS_PARTIAL_CONTENT);
reason_phrase = (char *)(http_hdr_reason_lookup(HTTP_STATUS_PARTIAL_CONTENT));
header->reason_set(reason_phrase, strlen(reason_phrase));
// set the right Content-Type for multiple entry Range
if (s->num_range_fields > 1) {
field = header->field_find(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE);
if (field != NULL) {
header->field_delete(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE);
}
field = header->field_create(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE);
field->value_append(header->m_heap, header->m_mime, range_type, sizeof(range_type) - 1);
header->field_attach(field);
// TODO: There's a known bug here where the Content-Length is not correct for multi-part
// Range: requests.
header->set_content_length(s->range_output_cl);
} else {
if (s->cache_info.object_read && s->cache_info.object_read->valid()) {
// TODO: It's unclear under which conditions we need to update the Content-Range: header,
// many times it's already set correctly before calling this. For now, always try do it
// when we have the information for it available.
// TODO: Also, it's unclear as to why object_read->valid() is not always true here.
char numbers[RANGE_NUMBERS_LENGTH];
header->field_delete(MIME_FIELD_CONTENT_RANGE, MIME_LEN_CONTENT_RANGE);
field = header->field_create(MIME_FIELD_CONTENT_RANGE, MIME_LEN_CONTENT_RANGE);
snprintf(numbers, sizeof(numbers), "bytes %" PRId64 "-%" PRId64 "/%" PRId64, s->ranges[0]._start, s->ranges[0]._end,
s->cache_info.object_read->object_size_get());
field->value_set(header->m_heap, header->m_mime, numbers, strlen(numbers));
header->field_attach(field);
}
// Always update the Content-Length: header.
header->set_content_length(s->range_output_cl);
}
}
#if TS_HAS_TESTS
void forceLinkRegressionHttpTransact();
void
forceLinkRegressionHttpTransactCaller()
{
forceLinkRegressionHttpTransact();
}
#endif
|
#ifndef WIN32
//===--- TerminalConfigUnix.cpp - termios storage -------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// TerminalReader and TerminalDisplay need to reset the terminal configuration
// upon destruction, to leave the terminal as before. To avoid a possible
// misunderstanding of what "before" means, centralize their storage of the
// previous termios and have them share it.
//
// Axel Naumann <axel@cern.ch>, 2011-05-12
//===----------------------------------------------------------------------===//
#include "textinput/TerminalConfigUnix.h"
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <cstring>
using namespace textinput;
using std::memcpy;
using std::signal;
using std::raise;
namespace {
void
TerminalConfigUnix__handleSignal(int signum) {
// Clean up before we are killed.
TerminalConfigUnix::Get().HandleSignal(signum);
}
}
const int TerminalConfigUnix::fgSignals[kNumHandledSignals] = {
// SIGKILL: can't handle by definition
// Order: most to least common signal
SIGTERM,
SIGABRT,
SIGSEGV,
SIGILL,
SIGBUS
};
TerminalConfigUnix&
TerminalConfigUnix::Get() {
static TerminalConfigUnix s;
return s;
}
TerminalConfigUnix::TerminalConfigUnix():
fIsAttached(false), fFD(fileno(stdin)), fOldTIOS(), fConfTIOS() {
#ifdef TCSANOW
fOldTIOS = new termios;
fConfTIOS = new termios;
tcgetattr(fFD, fOldTIOS);
*fConfTIOS = *fOldTIOS;
#endif
for (int i = 0; i < kNumHandledSignals; ++i) {
fPrevHandler[i] = signal(fgSignals[i], TerminalConfigUnix__handleSignal);
}
}
TerminalConfigUnix::~TerminalConfigUnix() {
// Restore signals and detach.
for (int i = 0; i < kNumHandledSignals; ++i) {
if (fPrevHandler[i]) {
signal(fgSignals[i], fPrevHandler[i]);
} else {
// default:
signal(fgSignals[i], SIG_DFL);
}
}
Detach();
delete fOldTIOS;
delete fConfTIOS;
}
void
TerminalConfigUnix::HandleSignal(int signum) {
// Process has received a fatal signal, detach.
bool sSignalHandlerActive = false;
if (!sSignalHandlerActive) {
sSignalHandlerActive = true;
Detach();
// find previous signal handler index:
for (int i = 0; i < kNumHandledSignals; ++i) {
if (fgSignals[i] == signum) {
// Call previous signal handler if it exists.
if (fPrevHandler[i]) {
fPrevHandler[i](signum);
// should not end up here...
sSignalHandlerActive = false;
return;
} else break;
}
}
}
// No previous handler found, re-raise to get default handling:
signal(signum, SIG_DFL); // unregister ourselves
raise(signum); // terminate through default handler
// should not end up here...
signal(signum, TerminalConfigUnix__handleSignal);
sSignalHandlerActive = false;
}
void
TerminalConfigUnix::Attach() {
if (fIsAttached) return;
#ifdef TCSANOW
if (IsInteractive()) {
tcsetattr(fFD, TCSANOW, fConfTIOS);
}
#endif
fIsAttached = true;
}
void
TerminalConfigUnix::Detach() {
// Reset the terminal configuration.
if (!fIsAttached) return;
#ifdef TCSANOW
if (IsInteractive()) {
tcsetattr(fFD, TCSANOW, fOldTIOS);
}
#endif
fIsAttached = false;
}
bool TerminalConfigUnix::IsInteractive() const {
// Whether both stdin and stdout are attached to a tty.
return isatty(fileno(stdin)) && isatty(fileno(stdout))
&& (getpgrp() == tcgetpgrp(STDOUT_FILENO));
}
#endif // ndef WIN32
Don't set the signal handler again; the program is supposed to call the default signal handler, and by setting ours again it doesn't.
Fixes problem with ".qqqqqqqq".
git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@39940 27541ba8-7e3a-0410-8455-c3a389f83636
#ifndef WIN32
//===--- TerminalConfigUnix.cpp - termios storage -------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// TerminalReader and TerminalDisplay need to reset the terminal configuration
// upon destruction, to leave the terminal as before. To avoid a possible
// misunderstanding of what "before" means, centralize their storage of the
// previous termios and have them share it.
//
// Axel Naumann <axel@cern.ch>, 2011-05-12
//===----------------------------------------------------------------------===//
#include "textinput/TerminalConfigUnix.h"
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <cstring>
using namespace textinput;
using std::memcpy;
using std::signal;
using std::raise;
namespace {
void
TerminalConfigUnix__handleSignal(int signum) {
// Clean up before we are killed.
TerminalConfigUnix::Get().HandleSignal(signum);
}
}
const int TerminalConfigUnix::fgSignals[kNumHandledSignals] = {
// SIGKILL: can't handle by definition
// Order: most to least common signal
SIGTERM,
SIGABRT,
SIGSEGV,
SIGILL,
SIGBUS
};
TerminalConfigUnix&
TerminalConfigUnix::Get() {
static TerminalConfigUnix s;
return s;
}
TerminalConfigUnix::TerminalConfigUnix():
fIsAttached(false), fFD(fileno(stdin)), fOldTIOS(), fConfTIOS() {
#ifdef TCSANOW
fOldTIOS = new termios;
fConfTIOS = new termios;
tcgetattr(fFD, fOldTIOS);
*fConfTIOS = *fOldTIOS;
#endif
for (int i = 0; i < kNumHandledSignals; ++i) {
fPrevHandler[i] = signal(fgSignals[i], TerminalConfigUnix__handleSignal);
}
}
TerminalConfigUnix::~TerminalConfigUnix() {
// Restore signals and detach.
for (int i = 0; i < kNumHandledSignals; ++i) {
if (fPrevHandler[i]) {
signal(fgSignals[i], fPrevHandler[i]);
} else {
// default:
signal(fgSignals[i], SIG_DFL);
}
}
Detach();
delete fOldTIOS;
delete fConfTIOS;
}
void
TerminalConfigUnix::HandleSignal(int signum) {
// Process has received a fatal signal, detach.
bool sSignalHandlerActive = false;
if (!sSignalHandlerActive) {
sSignalHandlerActive = true;
Detach();
// find previous signal handler index:
for (int i = 0; i < kNumHandledSignals; ++i) {
if (fgSignals[i] == signum) {
// Call previous signal handler if it exists.
if (fPrevHandler[i]) {
fPrevHandler[i](signum);
// should not end up here...
sSignalHandlerActive = false;
return;
} else break;
}
}
}
// No previous handler found, re-raise to get default handling:
signal(signum, SIG_DFL); // unregister ourselves
raise(signum); // terminate through default handler
// No need to recover our state; there will be no "next time":
// the signal raised above will cause the program to quit.
//signal(signum, TerminalConfigUnix__handleSignal);
//sSignalHandlerActive = false;
}
void
TerminalConfigUnix::Attach() {
if (fIsAttached) return;
#ifdef TCSANOW
if (IsInteractive()) {
tcsetattr(fFD, TCSANOW, fConfTIOS);
}
#endif
fIsAttached = true;
}
void
TerminalConfigUnix::Detach() {
// Reset the terminal configuration.
if (!fIsAttached) return;
#ifdef TCSANOW
if (IsInteractive()) {
tcsetattr(fFD, TCSANOW, fOldTIOS);
}
#endif
fIsAttached = false;
}
bool TerminalConfigUnix::IsInteractive() const {
// Whether both stdin and stdout are attached to a tty.
return isatty(fileno(stdin)) && isatty(fileno(stdout))
&& (getpgrp() == tcgetpgrp(STDOUT_FILENO));
}
#endif // ndef WIN32
|
/** @file
Http2Stream.cc
@section license License
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 "HTTP2.h"
#include "Http2Stream.h"
#include "Http2ClientSession.h"
#include "../http/HttpSM.h"
#include <numeric>
#define REMEMBER(e, r) \
{ \
this->_history.push_back(MakeSourceLocation(), e, r); \
}
#define Http2StreamDebug(fmt, ...) \
SsnDebug(_proxy_ssn, "http2_stream", "[%" PRId64 "] [%u] " fmt, _proxy_ssn->connection_id(), this->get_id(), ##__VA_ARGS__);
ClassAllocator<Http2Stream> http2StreamAllocator("http2StreamAllocator");
Http2Stream::Http2Stream(Http2StreamId sid, ssize_t initial_rwnd) : _id(sid), _client_rwnd(initial_rwnd)
{
SET_HANDLER(&Http2Stream::main_event_handler);
}
void
Http2Stream::init(Http2StreamId sid, ssize_t initial_rwnd)
{
this->mark_milestone(Http2StreamMilestone::OPEN);
this->_id = sid;
this->_thread = this_ethread();
this->_client_rwnd = initial_rwnd;
this->_reader = this->_request_buffer.alloc_reader();
// FIXME: Are you sure? every "stream" needs request_header?
_req_header.create(HTTP_TYPE_REQUEST);
response_header.create(HTTP_TYPE_RESPONSE);
http_parser_init(&http_parser);
}
int
Http2Stream::main_event_handler(int event, void *edata)
{
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
REMEMBER(event, this->reentrancy_count);
if (!this->_switch_thread_if_not_on_right_thread(event, edata)) {
// Not on the right thread
return 0;
}
ink_release_assert(this->_thread == this_ethread());
Event *e = static_cast<Event *>(edata);
reentrancy_count++;
if (e == cross_thread_event) {
cross_thread_event = nullptr;
} else if (e == active_event) {
event = VC_EVENT_ACTIVE_TIMEOUT;
active_event = nullptr;
} else if (e == inactive_event) {
if (inactive_timeout_at && inactive_timeout_at < Thread::get_hrtime()) {
event = VC_EVENT_INACTIVITY_TIMEOUT;
clear_inactive_timer();
}
} else if (e == read_event) {
read_event = nullptr;
} else if (e == write_event) {
write_event = nullptr;
} else if (e == buffer_full_write_event) {
buffer_full_write_event = nullptr;
}
switch (event) {
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_INACTIVITY_TIMEOUT:
if (_sm && read_vio.ntodo() > 0) {
MUTEX_TRY_LOCK(lock, read_vio.mutex, this_ethread());
if (lock.is_locked()) {
read_vio.cont->handleEvent(event, &read_vio);
} else {
if (this->_read_vio_event) {
this->_read_vio_event->cancel();
}
this->_read_vio_event = this_ethread()->schedule_imm(read_vio.cont, event, &read_vio);
}
} else if (_sm && write_vio.ntodo() > 0) {
MUTEX_TRY_LOCK(lock, write_vio.mutex, this_ethread());
if (lock.is_locked()) {
write_vio.cont->handleEvent(event, &write_vio);
} else {
if (this->_write_vio_event) {
this->_write_vio_event->cancel();
}
this->_write_vio_event = this_ethread()->schedule_imm(write_vio.cont, event, &write_vio);
}
}
break;
case VC_EVENT_WRITE_READY:
case VC_EVENT_WRITE_COMPLETE:
inactive_timeout_at = Thread::get_hrtime() + inactive_timeout;
if (e->cookie == &write_vio) {
if (write_vio.mutex && write_vio.cont && this->_sm) {
MUTEX_TRY_LOCK(lock, write_vio.mutex, this_ethread());
if (lock.is_locked()) {
write_vio.cont->handleEvent(event, &write_vio);
} else {
if (this->_write_vio_event) {
this->_write_vio_event->cancel();
}
this->_write_vio_event = this_ethread()->schedule_imm(write_vio.cont, event, &write_vio);
}
}
} else {
update_write_request(write_vio.get_reader(), INT64_MAX, true);
}
break;
case VC_EVENT_READ_COMPLETE:
case VC_EVENT_READ_READY:
inactive_timeout_at = Thread::get_hrtime() + inactive_timeout;
if (e->cookie == &read_vio) {
if (read_vio.mutex && read_vio.cont && this->_sm) {
MUTEX_TRY_LOCK(lock, read_vio.mutex, this_ethread());
if (lock.is_locked()) {
read_vio.cont->handleEvent(event, &read_vio);
} else {
if (this->_read_vio_event) {
this->_read_vio_event->cancel();
}
this->_read_vio_event = this_ethread()->schedule_imm(read_vio.cont, event, &read_vio);
}
}
} else {
this->update_read_request(INT64_MAX, true);
}
break;
case VC_EVENT_EOS:
if (e->cookie == &read_vio) {
SCOPED_MUTEX_LOCK(lock, read_vio.mutex, this_ethread());
read_vio.cont->handleEvent(VC_EVENT_EOS, &read_vio);
} else if (e->cookie == &write_vio) {
SCOPED_MUTEX_LOCK(lock, write_vio.mutex, this_ethread());
write_vio.cont->handleEvent(VC_EVENT_EOS, &write_vio);
}
break;
}
reentrancy_count--;
// Clean stream up if the terminate flag is set and we are at the bottom of the handler stack
terminate_if_possible();
return 0;
}
Http2ErrorCode
Http2Stream::decode_header_blocks(HpackHandle &hpack_handle, uint32_t maximum_table_size)
{
return http2_decode_header_blocks(&_req_header, (const uint8_t *)header_blocks, header_blocks_length, nullptr, hpack_handle,
trailing_header, maximum_table_size);
}
void
Http2Stream::send_request(Http2ConnectionState &cstate)
{
ink_release_assert(this->_sm != nullptr);
this->_http_sm_id = this->_sm->sm_id;
// Convert header to HTTP/1.1 format
http2_convert_header_from_2_to_1_1(&_req_header);
// Write header to a buffer. Borrowing logic from HttpSM::write_header_into_buffer.
// Seems like a function like this ought to be in HTTPHdr directly
int bufindex;
int dumpoffset = 0;
int done, tmp;
do {
bufindex = 0;
tmp = dumpoffset;
IOBufferBlock *block = this->_request_buffer.get_current_block();
if (!block) {
this->_request_buffer.add_block();
block = this->_request_buffer.get_current_block();
}
done = _req_header.print(block->start(), block->write_avail(), &bufindex, &tmp);
dumpoffset += bufindex;
this->_request_buffer.fill(bufindex);
if (!done) {
this->_request_buffer.add_block();
}
} while (!done);
if (bufindex == 0) {
// No data to signal read event
return;
}
if (this->recv_end_stream) {
this->read_vio.nbytes = bufindex;
this->signal_read_event(VC_EVENT_READ_COMPLETE);
} else {
this->signal_read_event(VC_EVENT_READ_READY);
}
}
bool
Http2Stream::change_state(uint8_t type, uint8_t flags)
{
switch (_state) {
case Http2StreamState::HTTP2_STREAM_STATE_IDLE:
if (type == HTTP2_FRAME_TYPE_HEADERS) {
if (recv_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE;
} else if (send_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_LOCAL;
} else {
_state = Http2StreamState::HTTP2_STREAM_STATE_OPEN;
}
} else if (type == HTTP2_FRAME_TYPE_CONTINUATION) {
if (recv_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE;
} else if (send_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_LOCAL;
} else {
_state = Http2StreamState::HTTP2_STREAM_STATE_OPEN;
}
} else if (type == HTTP2_FRAME_TYPE_PUSH_PROMISE) {
_state = Http2StreamState::HTTP2_STREAM_STATE_RESERVED_LOCAL;
} else {
return false;
}
break;
case Http2StreamState::HTTP2_STREAM_STATE_OPEN:
if (type == HTTP2_FRAME_TYPE_RST_STREAM) {
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
} else if (type == HTTP2_FRAME_TYPE_DATA) {
if (recv_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE;
} else if (send_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_LOCAL;
} else {
// Do not change state
}
} else {
// A stream in the "open" state may be used by both peers to send frames of any type.
return true;
}
break;
case Http2StreamState::HTTP2_STREAM_STATE_RESERVED_LOCAL:
if (type == HTTP2_FRAME_TYPE_HEADERS) {
if (flags & HTTP2_FLAGS_HEADERS_END_HEADERS) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE;
}
} else if (type == HTTP2_FRAME_TYPE_CONTINUATION) {
if (flags & HTTP2_FLAGS_CONTINUATION_END_HEADERS) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE;
}
} else {
return false;
}
break;
case Http2StreamState::HTTP2_STREAM_STATE_RESERVED_REMOTE:
// Currently ATS supports only HTTP/2 server features
return false;
case Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_LOCAL:
if (type == HTTP2_FRAME_TYPE_RST_STREAM || recv_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
} else {
// Error, set state closed
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
return false;
}
break;
case Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE:
if (type == HTTP2_FRAME_TYPE_RST_STREAM || send_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
} else if (type == HTTP2_FRAME_TYPE_HEADERS) { // w/o END_STREAM flag
// No state change here. Expect a following DATA frame with END_STREAM flag.
return true;
} else if (type == HTTP2_FRAME_TYPE_CONTINUATION) { // w/o END_STREAM flag
// No state change here. Expect a following DATA frame with END_STREAM flag.
return true;
} else {
// Error, set state closed
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
return false;
}
break;
case Http2StreamState::HTTP2_STREAM_STATE_CLOSED:
// No state changing
return true;
default:
return false;
}
Http2StreamDebug("%s", Http2DebugNames::get_state_name(_state));
return true;
}
VIO *
Http2Stream::do_io_read(Continuation *c, int64_t nbytes, MIOBuffer *buf)
{
if (buf) {
read_vio.buffer.writer_for(buf);
} else {
read_vio.buffer.clear();
}
read_vio.mutex = c ? c->mutex : this->mutex;
read_vio.cont = c;
read_vio.nbytes = nbytes;
read_vio.ndone = 0;
read_vio.vc_server = this;
read_vio.op = VIO::READ;
// TODO: re-enable read_vio
return &read_vio;
}
VIO *
Http2Stream::do_io_write(Continuation *c, int64_t nbytes, IOBufferReader *abuffer, bool owner)
{
if (abuffer) {
write_vio.buffer.reader_for(abuffer);
} else {
write_vio.buffer.clear();
}
write_vio.mutex = c ? c->mutex : this->mutex;
write_vio.cont = c;
write_vio.nbytes = nbytes;
write_vio.ndone = 0;
write_vio.vc_server = this;
write_vio.op = VIO::WRITE;
response_reader = abuffer;
update_write_request(abuffer, nbytes, false);
return &write_vio;
}
// Initiated from SM
void
Http2Stream::do_io_close(int /* flags */)
{
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
super::release(nullptr);
if (!closed) {
REMEMBER(NO_EVENT, this->reentrancy_count);
Http2StreamDebug("do_io_close");
// When we get here, the SM has initiated the shutdown. Either it received a WRITE_COMPLETE, or it is shutting down. Any
// remaining IO operations back to client should be abandoned. The SM-side buffers backing these operations will be deleted
// by the time this is called from transaction_done.
closed = true;
if (_proxy_ssn && this->is_client_state_writeable()) {
// Make sure any trailing end of stream frames are sent
// Wee will be removed at send_data_frames or closing connection phase
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(this->_proxy_ssn);
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->connection_state.mutex, this_ethread());
h2_proxy_ssn->connection_state.send_data_frames(this);
}
clear_timers();
clear_io_events();
// Wait until transaction_done is called from HttpSM to signal that the TXN_CLOSE hook has been executed
}
}
/*
* HttpSM has called TXN_close hooks.
*/
void
Http2Stream::transaction_done()
{
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
if (cross_thread_event) {
cross_thread_event->cancel();
cross_thread_event = nullptr;
}
if (!closed) {
do_io_close(); // Make sure we've been closed. If we didn't close the _proxy_ssn session better still be open
}
ink_release_assert(closed || !static_cast<Http2ClientSession *>(_proxy_ssn)->connection_state.is_state_closed());
_sm = nullptr;
if (closed) {
// Safe to initiate SSN_CLOSE if this is the last stream
ink_assert(cross_thread_event == nullptr);
// Schedule the destroy to occur after we unwind here. IF we call directly, may delete with reference on the stack.
terminate_stream = true;
terminate_if_possible();
}
}
void
Http2Stream::terminate_if_possible()
{
if (terminate_stream && reentrancy_count == 0) {
REMEMBER(NO_EVENT, this->reentrancy_count);
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(this->_proxy_ssn);
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->connection_state.mutex, this_ethread());
h2_proxy_ssn->connection_state.delete_stream(this);
destroy();
}
}
// Initiated from the Http2 side
void
Http2Stream::initiating_close()
{
if (!closed) {
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
REMEMBER(NO_EVENT, this->reentrancy_count);
Http2StreamDebug("initiating_close");
// Set the state of the connection to closed
// TODO - these states should be combined
closed = true;
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
// leaving the reference to the SM, so we can detach from the SM when we actually destroy
// _sm = NULL;
// Leaving reference to client session as well, so we can signal once the
// TXN_CLOSE has been sent
// _proxy_ssn = NULL;
clear_timers();
clear_io_events();
// This should result in do_io_close or release being called. That will schedule the final
// kill yourself signal
// Send the SM the EOS signal if there are no active VIO's to signal
// We are sending signals rather than calling the handlers directly to avoid the case where
// the HttpTunnel handler causes the HttpSM to be deleted on the stack.
bool sent_write_complete = false;
if (_sm) {
// Push out any last IO events
if (write_vio.cont) {
SCOPED_MUTEX_LOCK(lock, write_vio.mutex, this_ethread());
// Are we done?
if (write_vio.nbytes == write_vio.ndone) {
Http2StreamDebug("handle write from destroy (event=%d)", VC_EVENT_WRITE_COMPLETE);
write_event = send_tracked_event(write_event, VC_EVENT_WRITE_COMPLETE, &write_vio);
} else {
write_event = send_tracked_event(write_event, VC_EVENT_EOS, &write_vio);
Http2StreamDebug("handle write from destroy (event=%d)", VC_EVENT_EOS);
}
sent_write_complete = true;
}
}
// Send EOS to let SM know that we aren't sticking around
if (_sm && read_vio.cont) {
// Only bother with the EOS if we haven't sent the write complete
if (!sent_write_complete) {
SCOPED_MUTEX_LOCK(lock, read_vio.mutex, this_ethread());
Http2StreamDebug("send EOS to read cont");
read_event = send_tracked_event(read_event, VC_EVENT_EOS, &read_vio);
}
} else if (_sm) {
SCOPED_MUTEX_LOCK(lock, _sm->mutex, this_ethread());
_sm->handleEvent(VC_EVENT_ERROR);
} else if (!sent_write_complete) {
// Transaction is already gone or not started. Kill yourself
do_io_close();
destroy();
}
}
}
/* Replace existing event only if the new event is different than the inprogress event */
Event *
Http2Stream::send_tracked_event(Event *event, int send_event, VIO *vio)
{
if (event != nullptr) {
if (event->callback_event != send_event) {
event->cancel();
event = nullptr;
}
}
if (event == nullptr) {
REMEMBER(send_event, this->reentrancy_count);
event = this_ethread()->schedule_imm(this, send_event, vio);
}
return event;
}
void
Http2Stream::update_read_request(int64_t read_len, bool call_update, bool check_eos)
{
if (closed || _proxy_ssn == nullptr || _sm == nullptr || read_vio.mutex == nullptr) {
return;
}
if (!this->_switch_thread_if_not_on_right_thread(VC_EVENT_READ_READY, nullptr)) {
// Not on the right thread
return;
}
ink_release_assert(this->_thread == this_ethread());
SCOPED_MUTEX_LOCK(lock, read_vio.mutex, this_ethread());
if (read_vio.nbytes == 0) {
return;
}
// Try to be smart and only signal if there was additional data
int send_event = VC_EVENT_READ_READY;
if (read_vio.ntodo() == 0 || (this->recv_end_stream && this->read_vio.nbytes != INT64_MAX)) {
send_event = VC_EVENT_READ_COMPLETE;
}
int64_t read_avail = this->read_vio.buffer.writer()->max_read_avail();
if (read_avail > 0 || send_event == VC_EVENT_READ_COMPLETE) {
if (call_update) { // Safe to call vio handler directly
inactive_timeout_at = Thread::get_hrtime() + inactive_timeout;
if (read_vio.cont && this->_sm) {
read_vio.cont->handleEvent(send_event, &read_vio);
}
} else { // Called from do_io_read. Still setting things up. Send event
// to handle this after the dust settles
read_event = send_tracked_event(read_event, send_event, &read_vio);
}
}
}
void
Http2Stream::restart_sending()
{
this->send_response_body(true);
}
void
Http2Stream::update_write_request(IOBufferReader *buf_reader, int64_t write_len, bool call_update)
{
if (!this->is_client_state_writeable() || closed || _proxy_ssn == nullptr || write_vio.mutex == nullptr ||
(buf_reader == nullptr && write_len == 0) || this->response_reader == nullptr) {
return;
}
if (!this->_switch_thread_if_not_on_right_thread(VC_EVENT_WRITE_READY, nullptr)) {
// Not on the right thread
return;
}
ink_release_assert(this->_thread == this_ethread());
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(this->_proxy_ssn);
SCOPED_MUTEX_LOCK(lock, write_vio.mutex, this_ethread());
int64_t bytes_avail = this->response_reader->read_avail();
if (write_vio.nbytes > 0 && write_vio.ntodo() > 0) {
int64_t num_to_write = write_vio.ntodo();
if (num_to_write > write_len) {
num_to_write = write_len;
}
if (bytes_avail > num_to_write) {
bytes_avail = num_to_write;
}
}
Http2StreamDebug("write_vio.nbytes=%" PRId64 ", write_vio.ndone=%" PRId64 ", write_vio.write_avail=%" PRId64
", reader.read_avail=%" PRId64,
write_vio.nbytes, write_vio.ndone, write_vio.get_writer()->write_avail(), bytes_avail);
if (bytes_avail <= 0) {
return;
}
// Process the new data
if (!this->response_header_done) {
// Still parsing the response_header
int bytes_used = 0;
int state = this->response_header.parse_resp(&http_parser, this->response_reader, &bytes_used, false);
// HTTPHdr::parse_resp() consumed the response_reader in above (consumed size is `bytes_used`)
write_vio.ndone += bytes_used;
switch (state) {
case PARSE_RESULT_DONE: {
this->response_header_done = true;
// Schedule session shutdown if response header has "Connection: close"
MIMEField *field = this->response_header.field_find(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION);
if (field) {
int len;
const char *value = field->value_get(&len);
if (memcmp(HTTP_VALUE_CLOSE, value, HTTP_LEN_CLOSE) == 0) {
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->connection_state.mutex, this_ethread());
if (h2_proxy_ssn->connection_state.get_shutdown_state() == HTTP2_SHUTDOWN_NONE) {
h2_proxy_ssn->connection_state.set_shutdown_state(HTTP2_SHUTDOWN_NOT_INITIATED, Http2ErrorCode::HTTP2_ERROR_NO_ERROR);
}
}
}
{
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->connection_state.mutex, this_ethread());
// Send the response header back
h2_proxy_ssn->connection_state.send_headers_frame(this);
}
// Roll back states of response header to read final response
if (this->response_header.expect_final_response()) {
this->response_header_done = false;
response_header.destroy();
response_header.create(HTTP_TYPE_RESPONSE);
http_parser_clear(&http_parser);
http_parser_init(&http_parser);
}
this->signal_write_event(call_update);
if (this->response_reader->is_read_avail_more_than(0)) {
this->_milestones.mark(Http2StreamMilestone::START_TX_DATA_FRAMES);
this->send_response_body(call_update);
}
break;
}
case PARSE_RESULT_CONT:
// Let it ride for next time
break;
default:
break;
}
} else {
this->_milestones.mark(Http2StreamMilestone::START_TX_DATA_FRAMES);
this->send_response_body(call_update);
}
return;
}
void
Http2Stream::signal_read_event(int event)
{
if (this->read_vio.cont == nullptr || this->read_vio.cont->mutex == nullptr || this->read_vio.op == VIO::NONE) {
return;
}
MUTEX_TRY_LOCK(lock, read_vio.cont->mutex, this_ethread());
if (lock.is_locked()) {
this->read_vio.cont->handleEvent(event, &this->read_vio);
} else {
if (this->_read_vio_event) {
this->_read_vio_event->cancel();
}
this->_read_vio_event = this_ethread()->schedule_imm(read_vio.cont, event, &read_vio);
}
}
void
Http2Stream::signal_write_event(bool call_update)
{
if (this->write_vio.cont == nullptr || this->write_vio.op == VIO::NONE) {
return;
}
if (this->write_vio.get_writer()->write_avail() == 0) {
return;
}
int send_event = this->write_vio.ntodo() == 0 ? VC_EVENT_WRITE_COMPLETE : VC_EVENT_WRITE_READY;
if (call_update) {
// Coming from reenable. Safe to call the handler directly
if (write_vio.cont && this->_sm) {
write_vio.cont->handleEvent(send_event, &write_vio);
}
} else {
// Called from do_io_write. Might still be setting up state. Send an event to let the dust settle
write_event = send_tracked_event(write_event, send_event, &write_vio);
}
}
bool
Http2Stream::push_promise(URL &url, const MIMEField *accept_encoding)
{
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(this->_proxy_ssn);
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->connection_state.mutex, this_ethread());
return h2_proxy_ssn->connection_state.send_push_promise_frame(this, url, accept_encoding);
}
void
Http2Stream::send_response_body(bool call_update)
{
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(this->_proxy_ssn);
inactive_timeout_at = Thread::get_hrtime() + inactive_timeout;
if (Http2::stream_priority_enabled) {
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->connection_state.mutex, this_ethread());
h2_proxy_ssn->connection_state.schedule_stream(this);
// signal_write_event() will be called from `Http2ConnectionState::send_data_frames_depends_on_priority()`
// when write_vio is consumed
} else {
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->connection_state.mutex, this_ethread());
h2_proxy_ssn->connection_state.send_data_frames(this);
this->signal_write_event(call_update);
// XXX The call to signal_write_event can destroy/free the Http2Stream.
// Don't modify the Http2Stream after calling this method.
}
}
void
Http2Stream::reenable(VIO *vio)
{
if (this->_proxy_ssn) {
if (vio->op == VIO::WRITE) {
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
update_write_request(vio->get_reader(), INT64_MAX, true);
} else if (vio->op == VIO::READ) {
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
update_read_request(INT64_MAX, true);
}
}
}
void
Http2Stream::destroy()
{
REMEMBER(NO_EVENT, this->reentrancy_count);
Http2StreamDebug("Destroy stream, sent %" PRIu64 " bytes", this->bytes_sent);
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
// Clean up after yourself if this was an EOS
ink_release_assert(this->closed);
ink_release_assert(reentrancy_count == 0);
uint64_t cid = 0;
// Safe to initiate SSN_CLOSE if this is the last stream
if (_proxy_ssn) {
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(_proxy_ssn);
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->connection_state.mutex, this_ethread());
// Make sure the stream is removed from the stream list and priority tree
// In many cases, this has been called earlier, so this call is a no-op
h2_proxy_ssn->connection_state.delete_stream(this);
// Update session's stream counts, so it accurately goes into keep-alive state
h2_proxy_ssn->connection_state.release_stream(this);
cid = _proxy_ssn->connection_id();
}
// Clean up the write VIO in case of inactivity timeout
this->do_io_write(nullptr, 0, nullptr);
this->_milestones.mark(Http2StreamMilestone::CLOSE);
ink_hrtime total_time = this->_milestones.elapsed(Http2StreamMilestone::OPEN, Http2StreamMilestone::CLOSE);
HTTP2_SUM_THREAD_DYN_STAT(HTTP2_STAT_TOTAL_TRANSACTIONS_TIME, this->_thread, total_time);
// Slow Log
if (Http2::stream_slow_log_threshold != 0 && ink_hrtime_from_msec(Http2::stream_slow_log_threshold) < total_time) {
Error("[%" PRIu64 "] [%" PRIu32 "] [%" PRId64 "] Slow H2 Stream: "
"open: %" PRIu64 " "
"dec_hdrs: %.3f "
"txn: %.3f "
"enc_hdrs: %.3f "
"tx_hdrs: %.3f "
"tx_data: %.3f "
"close: %.3f",
cid, static_cast<uint32_t>(this->_id), this->_http_sm_id,
ink_hrtime_to_msec(this->_milestones[Http2StreamMilestone::OPEN]),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::START_DECODE_HEADERS),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::START_TXN),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::START_ENCODE_HEADERS),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::START_TX_HEADERS_FRAMES),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::START_TX_DATA_FRAMES),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::CLOSE));
}
_req_header.destroy();
response_header.destroy();
// Drop references to all buffer data
this->_request_buffer.clear();
// Free the mutexes in the VIO
read_vio.mutex.clear();
write_vio.mutex.clear();
if (header_blocks) {
ats_free(header_blocks);
}
clear_timers();
clear_io_events();
http_parser_clear(&http_parser);
super::destroy();
THREAD_FREE(this, http2StreamAllocator, this_ethread());
}
IOBufferReader *
Http2Stream::response_get_data_reader() const
{
return this->response_reader;
}
void
Http2Stream::set_active_timeout(ink_hrtime timeout_in)
{
active_timeout = timeout_in;
clear_active_timer();
if (active_timeout > 0) {
active_event = this_ethread()->schedule_in(this, active_timeout);
}
}
void
Http2Stream::set_inactivity_timeout(ink_hrtime timeout_in)
{
inactive_timeout = timeout_in;
if (inactive_timeout > 0) {
inactive_timeout_at = Thread::get_hrtime() + inactive_timeout;
if (!inactive_event) {
inactive_event = this_ethread()->schedule_every(this, HRTIME_SECONDS(1));
}
} else {
clear_inactive_timer();
}
}
void
Http2Stream::cancel_inactivity_timeout()
{
set_inactivity_timeout(0);
}
void
Http2Stream::clear_inactive_timer()
{
inactive_timeout_at = 0;
if (inactive_event) {
inactive_event->cancel();
inactive_event = nullptr;
}
}
void
Http2Stream::clear_active_timer()
{
if (active_event) {
active_event->cancel();
active_event = nullptr;
}
}
void
Http2Stream::clear_timers()
{
clear_inactive_timer();
clear_active_timer();
}
void
Http2Stream::clear_io_events()
{
if (read_event) {
read_event->cancel();
}
read_event = nullptr;
if (write_event) {
write_event->cancel();
}
write_event = nullptr;
if (buffer_full_write_event) {
buffer_full_write_event->cancel();
buffer_full_write_event = nullptr;
}
if (this->_read_vio_event) {
this->_read_vio_event->cancel();
this->_read_vio_event = nullptr;
}
if (this->_write_vio_event) {
this->_write_vio_event->cancel();
this->_write_vio_event = nullptr;
}
}
void
Http2Stream::release(IOBufferReader *r)
{
super::release(r);
_sm = nullptr; // State machine is on its own way down.
this->do_io_close();
}
void
Http2Stream::increment_client_transactions_stat()
{
HTTP2_INCREMENT_THREAD_DYN_STAT(HTTP2_STAT_CURRENT_CLIENT_STREAM_COUNT, _thread);
HTTP2_INCREMENT_THREAD_DYN_STAT(HTTP2_STAT_TOTAL_CLIENT_STREAM_COUNT, _thread);
}
void
Http2Stream::decrement_client_transactions_stat()
{
HTTP2_DECREMENT_THREAD_DYN_STAT(HTTP2_STAT_CURRENT_CLIENT_STREAM_COUNT, _thread);
}
ssize_t
Http2Stream::client_rwnd() const
{
return this->_client_rwnd;
}
Http2ErrorCode
Http2Stream::increment_client_rwnd(size_t amount)
{
this->_client_rwnd += amount;
this->_recent_rwnd_increment[this->_recent_rwnd_increment_index] = amount;
++this->_recent_rwnd_increment_index;
this->_recent_rwnd_increment_index %= this->_recent_rwnd_increment.size();
double sum = std::accumulate(this->_recent_rwnd_increment.begin(), this->_recent_rwnd_increment.end(), 0.0);
double avg = sum / this->_recent_rwnd_increment.size();
if (avg < Http2::min_avg_window_update) {
return Http2ErrorCode::HTTP2_ERROR_ENHANCE_YOUR_CALM;
}
return Http2ErrorCode::HTTP2_ERROR_NO_ERROR;
}
Http2ErrorCode
Http2Stream::decrement_client_rwnd(size_t amount)
{
this->_client_rwnd -= amount;
if (this->_client_rwnd < 0) {
return Http2ErrorCode::HTTP2_ERROR_PROTOCOL_ERROR;
} else {
return Http2ErrorCode::HTTP2_ERROR_NO_ERROR;
}
}
ssize_t
Http2Stream::server_rwnd() const
{
return this->_server_rwnd;
}
Http2ErrorCode
Http2Stream::increment_server_rwnd(size_t amount)
{
this->_server_rwnd += amount;
return Http2ErrorCode::HTTP2_ERROR_NO_ERROR;
}
Http2ErrorCode
Http2Stream::decrement_server_rwnd(size_t amount)
{
this->_server_rwnd -= amount;
if (this->_server_rwnd < 0) {
return Http2ErrorCode::HTTP2_ERROR_PROTOCOL_ERROR;
} else {
return Http2ErrorCode::HTTP2_ERROR_NO_ERROR;
}
}
bool
Http2Stream::_switch_thread_if_not_on_right_thread(int event, void *edata)
{
if (this->_thread != this_ethread()) {
SCOPED_MUTEX_LOCK(stream_lock, this->mutex, this_ethread());
if (cross_thread_event == nullptr) {
// Send to the right thread
cross_thread_event = this->_thread->schedule_imm(this, event, edata);
}
return false;
}
return true;
}
int
Http2Stream::get_transaction_priority_weight() const
{
return priority_node ? priority_node->weight : 0;
}
int
Http2Stream::get_transaction_priority_dependence() const
{
if (!priority_node) {
return -1;
} else {
return priority_node->parent ? priority_node->parent->id : 0;
}
}
Fix heap-use-after-free on Http2Stream::destroy()
/** @file
Http2Stream.cc
@section license License
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 "HTTP2.h"
#include "Http2Stream.h"
#include "Http2ClientSession.h"
#include "../http/HttpSM.h"
#include <numeric>
#define REMEMBER(e, r) \
{ \
this->_history.push_back(MakeSourceLocation(), e, r); \
}
#define Http2StreamDebug(fmt, ...) \
SsnDebug(_proxy_ssn, "http2_stream", "[%" PRId64 "] [%u] " fmt, _proxy_ssn->connection_id(), this->get_id(), ##__VA_ARGS__);
ClassAllocator<Http2Stream> http2StreamAllocator("http2StreamAllocator");
Http2Stream::Http2Stream(Http2StreamId sid, ssize_t initial_rwnd) : _id(sid), _client_rwnd(initial_rwnd)
{
SET_HANDLER(&Http2Stream::main_event_handler);
}
void
Http2Stream::init(Http2StreamId sid, ssize_t initial_rwnd)
{
this->mark_milestone(Http2StreamMilestone::OPEN);
this->_id = sid;
this->_thread = this_ethread();
this->_client_rwnd = initial_rwnd;
this->_reader = this->_request_buffer.alloc_reader();
// FIXME: Are you sure? every "stream" needs request_header?
_req_header.create(HTTP_TYPE_REQUEST);
response_header.create(HTTP_TYPE_RESPONSE);
http_parser_init(&http_parser);
}
int
Http2Stream::main_event_handler(int event, void *edata)
{
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
REMEMBER(event, this->reentrancy_count);
if (!this->_switch_thread_if_not_on_right_thread(event, edata)) {
// Not on the right thread
return 0;
}
ink_release_assert(this->_thread == this_ethread());
Event *e = static_cast<Event *>(edata);
reentrancy_count++;
if (e == cross_thread_event) {
cross_thread_event = nullptr;
} else if (e == active_event) {
event = VC_EVENT_ACTIVE_TIMEOUT;
active_event = nullptr;
} else if (e == inactive_event) {
if (inactive_timeout_at && inactive_timeout_at < Thread::get_hrtime()) {
event = VC_EVENT_INACTIVITY_TIMEOUT;
clear_inactive_timer();
}
} else if (e == read_event) {
read_event = nullptr;
} else if (e == write_event) {
write_event = nullptr;
} else if (e == buffer_full_write_event) {
buffer_full_write_event = nullptr;
}
switch (event) {
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_INACTIVITY_TIMEOUT:
if (_sm && read_vio.ntodo() > 0) {
MUTEX_TRY_LOCK(lock, read_vio.mutex, this_ethread());
if (lock.is_locked()) {
read_vio.cont->handleEvent(event, &read_vio);
} else {
if (this->_read_vio_event) {
this->_read_vio_event->cancel();
}
this->_read_vio_event = this_ethread()->schedule_imm(read_vio.cont, event, &read_vio);
}
} else if (_sm && write_vio.ntodo() > 0) {
MUTEX_TRY_LOCK(lock, write_vio.mutex, this_ethread());
if (lock.is_locked()) {
write_vio.cont->handleEvent(event, &write_vio);
} else {
if (this->_write_vio_event) {
this->_write_vio_event->cancel();
}
this->_write_vio_event = this_ethread()->schedule_imm(write_vio.cont, event, &write_vio);
}
}
break;
case VC_EVENT_WRITE_READY:
case VC_EVENT_WRITE_COMPLETE:
inactive_timeout_at = Thread::get_hrtime() + inactive_timeout;
if (e->cookie == &write_vio) {
if (write_vio.mutex && write_vio.cont && this->_sm) {
MUTEX_TRY_LOCK(lock, write_vio.mutex, this_ethread());
if (lock.is_locked()) {
write_vio.cont->handleEvent(event, &write_vio);
} else {
if (this->_write_vio_event) {
this->_write_vio_event->cancel();
}
this->_write_vio_event = this_ethread()->schedule_imm(write_vio.cont, event, &write_vio);
}
}
} else {
update_write_request(write_vio.get_reader(), INT64_MAX, true);
}
break;
case VC_EVENT_READ_COMPLETE:
case VC_EVENT_READ_READY:
inactive_timeout_at = Thread::get_hrtime() + inactive_timeout;
if (e->cookie == &read_vio) {
if (read_vio.mutex && read_vio.cont && this->_sm) {
MUTEX_TRY_LOCK(lock, read_vio.mutex, this_ethread());
if (lock.is_locked()) {
read_vio.cont->handleEvent(event, &read_vio);
} else {
if (this->_read_vio_event) {
this->_read_vio_event->cancel();
}
this->_read_vio_event = this_ethread()->schedule_imm(read_vio.cont, event, &read_vio);
}
}
} else {
this->update_read_request(INT64_MAX, true);
}
break;
case VC_EVENT_EOS:
if (e->cookie == &read_vio) {
SCOPED_MUTEX_LOCK(lock, read_vio.mutex, this_ethread());
read_vio.cont->handleEvent(VC_EVENT_EOS, &read_vio);
} else if (e->cookie == &write_vio) {
SCOPED_MUTEX_LOCK(lock, write_vio.mutex, this_ethread());
write_vio.cont->handleEvent(VC_EVENT_EOS, &write_vio);
}
break;
}
reentrancy_count--;
// Clean stream up if the terminate flag is set and we are at the bottom of the handler stack
terminate_if_possible();
return 0;
}
Http2ErrorCode
Http2Stream::decode_header_blocks(HpackHandle &hpack_handle, uint32_t maximum_table_size)
{
return http2_decode_header_blocks(&_req_header, (const uint8_t *)header_blocks, header_blocks_length, nullptr, hpack_handle,
trailing_header, maximum_table_size);
}
void
Http2Stream::send_request(Http2ConnectionState &cstate)
{
ink_release_assert(this->_sm != nullptr);
this->_http_sm_id = this->_sm->sm_id;
// Convert header to HTTP/1.1 format
http2_convert_header_from_2_to_1_1(&_req_header);
// Write header to a buffer. Borrowing logic from HttpSM::write_header_into_buffer.
// Seems like a function like this ought to be in HTTPHdr directly
int bufindex;
int dumpoffset = 0;
int done, tmp;
do {
bufindex = 0;
tmp = dumpoffset;
IOBufferBlock *block = this->_request_buffer.get_current_block();
if (!block) {
this->_request_buffer.add_block();
block = this->_request_buffer.get_current_block();
}
done = _req_header.print(block->start(), block->write_avail(), &bufindex, &tmp);
dumpoffset += bufindex;
this->_request_buffer.fill(bufindex);
if (!done) {
this->_request_buffer.add_block();
}
} while (!done);
if (bufindex == 0) {
// No data to signal read event
return;
}
if (this->recv_end_stream) {
this->read_vio.nbytes = bufindex;
this->signal_read_event(VC_EVENT_READ_COMPLETE);
} else {
this->signal_read_event(VC_EVENT_READ_READY);
}
}
bool
Http2Stream::change_state(uint8_t type, uint8_t flags)
{
switch (_state) {
case Http2StreamState::HTTP2_STREAM_STATE_IDLE:
if (type == HTTP2_FRAME_TYPE_HEADERS) {
if (recv_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE;
} else if (send_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_LOCAL;
} else {
_state = Http2StreamState::HTTP2_STREAM_STATE_OPEN;
}
} else if (type == HTTP2_FRAME_TYPE_CONTINUATION) {
if (recv_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE;
} else if (send_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_LOCAL;
} else {
_state = Http2StreamState::HTTP2_STREAM_STATE_OPEN;
}
} else if (type == HTTP2_FRAME_TYPE_PUSH_PROMISE) {
_state = Http2StreamState::HTTP2_STREAM_STATE_RESERVED_LOCAL;
} else {
return false;
}
break;
case Http2StreamState::HTTP2_STREAM_STATE_OPEN:
if (type == HTTP2_FRAME_TYPE_RST_STREAM) {
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
} else if (type == HTTP2_FRAME_TYPE_DATA) {
if (recv_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE;
} else if (send_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_LOCAL;
} else {
// Do not change state
}
} else {
// A stream in the "open" state may be used by both peers to send frames of any type.
return true;
}
break;
case Http2StreamState::HTTP2_STREAM_STATE_RESERVED_LOCAL:
if (type == HTTP2_FRAME_TYPE_HEADERS) {
if (flags & HTTP2_FLAGS_HEADERS_END_HEADERS) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE;
}
} else if (type == HTTP2_FRAME_TYPE_CONTINUATION) {
if (flags & HTTP2_FLAGS_CONTINUATION_END_HEADERS) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE;
}
} else {
return false;
}
break;
case Http2StreamState::HTTP2_STREAM_STATE_RESERVED_REMOTE:
// Currently ATS supports only HTTP/2 server features
return false;
case Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_LOCAL:
if (type == HTTP2_FRAME_TYPE_RST_STREAM || recv_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
} else {
// Error, set state closed
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
return false;
}
break;
case Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE:
if (type == HTTP2_FRAME_TYPE_RST_STREAM || send_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
} else if (type == HTTP2_FRAME_TYPE_HEADERS) { // w/o END_STREAM flag
// No state change here. Expect a following DATA frame with END_STREAM flag.
return true;
} else if (type == HTTP2_FRAME_TYPE_CONTINUATION) { // w/o END_STREAM flag
// No state change here. Expect a following DATA frame with END_STREAM flag.
return true;
} else {
// Error, set state closed
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
return false;
}
break;
case Http2StreamState::HTTP2_STREAM_STATE_CLOSED:
// No state changing
return true;
default:
return false;
}
Http2StreamDebug("%s", Http2DebugNames::get_state_name(_state));
return true;
}
VIO *
Http2Stream::do_io_read(Continuation *c, int64_t nbytes, MIOBuffer *buf)
{
if (buf) {
read_vio.buffer.writer_for(buf);
} else {
read_vio.buffer.clear();
}
read_vio.mutex = c ? c->mutex : this->mutex;
read_vio.cont = c;
read_vio.nbytes = nbytes;
read_vio.ndone = 0;
read_vio.vc_server = this;
read_vio.op = VIO::READ;
// TODO: re-enable read_vio
return &read_vio;
}
VIO *
Http2Stream::do_io_write(Continuation *c, int64_t nbytes, IOBufferReader *abuffer, bool owner)
{
if (abuffer) {
write_vio.buffer.reader_for(abuffer);
} else {
write_vio.buffer.clear();
}
write_vio.mutex = c ? c->mutex : this->mutex;
write_vio.cont = c;
write_vio.nbytes = nbytes;
write_vio.ndone = 0;
write_vio.vc_server = this;
write_vio.op = VIO::WRITE;
response_reader = abuffer;
update_write_request(abuffer, nbytes, false);
return &write_vio;
}
// Initiated from SM
void
Http2Stream::do_io_close(int /* flags */)
{
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
super::release(nullptr);
if (!closed) {
REMEMBER(NO_EVENT, this->reentrancy_count);
Http2StreamDebug("do_io_close");
// When we get here, the SM has initiated the shutdown. Either it received a WRITE_COMPLETE, or it is shutting down. Any
// remaining IO operations back to client should be abandoned. The SM-side buffers backing these operations will be deleted
// by the time this is called from transaction_done.
closed = true;
if (_proxy_ssn && this->is_client_state_writeable()) {
// Make sure any trailing end of stream frames are sent
// Wee will be removed at send_data_frames or closing connection phase
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(this->_proxy_ssn);
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->connection_state.mutex, this_ethread());
h2_proxy_ssn->connection_state.send_data_frames(this);
}
clear_timers();
clear_io_events();
// Wait until transaction_done is called from HttpSM to signal that the TXN_CLOSE hook has been executed
}
}
/*
* HttpSM has called TXN_close hooks.
*/
void
Http2Stream::transaction_done()
{
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
if (cross_thread_event) {
cross_thread_event->cancel();
cross_thread_event = nullptr;
}
if (!closed) {
do_io_close(); // Make sure we've been closed. If we didn't close the _proxy_ssn session better still be open
}
ink_release_assert(closed || !static_cast<Http2ClientSession *>(_proxy_ssn)->connection_state.is_state_closed());
_sm = nullptr;
if (closed) {
// Safe to initiate SSN_CLOSE if this is the last stream
ink_assert(cross_thread_event == nullptr);
// Schedule the destroy to occur after we unwind here. IF we call directly, may delete with reference on the stack.
terminate_stream = true;
terminate_if_possible();
}
}
void
Http2Stream::terminate_if_possible()
{
if (terminate_stream && reentrancy_count == 0) {
REMEMBER(NO_EVENT, this->reentrancy_count);
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(this->_proxy_ssn);
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->connection_state.mutex, this_ethread());
h2_proxy_ssn->connection_state.delete_stream(this);
destroy();
}
}
// Initiated from the Http2 side
void
Http2Stream::initiating_close()
{
if (!closed) {
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
REMEMBER(NO_EVENT, this->reentrancy_count);
Http2StreamDebug("initiating_close");
// Set the state of the connection to closed
// TODO - these states should be combined
closed = true;
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
// leaving the reference to the SM, so we can detach from the SM when we actually destroy
// _sm = NULL;
// Leaving reference to client session as well, so we can signal once the
// TXN_CLOSE has been sent
// _proxy_ssn = NULL;
clear_timers();
clear_io_events();
// This should result in do_io_close or release being called. That will schedule the final
// kill yourself signal
// Send the SM the EOS signal if there are no active VIO's to signal
// We are sending signals rather than calling the handlers directly to avoid the case where
// the HttpTunnel handler causes the HttpSM to be deleted on the stack.
bool sent_write_complete = false;
if (_sm) {
// Push out any last IO events
if (write_vio.cont) {
SCOPED_MUTEX_LOCK(lock, write_vio.mutex, this_ethread());
// Are we done?
if (write_vio.nbytes == write_vio.ndone) {
Http2StreamDebug("handle write from destroy (event=%d)", VC_EVENT_WRITE_COMPLETE);
write_event = send_tracked_event(write_event, VC_EVENT_WRITE_COMPLETE, &write_vio);
} else {
write_event = send_tracked_event(write_event, VC_EVENT_EOS, &write_vio);
Http2StreamDebug("handle write from destroy (event=%d)", VC_EVENT_EOS);
}
sent_write_complete = true;
}
}
// Send EOS to let SM know that we aren't sticking around
if (_sm && read_vio.cont) {
// Only bother with the EOS if we haven't sent the write complete
if (!sent_write_complete) {
SCOPED_MUTEX_LOCK(lock, read_vio.mutex, this_ethread());
Http2StreamDebug("send EOS to read cont");
read_event = send_tracked_event(read_event, VC_EVENT_EOS, &read_vio);
}
} else if (_sm) {
SCOPED_MUTEX_LOCK(lock, _sm->mutex, this_ethread());
_sm->handleEvent(VC_EVENT_ERROR);
} else if (!sent_write_complete) {
// Transaction is already gone or not started. Kill yourself
do_io_close();
destroy();
}
}
}
/* Replace existing event only if the new event is different than the inprogress event */
Event *
Http2Stream::send_tracked_event(Event *event, int send_event, VIO *vio)
{
if (event != nullptr) {
if (event->callback_event != send_event) {
event->cancel();
event = nullptr;
}
}
if (event == nullptr) {
REMEMBER(send_event, this->reentrancy_count);
event = this_ethread()->schedule_imm(this, send_event, vio);
}
return event;
}
void
Http2Stream::update_read_request(int64_t read_len, bool call_update, bool check_eos)
{
if (closed || _proxy_ssn == nullptr || _sm == nullptr || read_vio.mutex == nullptr) {
return;
}
if (!this->_switch_thread_if_not_on_right_thread(VC_EVENT_READ_READY, nullptr)) {
// Not on the right thread
return;
}
ink_release_assert(this->_thread == this_ethread());
SCOPED_MUTEX_LOCK(lock, read_vio.mutex, this_ethread());
if (read_vio.nbytes == 0) {
return;
}
// Try to be smart and only signal if there was additional data
int send_event = VC_EVENT_READ_READY;
if (read_vio.ntodo() == 0 || (this->recv_end_stream && this->read_vio.nbytes != INT64_MAX)) {
send_event = VC_EVENT_READ_COMPLETE;
}
int64_t read_avail = this->read_vio.buffer.writer()->max_read_avail();
if (read_avail > 0 || send_event == VC_EVENT_READ_COMPLETE) {
if (call_update) { // Safe to call vio handler directly
inactive_timeout_at = Thread::get_hrtime() + inactive_timeout;
if (read_vio.cont && this->_sm) {
read_vio.cont->handleEvent(send_event, &read_vio);
}
} else { // Called from do_io_read. Still setting things up. Send event
// to handle this after the dust settles
read_event = send_tracked_event(read_event, send_event, &read_vio);
}
}
}
void
Http2Stream::restart_sending()
{
this->send_response_body(true);
}
void
Http2Stream::update_write_request(IOBufferReader *buf_reader, int64_t write_len, bool call_update)
{
if (!this->is_client_state_writeable() || closed || _proxy_ssn == nullptr || write_vio.mutex == nullptr ||
(buf_reader == nullptr && write_len == 0) || this->response_reader == nullptr) {
return;
}
if (!this->_switch_thread_if_not_on_right_thread(VC_EVENT_WRITE_READY, nullptr)) {
// Not on the right thread
return;
}
ink_release_assert(this->_thread == this_ethread());
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(this->_proxy_ssn);
SCOPED_MUTEX_LOCK(lock, write_vio.mutex, this_ethread());
int64_t bytes_avail = this->response_reader->read_avail();
if (write_vio.nbytes > 0 && write_vio.ntodo() > 0) {
int64_t num_to_write = write_vio.ntodo();
if (num_to_write > write_len) {
num_to_write = write_len;
}
if (bytes_avail > num_to_write) {
bytes_avail = num_to_write;
}
}
Http2StreamDebug("write_vio.nbytes=%" PRId64 ", write_vio.ndone=%" PRId64 ", write_vio.write_avail=%" PRId64
", reader.read_avail=%" PRId64,
write_vio.nbytes, write_vio.ndone, write_vio.get_writer()->write_avail(), bytes_avail);
if (bytes_avail <= 0) {
return;
}
// Process the new data
if (!this->response_header_done) {
// Still parsing the response_header
int bytes_used = 0;
int state = this->response_header.parse_resp(&http_parser, this->response_reader, &bytes_used, false);
// HTTPHdr::parse_resp() consumed the response_reader in above (consumed size is `bytes_used`)
write_vio.ndone += bytes_used;
switch (state) {
case PARSE_RESULT_DONE: {
this->response_header_done = true;
// Schedule session shutdown if response header has "Connection: close"
MIMEField *field = this->response_header.field_find(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION);
if (field) {
int len;
const char *value = field->value_get(&len);
if (memcmp(HTTP_VALUE_CLOSE, value, HTTP_LEN_CLOSE) == 0) {
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->connection_state.mutex, this_ethread());
if (h2_proxy_ssn->connection_state.get_shutdown_state() == HTTP2_SHUTDOWN_NONE) {
h2_proxy_ssn->connection_state.set_shutdown_state(HTTP2_SHUTDOWN_NOT_INITIATED, Http2ErrorCode::HTTP2_ERROR_NO_ERROR);
}
}
}
{
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->connection_state.mutex, this_ethread());
// Send the response header back
h2_proxy_ssn->connection_state.send_headers_frame(this);
}
// Roll back states of response header to read final response
if (this->response_header.expect_final_response()) {
this->response_header_done = false;
response_header.destroy();
response_header.create(HTTP_TYPE_RESPONSE);
http_parser_clear(&http_parser);
http_parser_init(&http_parser);
}
this->signal_write_event(call_update);
if (this->response_reader->is_read_avail_more_than(0)) {
this->_milestones.mark(Http2StreamMilestone::START_TX_DATA_FRAMES);
this->send_response_body(call_update);
}
break;
}
case PARSE_RESULT_CONT:
// Let it ride for next time
break;
default:
break;
}
} else {
this->_milestones.mark(Http2StreamMilestone::START_TX_DATA_FRAMES);
this->send_response_body(call_update);
}
return;
}
void
Http2Stream::signal_read_event(int event)
{
if (this->read_vio.cont == nullptr || this->read_vio.cont->mutex == nullptr || this->read_vio.op == VIO::NONE) {
return;
}
MUTEX_TRY_LOCK(lock, read_vio.cont->mutex, this_ethread());
if (lock.is_locked()) {
this->read_vio.cont->handleEvent(event, &this->read_vio);
} else {
if (this->_read_vio_event) {
this->_read_vio_event->cancel();
}
this->_read_vio_event = this_ethread()->schedule_imm(read_vio.cont, event, &read_vio);
}
}
void
Http2Stream::signal_write_event(bool call_update)
{
if (this->write_vio.cont == nullptr || this->write_vio.op == VIO::NONE) {
return;
}
if (this->write_vio.get_writer()->write_avail() == 0) {
return;
}
int send_event = this->write_vio.ntodo() == 0 ? VC_EVENT_WRITE_COMPLETE : VC_EVENT_WRITE_READY;
if (call_update) {
// Coming from reenable. Safe to call the handler directly
if (write_vio.cont && this->_sm) {
write_vio.cont->handleEvent(send_event, &write_vio);
}
} else {
// Called from do_io_write. Might still be setting up state. Send an event to let the dust settle
write_event = send_tracked_event(write_event, send_event, &write_vio);
}
}
bool
Http2Stream::push_promise(URL &url, const MIMEField *accept_encoding)
{
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(this->_proxy_ssn);
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->connection_state.mutex, this_ethread());
return h2_proxy_ssn->connection_state.send_push_promise_frame(this, url, accept_encoding);
}
void
Http2Stream::send_response_body(bool call_update)
{
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(this->_proxy_ssn);
inactive_timeout_at = Thread::get_hrtime() + inactive_timeout;
if (Http2::stream_priority_enabled) {
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->connection_state.mutex, this_ethread());
h2_proxy_ssn->connection_state.schedule_stream(this);
// signal_write_event() will be called from `Http2ConnectionState::send_data_frames_depends_on_priority()`
// when write_vio is consumed
} else {
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->connection_state.mutex, this_ethread());
h2_proxy_ssn->connection_state.send_data_frames(this);
this->signal_write_event(call_update);
// XXX The call to signal_write_event can destroy/free the Http2Stream.
// Don't modify the Http2Stream after calling this method.
}
}
void
Http2Stream::reenable(VIO *vio)
{
if (this->_proxy_ssn) {
if (vio->op == VIO::WRITE) {
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
update_write_request(vio->get_reader(), INT64_MAX, true);
} else if (vio->op == VIO::READ) {
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
update_read_request(INT64_MAX, true);
}
}
}
void
Http2Stream::destroy()
{
REMEMBER(NO_EVENT, this->reentrancy_count);
Http2StreamDebug("Destroy stream, sent %" PRIu64 " bytes", this->bytes_sent);
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
// Clean up after yourself if this was an EOS
ink_release_assert(this->closed);
ink_release_assert(reentrancy_count == 0);
uint64_t cid = 0;
// Safe to initiate SSN_CLOSE if this is the last stream
if (_proxy_ssn) {
cid = _proxy_ssn->connection_id();
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(_proxy_ssn);
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->connection_state.mutex, this_ethread());
// Make sure the stream is removed from the stream list and priority tree
// In many cases, this has been called earlier, so this call is a no-op
h2_proxy_ssn->connection_state.delete_stream(this);
// Update session's stream counts, so it accurately goes into keep-alive state
h2_proxy_ssn->connection_state.release_stream(this);
// Do not access `_proxy_ssn` in below. It might be freed by `release_stream`.
}
// Clean up the write VIO in case of inactivity timeout
this->do_io_write(nullptr, 0, nullptr);
this->_milestones.mark(Http2StreamMilestone::CLOSE);
ink_hrtime total_time = this->_milestones.elapsed(Http2StreamMilestone::OPEN, Http2StreamMilestone::CLOSE);
HTTP2_SUM_THREAD_DYN_STAT(HTTP2_STAT_TOTAL_TRANSACTIONS_TIME, this->_thread, total_time);
// Slow Log
if (Http2::stream_slow_log_threshold != 0 && ink_hrtime_from_msec(Http2::stream_slow_log_threshold) < total_time) {
Error("[%" PRIu64 "] [%" PRIu32 "] [%" PRId64 "] Slow H2 Stream: "
"open: %" PRIu64 " "
"dec_hdrs: %.3f "
"txn: %.3f "
"enc_hdrs: %.3f "
"tx_hdrs: %.3f "
"tx_data: %.3f "
"close: %.3f",
cid, static_cast<uint32_t>(this->_id), this->_http_sm_id,
ink_hrtime_to_msec(this->_milestones[Http2StreamMilestone::OPEN]),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::START_DECODE_HEADERS),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::START_TXN),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::START_ENCODE_HEADERS),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::START_TX_HEADERS_FRAMES),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::START_TX_DATA_FRAMES),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::CLOSE));
}
_req_header.destroy();
response_header.destroy();
// Drop references to all buffer data
this->_request_buffer.clear();
// Free the mutexes in the VIO
read_vio.mutex.clear();
write_vio.mutex.clear();
if (header_blocks) {
ats_free(header_blocks);
}
clear_timers();
clear_io_events();
http_parser_clear(&http_parser);
super::destroy();
THREAD_FREE(this, http2StreamAllocator, this_ethread());
}
IOBufferReader *
Http2Stream::response_get_data_reader() const
{
return this->response_reader;
}
void
Http2Stream::set_active_timeout(ink_hrtime timeout_in)
{
active_timeout = timeout_in;
clear_active_timer();
if (active_timeout > 0) {
active_event = this_ethread()->schedule_in(this, active_timeout);
}
}
void
Http2Stream::set_inactivity_timeout(ink_hrtime timeout_in)
{
inactive_timeout = timeout_in;
if (inactive_timeout > 0) {
inactive_timeout_at = Thread::get_hrtime() + inactive_timeout;
if (!inactive_event) {
inactive_event = this_ethread()->schedule_every(this, HRTIME_SECONDS(1));
}
} else {
clear_inactive_timer();
}
}
void
Http2Stream::cancel_inactivity_timeout()
{
set_inactivity_timeout(0);
}
void
Http2Stream::clear_inactive_timer()
{
inactive_timeout_at = 0;
if (inactive_event) {
inactive_event->cancel();
inactive_event = nullptr;
}
}
void
Http2Stream::clear_active_timer()
{
if (active_event) {
active_event->cancel();
active_event = nullptr;
}
}
void
Http2Stream::clear_timers()
{
clear_inactive_timer();
clear_active_timer();
}
void
Http2Stream::clear_io_events()
{
if (read_event) {
read_event->cancel();
}
read_event = nullptr;
if (write_event) {
write_event->cancel();
}
write_event = nullptr;
if (buffer_full_write_event) {
buffer_full_write_event->cancel();
buffer_full_write_event = nullptr;
}
if (this->_read_vio_event) {
this->_read_vio_event->cancel();
this->_read_vio_event = nullptr;
}
if (this->_write_vio_event) {
this->_write_vio_event->cancel();
this->_write_vio_event = nullptr;
}
}
void
Http2Stream::release(IOBufferReader *r)
{
super::release(r);
_sm = nullptr; // State machine is on its own way down.
this->do_io_close();
}
void
Http2Stream::increment_client_transactions_stat()
{
HTTP2_INCREMENT_THREAD_DYN_STAT(HTTP2_STAT_CURRENT_CLIENT_STREAM_COUNT, _thread);
HTTP2_INCREMENT_THREAD_DYN_STAT(HTTP2_STAT_TOTAL_CLIENT_STREAM_COUNT, _thread);
}
void
Http2Stream::decrement_client_transactions_stat()
{
HTTP2_DECREMENT_THREAD_DYN_STAT(HTTP2_STAT_CURRENT_CLIENT_STREAM_COUNT, _thread);
}
ssize_t
Http2Stream::client_rwnd() const
{
return this->_client_rwnd;
}
Http2ErrorCode
Http2Stream::increment_client_rwnd(size_t amount)
{
this->_client_rwnd += amount;
this->_recent_rwnd_increment[this->_recent_rwnd_increment_index] = amount;
++this->_recent_rwnd_increment_index;
this->_recent_rwnd_increment_index %= this->_recent_rwnd_increment.size();
double sum = std::accumulate(this->_recent_rwnd_increment.begin(), this->_recent_rwnd_increment.end(), 0.0);
double avg = sum / this->_recent_rwnd_increment.size();
if (avg < Http2::min_avg_window_update) {
return Http2ErrorCode::HTTP2_ERROR_ENHANCE_YOUR_CALM;
}
return Http2ErrorCode::HTTP2_ERROR_NO_ERROR;
}
Http2ErrorCode
Http2Stream::decrement_client_rwnd(size_t amount)
{
this->_client_rwnd -= amount;
if (this->_client_rwnd < 0) {
return Http2ErrorCode::HTTP2_ERROR_PROTOCOL_ERROR;
} else {
return Http2ErrorCode::HTTP2_ERROR_NO_ERROR;
}
}
ssize_t
Http2Stream::server_rwnd() const
{
return this->_server_rwnd;
}
Http2ErrorCode
Http2Stream::increment_server_rwnd(size_t amount)
{
this->_server_rwnd += amount;
return Http2ErrorCode::HTTP2_ERROR_NO_ERROR;
}
Http2ErrorCode
Http2Stream::decrement_server_rwnd(size_t amount)
{
this->_server_rwnd -= amount;
if (this->_server_rwnd < 0) {
return Http2ErrorCode::HTTP2_ERROR_PROTOCOL_ERROR;
} else {
return Http2ErrorCode::HTTP2_ERROR_NO_ERROR;
}
}
bool
Http2Stream::_switch_thread_if_not_on_right_thread(int event, void *edata)
{
if (this->_thread != this_ethread()) {
SCOPED_MUTEX_LOCK(stream_lock, this->mutex, this_ethread());
if (cross_thread_event == nullptr) {
// Send to the right thread
cross_thread_event = this->_thread->schedule_imm(this, event, edata);
}
return false;
}
return true;
}
int
Http2Stream::get_transaction_priority_weight() const
{
return priority_node ? priority_node->weight : 0;
}
int
Http2Stream::get_transaction_priority_dependence() const
{
if (!priority_node) {
return -1;
} else {
return priority_node->parent ? priority_node->parent->id : 0;
}
}
|
/** @file
Http2Stream.cc
@section license License
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 "Http2Stream.h"
#include "HTTP2.h"
#include "Http2ClientSession.h"
#include "../http/HttpSM.h"
#include <numeric>
#define REMEMBER(e, r) \
{ \
this->_history.push_back(MakeSourceLocation(), e, r); \
}
#define Http2StreamDebug(fmt, ...) \
SsnDebug(_proxy_ssn, "http2_stream", "[%" PRId64 "] [%u] " fmt, _proxy_ssn->connection_id(), this->get_id(), ##__VA_ARGS__);
ClassAllocator<Http2Stream, true> http2StreamAllocator("http2StreamAllocator");
Http2Stream::Http2Stream(ProxySession *session, Http2StreamId sid, ssize_t initial_rwnd)
: super(session), _id(sid), _client_rwnd(initial_rwnd)
{
SET_HANDLER(&Http2Stream::main_event_handler);
this->mark_milestone(Http2StreamMilestone::OPEN);
this->_sm = nullptr;
this->_id = sid;
this->_thread = this_ethread();
this->_client_rwnd = initial_rwnd;
this->_server_rwnd = Http2::initial_window_size;
this->_reader = this->_request_buffer.alloc_reader();
_req_header.create(HTTP_TYPE_REQUEST);
response_header.create(HTTP_TYPE_RESPONSE);
// TODO: init _req_header instead of response_header if this Http2Stream is outgoing
http2_init_pseudo_headers(response_header);
http_parser_init(&http_parser);
}
Http2Stream::~Http2Stream()
{
REMEMBER(NO_EVENT, this->reentrancy_count);
Http2StreamDebug("Destroy stream, sent %" PRIu64 " bytes", this->bytes_sent);
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
// Clean up after yourself if this was an EOS
ink_release_assert(this->closed);
ink_release_assert(reentrancy_count == 0);
uint64_t cid = 0;
// Safe to initiate SSN_CLOSE if this is the last stream
if (_proxy_ssn) {
cid = _proxy_ssn->connection_id();
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(_proxy_ssn);
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->mutex, this_ethread());
// Make sure the stream is removed from the stream list and priority tree
// In many cases, this has been called earlier, so this call is a no-op
h2_proxy_ssn->connection_state.delete_stream(this);
h2_proxy_ssn->connection_state.decrement_stream_count();
// Update session's stream counts, so it accurately goes into keep-alive state
h2_proxy_ssn->connection_state.release_stream();
// Do not access `_proxy_ssn` in below. It might be freed by `release_stream`.
}
// Clean up the write VIO in case of inactivity timeout
this->do_io_write(nullptr, 0, nullptr);
this->_milestones.mark(Http2StreamMilestone::CLOSE);
ink_hrtime total_time = this->_milestones.elapsed(Http2StreamMilestone::OPEN, Http2StreamMilestone::CLOSE);
HTTP2_SUM_THREAD_DYN_STAT(HTTP2_STAT_TOTAL_TRANSACTIONS_TIME, this->_thread, total_time);
// Slow Log
if (Http2::stream_slow_log_threshold != 0 && ink_hrtime_from_msec(Http2::stream_slow_log_threshold) < total_time) {
Error("[%" PRIu64 "] [%" PRIu32 "] [%" PRId64 "] Slow H2 Stream: "
"open: %" PRIu64 " "
"dec_hdrs: %.3f "
"txn: %.3f "
"enc_hdrs: %.3f "
"tx_hdrs: %.3f "
"tx_data: %.3f "
"close: %.3f",
cid, static_cast<uint32_t>(this->_id), this->_http_sm_id,
ink_hrtime_to_msec(this->_milestones[Http2StreamMilestone::OPEN]),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::START_DECODE_HEADERS),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::START_TXN),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::START_ENCODE_HEADERS),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::START_TX_HEADERS_FRAMES),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::START_TX_DATA_FRAMES),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::CLOSE));
}
_req_header.destroy();
response_header.destroy();
// Drop references to all buffer data
this->_request_buffer.clear();
// Free the mutexes in the VIO
read_vio.mutex.clear();
write_vio.mutex.clear();
if (header_blocks) {
ats_free(header_blocks);
}
_clear_timers();
clear_io_events();
http_parser_clear(&http_parser);
}
int
Http2Stream::main_event_handler(int event, void *edata)
{
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
REMEMBER(event, this->reentrancy_count);
if (!this->_switch_thread_if_not_on_right_thread(event, edata)) {
// Not on the right thread
return 0;
}
ink_release_assert(this->_thread == this_ethread());
Event *e = static_cast<Event *>(edata);
reentrancy_count++;
if (e == _read_vio_event) {
_read_vio_event = nullptr;
this->signal_read_event(e->callback_event);
reentrancy_count--;
return 0;
} else if (e == _write_vio_event) {
_write_vio_event = nullptr;
this->signal_write_event(e->callback_event);
reentrancy_count--;
return 0;
} else if (e == cross_thread_event) {
cross_thread_event = nullptr;
} else if (e == read_event) {
read_event = nullptr;
} else if (e == write_event) {
write_event = nullptr;
}
switch (event) {
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_INACTIVITY_TIMEOUT:
if (_sm && read_vio.ntodo() > 0) {
this->signal_read_event(event);
} else if (_sm && write_vio.ntodo() > 0) {
this->signal_write_event(event);
}
break;
case VC_EVENT_WRITE_READY:
case VC_EVENT_WRITE_COMPLETE:
_timeout.update_inactivity();
if (e->cookie == &write_vio) {
if (write_vio.mutex && write_vio.cont && this->_sm) {
this->signal_write_event(event);
}
} else {
update_write_request(true);
}
break;
case VC_EVENT_READ_COMPLETE:
case VC_EVENT_READ_READY:
_timeout.update_inactivity();
if (e->cookie == &read_vio) {
if (read_vio.mutex && read_vio.cont && this->_sm) {
signal_read_event(event);
}
} else {
this->update_read_request(true);
}
break;
case VC_EVENT_EOS:
if (e->cookie == &read_vio) {
SCOPED_MUTEX_LOCK(lock, read_vio.mutex, this_ethread());
read_vio.cont->handleEvent(VC_EVENT_EOS, &read_vio);
} else if (e->cookie == &write_vio) {
SCOPED_MUTEX_LOCK(lock, write_vio.mutex, this_ethread());
write_vio.cont->handleEvent(VC_EVENT_EOS, &write_vio);
}
break;
}
reentrancy_count--;
// Clean stream up if the terminate flag is set and we are at the bottom of the handler stack
terminate_if_possible();
return 0;
}
Http2ErrorCode
Http2Stream::decode_header_blocks(HpackHandle &hpack_handle, uint32_t maximum_table_size)
{
return http2_decode_header_blocks(&_req_header, (const uint8_t *)header_blocks, header_blocks_length, nullptr, hpack_handle,
trailing_header, maximum_table_size);
}
void
Http2Stream::send_request(Http2ConnectionState &cstate)
{
ink_release_assert(this->_sm != nullptr);
this->_http_sm_id = this->_sm->sm_id;
// Convert header to HTTP/1.1 format
http2_convert_header_from_2_to_1_1(&_req_header);
// Write header to a buffer. Borrowing logic from HttpSM::write_header_into_buffer.
// Seems like a function like this ought to be in HTTPHdr directly
int bufindex;
int dumpoffset = 0;
int done, tmp;
do {
bufindex = 0;
tmp = dumpoffset;
IOBufferBlock *block = this->_request_buffer.get_current_block();
if (!block) {
this->_request_buffer.add_block();
block = this->_request_buffer.get_current_block();
}
done = _req_header.print(block->start(), block->write_avail(), &bufindex, &tmp);
dumpoffset += bufindex;
this->_request_buffer.fill(bufindex);
if (!done) {
this->_request_buffer.add_block();
}
} while (!done);
if (bufindex == 0) {
// No data to signal read event
return;
}
// Is the _sm ready to process the header?
if (this->read_vio.nbytes > 0) {
if (this->recv_end_stream) {
this->read_vio.nbytes = bufindex;
this->signal_read_event(VC_EVENT_READ_COMPLETE);
} else {
// End of header but not end of stream, must have some body frames coming
this->has_body = true;
this->signal_read_event(VC_EVENT_READ_READY);
}
}
}
bool
Http2Stream::change_state(uint8_t type, uint8_t flags)
{
switch (_state) {
case Http2StreamState::HTTP2_STREAM_STATE_IDLE:
if (type == HTTP2_FRAME_TYPE_HEADERS) {
if (recv_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE;
} else if (send_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_LOCAL;
} else {
_state = Http2StreamState::HTTP2_STREAM_STATE_OPEN;
}
} else if (type == HTTP2_FRAME_TYPE_CONTINUATION) {
if (recv_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE;
} else if (send_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_LOCAL;
} else {
_state = Http2StreamState::HTTP2_STREAM_STATE_OPEN;
}
} else if (type == HTTP2_FRAME_TYPE_PUSH_PROMISE) {
_state = Http2StreamState::HTTP2_STREAM_STATE_RESERVED_LOCAL;
} else {
return false;
}
break;
case Http2StreamState::HTTP2_STREAM_STATE_OPEN:
if (type == HTTP2_FRAME_TYPE_RST_STREAM) {
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
} else if (type == HTTP2_FRAME_TYPE_HEADERS || type == HTTP2_FRAME_TYPE_DATA) {
if (recv_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE;
} else if (send_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_LOCAL;
} else {
// Do not change state
}
} else {
// A stream in the "open" state may be used by both peers to send frames of any type.
return true;
}
break;
case Http2StreamState::HTTP2_STREAM_STATE_RESERVED_LOCAL:
if (type == HTTP2_FRAME_TYPE_HEADERS) {
if (flags & HTTP2_FLAGS_HEADERS_END_HEADERS) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE;
}
} else if (type == HTTP2_FRAME_TYPE_CONTINUATION) {
if (flags & HTTP2_FLAGS_CONTINUATION_END_HEADERS) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE;
}
} else {
return false;
}
break;
case Http2StreamState::HTTP2_STREAM_STATE_RESERVED_REMOTE:
// Currently ATS supports only HTTP/2 server features
return false;
case Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_LOCAL:
if (type == HTTP2_FRAME_TYPE_RST_STREAM || recv_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
} else {
// Error, set state closed
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
return false;
}
break;
case Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE:
if (type == HTTP2_FRAME_TYPE_RST_STREAM || send_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
} else if (type == HTTP2_FRAME_TYPE_HEADERS) { // w/o END_STREAM flag
// No state change here. Expect a following DATA frame with END_STREAM flag.
return true;
} else if (type == HTTP2_FRAME_TYPE_CONTINUATION) { // w/o END_STREAM flag
// No state change here. Expect a following DATA frame with END_STREAM flag.
return true;
} else {
// Error, set state closed
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
return false;
}
break;
case Http2StreamState::HTTP2_STREAM_STATE_CLOSED:
// No state changing
return true;
default:
return false;
}
Http2StreamDebug("%s", Http2DebugNames::get_state_name(_state));
return true;
}
VIO *
Http2Stream::do_io_read(Continuation *c, int64_t nbytes, MIOBuffer *buf)
{
if (buf) {
read_vio.buffer.writer_for(buf);
} else {
read_vio.buffer.clear();
}
read_vio.mutex = c ? c->mutex : this->mutex;
read_vio.cont = c;
read_vio.nbytes = nbytes;
read_vio.ndone = 0;
read_vio.vc_server = this;
read_vio.op = VIO::READ;
// TODO: re-enable read_vio
return &read_vio;
}
VIO *
Http2Stream::do_io_write(Continuation *c, int64_t nbytes, IOBufferReader *abuffer, bool owner)
{
if (abuffer) {
write_vio.buffer.reader_for(abuffer);
} else {
write_vio.buffer.clear();
}
write_vio.mutex = c ? c->mutex : this->mutex;
write_vio.cont = c;
write_vio.nbytes = nbytes;
write_vio.ndone = 0;
write_vio.vc_server = this;
write_vio.op = VIO::WRITE;
if (c != nullptr && nbytes > 0 && this->is_client_state_writeable()) {
update_write_request(false);
} else if (!this->is_client_state_writeable()) {
// Cannot start a write on a closed stream
return nullptr;
}
return &write_vio;
}
// Initiated from SM
void
Http2Stream::do_io_close(int /* flags */)
{
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
if (!closed) {
REMEMBER(NO_EVENT, this->reentrancy_count);
Http2StreamDebug("do_io_close");
// When we get here, the SM has initiated the shutdown. Either it received a WRITE_COMPLETE, or it is shutting down. Any
// remaining IO operations back to client should be abandoned. The SM-side buffers backing these operations will be deleted
// by the time this is called from transaction_done.
closed = true;
if (_proxy_ssn && this->is_client_state_writeable()) {
// Make sure any trailing end of stream frames are sent
// We will be removed at send_data_frames or closing connection phase
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(this->_proxy_ssn);
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->mutex, this_ethread());
h2_proxy_ssn->connection_state.send_data_frames(this);
}
_clear_timers();
clear_io_events();
// Wait until transaction_done is called from HttpSM to signal that the TXN_CLOSE hook has been executed
}
}
/*
* HttpSM has called TXN_close hooks.
*/
void
Http2Stream::transaction_done()
{
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
super::transaction_done();
if (!closed) {
do_io_close(); // Make sure we've been closed. If we didn't close the _proxy_ssn session better still be open
}
ink_release_assert(closed || !static_cast<Http2ClientSession *>(_proxy_ssn)->connection_state.is_state_closed());
_sm = nullptr;
if (closed) {
// Safe to initiate SSN_CLOSE if this is the last stream
ink_assert(cross_thread_event == nullptr);
// Schedule the destroy to occur after we unwind here. IF we call directly, may delete with reference on the stack.
terminate_stream = true;
terminate_if_possible();
}
}
void
Http2Stream::terminate_if_possible()
{
if (terminate_stream && reentrancy_count == 0) {
REMEMBER(NO_EVENT, this->reentrancy_count);
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(this->_proxy_ssn);
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->mutex, this_ethread());
THREAD_FREE(this, http2StreamAllocator, this_ethread());
}
}
// Initiated from the Http2 side
void
Http2Stream::initiating_close()
{
if (!closed) {
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
REMEMBER(NO_EVENT, this->reentrancy_count);
Http2StreamDebug("initiating_close");
// Set the state of the connection to closed
// TODO - these states should be combined
closed = true;
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
// leaving the reference to the SM, so we can detach from the SM when we actually destroy
// _sm = NULL;
// Leaving reference to client session as well, so we can signal once the
// TXN_CLOSE has been sent
// _proxy_ssn = NULL;
_clear_timers();
clear_io_events();
// This should result in do_io_close or release being called. That will schedule the final
// kill yourself signal
// We are sending signals rather than calling the handlers directly to avoid the case where
// the HttpTunnel handler causes the HttpSM to be deleted on the stack.
bool sent_write_complete = false;
if (_sm) {
// Push out any last IO events
if (write_vio.cont) {
SCOPED_MUTEX_LOCK(lock, write_vio.mutex, this_ethread());
// Are we done?
if (write_vio.nbytes > 0 && write_vio.nbytes == write_vio.ndone) {
Http2StreamDebug("handle write from destroy (event=%d)", VC_EVENT_WRITE_COMPLETE);
write_event = send_tracked_event(write_event, VC_EVENT_WRITE_COMPLETE, &write_vio);
} else {
write_event = send_tracked_event(write_event, VC_EVENT_EOS, &write_vio);
Http2StreamDebug("handle write from destroy (event=%d)", VC_EVENT_EOS);
}
sent_write_complete = true;
}
}
// Send EOS to let SM know that we aren't sticking around
if (_sm && read_vio.cont) {
// Only bother with the EOS if we haven't sent the write complete
if (!sent_write_complete) {
SCOPED_MUTEX_LOCK(lock, read_vio.mutex, this_ethread());
Http2StreamDebug("send EOS to read cont");
read_event = send_tracked_event(read_event, VC_EVENT_EOS, &read_vio);
}
} else if (!sent_write_complete) {
// Transaction is already gone or not started. Kill yourself
terminate_stream = true;
terminate_if_possible();
}
}
}
/* Replace existing event only if the new event is different than the inprogress event */
Event *
Http2Stream::send_tracked_event(Event *event, int send_event, VIO *vio)
{
if (event != nullptr) {
if (event->callback_event != send_event) {
event->cancel();
event = nullptr;
}
}
if (event == nullptr) {
REMEMBER(send_event, this->reentrancy_count);
event = this_ethread()->schedule_imm(this, send_event, vio);
}
return event;
}
void
Http2Stream::update_read_request(bool call_update)
{
if (closed || _proxy_ssn == nullptr || _sm == nullptr || read_vio.mutex == nullptr) {
return;
}
if (!this->_switch_thread_if_not_on_right_thread(VC_EVENT_READ_READY, nullptr)) {
// Not on the right thread
return;
}
ink_release_assert(this->_thread == this_ethread());
SCOPED_MUTEX_LOCK(lock, read_vio.mutex, this_ethread());
if (read_vio.nbytes == 0) {
return;
}
// Try to be smart and only signal if there was additional data
int send_event = VC_EVENT_READ_READY;
if (read_vio.ntodo() == 0 || (this->recv_end_stream && this->read_vio.nbytes != INT64_MAX)) {
send_event = VC_EVENT_READ_COMPLETE;
}
int64_t read_avail = this->read_vio.buffer.writer()->max_read_avail();
if (read_avail > 0 || send_event == VC_EVENT_READ_COMPLETE) {
if (call_update) { // Safe to call vio handler directly
_timeout.update_inactivity();
if (read_vio.cont && this->_sm) {
read_vio.cont->handleEvent(send_event, &read_vio);
}
} else { // Called from do_io_read. Still setting things up. Send event
// to handle this after the dust settles
read_event = send_tracked_event(read_event, send_event, &read_vio);
}
}
}
void
Http2Stream::restart_sending()
{
if (!this->response_header_done) {
return;
}
IOBufferReader *reader = this->response_get_data_reader();
if (reader && !reader->is_read_avail_more_than(0)) {
return;
}
if (this->write_vio.mutex && this->write_vio.ntodo() == 0) {
return;
}
this->send_response_body(true);
}
void
Http2Stream::update_write_request(bool call_update)
{
if (!this->is_client_state_writeable() || closed || _proxy_ssn == nullptr || write_vio.mutex == nullptr ||
write_vio.get_reader() == nullptr) {
return;
}
if (!this->_switch_thread_if_not_on_right_thread(VC_EVENT_WRITE_READY, nullptr)) {
// Not on the right thread
return;
}
ink_release_assert(this->_thread == this_ethread());
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(this->_proxy_ssn);
SCOPED_MUTEX_LOCK(lock, write_vio.mutex, this_ethread());
IOBufferReader *vio_reader = write_vio.get_reader();
if (write_vio.ntodo() == 0 || !vio_reader->is_read_avail_more_than(0)) {
return;
}
// Process the new data
if (!this->response_header_done) {
// Still parsing the response_header
int bytes_used = 0;
int state = this->response_header.parse_resp(&http_parser, vio_reader, &bytes_used, false);
// HTTPHdr::parse_resp() consumed the vio_reader in above (consumed size is `bytes_used`)
write_vio.ndone += bytes_used;
switch (state) {
case PARSE_RESULT_DONE: {
this->response_header_done = true;
// Schedule session shutdown if response header has "Connection: close"
MIMEField *field = this->response_header.field_find(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION);
if (field) {
int len;
const char *value = field->value_get(&len);
if (memcmp(HTTP_VALUE_CLOSE, value, HTTP_LEN_CLOSE) == 0) {
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->mutex, this_ethread());
if (h2_proxy_ssn->connection_state.get_shutdown_state() == HTTP2_SHUTDOWN_NONE) {
h2_proxy_ssn->connection_state.set_shutdown_state(HTTP2_SHUTDOWN_NOT_INITIATED, Http2ErrorCode::HTTP2_ERROR_NO_ERROR);
}
}
}
{
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->mutex, this_ethread());
// Send the response header back
h2_proxy_ssn->connection_state.send_headers_frame(this);
}
// Roll back states of response header to read final response
if (this->response_header.expect_final_response()) {
this->response_header_done = false;
response_header.destroy();
response_header.create(HTTP_TYPE_RESPONSE);
http2_init_pseudo_headers(response_header);
http_parser_clear(&http_parser);
http_parser_init(&http_parser);
}
this->signal_write_event(call_update);
if (vio_reader->is_read_avail_more_than(0)) {
this->_milestones.mark(Http2StreamMilestone::START_TX_DATA_FRAMES);
this->send_response_body(call_update);
}
break;
}
case PARSE_RESULT_CONT:
// Let it ride for next time
break;
default:
break;
}
} else {
this->_milestones.mark(Http2StreamMilestone::START_TX_DATA_FRAMES);
this->send_response_body(call_update);
}
return;
}
void
Http2Stream::signal_read_event(int event)
{
if (this->read_vio.cont == nullptr || this->read_vio.cont->mutex == nullptr || this->read_vio.op == VIO::NONE) {
return;
}
MUTEX_TRY_LOCK(lock, read_vio.cont->mutex, this_ethread());
if (lock.is_locked()) {
_timeout.update_inactivity();
this->read_vio.cont->handleEvent(event, &this->read_vio);
} else {
if (this->_read_vio_event) {
this->_read_vio_event->cancel();
}
this->_read_vio_event = this_ethread()->schedule_in(this, retry_delay, event, &read_vio);
}
}
void
Http2Stream::signal_write_event(int event)
{
// Don't signal a write event if in fact nothing was written
if (this->write_vio.cont == nullptr || this->write_vio.cont->mutex == nullptr || this->write_vio.op == VIO::NONE ||
this->write_vio.nbytes == 0) {
return;
}
MUTEX_TRY_LOCK(lock, write_vio.cont->mutex, this_ethread());
if (lock.is_locked()) {
_timeout.update_inactivity();
this->write_vio.cont->handleEvent(event, &this->write_vio);
} else {
if (this->_write_vio_event) {
this->_write_vio_event->cancel();
}
this->_write_vio_event = this_ethread()->schedule_in(this, retry_delay, event, &write_vio);
}
}
void
Http2Stream::signal_write_event(bool call_update)
{
if (this->write_vio.cont == nullptr || this->write_vio.op == VIO::NONE) {
return;
}
if (this->write_vio.get_writer()->write_avail() == 0) {
return;
}
int send_event = this->write_vio.ntodo() == 0 ? VC_EVENT_WRITE_COMPLETE : VC_EVENT_WRITE_READY;
if (call_update) {
// Coming from reenable. Safe to call the handler directly
if (write_vio.cont && this->_sm) {
write_vio.cont->handleEvent(send_event, &write_vio);
}
} else {
// Called from do_io_write. Might still be setting up state. Send an event to let the dust settle
write_event = send_tracked_event(write_event, send_event, &write_vio);
}
}
bool
Http2Stream::push_promise(URL &url, const MIMEField *accept_encoding)
{
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(this->_proxy_ssn);
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->mutex, this_ethread());
return h2_proxy_ssn->connection_state.send_push_promise_frame(this, url, accept_encoding);
}
void
Http2Stream::send_response_body(bool call_update)
{
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(this->_proxy_ssn);
_timeout.update_inactivity();
if (Http2::stream_priority_enabled) {
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->mutex, this_ethread());
h2_proxy_ssn->connection_state.schedule_stream(this);
// signal_write_event() will be called from `Http2ConnectionState::send_data_frames_depends_on_priority()`
// when write_vio is consumed
} else {
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->mutex, this_ethread());
h2_proxy_ssn->connection_state.send_data_frames(this);
this->signal_write_event(call_update);
// XXX The call to signal_write_event can destroy/free the Http2Stream.
// Don't modify the Http2Stream after calling this method.
}
}
void
Http2Stream::reenable(VIO *vio)
{
if (this->_proxy_ssn) {
if (vio->op == VIO::WRITE) {
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
update_write_request(true);
} else if (vio->op == VIO::READ) {
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(this->_proxy_ssn);
{
SCOPED_MUTEX_LOCK(ssn_lock, h2_proxy_ssn->mutex, this_ethread());
h2_proxy_ssn->connection_state.restart_receiving(this);
}
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
update_read_request(true);
}
}
}
IOBufferReader *
Http2Stream::response_get_data_reader() const
{
return write_vio.get_reader();
}
void
Http2Stream::set_active_timeout(ink_hrtime timeout_in)
{
_timeout.set_active_timeout(timeout_in);
}
void
Http2Stream::set_inactivity_timeout(ink_hrtime timeout_in)
{
_timeout.set_inactive_timeout(timeout_in);
}
void
Http2Stream::cancel_active_timeout()
{
_timeout.cancel_active_timeout();
}
void
Http2Stream::cancel_inactivity_timeout()
{
_timeout.cancel_inactive_timeout();
}
bool
Http2Stream::is_active_timeout_expired(ink_hrtime now)
{
return _timeout.is_active_timeout_expired(now);
}
bool
Http2Stream::is_inactive_timeout_expired(ink_hrtime now)
{
return _timeout.is_inactive_timeout_expired(now);
}
void
Http2Stream::clear_io_events()
{
if (cross_thread_event) {
cross_thread_event->cancel();
cross_thread_event = nullptr;
}
if (read_event) {
read_event->cancel();
read_event = nullptr;
}
if (write_event) {
write_event->cancel();
write_event = nullptr;
}
if (this->_read_vio_event) {
this->_read_vio_event->cancel();
this->_read_vio_event = nullptr;
}
if (this->_write_vio_event) {
this->_write_vio_event->cancel();
this->_write_vio_event = nullptr;
}
}
// release and do_io_close are the same for the HTTP/2 protocol
void
Http2Stream::release()
{
this->do_io_close();
}
void
Http2Stream::increment_transactions_stat()
{
HTTP2_INCREMENT_THREAD_DYN_STAT(HTTP2_STAT_CURRENT_CLIENT_STREAM_COUNT, _thread);
HTTP2_INCREMENT_THREAD_DYN_STAT(HTTP2_STAT_TOTAL_CLIENT_STREAM_COUNT, _thread);
}
void
Http2Stream::decrement_transactions_stat()
{
HTTP2_DECREMENT_THREAD_DYN_STAT(HTTP2_STAT_CURRENT_CLIENT_STREAM_COUNT, _thread);
}
ssize_t
Http2Stream::client_rwnd() const
{
return this->_client_rwnd;
}
Http2ErrorCode
Http2Stream::increment_client_rwnd(size_t amount)
{
this->_client_rwnd += amount;
this->_recent_rwnd_increment[this->_recent_rwnd_increment_index] = amount;
++this->_recent_rwnd_increment_index;
this->_recent_rwnd_increment_index %= this->_recent_rwnd_increment.size();
double sum = std::accumulate(this->_recent_rwnd_increment.begin(), this->_recent_rwnd_increment.end(), 0.0);
double avg = sum / this->_recent_rwnd_increment.size();
if (avg < Http2::min_avg_window_update) {
return Http2ErrorCode::HTTP2_ERROR_ENHANCE_YOUR_CALM;
}
return Http2ErrorCode::HTTP2_ERROR_NO_ERROR;
}
Http2ErrorCode
Http2Stream::decrement_client_rwnd(size_t amount)
{
this->_client_rwnd -= amount;
if (this->_client_rwnd < 0) {
return Http2ErrorCode::HTTP2_ERROR_PROTOCOL_ERROR;
} else {
return Http2ErrorCode::HTTP2_ERROR_NO_ERROR;
}
}
ssize_t
Http2Stream::server_rwnd() const
{
return this->_server_rwnd;
}
Http2ErrorCode
Http2Stream::increment_server_rwnd(size_t amount)
{
this->_server_rwnd += amount;
return Http2ErrorCode::HTTP2_ERROR_NO_ERROR;
}
Http2ErrorCode
Http2Stream::decrement_server_rwnd(size_t amount)
{
this->_server_rwnd -= amount;
if (this->_server_rwnd < 0) {
return Http2ErrorCode::HTTP2_ERROR_PROTOCOL_ERROR;
} else {
return Http2ErrorCode::HTTP2_ERROR_NO_ERROR;
}
}
bool
Http2Stream::_switch_thread_if_not_on_right_thread(int event, void *edata)
{
if (this->_thread != this_ethread()) {
SCOPED_MUTEX_LOCK(stream_lock, this->mutex, this_ethread());
if (cross_thread_event == nullptr) {
// Send to the right thread
cross_thread_event = this->_thread->schedule_imm(this, event, edata);
}
return false;
}
return true;
}
int
Http2Stream::get_transaction_priority_weight() const
{
return priority_node ? priority_node->weight : 0;
}
int
Http2Stream::get_transaction_priority_dependence() const
{
if (!priority_node) {
return -1;
} else {
return priority_node->parent ? priority_node->parent->id : 0;
}
}
int64_t
Http2Stream::read_vio_read_avail()
{
MIOBuffer *writer = this->read_vio.get_writer();
if (writer) {
return writer->max_read_avail();
}
return 0;
}
bool
Http2Stream::has_request_body(int64_t content_length, bool is_chunked_set) const
{
return has_body;
}
Add debug message when there is a header parse error for http/2 (#8234)
/** @file
Http2Stream.cc
@section license License
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 "Http2Stream.h"
#include "HTTP2.h"
#include "Http2ClientSession.h"
#include "../http/HttpSM.h"
#include <numeric>
#define REMEMBER(e, r) \
{ \
this->_history.push_back(MakeSourceLocation(), e, r); \
}
#define Http2StreamDebug(fmt, ...) \
SsnDebug(_proxy_ssn, "http2_stream", "[%" PRId64 "] [%u] " fmt, _proxy_ssn->connection_id(), this->get_id(), ##__VA_ARGS__);
ClassAllocator<Http2Stream, true> http2StreamAllocator("http2StreamAllocator");
Http2Stream::Http2Stream(ProxySession *session, Http2StreamId sid, ssize_t initial_rwnd)
: super(session), _id(sid), _client_rwnd(initial_rwnd)
{
SET_HANDLER(&Http2Stream::main_event_handler);
this->mark_milestone(Http2StreamMilestone::OPEN);
this->_sm = nullptr;
this->_id = sid;
this->_thread = this_ethread();
this->_client_rwnd = initial_rwnd;
this->_server_rwnd = Http2::initial_window_size;
this->_reader = this->_request_buffer.alloc_reader();
_req_header.create(HTTP_TYPE_REQUEST);
response_header.create(HTTP_TYPE_RESPONSE);
// TODO: init _req_header instead of response_header if this Http2Stream is outgoing
http2_init_pseudo_headers(response_header);
http_parser_init(&http_parser);
}
Http2Stream::~Http2Stream()
{
REMEMBER(NO_EVENT, this->reentrancy_count);
Http2StreamDebug("Destroy stream, sent %" PRIu64 " bytes", this->bytes_sent);
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
// Clean up after yourself if this was an EOS
ink_release_assert(this->closed);
ink_release_assert(reentrancy_count == 0);
uint64_t cid = 0;
// Safe to initiate SSN_CLOSE if this is the last stream
if (_proxy_ssn) {
cid = _proxy_ssn->connection_id();
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(_proxy_ssn);
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->mutex, this_ethread());
// Make sure the stream is removed from the stream list and priority tree
// In many cases, this has been called earlier, so this call is a no-op
h2_proxy_ssn->connection_state.delete_stream(this);
h2_proxy_ssn->connection_state.decrement_stream_count();
// Update session's stream counts, so it accurately goes into keep-alive state
h2_proxy_ssn->connection_state.release_stream();
// Do not access `_proxy_ssn` in below. It might be freed by `release_stream`.
}
// Clean up the write VIO in case of inactivity timeout
this->do_io_write(nullptr, 0, nullptr);
this->_milestones.mark(Http2StreamMilestone::CLOSE);
ink_hrtime total_time = this->_milestones.elapsed(Http2StreamMilestone::OPEN, Http2StreamMilestone::CLOSE);
HTTP2_SUM_THREAD_DYN_STAT(HTTP2_STAT_TOTAL_TRANSACTIONS_TIME, this->_thread, total_time);
// Slow Log
if (Http2::stream_slow_log_threshold != 0 && ink_hrtime_from_msec(Http2::stream_slow_log_threshold) < total_time) {
Error("[%" PRIu64 "] [%" PRIu32 "] [%" PRId64 "] Slow H2 Stream: "
"open: %" PRIu64 " "
"dec_hdrs: %.3f "
"txn: %.3f "
"enc_hdrs: %.3f "
"tx_hdrs: %.3f "
"tx_data: %.3f "
"close: %.3f",
cid, static_cast<uint32_t>(this->_id), this->_http_sm_id,
ink_hrtime_to_msec(this->_milestones[Http2StreamMilestone::OPEN]),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::START_DECODE_HEADERS),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::START_TXN),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::START_ENCODE_HEADERS),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::START_TX_HEADERS_FRAMES),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::START_TX_DATA_FRAMES),
this->_milestones.difference_sec(Http2StreamMilestone::OPEN, Http2StreamMilestone::CLOSE));
}
_req_header.destroy();
response_header.destroy();
// Drop references to all buffer data
this->_request_buffer.clear();
// Free the mutexes in the VIO
read_vio.mutex.clear();
write_vio.mutex.clear();
if (header_blocks) {
ats_free(header_blocks);
}
_clear_timers();
clear_io_events();
http_parser_clear(&http_parser);
}
int
Http2Stream::main_event_handler(int event, void *edata)
{
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
REMEMBER(event, this->reentrancy_count);
if (!this->_switch_thread_if_not_on_right_thread(event, edata)) {
// Not on the right thread
return 0;
}
ink_release_assert(this->_thread == this_ethread());
Event *e = static_cast<Event *>(edata);
reentrancy_count++;
if (e == _read_vio_event) {
_read_vio_event = nullptr;
this->signal_read_event(e->callback_event);
reentrancy_count--;
return 0;
} else if (e == _write_vio_event) {
_write_vio_event = nullptr;
this->signal_write_event(e->callback_event);
reentrancy_count--;
return 0;
} else if (e == cross_thread_event) {
cross_thread_event = nullptr;
} else if (e == read_event) {
read_event = nullptr;
} else if (e == write_event) {
write_event = nullptr;
}
switch (event) {
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_INACTIVITY_TIMEOUT:
if (_sm && read_vio.ntodo() > 0) {
this->signal_read_event(event);
} else if (_sm && write_vio.ntodo() > 0) {
this->signal_write_event(event);
}
break;
case VC_EVENT_WRITE_READY:
case VC_EVENT_WRITE_COMPLETE:
_timeout.update_inactivity();
if (e->cookie == &write_vio) {
if (write_vio.mutex && write_vio.cont && this->_sm) {
this->signal_write_event(event);
}
} else {
update_write_request(true);
}
break;
case VC_EVENT_READ_COMPLETE:
case VC_EVENT_READ_READY:
_timeout.update_inactivity();
if (e->cookie == &read_vio) {
if (read_vio.mutex && read_vio.cont && this->_sm) {
signal_read_event(event);
}
} else {
this->update_read_request(true);
}
break;
case VC_EVENT_EOS:
if (e->cookie == &read_vio) {
SCOPED_MUTEX_LOCK(lock, read_vio.mutex, this_ethread());
read_vio.cont->handleEvent(VC_EVENT_EOS, &read_vio);
} else if (e->cookie == &write_vio) {
SCOPED_MUTEX_LOCK(lock, write_vio.mutex, this_ethread());
write_vio.cont->handleEvent(VC_EVENT_EOS, &write_vio);
}
break;
}
reentrancy_count--;
// Clean stream up if the terminate flag is set and we are at the bottom of the handler stack
terminate_if_possible();
return 0;
}
Http2ErrorCode
Http2Stream::decode_header_blocks(HpackHandle &hpack_handle, uint32_t maximum_table_size)
{
Http2ErrorCode error = http2_decode_header_blocks(&_req_header, header_blocks, header_blocks_length, nullptr, hpack_handle,
trailing_header, maximum_table_size);
if (error != Http2ErrorCode::HTTP2_ERROR_NO_ERROR) {
Http2StreamDebug("Error decoding header blocks: %u", static_cast<uint32_t>(error));
}
return error;
}
void
Http2Stream::send_request(Http2ConnectionState &cstate)
{
ink_release_assert(this->_sm != nullptr);
this->_http_sm_id = this->_sm->sm_id;
// Convert header to HTTP/1.1 format
http2_convert_header_from_2_to_1_1(&_req_header);
// Write header to a buffer. Borrowing logic from HttpSM::write_header_into_buffer.
// Seems like a function like this ought to be in HTTPHdr directly
int bufindex;
int dumpoffset = 0;
int done, tmp;
do {
bufindex = 0;
tmp = dumpoffset;
IOBufferBlock *block = this->_request_buffer.get_current_block();
if (!block) {
this->_request_buffer.add_block();
block = this->_request_buffer.get_current_block();
}
done = _req_header.print(block->start(), block->write_avail(), &bufindex, &tmp);
dumpoffset += bufindex;
this->_request_buffer.fill(bufindex);
if (!done) {
this->_request_buffer.add_block();
}
} while (!done);
if (bufindex == 0) {
// No data to signal read event
return;
}
// Is the _sm ready to process the header?
if (this->read_vio.nbytes > 0) {
if (this->recv_end_stream) {
this->read_vio.nbytes = bufindex;
this->signal_read_event(VC_EVENT_READ_COMPLETE);
} else {
// End of header but not end of stream, must have some body frames coming
this->has_body = true;
this->signal_read_event(VC_EVENT_READ_READY);
}
}
}
bool
Http2Stream::change_state(uint8_t type, uint8_t flags)
{
switch (_state) {
case Http2StreamState::HTTP2_STREAM_STATE_IDLE:
if (type == HTTP2_FRAME_TYPE_HEADERS) {
if (recv_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE;
} else if (send_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_LOCAL;
} else {
_state = Http2StreamState::HTTP2_STREAM_STATE_OPEN;
}
} else if (type == HTTP2_FRAME_TYPE_CONTINUATION) {
if (recv_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE;
} else if (send_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_LOCAL;
} else {
_state = Http2StreamState::HTTP2_STREAM_STATE_OPEN;
}
} else if (type == HTTP2_FRAME_TYPE_PUSH_PROMISE) {
_state = Http2StreamState::HTTP2_STREAM_STATE_RESERVED_LOCAL;
} else {
return false;
}
break;
case Http2StreamState::HTTP2_STREAM_STATE_OPEN:
if (type == HTTP2_FRAME_TYPE_RST_STREAM) {
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
} else if (type == HTTP2_FRAME_TYPE_HEADERS || type == HTTP2_FRAME_TYPE_DATA) {
if (recv_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE;
} else if (send_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_LOCAL;
} else {
// Do not change state
}
} else {
// A stream in the "open" state may be used by both peers to send frames of any type.
return true;
}
break;
case Http2StreamState::HTTP2_STREAM_STATE_RESERVED_LOCAL:
if (type == HTTP2_FRAME_TYPE_HEADERS) {
if (flags & HTTP2_FLAGS_HEADERS_END_HEADERS) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE;
}
} else if (type == HTTP2_FRAME_TYPE_CONTINUATION) {
if (flags & HTTP2_FLAGS_CONTINUATION_END_HEADERS) {
_state = Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE;
}
} else {
return false;
}
break;
case Http2StreamState::HTTP2_STREAM_STATE_RESERVED_REMOTE:
// Currently ATS supports only HTTP/2 server features
return false;
case Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_LOCAL:
if (type == HTTP2_FRAME_TYPE_RST_STREAM || recv_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
} else {
// Error, set state closed
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
return false;
}
break;
case Http2StreamState::HTTP2_STREAM_STATE_HALF_CLOSED_REMOTE:
if (type == HTTP2_FRAME_TYPE_RST_STREAM || send_end_stream) {
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
} else if (type == HTTP2_FRAME_TYPE_HEADERS) { // w/o END_STREAM flag
// No state change here. Expect a following DATA frame with END_STREAM flag.
return true;
} else if (type == HTTP2_FRAME_TYPE_CONTINUATION) { // w/o END_STREAM flag
// No state change here. Expect a following DATA frame with END_STREAM flag.
return true;
} else {
// Error, set state closed
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
return false;
}
break;
case Http2StreamState::HTTP2_STREAM_STATE_CLOSED:
// No state changing
return true;
default:
return false;
}
Http2StreamDebug("%s", Http2DebugNames::get_state_name(_state));
return true;
}
VIO *
Http2Stream::do_io_read(Continuation *c, int64_t nbytes, MIOBuffer *buf)
{
if (buf) {
read_vio.buffer.writer_for(buf);
} else {
read_vio.buffer.clear();
}
read_vio.mutex = c ? c->mutex : this->mutex;
read_vio.cont = c;
read_vio.nbytes = nbytes;
read_vio.ndone = 0;
read_vio.vc_server = this;
read_vio.op = VIO::READ;
// TODO: re-enable read_vio
return &read_vio;
}
VIO *
Http2Stream::do_io_write(Continuation *c, int64_t nbytes, IOBufferReader *abuffer, bool owner)
{
if (abuffer) {
write_vio.buffer.reader_for(abuffer);
} else {
write_vio.buffer.clear();
}
write_vio.mutex = c ? c->mutex : this->mutex;
write_vio.cont = c;
write_vio.nbytes = nbytes;
write_vio.ndone = 0;
write_vio.vc_server = this;
write_vio.op = VIO::WRITE;
if (c != nullptr && nbytes > 0 && this->is_client_state_writeable()) {
update_write_request(false);
} else if (!this->is_client_state_writeable()) {
// Cannot start a write on a closed stream
return nullptr;
}
return &write_vio;
}
// Initiated from SM
void
Http2Stream::do_io_close(int /* flags */)
{
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
if (!closed) {
REMEMBER(NO_EVENT, this->reentrancy_count);
Http2StreamDebug("do_io_close");
// When we get here, the SM has initiated the shutdown. Either it received a WRITE_COMPLETE, or it is shutting down. Any
// remaining IO operations back to client should be abandoned. The SM-side buffers backing these operations will be deleted
// by the time this is called from transaction_done.
closed = true;
if (_proxy_ssn && this->is_client_state_writeable()) {
// Make sure any trailing end of stream frames are sent
// We will be removed at send_data_frames or closing connection phase
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(this->_proxy_ssn);
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->mutex, this_ethread());
h2_proxy_ssn->connection_state.send_data_frames(this);
}
_clear_timers();
clear_io_events();
// Wait until transaction_done is called from HttpSM to signal that the TXN_CLOSE hook has been executed
}
}
/*
* HttpSM has called TXN_close hooks.
*/
void
Http2Stream::transaction_done()
{
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
super::transaction_done();
if (!closed) {
do_io_close(); // Make sure we've been closed. If we didn't close the _proxy_ssn session better still be open
}
ink_release_assert(closed || !static_cast<Http2ClientSession *>(_proxy_ssn)->connection_state.is_state_closed());
_sm = nullptr;
if (closed) {
// Safe to initiate SSN_CLOSE if this is the last stream
ink_assert(cross_thread_event == nullptr);
// Schedule the destroy to occur after we unwind here. IF we call directly, may delete with reference on the stack.
terminate_stream = true;
terminate_if_possible();
}
}
void
Http2Stream::terminate_if_possible()
{
if (terminate_stream && reentrancy_count == 0) {
REMEMBER(NO_EVENT, this->reentrancy_count);
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(this->_proxy_ssn);
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->mutex, this_ethread());
THREAD_FREE(this, http2StreamAllocator, this_ethread());
}
}
// Initiated from the Http2 side
void
Http2Stream::initiating_close()
{
if (!closed) {
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
REMEMBER(NO_EVENT, this->reentrancy_count);
Http2StreamDebug("initiating_close");
// Set the state of the connection to closed
// TODO - these states should be combined
closed = true;
_state = Http2StreamState::HTTP2_STREAM_STATE_CLOSED;
// leaving the reference to the SM, so we can detach from the SM when we actually destroy
// _sm = NULL;
// Leaving reference to client session as well, so we can signal once the
// TXN_CLOSE has been sent
// _proxy_ssn = NULL;
_clear_timers();
clear_io_events();
// This should result in do_io_close or release being called. That will schedule the final
// kill yourself signal
// We are sending signals rather than calling the handlers directly to avoid the case where
// the HttpTunnel handler causes the HttpSM to be deleted on the stack.
bool sent_write_complete = false;
if (_sm) {
// Push out any last IO events
if (write_vio.cont) {
SCOPED_MUTEX_LOCK(lock, write_vio.mutex, this_ethread());
// Are we done?
if (write_vio.nbytes > 0 && write_vio.nbytes == write_vio.ndone) {
Http2StreamDebug("handle write from destroy (event=%d)", VC_EVENT_WRITE_COMPLETE);
write_event = send_tracked_event(write_event, VC_EVENT_WRITE_COMPLETE, &write_vio);
} else {
write_event = send_tracked_event(write_event, VC_EVENT_EOS, &write_vio);
Http2StreamDebug("handle write from destroy (event=%d)", VC_EVENT_EOS);
}
sent_write_complete = true;
}
}
// Send EOS to let SM know that we aren't sticking around
if (_sm && read_vio.cont) {
// Only bother with the EOS if we haven't sent the write complete
if (!sent_write_complete) {
SCOPED_MUTEX_LOCK(lock, read_vio.mutex, this_ethread());
Http2StreamDebug("send EOS to read cont");
read_event = send_tracked_event(read_event, VC_EVENT_EOS, &read_vio);
}
} else if (!sent_write_complete) {
// Transaction is already gone or not started. Kill yourself
terminate_stream = true;
terminate_if_possible();
}
}
}
/* Replace existing event only if the new event is different than the inprogress event */
Event *
Http2Stream::send_tracked_event(Event *event, int send_event, VIO *vio)
{
if (event != nullptr) {
if (event->callback_event != send_event) {
event->cancel();
event = nullptr;
}
}
if (event == nullptr) {
REMEMBER(send_event, this->reentrancy_count);
event = this_ethread()->schedule_imm(this, send_event, vio);
}
return event;
}
void
Http2Stream::update_read_request(bool call_update)
{
if (closed || _proxy_ssn == nullptr || _sm == nullptr || read_vio.mutex == nullptr) {
return;
}
if (!this->_switch_thread_if_not_on_right_thread(VC_EVENT_READ_READY, nullptr)) {
// Not on the right thread
return;
}
ink_release_assert(this->_thread == this_ethread());
SCOPED_MUTEX_LOCK(lock, read_vio.mutex, this_ethread());
if (read_vio.nbytes == 0) {
return;
}
// Try to be smart and only signal if there was additional data
int send_event = VC_EVENT_READ_READY;
if (read_vio.ntodo() == 0 || (this->recv_end_stream && this->read_vio.nbytes != INT64_MAX)) {
send_event = VC_EVENT_READ_COMPLETE;
}
int64_t read_avail = this->read_vio.buffer.writer()->max_read_avail();
if (read_avail > 0 || send_event == VC_EVENT_READ_COMPLETE) {
if (call_update) { // Safe to call vio handler directly
_timeout.update_inactivity();
if (read_vio.cont && this->_sm) {
read_vio.cont->handleEvent(send_event, &read_vio);
}
} else { // Called from do_io_read. Still setting things up. Send event
// to handle this after the dust settles
read_event = send_tracked_event(read_event, send_event, &read_vio);
}
}
}
void
Http2Stream::restart_sending()
{
if (!this->response_header_done) {
return;
}
IOBufferReader *reader = this->response_get_data_reader();
if (reader && !reader->is_read_avail_more_than(0)) {
return;
}
if (this->write_vio.mutex && this->write_vio.ntodo() == 0) {
return;
}
this->send_response_body(true);
}
void
Http2Stream::update_write_request(bool call_update)
{
if (!this->is_client_state_writeable() || closed || _proxy_ssn == nullptr || write_vio.mutex == nullptr ||
write_vio.get_reader() == nullptr) {
return;
}
if (!this->_switch_thread_if_not_on_right_thread(VC_EVENT_WRITE_READY, nullptr)) {
// Not on the right thread
return;
}
ink_release_assert(this->_thread == this_ethread());
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(this->_proxy_ssn);
SCOPED_MUTEX_LOCK(lock, write_vio.mutex, this_ethread());
IOBufferReader *vio_reader = write_vio.get_reader();
if (write_vio.ntodo() == 0 || !vio_reader->is_read_avail_more_than(0)) {
return;
}
// Process the new data
if (!this->response_header_done) {
// Still parsing the response_header
int bytes_used = 0;
int state = this->response_header.parse_resp(&http_parser, vio_reader, &bytes_used, false);
// HTTPHdr::parse_resp() consumed the vio_reader in above (consumed size is `bytes_used`)
write_vio.ndone += bytes_used;
switch (state) {
case PARSE_RESULT_DONE: {
this->response_header_done = true;
// Schedule session shutdown if response header has "Connection: close"
MIMEField *field = this->response_header.field_find(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION);
if (field) {
int len;
const char *value = field->value_get(&len);
if (memcmp(HTTP_VALUE_CLOSE, value, HTTP_LEN_CLOSE) == 0) {
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->mutex, this_ethread());
if (h2_proxy_ssn->connection_state.get_shutdown_state() == HTTP2_SHUTDOWN_NONE) {
h2_proxy_ssn->connection_state.set_shutdown_state(HTTP2_SHUTDOWN_NOT_INITIATED, Http2ErrorCode::HTTP2_ERROR_NO_ERROR);
}
}
}
{
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->mutex, this_ethread());
// Send the response header back
h2_proxy_ssn->connection_state.send_headers_frame(this);
}
// Roll back states of response header to read final response
if (this->response_header.expect_final_response()) {
this->response_header_done = false;
response_header.destroy();
response_header.create(HTTP_TYPE_RESPONSE);
http2_init_pseudo_headers(response_header);
http_parser_clear(&http_parser);
http_parser_init(&http_parser);
}
this->signal_write_event(call_update);
if (vio_reader->is_read_avail_more_than(0)) {
this->_milestones.mark(Http2StreamMilestone::START_TX_DATA_FRAMES);
this->send_response_body(call_update);
}
break;
}
case PARSE_RESULT_CONT:
// Let it ride for next time
break;
default:
break;
}
} else {
this->_milestones.mark(Http2StreamMilestone::START_TX_DATA_FRAMES);
this->send_response_body(call_update);
}
return;
}
void
Http2Stream::signal_read_event(int event)
{
if (this->read_vio.cont == nullptr || this->read_vio.cont->mutex == nullptr || this->read_vio.op == VIO::NONE) {
return;
}
MUTEX_TRY_LOCK(lock, read_vio.cont->mutex, this_ethread());
if (lock.is_locked()) {
_timeout.update_inactivity();
this->read_vio.cont->handleEvent(event, &this->read_vio);
} else {
if (this->_read_vio_event) {
this->_read_vio_event->cancel();
}
this->_read_vio_event = this_ethread()->schedule_in(this, retry_delay, event, &read_vio);
}
}
void
Http2Stream::signal_write_event(int event)
{
// Don't signal a write event if in fact nothing was written
if (this->write_vio.cont == nullptr || this->write_vio.cont->mutex == nullptr || this->write_vio.op == VIO::NONE ||
this->write_vio.nbytes == 0) {
return;
}
MUTEX_TRY_LOCK(lock, write_vio.cont->mutex, this_ethread());
if (lock.is_locked()) {
_timeout.update_inactivity();
this->write_vio.cont->handleEvent(event, &this->write_vio);
} else {
if (this->_write_vio_event) {
this->_write_vio_event->cancel();
}
this->_write_vio_event = this_ethread()->schedule_in(this, retry_delay, event, &write_vio);
}
}
void
Http2Stream::signal_write_event(bool call_update)
{
if (this->write_vio.cont == nullptr || this->write_vio.op == VIO::NONE) {
return;
}
if (this->write_vio.get_writer()->write_avail() == 0) {
return;
}
int send_event = this->write_vio.ntodo() == 0 ? VC_EVENT_WRITE_COMPLETE : VC_EVENT_WRITE_READY;
if (call_update) {
// Coming from reenable. Safe to call the handler directly
if (write_vio.cont && this->_sm) {
write_vio.cont->handleEvent(send_event, &write_vio);
}
} else {
// Called from do_io_write. Might still be setting up state. Send an event to let the dust settle
write_event = send_tracked_event(write_event, send_event, &write_vio);
}
}
bool
Http2Stream::push_promise(URL &url, const MIMEField *accept_encoding)
{
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(this->_proxy_ssn);
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->mutex, this_ethread());
return h2_proxy_ssn->connection_state.send_push_promise_frame(this, url, accept_encoding);
}
void
Http2Stream::send_response_body(bool call_update)
{
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(this->_proxy_ssn);
_timeout.update_inactivity();
if (Http2::stream_priority_enabled) {
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->mutex, this_ethread());
h2_proxy_ssn->connection_state.schedule_stream(this);
// signal_write_event() will be called from `Http2ConnectionState::send_data_frames_depends_on_priority()`
// when write_vio is consumed
} else {
SCOPED_MUTEX_LOCK(lock, h2_proxy_ssn->mutex, this_ethread());
h2_proxy_ssn->connection_state.send_data_frames(this);
this->signal_write_event(call_update);
// XXX The call to signal_write_event can destroy/free the Http2Stream.
// Don't modify the Http2Stream after calling this method.
}
}
void
Http2Stream::reenable(VIO *vio)
{
if (this->_proxy_ssn) {
if (vio->op == VIO::WRITE) {
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
update_write_request(true);
} else if (vio->op == VIO::READ) {
Http2ClientSession *h2_proxy_ssn = static_cast<Http2ClientSession *>(this->_proxy_ssn);
{
SCOPED_MUTEX_LOCK(ssn_lock, h2_proxy_ssn->mutex, this_ethread());
h2_proxy_ssn->connection_state.restart_receiving(this);
}
SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread());
update_read_request(true);
}
}
}
IOBufferReader *
Http2Stream::response_get_data_reader() const
{
return write_vio.get_reader();
}
void
Http2Stream::set_active_timeout(ink_hrtime timeout_in)
{
_timeout.set_active_timeout(timeout_in);
}
void
Http2Stream::set_inactivity_timeout(ink_hrtime timeout_in)
{
_timeout.set_inactive_timeout(timeout_in);
}
void
Http2Stream::cancel_active_timeout()
{
_timeout.cancel_active_timeout();
}
void
Http2Stream::cancel_inactivity_timeout()
{
_timeout.cancel_inactive_timeout();
}
bool
Http2Stream::is_active_timeout_expired(ink_hrtime now)
{
return _timeout.is_active_timeout_expired(now);
}
bool
Http2Stream::is_inactive_timeout_expired(ink_hrtime now)
{
return _timeout.is_inactive_timeout_expired(now);
}
void
Http2Stream::clear_io_events()
{
if (cross_thread_event) {
cross_thread_event->cancel();
cross_thread_event = nullptr;
}
if (read_event) {
read_event->cancel();
read_event = nullptr;
}
if (write_event) {
write_event->cancel();
write_event = nullptr;
}
if (this->_read_vio_event) {
this->_read_vio_event->cancel();
this->_read_vio_event = nullptr;
}
if (this->_write_vio_event) {
this->_write_vio_event->cancel();
this->_write_vio_event = nullptr;
}
}
// release and do_io_close are the same for the HTTP/2 protocol
void
Http2Stream::release()
{
this->do_io_close();
}
void
Http2Stream::increment_transactions_stat()
{
HTTP2_INCREMENT_THREAD_DYN_STAT(HTTP2_STAT_CURRENT_CLIENT_STREAM_COUNT, _thread);
HTTP2_INCREMENT_THREAD_DYN_STAT(HTTP2_STAT_TOTAL_CLIENT_STREAM_COUNT, _thread);
}
void
Http2Stream::decrement_transactions_stat()
{
HTTP2_DECREMENT_THREAD_DYN_STAT(HTTP2_STAT_CURRENT_CLIENT_STREAM_COUNT, _thread);
}
ssize_t
Http2Stream::client_rwnd() const
{
return this->_client_rwnd;
}
Http2ErrorCode
Http2Stream::increment_client_rwnd(size_t amount)
{
this->_client_rwnd += amount;
this->_recent_rwnd_increment[this->_recent_rwnd_increment_index] = amount;
++this->_recent_rwnd_increment_index;
this->_recent_rwnd_increment_index %= this->_recent_rwnd_increment.size();
double sum = std::accumulate(this->_recent_rwnd_increment.begin(), this->_recent_rwnd_increment.end(), 0.0);
double avg = sum / this->_recent_rwnd_increment.size();
if (avg < Http2::min_avg_window_update) {
return Http2ErrorCode::HTTP2_ERROR_ENHANCE_YOUR_CALM;
}
return Http2ErrorCode::HTTP2_ERROR_NO_ERROR;
}
Http2ErrorCode
Http2Stream::decrement_client_rwnd(size_t amount)
{
this->_client_rwnd -= amount;
if (this->_client_rwnd < 0) {
return Http2ErrorCode::HTTP2_ERROR_PROTOCOL_ERROR;
} else {
return Http2ErrorCode::HTTP2_ERROR_NO_ERROR;
}
}
ssize_t
Http2Stream::server_rwnd() const
{
return this->_server_rwnd;
}
Http2ErrorCode
Http2Stream::increment_server_rwnd(size_t amount)
{
this->_server_rwnd += amount;
return Http2ErrorCode::HTTP2_ERROR_NO_ERROR;
}
Http2ErrorCode
Http2Stream::decrement_server_rwnd(size_t amount)
{
this->_server_rwnd -= amount;
if (this->_server_rwnd < 0) {
return Http2ErrorCode::HTTP2_ERROR_PROTOCOL_ERROR;
} else {
return Http2ErrorCode::HTTP2_ERROR_NO_ERROR;
}
}
bool
Http2Stream::_switch_thread_if_not_on_right_thread(int event, void *edata)
{
if (this->_thread != this_ethread()) {
SCOPED_MUTEX_LOCK(stream_lock, this->mutex, this_ethread());
if (cross_thread_event == nullptr) {
// Send to the right thread
cross_thread_event = this->_thread->schedule_imm(this, event, edata);
}
return false;
}
return true;
}
int
Http2Stream::get_transaction_priority_weight() const
{
return priority_node ? priority_node->weight : 0;
}
int
Http2Stream::get_transaction_priority_dependence() const
{
if (!priority_node) {
return -1;
} else {
return priority_node->parent ? priority_node->parent->id : 0;
}
}
int64_t
Http2Stream::read_vio_read_avail()
{
MIOBuffer *writer = this->read_vio.get_writer();
if (writer) {
return writer->max_read_avail();
}
return 0;
}
bool
Http2Stream::has_request_body(int64_t content_length, bool is_chunked_set) const
{
return has_body;
}
|
/** @file
This file implements the LogConfig object.
@section license License
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 "tscore/ink_platform.h"
#include "tscore/I_Layout.h"
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#include <memory>
#include "tscore/ink_platform.h"
#include "tscore/ink_file.h"
#include "tscore/List.h"
#include "Log.h"
#include "LogField.h"
#include "LogFilter.h"
#include "LogFormat.h"
#include "LogFile.h"
#include "LogBuffer.h"
#include "LogHost.h"
#include "LogObject.h"
#include "LogConfig.h"
#include "LogUtils.h"
#include "tscore/SimpleTokenizer.h"
#include "LogCollationAccept.h"
#include "YamlLogConfig.h"
#define DISK_IS_CONFIG_FULL_MESSAGE \
"Access logging to local log directory suspended - " \
"configured space allocation exhausted."
#define DISK_IS_ACTUAL_FULL_MESSAGE \
"Access logging to local log directory suspended - " \
"no more space on the logging partition."
#define DISK_IS_CONFIG_LOW_MESSAGE \
"Access logging to local log directory suspended - " \
"configured space allocation almost exhausted."
#define DISK_IS_ACTUAL_LOW_MESSAGE "Access logging to local log directory suspended - partition space is low."
#define PARTITION_HEADROOM_MB 10
#define DIAGS_LOG_FILENAME "diags.log"
void
LogConfig::setup_default_values()
{
const unsigned int bufSize = 512;
char name[bufSize];
if (!gethostname(name, bufSize)) {
ink_strlcpy(name, "unknown_host_name", sizeof(name));
}
hostname = ats_strdup(name);
log_buffer_size = (int)(10 * LOG_KILOBYTE);
max_secs_per_buffer = 5;
max_space_mb_for_logs = 100;
max_space_mb_for_orphan_logs = 25;
max_space_mb_headroom = 10;
logfile_perm = 0644;
logfile_dir = ats_strdup(".");
collation_mode = Log::NO_COLLATION;
collation_host = ats_strdup("none");
collation_port = 0;
collation_host_tagged = false;
collation_preproc_threads = 1;
collation_secret = ats_strdup("foobar");
collation_retry_sec = 0;
collation_max_send_buffers = 0;
rolling_enabled = Log::NO_ROLLING;
rolling_interval_sec = 86400; // 24 hours
rolling_offset_hr = 0;
rolling_size_mb = 10;
auto_delete_rolled_files = true;
roll_log_files_now = false;
sampling_frequency = 1;
file_stat_frequency = 16;
space_used_frequency = 900;
use_orphan_log_space_value = false;
ascii_buffer_size = 4 * 9216;
max_line_size = 9216; // size of pipe buffer for SunOS 5.6
}
void *
LogConfig::reconfigure_mgmt_variables(void * /* token ATS_UNUSED */, char * /* data_raw ATS_UNUSED */,
int /* data_len ATS_UNUSED */)
{
Note("received log reconfiguration event, rolling now");
Log::config->roll_log_files_now = true;
return nullptr;
}
void
LogConfig::read_configuration_variables()
{
int val;
char *ptr;
val = (int)REC_ConfigReadInteger("proxy.config.log.log_buffer_size");
if (val > 0) {
log_buffer_size = val;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.max_secs_per_buffer");
if (val > 0) {
max_secs_per_buffer = val;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.max_space_mb_for_logs");
if (val > 0) {
max_space_mb_for_logs = val;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.max_space_mb_for_orphan_logs");
if (val > 0) {
max_space_mb_for_orphan_logs = val;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.max_space_mb_headroom");
if (val > 0) {
max_space_mb_headroom = val;
}
ptr = REC_ConfigReadString("proxy.config.log.logfile_perm");
int logfile_perm_parsed = ink_fileperm_parse(ptr);
if (logfile_perm_parsed != -1) {
logfile_perm = logfile_perm_parsed;
}
ats_free(ptr);
ptr = REC_ConfigReadString("proxy.config.log.hostname");
if (ptr != nullptr) {
ats_free(hostname);
hostname = ptr;
}
ats_free(logfile_dir);
logfile_dir = ats_stringdup(RecConfigReadLogDir());
if (access(logfile_dir, R_OK | W_OK | X_OK) == -1) {
// Try 'system_root_dir/var/log/trafficserver' directory
fprintf(stderr, "unable to access log directory '%s': %d, %s\n", logfile_dir, errno, strerror(errno));
fprintf(stderr, "please set 'proxy.config.log.logfile_dir'\n");
::exit(1);
}
// COLLATION
val = (int)REC_ConfigReadInteger("proxy.local.log.collation_mode");
// do not restrict value so that error message is logged if
// collation_mode is out of range
collation_mode = val;
ptr = REC_ConfigReadString("proxy.config.log.collation_host");
if (ptr != nullptr) {
ats_free(collation_host);
collation_host = ptr;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.collation_port");
if (val >= 0) {
collation_port = val;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.collation_host_tagged");
collation_host_tagged = (val > 0);
val = (int)REC_ConfigReadInteger("proxy.config.log.collation_preproc_threads");
if (val > 0 && val <= 128) {
collation_preproc_threads = val;
}
ptr = REC_ConfigReadString("proxy.config.log.collation_secret");
if (ptr != nullptr) {
ats_free(collation_secret);
collation_secret = ptr;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.collation_retry_sec");
if (val >= 0) {
collation_retry_sec = val;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.collation_max_send_buffers");
if (val >= 0) {
collation_max_send_buffers = val;
}
// ROLLING
// we don't check for valid values of rolling_enabled, rolling_interval_sec,
// rolling_offset_hr, or rolling_size_mb because the LogObject takes care of this
//
rolling_interval_sec = (int)REC_ConfigReadInteger("proxy.config.log.rolling_interval_sec");
rolling_offset_hr = (int)REC_ConfigReadInteger("proxy.config.log.rolling_offset_hr");
rolling_size_mb = (int)REC_ConfigReadInteger("proxy.config.log.rolling_size_mb");
rolling_min_count = (int)REC_ConfigReadInteger("proxy.config.log.rolling_min_count");
val = (int)REC_ConfigReadInteger("proxy.config.log.rolling_enabled");
if (LogRollingEnabledIsValid(val)) {
rolling_enabled = (Log::RollingEnabledValues)val;
} else {
Warning("invalid value '%d' for '%s', disabling log rolling", val, "proxy.config.log.rolling_enabled");
rolling_enabled = Log::NO_ROLLING;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.auto_delete_rolled_files");
auto_delete_rolled_files = (val > 0);
// Read in min_count control values for auto deletion
if (auto_delete_rolled_files) {
// For diagnostic logs
val = (int)REC_ConfigReadInteger("proxy.config.diags.logfile.rolling_min_count");
val = ((val == 0) ? INT_MAX : val);
deleting_info.insert(new LogDeletingInfo(DIAGS_LOG_FILENAME, val));
// For traffic.out
ats_scoped_str name(REC_ConfigReadString("proxy.config.output.logfile"));
val = (int)REC_ConfigReadInteger("proxy.config.output.logfile.rolling_min_count");
val = ((val == 0) ? INT_MAX : val);
if (name) {
deleting_info.insert(new LogDeletingInfo(name.get(), val));
} else {
deleting_info.insert(new LogDeletingInfo("traffic.out", val));
}
}
// PERFORMANCE
val = (int)REC_ConfigReadInteger("proxy.config.log.sampling_frequency");
if (val > 0) {
sampling_frequency = val;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.file_stat_frequency");
if (val > 0) {
file_stat_frequency = val;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.space_used_frequency");
if (val > 0) {
space_used_frequency = val;
}
// ASCII BUFFER
val = (int)REC_ConfigReadInteger("proxy.config.log.ascii_buffer_size");
if (val > 0) {
ascii_buffer_size = val;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.max_line_size");
if (val > 0) {
max_line_size = val;
}
}
/*-------------------------------------------------------------------------
LogConfig::LogConfig
Read the logging configuration variables from the config file and
initialize the LogConfig member variables. Assign some meaningful
default value if we get garbage back from the config file.
-------------------------------------------------------------------------*/
// TODO: Is UINT_MAX here really correct?
LogConfig::LogConfig()
: initialized(false),
reconfiguration_needed(false),
logging_space_exhausted(false),
m_space_used(0),
m_partition_space_left((int64_t)UINT_MAX),
m_log_collation_accept(nullptr),
m_disk_full(false),
m_disk_low(false),
m_partition_full(false),
m_partition_low(false),
m_log_directory_inaccessible(false)
{
// Setup the default values for all LogConfig public variables so that
// a LogConfig object is valid upon return from the constructor even
// if no configuration file is read
//
setup_default_values();
}
/*-------------------------------------------------------------------------
LogConfig::~LogConfig
Delete all config variable strings.
-------------------------------------------------------------------------*/
LogConfig::~LogConfig()
{
// we don't delete the log collation accept because it may be transferred
// to another LogConfig object
//
// delete m_log_collation_accept;
ats_free(hostname);
ats_free(logfile_dir);
ats_free(collation_host);
ats_free(collation_secret);
}
/*-------------------------------------------------------------------------
LogConfig::setup_collation
-------------------------------------------------------------------------*/
void
LogConfig::setup_collation(LogConfig *prev_config)
{
// Set-up the collation status, but only if collation is enabled and
// there are valid entries for the collation host and port.
//
if (collation_mode < Log::NO_COLLATION || collation_mode >= Log::N_COLLATION_MODES) {
Note("Invalid value %d for proxy.local.log.collation_mode"
" configuration variable (valid range is from %d to %d)\n"
"Log collation disabled",
collation_mode, Log::NO_COLLATION, Log::N_COLLATION_MODES - 1);
} else if (collation_mode == Log::NO_COLLATION) {
// if the previous configuration had a collation accept, delete it
//
if (prev_config && prev_config->m_log_collation_accept) {
delete prev_config->m_log_collation_accept;
prev_config->m_log_collation_accept = nullptr;
}
} else {
Warning("Log collation is deprecated as of ATS v8.0.0!");
if (!collation_port) {
Note("Cannot activate log collation, %d is an invalid collation port", collation_port);
} else if (collation_mode > Log::COLLATION_HOST && strcmp(collation_host, "none") == 0) {
Note("Cannot activate log collation, \"%s\" is an invalid collation host", collation_host);
} else {
if (collation_mode == Log::COLLATION_HOST) {
ink_assert(m_log_collation_accept == nullptr);
if (prev_config && prev_config->m_log_collation_accept) {
if (prev_config->collation_port == collation_port) {
m_log_collation_accept = prev_config->m_log_collation_accept;
} else {
delete prev_config->m_log_collation_accept;
}
}
if (!m_log_collation_accept) {
Log::collation_port = collation_port;
m_log_collation_accept = new LogCollationAccept(collation_port);
}
Debug("log", "I am a collation host listening on port %d.", collation_port);
} else {
Debug("log",
"I am a collation client (%d)."
" My collation host is %s:%d",
collation_mode, collation_host, collation_port);
}
Debug("log", "using iocore log collation");
if (collation_host_tagged) {
LogFormat::turn_tagging_on();
} else {
LogFormat::turn_tagging_off();
}
}
}
}
/*-------------------------------------------------------------------------
LogConfig::init
-------------------------------------------------------------------------*/
void
LogConfig::init(LogConfig *prev_config)
{
LogObject *errlog = nullptr;
ink_assert(!initialized);
setup_collation(prev_config);
update_space_used();
// create log objects
//
if (Log::transaction_logging_enabled()) {
setup_log_objects();
}
// ----------------------------------------------------------------------
// Construct a new error log object candidate.
if (Log::error_logging_enabled()) {
std::unique_ptr<LogFormat> fmt(MakeTextLogFormat("error"));
Debug("log", "creating predefined error log object");
errlog = new LogObject(fmt.get(), logfile_dir, "error.log", LOG_FILE_ASCII, nullptr, (Log::RollingEnabledValues)rolling_enabled,
collation_preproc_threads, rolling_interval_sec, rolling_offset_hr, rolling_size_mb);
log_object_manager.manage_object(errlog);
errlog->set_fmt_timestamps();
} else {
Log::error_log = nullptr;
}
if (prev_config) {
// Transfer objects from previous configuration.
transfer_objects(prev_config);
// After transferring objects, we are going to keep either the new error log or the old one. Figure out
// which one we are keeping and make that the global ...
if (Log::error_log) {
errlog = this->log_object_manager.find_by_format_name(Log::error_log->m_format->name());
}
}
ink_atomic_swap(&Log::error_log, errlog);
// determine if we should use the orphan log space value or not
// we use it if all objects are collation clients, or if some are and
// the specified space for collation is larger than that for local files
//
size_t num_collation_clients = log_object_manager.get_num_collation_clients();
use_orphan_log_space_value = (num_collation_clients == 0 ? false :
(log_object_manager.get_num_objects() == num_collation_clients ?
true :
max_space_mb_for_orphan_logs > max_space_mb_for_logs));
initialized = true;
}
/*-------------------------------------------------------------------------
LogConfig::display
Dump the values for the current LogConfig object.
-------------------------------------------------------------------------*/
void
LogConfig::display(FILE *fd)
{
fprintf(fd, "-----------------------------\n");
fprintf(fd, "--- Logging Configuration ---\n");
fprintf(fd, "-----------------------------\n");
fprintf(fd, "Config variables:\n");
fprintf(fd, " log_buffer_size = %d\n", log_buffer_size);
fprintf(fd, " max_secs_per_buffer = %d\n", max_secs_per_buffer);
fprintf(fd, " max_space_mb_for_logs = %d\n", max_space_mb_for_logs);
fprintf(fd, " max_space_mb_for_orphan_logs = %d\n", max_space_mb_for_orphan_logs);
fprintf(fd, " use_orphan_log_space_value = %d\n", use_orphan_log_space_value);
fprintf(fd, " max_space_mb_headroom = %d\n", max_space_mb_headroom);
fprintf(fd, " hostname = %s\n", hostname);
fprintf(fd, " logfile_dir = %s\n", logfile_dir);
fprintf(fd, " logfile_perm = 0%o\n", logfile_perm);
fprintf(fd, " collation_mode = %d\n", collation_mode);
fprintf(fd, " collation_host = %s\n", collation_host);
fprintf(fd, " collation_port = %d\n", collation_port);
fprintf(fd, " collation_host_tagged = %d\n", collation_host_tagged);
fprintf(fd, " collation_preproc_threads = %d\n", collation_preproc_threads);
fprintf(fd, " collation_secret = %s\n", collation_secret);
fprintf(fd, " rolling_enabled = %d\n", rolling_enabled);
fprintf(fd, " rolling_interval_sec = %d\n", rolling_interval_sec);
fprintf(fd, " rolling_offset_hr = %d\n", rolling_offset_hr);
fprintf(fd, " rolling_size_mb = %d\n", rolling_size_mb);
fprintf(fd, " auto_delete_rolled_files = %d\n", auto_delete_rolled_files);
fprintf(fd, " sampling_frequency = %d\n", sampling_frequency);
fprintf(fd, " file_stat_frequency = %d\n", file_stat_frequency);
fprintf(fd, " space_used_frequency = %d\n", space_used_frequency);
fprintf(fd, "\n");
fprintf(fd, "************ Log Objects (%u objects) ************\n", (unsigned int)log_object_manager.get_num_objects());
log_object_manager.display(fd);
fprintf(fd, "************ Filter List (%u filters) ************\n", filter_list.count());
filter_list.display(fd);
fprintf(fd, "************ Format List (%u formats) ************\n", format_list.count());
format_list.display(fd);
}
//-----------------------------------------------------------------------------
// setup_log_objects
//
// Construct: All custom objects.
//
// Upon return from this function:
// - global_object_list has the aforementioned objects
// - global_filter_list has all custom filters
//
void
LogConfig::setup_log_objects()
{
Debug("log", "creating objects...");
filter_list.clear();
// Evaluate logging.yaml to construct the custom log objects.
evaluate_config();
// Open local pipes so readers can see them.
log_object_manager.open_local_pipes();
if (is_debug_tag_set("log")) {
log_object_manager.display();
}
}
/*-------------------------------------------------------------------------
LogConfig::reconfigure
This is the manager callback for any logging config variable change.
Since we want to access the config variables to build a new config
object, but can't from this function (big lock technology in the
manager), we'll just set a flag and call the real reconfiguration
function from the logging thread.
-------------------------------------------------------------------------*/
int
LogConfig::reconfigure(const char * /* name ATS_UNUSED */, RecDataT /* data_type ATS_UNUSED */, RecData /* data ATS_UNUSED */,
void * /* cookie ATS_UNUSED */)
{
Debug("log-config", "Reconfiguration request accepted");
Log::config->reconfiguration_needed = true;
return 0;
}
/*-------------------------------------------------------------------------
LogConfig::register_config_callbacks
This static function is called by Log::init to register the config update
function for each of the logging configuration variables.
-------------------------------------------------------------------------*/
void
LogConfig::register_config_callbacks()
{
static const char *names[] = {
"proxy.config.log.log_buffer_size",
"proxy.config.log.max_secs_per_buffer",
"proxy.config.log.max_space_mb_for_logs",
"proxy.config.log.max_space_mb_for_orphan_logs",
"proxy.config.log.max_space_mb_headroom",
"proxy.config.log.logfile_perm",
"proxy.config.log.hostname",
"proxy.config.log.logfile_dir",
"proxy.local.log.collation_mode",
"proxy.config.log.collation_host",
"proxy.config.log.collation_port",
"proxy.config.log.collation_host_tagged",
"proxy.config.log.collation_secret",
"proxy.config.log.collation_retry_sec",
"proxy.config.log.collation_max_send_buffers",
"proxy.config.log.rolling_enabled",
"proxy.config.log.rolling_interval_sec",
"proxy.config.log.rolling_offset_hr",
"proxy.config.log.rolling_size_mb",
"proxy.config.log.auto_delete_rolled_files",
"proxy.config.log.config.filename",
"proxy.config.log.sampling_frequency",
"proxy.config.log.file_stat_frequency",
"proxy.config.log.space_used_frequency",
};
for (unsigned i = 0; i < countof(names); ++i) {
REC_RegisterConfigUpdateFunc(names[i], &LogConfig::reconfigure, nullptr);
}
}
/*-------------------------------------------------------------------------
LogConfig::register_stat_callbacks
This static function is called by Log::init to register the stat update
function for each of the logging stats variables.
-------------------------------------------------------------------------*/
void
LogConfig::register_stat_callbacks()
{
//
// events
//
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.event_log_error_ok", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_event_log_error_ok_stat, RecRawStatSyncCount);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.event_log_error_skip", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_event_log_error_skip_stat, RecRawStatSyncCount);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.event_log_error_aggr", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_event_log_error_aggr_stat, RecRawStatSyncCount);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.event_log_error_full", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_event_log_error_full_stat, RecRawStatSyncCount);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.event_log_error_fail", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_event_log_error_fail_stat, RecRawStatSyncCount);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.event_log_access_ok", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_event_log_access_ok_stat, RecRawStatSyncCount);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.event_log_access_skip", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_event_log_access_skip_stat, RecRawStatSyncCount);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.event_log_access_aggr", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_event_log_access_aggr_stat, RecRawStatSyncCount);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.event_log_access_full", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_event_log_access_full_stat, RecRawStatSyncCount);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.event_log_access_fail", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_event_log_access_fail_stat, RecRawStatSyncCount);
//
// number vs bytes of logs
//
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.num_sent_to_network", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_num_sent_to_network_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.num_lost_before_sent_to_network", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_num_lost_before_sent_to_network_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.num_received_from_network", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_num_received_from_network_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.num_flush_to_disk", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_num_flush_to_disk_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.num_lost_before_flush_to_disk", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_num_lost_before_flush_to_disk_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.bytes_lost_before_preproc", RECD_INT, RECP_PERSISTENT,
(int)log_stat_bytes_lost_before_preproc_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.bytes_sent_to_network", RECD_INT, RECP_PERSISTENT,
(int)log_stat_bytes_sent_to_network_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.bytes_lost_before_sent_to_network", RECD_INT, RECP_PERSISTENT,
(int)log_stat_bytes_lost_before_sent_to_network_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.bytes_received_from_network", RECD_INT, RECP_PERSISTENT,
(int)log_stat_bytes_received_from_network_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.bytes_flush_to_disk", RECD_INT, RECP_PERSISTENT,
(int)log_stat_bytes_flush_to_disk_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.bytes_lost_before_flush_to_disk", RECD_INT, RECP_PERSISTENT,
(int)log_stat_bytes_lost_before_flush_to_disk_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.bytes_written_to_disk", RECD_INT, RECP_PERSISTENT,
(int)log_stat_bytes_written_to_disk_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.bytes_lost_before_written_to_disk", RECD_INT, RECP_PERSISTENT,
(int)log_stat_bytes_lost_before_written_to_disk_stat, RecRawStatSyncSum);
//
// I/O
//
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.log_files_open", RECD_COUNTER, RECP_NON_PERSISTENT,
(int)log_stat_log_files_open_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.log_files_space_used", RECD_INT, RECP_NON_PERSISTENT,
(int)log_stat_log_files_space_used_stat, RecRawStatSyncSum);
}
/*-------------------------------------------------------------------------
LogConfig::register_mgmt_callbacks
This static function is called by Log::init to register the mgmt callback
function for each of the logging mgmt messages.
-------------------------------------------------------------------------*/
void
LogConfig::register_mgmt_callbacks()
{
RecRegisterManagerCb(REC_EVENT_ROLL_LOG_FILES, &LogConfig::reconfigure_mgmt_variables, nullptr);
}
/*-------------------------------------------------------------------------
LogConfig::space_to_write
This function returns true if there is enough disk space to write the
given number of bytes, false otherwise.
-------------------------------------------------------------------------*/
bool
LogConfig::space_to_write(int64_t bytes_to_write) const
{
int64_t config_space, partition_headroom;
int64_t logical_space_used, physical_space_left;
bool space;
config_space = (int64_t)get_max_space_mb() * LOG_MEGABYTE;
partition_headroom = (int64_t)PARTITION_HEADROOM_MB * LOG_MEGABYTE;
logical_space_used = m_space_used + bytes_to_write;
physical_space_left = m_partition_space_left - (int64_t)bytes_to_write;
space = ((logical_space_used < config_space) && (physical_space_left > partition_headroom));
Debug("logspace",
"logical space used %" PRId64 ", configured space %" PRId64 ", physical space left %" PRId64 ", partition headroom %" PRId64
", space %s available",
logical_space_used, config_space, physical_space_left, partition_headroom, space ? "is" : "is not");
return space;
}
/*-------------------------------------------------------------------------
LogConfig::update_space_used
Update the m_space_used variable by reading the logging dir and counting
the total bytes being occupied by files. If we've used too much space
(space_used > max_space - headroom) then start deleting some files (if
auto_delete_rolled_files is set) to make room. Finally, update the
space_used stat.
This routine will only be executed SINGLE-THREADED, either by the main
thread when a LogConfig is initialized, or by the event thread during the
periodic space check.
-------------------------------------------------------------------------*/
void
LogConfig::update_space_used()
{
// no need to update space used if log directory is inaccessible
//
if (m_log_directory_inaccessible) {
return;
}
int candidate_count;
int64_t total_space_used, partition_space_left;
char path[MAXPATHLEN];
int sret;
struct dirent *entry;
struct stat sbuf;
DIR *ld;
// check if logging directory has been specified
//
if (!logfile_dir) {
const char *msg = "Logging directory not specified";
Error("%s", msg);
LogUtils::manager_alarm(LogUtils::LOG_ALARM_ERROR, "%s", msg);
m_log_directory_inaccessible = true;
return;
}
// check if logging directory exists and is searchable readable & writable
int err;
do {
err = access(logfile_dir, R_OK | W_OK | X_OK);
} while ((err < 0) && (errno == EINTR));
if (err < 0) {
const char *msg = "Error accessing logging directory %s: %s.";
Error(msg, logfile_dir, strerror(errno));
LogUtils::manager_alarm(LogUtils::LOG_ALARM_ERROR, msg, logfile_dir, strerror(errno));
m_log_directory_inaccessible = true;
return;
}
ld = ::opendir(logfile_dir);
if (ld == nullptr) {
const char *msg = "Error opening logging directory %s to perform a space check: %s.";
Error(msg, logfile_dir, strerror(errno));
LogUtils::manager_alarm(LogUtils::LOG_ALARM_ERROR, msg, logfile_dir, strerror(errno));
m_log_directory_inaccessible = true;
return;
}
total_space_used = 0LL;
candidate_count = 0;
for (auto it = deleting_info.begin(); it != deleting_info.end(); it++) {
Debug("%s", it->name.c_str());
}
while ((entry = readdir(ld))) {
snprintf(path, MAXPATHLEN, "%s/%s", logfile_dir, entry->d_name);
sret = ::stat(path, &sbuf);
if (sret != -1 && S_ISREG(sbuf.st_mode)) {
total_space_used += (int64_t)sbuf.st_size;
if (auto_delete_rolled_files && LogFile::rolled_logfile(entry->d_name)) {
//
// then check if the candidate belongs to any given log type
//
ts::TextView type_name(entry->d_name, strlen(entry->d_name));
auto suffix = type_name;
type_name.remove_suffix(suffix.remove_prefix(suffix.find('.') + 1).remove_prefix(suffix.find('.')).size());
auto iter = deleting_info.find(type_name);
if (iter == deleting_info.end()) {
// We won't delete the log if its name doesn't match any give type.
break;
}
auto &candidates = iter->candidates;
candidates.push_back(LogDeleteCandidate(path, (int64_t)sbuf.st_size, sbuf.st_mtime));
candidate_count++;
}
}
}
::closedir(ld);
//
// Now check the partition to see if there is enough *actual* space.
//
partition_space_left = m_partition_space_left;
struct statvfs fs;
if (::statvfs(logfile_dir, &fs) >= 0) {
partition_space_left = (int64_t)fs.f_bavail * (int64_t)fs.f_bsize;
}
//
// Update the config variables for space used/left
//
m_space_used = total_space_used;
m_partition_space_left = partition_space_left;
RecSetRawStatSum(log_rsb, log_stat_log_files_space_used_stat, m_space_used);
RecSetRawStatCount(log_rsb, log_stat_log_files_space_used_stat, 1);
Debug("logspace", "%" PRId64 " bytes being used for logs", m_space_used);
Debug("logspace", "%" PRId64 " bytes left on partition", m_partition_space_left);
//
// Now that we have an accurate picture of the amount of space being
// used by logging, we can see if we're running low on space. If so,
// we might consider deleting some files that are stored in the
// candidate array.
//
// To delete oldest files first, we'll sort our candidate array by
// timestamps, making the oldest files first in the array (thus first
// selected).
//
int64_t max_space = (int64_t)get_max_space_mb() * LOG_MEGABYTE;
int64_t headroom = (int64_t)max_space_mb_headroom * LOG_MEGABYTE;
if (candidate_count > 0 && !space_to_write(headroom)) {
Debug("logspace", "headroom reached, trying to clear space ...");
Debug("logspace", "sorting %d delete candidates ...", candidate_count);
deleting_info.apply([](LogDeletingInfo &info) {
std::sort(info.candidates.begin(), info.candidates.end(),
[](LogDeleteCandidate const &a, LogDeleteCandidate const &b) { return a.mtime > b.mtime; });
});
while (candidate_count > 0) {
if (space_to_write(headroom + log_buffer_size)) {
Debug("logspace", "low water mark reached; stop deleting");
break;
}
// Select the group with biggest ratio
auto target =
std::max_element(deleting_info.begin(), deleting_info.end(), [](LogDeletingInfo const &A, LogDeletingInfo const &B) {
double diff =
static_cast<double>(A.candidates.size()) / A.min_count - static_cast<double>(B.candidates.size()) / B.min_count;
return diff < 0.0;
});
auto &candidates = target->candidates;
// Check if any candidate exists
if (candidates.empty()) {
// This shouldn't be triggered unless min_count are configured wrong or extra non-log files occupy the directory
Debug("logspace", "No more victims for log type %s. Check your rolling_min_count settings and logging directory.",
target->name.c_str());
} else {
auto &victim = candidates.back();
Debug("logspace", "auto-deleting %s", victim.name.c_str());
if (unlink(victim.name.c_str()) < 0) {
Note("Traffic Server was Unable to auto-delete rolled "
"logfile %s: %s.",
victim.name.c_str(), strerror(errno));
} else {
Debug("logspace",
"The rolled logfile, %s, was auto-deleted; "
"%" PRId64 " bytes were reclaimed.",
victim.name.c_str(), victim.size);
// Update after successful unlink;
m_space_used -= victim.size;
m_partition_space_left += victim.size;
}
// Update total candidates and remove victim
--candidate_count;
candidates.pop_back();
}
}
}
//
// Clean up the candidate array
//
deleting_info.apply([](LogDeletingInfo &info) { info.clear(); });
//
// Now that we've updated the m_space_used value, see if we need to
// issue any alarms or warnings about space
//
if (!space_to_write(headroom)) {
if (!logging_space_exhausted) {
Note("Logging space exhausted, any logs writing to local disk will be dropped!");
}
logging_space_exhausted = true;
//
// Despite our best efforts, we still can't write to the disk.
// Find out why and set/clear warnings.
//
// First, are we out of space based on configuration?
//
if (m_space_used >= max_space) {
if (!m_disk_full) {
m_disk_full = true;
LogUtils::manager_alarm(LogUtils::LOG_ALARM_ERROR, DISK_IS_CONFIG_FULL_MESSAGE);
Warning(DISK_IS_CONFIG_FULL_MESSAGE);
}
}
//
// How about out of actual space on the partition?
//
else if (m_partition_space_left <= 0) {
if (!m_partition_full) {
m_partition_full = true;
LogUtils::manager_alarm(LogUtils::LOG_ALARM_ERROR, DISK_IS_ACTUAL_FULL_MESSAGE);
Warning(DISK_IS_ACTUAL_FULL_MESSAGE);
}
}
//
// How about being within the headroom limit?
//
else if (m_space_used + headroom >= max_space) {
if (!m_disk_low) {
m_disk_low = true;
LogUtils::manager_alarm(LogUtils::LOG_ALARM_ERROR, DISK_IS_CONFIG_LOW_MESSAGE);
Warning(DISK_IS_CONFIG_LOW_MESSAGE);
}
} else {
if (!m_partition_low) {
m_partition_low = true;
LogUtils::manager_alarm(LogUtils::LOG_ALARM_ERROR, DISK_IS_ACTUAL_LOW_MESSAGE);
Warning(DISK_IS_ACTUAL_LOW_MESSAGE);
}
}
} else {
//
// We have enough space to log again; clear any previous messages
//
if (logging_space_exhausted) {
Note("Logging space is no longer exhausted.");
}
logging_space_exhausted = false;
if (m_disk_full || m_partition_full) {
Note("Logging disk is no longer full; access logging to local log directory resumed.");
m_disk_full = false;
m_partition_full = false;
}
if (m_disk_low || m_partition_low) {
Note("Logging disk is no longer low; access logging to local log directory resumed.");
m_disk_low = false;
m_partition_low = false;
}
}
}
bool
LogConfig::evaluate_config()
{
ats_scoped_str path(RecConfigReadConfigPath("proxy.config.log.config.filename", "logging.yaml"));
struct stat sbuf;
if (stat(path.get(), &sbuf) == -1 && errno == ENOENT) {
Warning("logging configuration '%s' doesn't exist", path.get());
return false;
}
Note("loading logging.yaml");
YamlLogConfig y(this);
bool zret = y.parse(path.get());
if (zret) {
Note("logging.yaml done reloading!");
} else {
Note("failed to reload logging.yaml");
}
return zret;
}
Remove unnecessary print
/** @file
This file implements the LogConfig object.
@section license License
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 "tscore/ink_platform.h"
#include "tscore/I_Layout.h"
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#include <memory>
#include "tscore/ink_platform.h"
#include "tscore/ink_file.h"
#include "tscore/List.h"
#include "Log.h"
#include "LogField.h"
#include "LogFilter.h"
#include "LogFormat.h"
#include "LogFile.h"
#include "LogBuffer.h"
#include "LogHost.h"
#include "LogObject.h"
#include "LogConfig.h"
#include "LogUtils.h"
#include "tscore/SimpleTokenizer.h"
#include "LogCollationAccept.h"
#include "YamlLogConfig.h"
#define DISK_IS_CONFIG_FULL_MESSAGE \
"Access logging to local log directory suspended - " \
"configured space allocation exhausted."
#define DISK_IS_ACTUAL_FULL_MESSAGE \
"Access logging to local log directory suspended - " \
"no more space on the logging partition."
#define DISK_IS_CONFIG_LOW_MESSAGE \
"Access logging to local log directory suspended - " \
"configured space allocation almost exhausted."
#define DISK_IS_ACTUAL_LOW_MESSAGE "Access logging to local log directory suspended - partition space is low."
#define PARTITION_HEADROOM_MB 10
#define DIAGS_LOG_FILENAME "diags.log"
void
LogConfig::setup_default_values()
{
const unsigned int bufSize = 512;
char name[bufSize];
if (!gethostname(name, bufSize)) {
ink_strlcpy(name, "unknown_host_name", sizeof(name));
}
hostname = ats_strdup(name);
log_buffer_size = (int)(10 * LOG_KILOBYTE);
max_secs_per_buffer = 5;
max_space_mb_for_logs = 100;
max_space_mb_for_orphan_logs = 25;
max_space_mb_headroom = 10;
logfile_perm = 0644;
logfile_dir = ats_strdup(".");
collation_mode = Log::NO_COLLATION;
collation_host = ats_strdup("none");
collation_port = 0;
collation_host_tagged = false;
collation_preproc_threads = 1;
collation_secret = ats_strdup("foobar");
collation_retry_sec = 0;
collation_max_send_buffers = 0;
rolling_enabled = Log::NO_ROLLING;
rolling_interval_sec = 86400; // 24 hours
rolling_offset_hr = 0;
rolling_size_mb = 10;
auto_delete_rolled_files = true;
roll_log_files_now = false;
sampling_frequency = 1;
file_stat_frequency = 16;
space_used_frequency = 900;
use_orphan_log_space_value = false;
ascii_buffer_size = 4 * 9216;
max_line_size = 9216; // size of pipe buffer for SunOS 5.6
}
void *
LogConfig::reconfigure_mgmt_variables(void * /* token ATS_UNUSED */, char * /* data_raw ATS_UNUSED */,
int /* data_len ATS_UNUSED */)
{
Note("received log reconfiguration event, rolling now");
Log::config->roll_log_files_now = true;
return nullptr;
}
void
LogConfig::read_configuration_variables()
{
int val;
char *ptr;
val = (int)REC_ConfigReadInteger("proxy.config.log.log_buffer_size");
if (val > 0) {
log_buffer_size = val;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.max_secs_per_buffer");
if (val > 0) {
max_secs_per_buffer = val;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.max_space_mb_for_logs");
if (val > 0) {
max_space_mb_for_logs = val;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.max_space_mb_for_orphan_logs");
if (val > 0) {
max_space_mb_for_orphan_logs = val;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.max_space_mb_headroom");
if (val > 0) {
max_space_mb_headroom = val;
}
ptr = REC_ConfigReadString("proxy.config.log.logfile_perm");
int logfile_perm_parsed = ink_fileperm_parse(ptr);
if (logfile_perm_parsed != -1) {
logfile_perm = logfile_perm_parsed;
}
ats_free(ptr);
ptr = REC_ConfigReadString("proxy.config.log.hostname");
if (ptr != nullptr) {
ats_free(hostname);
hostname = ptr;
}
ats_free(logfile_dir);
logfile_dir = ats_stringdup(RecConfigReadLogDir());
if (access(logfile_dir, R_OK | W_OK | X_OK) == -1) {
// Try 'system_root_dir/var/log/trafficserver' directory
fprintf(stderr, "unable to access log directory '%s': %d, %s\n", logfile_dir, errno, strerror(errno));
fprintf(stderr, "please set 'proxy.config.log.logfile_dir'\n");
::exit(1);
}
// COLLATION
val = (int)REC_ConfigReadInteger("proxy.local.log.collation_mode");
// do not restrict value so that error message is logged if
// collation_mode is out of range
collation_mode = val;
ptr = REC_ConfigReadString("proxy.config.log.collation_host");
if (ptr != nullptr) {
ats_free(collation_host);
collation_host = ptr;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.collation_port");
if (val >= 0) {
collation_port = val;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.collation_host_tagged");
collation_host_tagged = (val > 0);
val = (int)REC_ConfigReadInteger("proxy.config.log.collation_preproc_threads");
if (val > 0 && val <= 128) {
collation_preproc_threads = val;
}
ptr = REC_ConfigReadString("proxy.config.log.collation_secret");
if (ptr != nullptr) {
ats_free(collation_secret);
collation_secret = ptr;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.collation_retry_sec");
if (val >= 0) {
collation_retry_sec = val;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.collation_max_send_buffers");
if (val >= 0) {
collation_max_send_buffers = val;
}
// ROLLING
// we don't check for valid values of rolling_enabled, rolling_interval_sec,
// rolling_offset_hr, or rolling_size_mb because the LogObject takes care of this
//
rolling_interval_sec = (int)REC_ConfigReadInteger("proxy.config.log.rolling_interval_sec");
rolling_offset_hr = (int)REC_ConfigReadInteger("proxy.config.log.rolling_offset_hr");
rolling_size_mb = (int)REC_ConfigReadInteger("proxy.config.log.rolling_size_mb");
rolling_min_count = (int)REC_ConfigReadInteger("proxy.config.log.rolling_min_count");
val = (int)REC_ConfigReadInteger("proxy.config.log.rolling_enabled");
if (LogRollingEnabledIsValid(val)) {
rolling_enabled = (Log::RollingEnabledValues)val;
} else {
Warning("invalid value '%d' for '%s', disabling log rolling", val, "proxy.config.log.rolling_enabled");
rolling_enabled = Log::NO_ROLLING;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.auto_delete_rolled_files");
auto_delete_rolled_files = (val > 0);
// Read in min_count control values for auto deletion
if (auto_delete_rolled_files) {
// For diagnostic logs
val = (int)REC_ConfigReadInteger("proxy.config.diags.logfile.rolling_min_count");
val = ((val == 0) ? INT_MAX : val);
deleting_info.insert(new LogDeletingInfo(DIAGS_LOG_FILENAME, val));
// For traffic.out
ats_scoped_str name(REC_ConfigReadString("proxy.config.output.logfile"));
val = (int)REC_ConfigReadInteger("proxy.config.output.logfile.rolling_min_count");
val = ((val == 0) ? INT_MAX : val);
if (name) {
deleting_info.insert(new LogDeletingInfo(name.get(), val));
} else {
deleting_info.insert(new LogDeletingInfo("traffic.out", val));
}
}
// PERFORMANCE
val = (int)REC_ConfigReadInteger("proxy.config.log.sampling_frequency");
if (val > 0) {
sampling_frequency = val;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.file_stat_frequency");
if (val > 0) {
file_stat_frequency = val;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.space_used_frequency");
if (val > 0) {
space_used_frequency = val;
}
// ASCII BUFFER
val = (int)REC_ConfigReadInteger("proxy.config.log.ascii_buffer_size");
if (val > 0) {
ascii_buffer_size = val;
}
val = (int)REC_ConfigReadInteger("proxy.config.log.max_line_size");
if (val > 0) {
max_line_size = val;
}
}
/*-------------------------------------------------------------------------
LogConfig::LogConfig
Read the logging configuration variables from the config file and
initialize the LogConfig member variables. Assign some meaningful
default value if we get garbage back from the config file.
-------------------------------------------------------------------------*/
// TODO: Is UINT_MAX here really correct?
LogConfig::LogConfig()
: initialized(false),
reconfiguration_needed(false),
logging_space_exhausted(false),
m_space_used(0),
m_partition_space_left((int64_t)UINT_MAX),
m_log_collation_accept(nullptr),
m_disk_full(false),
m_disk_low(false),
m_partition_full(false),
m_partition_low(false),
m_log_directory_inaccessible(false)
{
// Setup the default values for all LogConfig public variables so that
// a LogConfig object is valid upon return from the constructor even
// if no configuration file is read
//
setup_default_values();
}
/*-------------------------------------------------------------------------
LogConfig::~LogConfig
Delete all config variable strings.
-------------------------------------------------------------------------*/
LogConfig::~LogConfig()
{
// we don't delete the log collation accept because it may be transferred
// to another LogConfig object
//
// delete m_log_collation_accept;
ats_free(hostname);
ats_free(logfile_dir);
ats_free(collation_host);
ats_free(collation_secret);
}
/*-------------------------------------------------------------------------
LogConfig::setup_collation
-------------------------------------------------------------------------*/
void
LogConfig::setup_collation(LogConfig *prev_config)
{
// Set-up the collation status, but only if collation is enabled and
// there are valid entries for the collation host and port.
//
if (collation_mode < Log::NO_COLLATION || collation_mode >= Log::N_COLLATION_MODES) {
Note("Invalid value %d for proxy.local.log.collation_mode"
" configuration variable (valid range is from %d to %d)\n"
"Log collation disabled",
collation_mode, Log::NO_COLLATION, Log::N_COLLATION_MODES - 1);
} else if (collation_mode == Log::NO_COLLATION) {
// if the previous configuration had a collation accept, delete it
//
if (prev_config && prev_config->m_log_collation_accept) {
delete prev_config->m_log_collation_accept;
prev_config->m_log_collation_accept = nullptr;
}
} else {
Warning("Log collation is deprecated as of ATS v8.0.0!");
if (!collation_port) {
Note("Cannot activate log collation, %d is an invalid collation port", collation_port);
} else if (collation_mode > Log::COLLATION_HOST && strcmp(collation_host, "none") == 0) {
Note("Cannot activate log collation, \"%s\" is an invalid collation host", collation_host);
} else {
if (collation_mode == Log::COLLATION_HOST) {
ink_assert(m_log_collation_accept == nullptr);
if (prev_config && prev_config->m_log_collation_accept) {
if (prev_config->collation_port == collation_port) {
m_log_collation_accept = prev_config->m_log_collation_accept;
} else {
delete prev_config->m_log_collation_accept;
}
}
if (!m_log_collation_accept) {
Log::collation_port = collation_port;
m_log_collation_accept = new LogCollationAccept(collation_port);
}
Debug("log", "I am a collation host listening on port %d.", collation_port);
} else {
Debug("log",
"I am a collation client (%d)."
" My collation host is %s:%d",
collation_mode, collation_host, collation_port);
}
Debug("log", "using iocore log collation");
if (collation_host_tagged) {
LogFormat::turn_tagging_on();
} else {
LogFormat::turn_tagging_off();
}
}
}
}
/*-------------------------------------------------------------------------
LogConfig::init
-------------------------------------------------------------------------*/
void
LogConfig::init(LogConfig *prev_config)
{
LogObject *errlog = nullptr;
ink_assert(!initialized);
setup_collation(prev_config);
update_space_used();
// create log objects
//
if (Log::transaction_logging_enabled()) {
setup_log_objects();
}
// ----------------------------------------------------------------------
// Construct a new error log object candidate.
if (Log::error_logging_enabled()) {
std::unique_ptr<LogFormat> fmt(MakeTextLogFormat("error"));
Debug("log", "creating predefined error log object");
errlog = new LogObject(fmt.get(), logfile_dir, "error.log", LOG_FILE_ASCII, nullptr, (Log::RollingEnabledValues)rolling_enabled,
collation_preproc_threads, rolling_interval_sec, rolling_offset_hr, rolling_size_mb);
log_object_manager.manage_object(errlog);
errlog->set_fmt_timestamps();
} else {
Log::error_log = nullptr;
}
if (prev_config) {
// Transfer objects from previous configuration.
transfer_objects(prev_config);
// After transferring objects, we are going to keep either the new error log or the old one. Figure out
// which one we are keeping and make that the global ...
if (Log::error_log) {
errlog = this->log_object_manager.find_by_format_name(Log::error_log->m_format->name());
}
}
ink_atomic_swap(&Log::error_log, errlog);
// determine if we should use the orphan log space value or not
// we use it if all objects are collation clients, or if some are and
// the specified space for collation is larger than that for local files
//
size_t num_collation_clients = log_object_manager.get_num_collation_clients();
use_orphan_log_space_value = (num_collation_clients == 0 ? false :
(log_object_manager.get_num_objects() == num_collation_clients ?
true :
max_space_mb_for_orphan_logs > max_space_mb_for_logs));
initialized = true;
}
/*-------------------------------------------------------------------------
LogConfig::display
Dump the values for the current LogConfig object.
-------------------------------------------------------------------------*/
void
LogConfig::display(FILE *fd)
{
fprintf(fd, "-----------------------------\n");
fprintf(fd, "--- Logging Configuration ---\n");
fprintf(fd, "-----------------------------\n");
fprintf(fd, "Config variables:\n");
fprintf(fd, " log_buffer_size = %d\n", log_buffer_size);
fprintf(fd, " max_secs_per_buffer = %d\n", max_secs_per_buffer);
fprintf(fd, " max_space_mb_for_logs = %d\n", max_space_mb_for_logs);
fprintf(fd, " max_space_mb_for_orphan_logs = %d\n", max_space_mb_for_orphan_logs);
fprintf(fd, " use_orphan_log_space_value = %d\n", use_orphan_log_space_value);
fprintf(fd, " max_space_mb_headroom = %d\n", max_space_mb_headroom);
fprintf(fd, " hostname = %s\n", hostname);
fprintf(fd, " logfile_dir = %s\n", logfile_dir);
fprintf(fd, " logfile_perm = 0%o\n", logfile_perm);
fprintf(fd, " collation_mode = %d\n", collation_mode);
fprintf(fd, " collation_host = %s\n", collation_host);
fprintf(fd, " collation_port = %d\n", collation_port);
fprintf(fd, " collation_host_tagged = %d\n", collation_host_tagged);
fprintf(fd, " collation_preproc_threads = %d\n", collation_preproc_threads);
fprintf(fd, " collation_secret = %s\n", collation_secret);
fprintf(fd, " rolling_enabled = %d\n", rolling_enabled);
fprintf(fd, " rolling_interval_sec = %d\n", rolling_interval_sec);
fprintf(fd, " rolling_offset_hr = %d\n", rolling_offset_hr);
fprintf(fd, " rolling_size_mb = %d\n", rolling_size_mb);
fprintf(fd, " auto_delete_rolled_files = %d\n", auto_delete_rolled_files);
fprintf(fd, " sampling_frequency = %d\n", sampling_frequency);
fprintf(fd, " file_stat_frequency = %d\n", file_stat_frequency);
fprintf(fd, " space_used_frequency = %d\n", space_used_frequency);
fprintf(fd, "\n");
fprintf(fd, "************ Log Objects (%u objects) ************\n", (unsigned int)log_object_manager.get_num_objects());
log_object_manager.display(fd);
fprintf(fd, "************ Filter List (%u filters) ************\n", filter_list.count());
filter_list.display(fd);
fprintf(fd, "************ Format List (%u formats) ************\n", format_list.count());
format_list.display(fd);
}
//-----------------------------------------------------------------------------
// setup_log_objects
//
// Construct: All custom objects.
//
// Upon return from this function:
// - global_object_list has the aforementioned objects
// - global_filter_list has all custom filters
//
void
LogConfig::setup_log_objects()
{
Debug("log", "creating objects...");
filter_list.clear();
// Evaluate logging.yaml to construct the custom log objects.
evaluate_config();
// Open local pipes so readers can see them.
log_object_manager.open_local_pipes();
if (is_debug_tag_set("log")) {
log_object_manager.display();
}
}
/*-------------------------------------------------------------------------
LogConfig::reconfigure
This is the manager callback for any logging config variable change.
Since we want to access the config variables to build a new config
object, but can't from this function (big lock technology in the
manager), we'll just set a flag and call the real reconfiguration
function from the logging thread.
-------------------------------------------------------------------------*/
int
LogConfig::reconfigure(const char * /* name ATS_UNUSED */, RecDataT /* data_type ATS_UNUSED */, RecData /* data ATS_UNUSED */,
void * /* cookie ATS_UNUSED */)
{
Debug("log-config", "Reconfiguration request accepted");
Log::config->reconfiguration_needed = true;
return 0;
}
/*-------------------------------------------------------------------------
LogConfig::register_config_callbacks
This static function is called by Log::init to register the config update
function for each of the logging configuration variables.
-------------------------------------------------------------------------*/
void
LogConfig::register_config_callbacks()
{
static const char *names[] = {
"proxy.config.log.log_buffer_size",
"proxy.config.log.max_secs_per_buffer",
"proxy.config.log.max_space_mb_for_logs",
"proxy.config.log.max_space_mb_for_orphan_logs",
"proxy.config.log.max_space_mb_headroom",
"proxy.config.log.logfile_perm",
"proxy.config.log.hostname",
"proxy.config.log.logfile_dir",
"proxy.local.log.collation_mode",
"proxy.config.log.collation_host",
"proxy.config.log.collation_port",
"proxy.config.log.collation_host_tagged",
"proxy.config.log.collation_secret",
"proxy.config.log.collation_retry_sec",
"proxy.config.log.collation_max_send_buffers",
"proxy.config.log.rolling_enabled",
"proxy.config.log.rolling_interval_sec",
"proxy.config.log.rolling_offset_hr",
"proxy.config.log.rolling_size_mb",
"proxy.config.log.auto_delete_rolled_files",
"proxy.config.log.config.filename",
"proxy.config.log.sampling_frequency",
"proxy.config.log.file_stat_frequency",
"proxy.config.log.space_used_frequency",
};
for (unsigned i = 0; i < countof(names); ++i) {
REC_RegisterConfigUpdateFunc(names[i], &LogConfig::reconfigure, nullptr);
}
}
/*-------------------------------------------------------------------------
LogConfig::register_stat_callbacks
This static function is called by Log::init to register the stat update
function for each of the logging stats variables.
-------------------------------------------------------------------------*/
void
LogConfig::register_stat_callbacks()
{
//
// events
//
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.event_log_error_ok", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_event_log_error_ok_stat, RecRawStatSyncCount);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.event_log_error_skip", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_event_log_error_skip_stat, RecRawStatSyncCount);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.event_log_error_aggr", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_event_log_error_aggr_stat, RecRawStatSyncCount);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.event_log_error_full", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_event_log_error_full_stat, RecRawStatSyncCount);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.event_log_error_fail", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_event_log_error_fail_stat, RecRawStatSyncCount);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.event_log_access_ok", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_event_log_access_ok_stat, RecRawStatSyncCount);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.event_log_access_skip", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_event_log_access_skip_stat, RecRawStatSyncCount);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.event_log_access_aggr", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_event_log_access_aggr_stat, RecRawStatSyncCount);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.event_log_access_full", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_event_log_access_full_stat, RecRawStatSyncCount);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.event_log_access_fail", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_event_log_access_fail_stat, RecRawStatSyncCount);
//
// number vs bytes of logs
//
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.num_sent_to_network", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_num_sent_to_network_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.num_lost_before_sent_to_network", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_num_lost_before_sent_to_network_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.num_received_from_network", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_num_received_from_network_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.num_flush_to_disk", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_num_flush_to_disk_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.num_lost_before_flush_to_disk", RECD_COUNTER, RECP_PERSISTENT,
(int)log_stat_num_lost_before_flush_to_disk_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.bytes_lost_before_preproc", RECD_INT, RECP_PERSISTENT,
(int)log_stat_bytes_lost_before_preproc_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.bytes_sent_to_network", RECD_INT, RECP_PERSISTENT,
(int)log_stat_bytes_sent_to_network_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.bytes_lost_before_sent_to_network", RECD_INT, RECP_PERSISTENT,
(int)log_stat_bytes_lost_before_sent_to_network_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.bytes_received_from_network", RECD_INT, RECP_PERSISTENT,
(int)log_stat_bytes_received_from_network_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.bytes_flush_to_disk", RECD_INT, RECP_PERSISTENT,
(int)log_stat_bytes_flush_to_disk_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.bytes_lost_before_flush_to_disk", RECD_INT, RECP_PERSISTENT,
(int)log_stat_bytes_lost_before_flush_to_disk_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.bytes_written_to_disk", RECD_INT, RECP_PERSISTENT,
(int)log_stat_bytes_written_to_disk_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.bytes_lost_before_written_to_disk", RECD_INT, RECP_PERSISTENT,
(int)log_stat_bytes_lost_before_written_to_disk_stat, RecRawStatSyncSum);
//
// I/O
//
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.log_files_open", RECD_COUNTER, RECP_NON_PERSISTENT,
(int)log_stat_log_files_open_stat, RecRawStatSyncSum);
RecRegisterRawStat(log_rsb, RECT_PROCESS, "proxy.process.log.log_files_space_used", RECD_INT, RECP_NON_PERSISTENT,
(int)log_stat_log_files_space_used_stat, RecRawStatSyncSum);
}
/*-------------------------------------------------------------------------
LogConfig::register_mgmt_callbacks
This static function is called by Log::init to register the mgmt callback
function for each of the logging mgmt messages.
-------------------------------------------------------------------------*/
void
LogConfig::register_mgmt_callbacks()
{
RecRegisterManagerCb(REC_EVENT_ROLL_LOG_FILES, &LogConfig::reconfigure_mgmt_variables, nullptr);
}
/*-------------------------------------------------------------------------
LogConfig::space_to_write
This function returns true if there is enough disk space to write the
given number of bytes, false otherwise.
-------------------------------------------------------------------------*/
bool
LogConfig::space_to_write(int64_t bytes_to_write) const
{
int64_t config_space, partition_headroom;
int64_t logical_space_used, physical_space_left;
bool space;
config_space = (int64_t)get_max_space_mb() * LOG_MEGABYTE;
partition_headroom = (int64_t)PARTITION_HEADROOM_MB * LOG_MEGABYTE;
logical_space_used = m_space_used + bytes_to_write;
physical_space_left = m_partition_space_left - (int64_t)bytes_to_write;
space = ((logical_space_used < config_space) && (physical_space_left > partition_headroom));
Debug("logspace",
"logical space used %" PRId64 ", configured space %" PRId64 ", physical space left %" PRId64 ", partition headroom %" PRId64
", space %s available",
logical_space_used, config_space, physical_space_left, partition_headroom, space ? "is" : "is not");
return space;
}
/*-------------------------------------------------------------------------
LogConfig::update_space_used
Update the m_space_used variable by reading the logging dir and counting
the total bytes being occupied by files. If we've used too much space
(space_used > max_space - headroom) then start deleting some files (if
auto_delete_rolled_files is set) to make room. Finally, update the
space_used stat.
This routine will only be executed SINGLE-THREADED, either by the main
thread when a LogConfig is initialized, or by the event thread during the
periodic space check.
-------------------------------------------------------------------------*/
void
LogConfig::update_space_used()
{
// no need to update space used if log directory is inaccessible
//
if (m_log_directory_inaccessible) {
return;
}
int candidate_count;
int64_t total_space_used, partition_space_left;
char path[MAXPATHLEN];
int sret;
struct dirent *entry;
struct stat sbuf;
DIR *ld;
// check if logging directory has been specified
//
if (!logfile_dir) {
const char *msg = "Logging directory not specified";
Error("%s", msg);
LogUtils::manager_alarm(LogUtils::LOG_ALARM_ERROR, "%s", msg);
m_log_directory_inaccessible = true;
return;
}
// check if logging directory exists and is searchable readable & writable
int err;
do {
err = access(logfile_dir, R_OK | W_OK | X_OK);
} while ((err < 0) && (errno == EINTR));
if (err < 0) {
const char *msg = "Error accessing logging directory %s: %s.";
Error(msg, logfile_dir, strerror(errno));
LogUtils::manager_alarm(LogUtils::LOG_ALARM_ERROR, msg, logfile_dir, strerror(errno));
m_log_directory_inaccessible = true;
return;
}
ld = ::opendir(logfile_dir);
if (ld == nullptr) {
const char *msg = "Error opening logging directory %s to perform a space check: %s.";
Error(msg, logfile_dir, strerror(errno));
LogUtils::manager_alarm(LogUtils::LOG_ALARM_ERROR, msg, logfile_dir, strerror(errno));
m_log_directory_inaccessible = true;
return;
}
total_space_used = 0LL;
candidate_count = 0;
while ((entry = readdir(ld))) {
snprintf(path, MAXPATHLEN, "%s/%s", logfile_dir, entry->d_name);
sret = ::stat(path, &sbuf);
if (sret != -1 && S_ISREG(sbuf.st_mode)) {
total_space_used += (int64_t)sbuf.st_size;
if (auto_delete_rolled_files && LogFile::rolled_logfile(entry->d_name)) {
//
// then check if the candidate belongs to any given log type
//
ts::TextView type_name(entry->d_name, strlen(entry->d_name));
auto suffix = type_name;
type_name.remove_suffix(suffix.remove_prefix(suffix.find('.') + 1).remove_prefix(suffix.find('.')).size());
auto iter = deleting_info.find(type_name);
if (iter == deleting_info.end()) {
// We won't delete the log if its name doesn't match any give type.
break;
}
auto &candidates = iter->candidates;
candidates.push_back(LogDeleteCandidate(path, (int64_t)sbuf.st_size, sbuf.st_mtime));
candidate_count++;
}
}
}
::closedir(ld);
//
// Now check the partition to see if there is enough *actual* space.
//
partition_space_left = m_partition_space_left;
struct statvfs fs;
if (::statvfs(logfile_dir, &fs) >= 0) {
partition_space_left = (int64_t)fs.f_bavail * (int64_t)fs.f_bsize;
}
//
// Update the config variables for space used/left
//
m_space_used = total_space_used;
m_partition_space_left = partition_space_left;
RecSetRawStatSum(log_rsb, log_stat_log_files_space_used_stat, m_space_used);
RecSetRawStatCount(log_rsb, log_stat_log_files_space_used_stat, 1);
Debug("logspace", "%" PRId64 " bytes being used for logs", m_space_used);
Debug("logspace", "%" PRId64 " bytes left on partition", m_partition_space_left);
//
// Now that we have an accurate picture of the amount of space being
// used by logging, we can see if we're running low on space. If so,
// we might consider deleting some files that are stored in the
// candidate array.
//
// To delete oldest files first, we'll sort our candidate array by
// timestamps, making the oldest files first in the array (thus first
// selected).
//
int64_t max_space = (int64_t)get_max_space_mb() * LOG_MEGABYTE;
int64_t headroom = (int64_t)max_space_mb_headroom * LOG_MEGABYTE;
if (candidate_count > 0 && !space_to_write(headroom)) {
Debug("logspace", "headroom reached, trying to clear space ...");
Debug("logspace", "sorting %d delete candidates ...", candidate_count);
deleting_info.apply([](LogDeletingInfo &info) {
std::sort(info.candidates.begin(), info.candidates.end(),
[](LogDeleteCandidate const &a, LogDeleteCandidate const &b) { return a.mtime > b.mtime; });
});
while (candidate_count > 0) {
if (space_to_write(headroom + log_buffer_size)) {
Debug("logspace", "low water mark reached; stop deleting");
break;
}
// Select the group with biggest ratio
auto target =
std::max_element(deleting_info.begin(), deleting_info.end(), [](LogDeletingInfo const &A, LogDeletingInfo const &B) {
double diff =
static_cast<double>(A.candidates.size()) / A.min_count - static_cast<double>(B.candidates.size()) / B.min_count;
return diff < 0.0;
});
auto &candidates = target->candidates;
// Check if any candidate exists
if (candidates.empty()) {
// This shouldn't be triggered unless min_count are configured wrong or extra non-log files occupy the directory
Debug("logspace", "No more victims for log type %s. Check your rolling_min_count settings and logging directory.",
target->name.c_str());
} else {
auto &victim = candidates.back();
Debug("logspace", "auto-deleting %s", victim.name.c_str());
if (unlink(victim.name.c_str()) < 0) {
Note("Traffic Server was Unable to auto-delete rolled "
"logfile %s: %s.",
victim.name.c_str(), strerror(errno));
} else {
Debug("logspace",
"The rolled logfile, %s, was auto-deleted; "
"%" PRId64 " bytes were reclaimed.",
victim.name.c_str(), victim.size);
// Update after successful unlink;
m_space_used -= victim.size;
m_partition_space_left += victim.size;
}
// Update total candidates and remove victim
--candidate_count;
candidates.pop_back();
}
}
}
//
// Clean up the candidate array
//
deleting_info.apply([](LogDeletingInfo &info) { info.clear(); });
//
// Now that we've updated the m_space_used value, see if we need to
// issue any alarms or warnings about space
//
if (!space_to_write(headroom)) {
if (!logging_space_exhausted) {
Note("Logging space exhausted, any logs writing to local disk will be dropped!");
}
logging_space_exhausted = true;
//
// Despite our best efforts, we still can't write to the disk.
// Find out why and set/clear warnings.
//
// First, are we out of space based on configuration?
//
if (m_space_used >= max_space) {
if (!m_disk_full) {
m_disk_full = true;
LogUtils::manager_alarm(LogUtils::LOG_ALARM_ERROR, DISK_IS_CONFIG_FULL_MESSAGE);
Warning(DISK_IS_CONFIG_FULL_MESSAGE);
}
}
//
// How about out of actual space on the partition?
//
else if (m_partition_space_left <= 0) {
if (!m_partition_full) {
m_partition_full = true;
LogUtils::manager_alarm(LogUtils::LOG_ALARM_ERROR, DISK_IS_ACTUAL_FULL_MESSAGE);
Warning(DISK_IS_ACTUAL_FULL_MESSAGE);
}
}
//
// How about being within the headroom limit?
//
else if (m_space_used + headroom >= max_space) {
if (!m_disk_low) {
m_disk_low = true;
LogUtils::manager_alarm(LogUtils::LOG_ALARM_ERROR, DISK_IS_CONFIG_LOW_MESSAGE);
Warning(DISK_IS_CONFIG_LOW_MESSAGE);
}
} else {
if (!m_partition_low) {
m_partition_low = true;
LogUtils::manager_alarm(LogUtils::LOG_ALARM_ERROR, DISK_IS_ACTUAL_LOW_MESSAGE);
Warning(DISK_IS_ACTUAL_LOW_MESSAGE);
}
}
} else {
//
// We have enough space to log again; clear any previous messages
//
if (logging_space_exhausted) {
Note("Logging space is no longer exhausted.");
}
logging_space_exhausted = false;
if (m_disk_full || m_partition_full) {
Note("Logging disk is no longer full; access logging to local log directory resumed.");
m_disk_full = false;
m_partition_full = false;
}
if (m_disk_low || m_partition_low) {
Note("Logging disk is no longer low; access logging to local log directory resumed.");
m_disk_low = false;
m_partition_low = false;
}
}
}
bool
LogConfig::evaluate_config()
{
ats_scoped_str path(RecConfigReadConfigPath("proxy.config.log.config.filename", "logging.yaml"));
struct stat sbuf;
if (stat(path.get(), &sbuf) == -1 && errno == ENOENT) {
Warning("logging configuration '%s' doesn't exist", path.get());
return false;
}
Note("loading logging.yaml");
YamlLogConfig y(this);
bool zret = y.parse(path.get());
if (zret) {
Note("logging.yaml done reloading!");
} else {
Note("failed to reload logging.yaml");
}
return zret;
}
|
/*
* Copyright (c) 2020 Samsung Electronics Co., Ltd.
*
* 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.
*/
// CLASS HEADER
#include <dali/internal/imaging/common/pixel-manipulation.h>
// INTERNAL HEADERS
#include <dali/public-api/images/pixel.h>
#include <dali/integration-api/debug.h>
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
struct Location
{
unsigned int bitShift;
unsigned int bitMask;
bool available;
};
struct Locations
{
Location luminance;
Location alpha;
Location red;
Location green;
Location blue;
};
bool HasChannel( Dali::Pixel::Format pixelFormat, Channel channel )
{
switch (pixelFormat)
{
case Dali::Pixel::A8:
{
return (channel == ALPHA);
}
case Dali::Pixel::L8:
{
return (channel == LUMINANCE);
}
case Dali::Pixel::LA88:
{
return ( channel == LUMINANCE || channel == ALPHA );
}
case Dali::Pixel::RGB565:
case Dali::Pixel::BGR565:
case Dali::Pixel::RGB888:
case Dali::Pixel::RGB8888:
case Dali::Pixel::BGR8888:
case Dali::Pixel::RGB16F:
case Dali::Pixel::RGB32F:
{
return ( channel == RED || channel == GREEN || channel == BLUE );
}
case Dali::Pixel::RGBA8888:
case Dali::Pixel::BGRA8888:
case Dali::Pixel::RGBA4444:
case Dali::Pixel::BGRA4444:
case Dali::Pixel::RGBA5551:
case Dali::Pixel::BGRA5551:
{
return ( channel == RED || channel == GREEN || channel == BLUE || channel == ALPHA );
}
case Dali::Pixel::DEPTH_UNSIGNED_INT:
case Dali::Pixel::DEPTH_FLOAT:
{
return ( channel == DEPTH );
}
case Dali::Pixel::DEPTH_STENCIL:
{
return ( channel == DEPTH || channel == STENCIL );
}
case Dali::Pixel::INVALID:
case Dali::Pixel::COMPRESSED_R11_EAC:
case Dali::Pixel::COMPRESSED_SIGNED_R11_EAC:
case Dali::Pixel::COMPRESSED_RG11_EAC:
case Dali::Pixel::COMPRESSED_SIGNED_RG11_EAC:
case Dali::Pixel::COMPRESSED_RGB8_ETC2:
case Dali::Pixel::COMPRESSED_SRGB8_ETC2:
case Dali::Pixel::COMPRESSED_RGB8_ETC1:
case Dali::Pixel::COMPRESSED_RGB_PVRTC_4BPPV1:
case Dali::Pixel::COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:
case Dali::Pixel::COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:
case Dali::Pixel::COMPRESSED_RGBA8_ETC2_EAC:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_4x4_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_5x4_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_5x5_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_6x5_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_6x6_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_8x5_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_8x6_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_8x8_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x5_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x6_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x8_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x10_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_12x10_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_12x12_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:
{
DALI_LOG_ERROR("Pixel formats for compressed images are not compatible with simple channels.\n");
break;
}
}
return false;
}
unsigned int ReadChannel( unsigned char* pixelData,
Dali::Pixel::Format pixelFormat,
Channel channel )
{
switch (pixelFormat)
{
case Dali::Pixel::A8:
{
if( channel == ALPHA )
{
return static_cast<unsigned int>(*pixelData);
}
else return 0u;
}
case Dali::Pixel::L8:
{
if( channel == LUMINANCE )
{
return static_cast<unsigned int>(*pixelData);
}
else return 0u;
}
case Dali::Pixel::LA88:
{
if( channel == LUMINANCE )
{
return static_cast<unsigned int>(*pixelData);
}
else if( channel == ALPHA )
{
return static_cast<unsigned int>(*(pixelData+1));
}
else return 0u;
}
case Dali::Pixel::RGB565:
{
if( channel == RED )
{
return (static_cast<unsigned int>(*pixelData) & 0xF8) >> 3;
}
else if( channel == GREEN )
{
return ((static_cast<unsigned int>(*pixelData) & 0x07) << 3) |
((static_cast<unsigned int>(*(pixelData+1)) & 0xE0) >> 5);
}
else if( channel == BLUE )
{
return static_cast<unsigned int>(*(pixelData+1)) & 0x1F;
}
else return 0u;
}
case Dali::Pixel::BGR565:
{
if( channel == BLUE )
{
return (static_cast<unsigned int>(*pixelData) & 0xF8) >> 3;
}
else if( channel == GREEN )
{
return ((static_cast<unsigned int>(*pixelData) & 0x07) << 3) |
((static_cast<unsigned int>(*(pixelData+1)) & 0xE0) >> 5);
}
else if( channel == RED )
{
return (static_cast<unsigned int>(*(pixelData+1) & 0x1F) );
}
else return 0u;
}
case Dali::Pixel::RGB888:
case Dali::Pixel::RGB8888:
{
if( channel == RED )
{
return static_cast<unsigned int>(*pixelData);
}
else if( channel == GREEN )
{
return static_cast<unsigned int>(*(pixelData+1));
}
else if( channel == BLUE )
{
return static_cast<unsigned int>(*(pixelData+2));
}
else return 0u;
}
case Dali::Pixel::BGR8888:
{
if( channel == BLUE )
{
return static_cast<unsigned int>(*pixelData);
}
else if( channel == GREEN )
{
return static_cast<unsigned int>(*(pixelData+1));
}
else if( channel == RED )
{
return static_cast<unsigned int>(*(pixelData+2));
}
else return 0u;
}
case Dali::Pixel::RGBA8888:
{
if( channel == RED )
{
return static_cast<unsigned int>(*pixelData);
}
else if( channel == GREEN )
{
return static_cast<unsigned int>(*(pixelData+1));
}
else if( channel == BLUE )
{
return static_cast<unsigned int>(*(pixelData+2));
}
else if( channel == ALPHA )
{
return static_cast<unsigned int>(*(pixelData+3));
}
else return 0u;
}
case Dali::Pixel::BGRA8888:
{
if( channel == BLUE )
{
return static_cast<unsigned int>(*pixelData);
}
else if( channel == GREEN )
{
return static_cast<unsigned int>(*(pixelData+1));
}
else if( channel == RED )
{
return static_cast<unsigned int>(*(pixelData+2));
}
else if( channel == ALPHA )
{
return static_cast<unsigned int>(*(pixelData+3));
}
else return 0u;
}
case Dali::Pixel::RGBA4444:
{
if( channel == RED )
{
return (static_cast<unsigned int>(*pixelData) & 0xF0) >> 4;
}
else if( channel == GREEN )
{
return (static_cast<unsigned int>(*pixelData) & 0x0F);
}
else if( channel == BLUE )
{
return (static_cast<unsigned int>(*(pixelData+1)) & 0xF0) >> 4;
}
else if( channel == ALPHA )
{
return (static_cast<unsigned int>(*(pixelData+1)) & 0x0F);
}
else return 0u;
}
case Dali::Pixel::BGRA4444:
{
if( channel == BLUE )
{
return (static_cast<unsigned int>(*pixelData) & 0xF0) >> 4;
}
else if( channel == GREEN )
{
return (static_cast<unsigned int>(*pixelData) & 0x0F);
}
else if( channel == RED )
{
return (static_cast<unsigned int>(*(pixelData+1)) & 0xF0) >> 4;
}
else if( channel == ALPHA )
{
return (static_cast<unsigned int>(*(pixelData+1)) & 0x0F);
}
else return 0u;
}
case Dali::Pixel::RGBA5551:
{
if( channel == RED )
{
return (static_cast<unsigned int>(*pixelData) & 0xF8) >> 3;
}
else if( channel == GREEN )
{
return ((static_cast<unsigned int>(*pixelData) & 0x07) << 2) |
((static_cast<unsigned int>(*(pixelData+1)) & 0xC0) >> 6);
}
else if( channel == BLUE )
{
return (static_cast<unsigned int>(*(pixelData+1)) & 0x3E) >> 1;
}
else if( channel == ALPHA )
{
return static_cast<unsigned int>(*(pixelData+1)) & 0x01;
}
else return 0u;
}
case Dali::Pixel::BGRA5551:
{
if( channel == BLUE )
{
return (static_cast<unsigned int>(*pixelData) & 0xF8) >> 3;
}
else if( channel == GREEN )
{
return ((static_cast<unsigned int>(*pixelData) & 0x07) << 2) |
((static_cast<unsigned int>(*(pixelData+1)) & 0xC0) >> 6);
}
else if( channel == RED )
{
return ( static_cast<unsigned int>(*(pixelData+1)) & 0x3E) >> 1;
}
else if( channel == ALPHA )
{
return static_cast<unsigned int>(*(pixelData+1)) & 0x01;
}
else return 0u;
}
case Dali::Pixel::DEPTH_UNSIGNED_INT:
case Dali::Pixel::DEPTH_FLOAT:
case Dali::Pixel::DEPTH_STENCIL:
{
return 0u;
}
default:
{
return 0u;
}
}
}
void WriteChannel( unsigned char* pixelData,
Dali::Pixel::Format pixelFormat,
Channel channel,
unsigned int channelValue )
{
switch (pixelFormat)
{
case Dali::Pixel::A8:
{
if( channel == ALPHA )
{
*pixelData = static_cast<unsigned char>( channelValue & 0xFF );
}
break;
}
case Dali::Pixel::L8:
{
if( channel == LUMINANCE )
{
*pixelData = static_cast<unsigned char>( channelValue & 0xFF );
}
break;
}
case Dali::Pixel::LA88:
{
if( channel == LUMINANCE )
{
*pixelData = static_cast<unsigned char>( channelValue & 0xFF );
}
else if( channel == ALPHA )
{
*(pixelData+1) = static_cast<unsigned char>( channelValue & 0xFF );
}
break;
}
case Dali::Pixel::RGB565:
{
if( channel == RED )
{
*pixelData &= static_cast<unsigned char>( ~0xF8 );
*pixelData |= static_cast<unsigned char>( (channelValue << 3) & 0xF8 );
}
else if( channel == GREEN )
{
*pixelData &= static_cast<unsigned char>( ~0x07 );
*pixelData |= static_cast<unsigned char>( (channelValue >> 3) & 0x07 );
*(pixelData+1) &= static_cast<unsigned char>( ~0xE0 );
*(pixelData+1) |= static_cast<unsigned char>( (channelValue << 5) & 0xE0 );
}
else if( channel == BLUE )
{
*(pixelData+1) &= static_cast<unsigned char>( ~0x1F );
*(pixelData+1) |= static_cast<unsigned char>( channelValue & 0x1F );
}
break;
}
case Dali::Pixel::BGR565:
{
if( channel == BLUE )
{
*pixelData &= static_cast<unsigned char>( ~0xF8 );
*pixelData |= static_cast<unsigned char>( (channelValue << 3) & 0xF8 );
}
else if( channel == GREEN )
{
*pixelData &= static_cast<unsigned char>( ~0x07 );
*pixelData |= static_cast<unsigned char>( (channelValue >> 3) & 0x07 );
*(pixelData+1) &= static_cast<unsigned char>( ~0xE0 );
*(pixelData+1) |= static_cast<unsigned char>( (channelValue << 5) & 0xE0 );
}
else if( channel == RED )
{
*(pixelData+1) &= static_cast<unsigned char>( ~0x1F );
*(pixelData+1) |= static_cast<unsigned char>( channelValue & 0x1F );
}
break;
}
case Dali::Pixel::RGB888:
case Dali::Pixel::RGB8888:
{
if( channel == RED )
{
*pixelData = static_cast<unsigned char>( channelValue & 0xFF );
}
else if( channel == GREEN )
{
*(pixelData+1) = static_cast<unsigned char>( channelValue & 0xFF );
}
else if( channel == BLUE )
{
*(pixelData+2) = static_cast<unsigned char>( channelValue & 0xFF );
}
break;
}
case Dali::Pixel::BGR8888:
{
if( channel == BLUE )
{
*pixelData = static_cast<unsigned char>( channelValue & 0xFF );
}
else if( channel == GREEN )
{
*(pixelData+1) = static_cast<unsigned char>( channelValue & 0xFF );
}
else if( channel == RED )
{
*(pixelData+2) = static_cast<unsigned char>( channelValue & 0xFF );
}
break;
}
case Dali::Pixel::RGBA8888:
{
if( channel == RED )
{
*pixelData = static_cast<unsigned char>( channelValue & 0xFF );
}
else if( channel == GREEN )
{
*(pixelData+1) = static_cast<unsigned char>( channelValue & 0xFF );
}
else if( channel == BLUE )
{
*(pixelData+2) = static_cast<unsigned char>( channelValue & 0xFF );
}
else if( channel == ALPHA )
{
*(pixelData+3) = static_cast<unsigned char>( channelValue & 0xFF );
}
break;
}
case Dali::Pixel::BGRA8888:
{
if( channel == BLUE )
{
*pixelData = static_cast<unsigned char>( channelValue & 0xFF );
}
else if( channel == GREEN )
{
*(pixelData+1) = static_cast<unsigned char>( channelValue & 0xFF );
}
else if( channel == RED )
{
*(pixelData+2) = static_cast<unsigned char>( channelValue & 0xFF );
}
else if( channel == ALPHA )
{
*(pixelData+3) = static_cast<unsigned char>( channelValue & 0xFF );
}
break;
}
case Dali::Pixel::RGBA4444:
{
if( channel == RED )
{
*pixelData &= static_cast<unsigned char>( ~0xF0 );
*pixelData |= static_cast<unsigned char>( (channelValue << 4) & 0xF0 );
}
else if( channel == GREEN )
{
*pixelData &= static_cast<unsigned char>( ~0x0F );
*pixelData |= static_cast<unsigned char>( channelValue & 0x0F );
}
else if( channel == BLUE )
{
*(pixelData+1) &= static_cast<unsigned char>( ~0xF0 );
*(pixelData+1) |= static_cast<unsigned char>( (channelValue << 4) & 0xF0 );
}
else if( channel == ALPHA )
{
*(pixelData+1) &= static_cast<unsigned char>( ~0x0F );
*(pixelData+1) |= static_cast<unsigned char>( channelValue & 0x0F );
}
break;
}
case Dali::Pixel::BGRA4444:
{
if( channel == BLUE )
{
*pixelData &= static_cast<unsigned char>( ~0xF0 );
*pixelData |= static_cast<unsigned char>( (channelValue << 4) & 0xF0 );
}
else if( channel == GREEN )
{
*pixelData &= static_cast<unsigned char>( ~0x0F );
*pixelData |= static_cast<unsigned char>( channelValue & 0x0F );
}
else if( channel == RED )
{
*(pixelData+1) &= static_cast<unsigned char>( ~0xF0 );
*(pixelData+1) |= static_cast<unsigned char>( (channelValue << 4) & 0xF0 );
}
else if( channel == ALPHA )
{
*(pixelData+1) &= static_cast<unsigned char>( ~0x0F );
*(pixelData+1) |= static_cast<unsigned char>( channelValue & 0x0F );
}
break;
}
case Dali::Pixel::RGBA5551:
{
// rrrrrggg ggbbbbba
// F8 7 C0 3E 1
if( channel == RED )
{
*pixelData &= static_cast<unsigned char>( ~0xF8 );
*pixelData |= static_cast<unsigned char>( (channelValue << 3) & 0xF8 );
}
else if( channel == GREEN )
{
*pixelData &= static_cast<unsigned char>( ~0x07 );
*pixelData |= static_cast<unsigned char>( (channelValue >> 2) & 0x07 );
*(pixelData+1) &= static_cast<unsigned char>( ~0xC0 );
*(pixelData+1) |= static_cast<unsigned char>( (channelValue << 6) & 0xC0 );
}
else if( channel == BLUE )
{
*(pixelData+1) &= static_cast<unsigned char>( ~0x3E );
*(pixelData+1) |= static_cast<unsigned char>( (channelValue << 1) & 0x3E );
}
else if( channel == ALPHA )
{
*(pixelData+1) &= static_cast<unsigned char>( ~0x01 );
*(pixelData+1) |= static_cast<unsigned char>( channelValue & 0x01 );
}
break;
}
case Dali::Pixel::BGRA5551:
{
if( channel == BLUE )
{
*pixelData &= static_cast<unsigned char>( ~0xF8 );
*pixelData |= static_cast<unsigned char>( (channelValue << 3) & 0xF8 );
}
else if( channel == GREEN )
{
*pixelData &= static_cast<unsigned char>( ~0x07 );
*pixelData |= static_cast<unsigned char>( (channelValue >> 2) & 0x07 );
*(pixelData+1) &= static_cast<unsigned char>( ~0xC0 );
*(pixelData+1) |= static_cast<unsigned char>( (channelValue << 6) & 0xC0 );
}
else if( channel == RED )
{
*(pixelData+1) &= static_cast<unsigned char>( ~0x3E );
*(pixelData+1) |= static_cast<unsigned char>( (channelValue << 1 ) & 0x3E );
}
else if( channel == ALPHA )
{
*(pixelData+1) &= static_cast<unsigned char>( ~0x01 );
*(pixelData+1) |= static_cast<unsigned char>( channelValue & 0x01 );
}
break;
}
case Dali::Pixel::DEPTH_UNSIGNED_INT:
case Dali::Pixel::DEPTH_FLOAT:
case Dali::Pixel::DEPTH_STENCIL:
{
break;
}
default:
break;
}
}
void ConvertColorChannelsToRGBA8888(
unsigned char* srcPixel, int srcOffset, Dali::Pixel::Format srcFormat,
unsigned char* destPixel, int destOffset )
{
int red = ReadChannel(srcPixel+srcOffset, srcFormat, RED );
int green = ReadChannel(srcPixel+srcOffset, srcFormat, GREEN );
int blue = ReadChannel(srcPixel+srcOffset, srcFormat, BLUE );
switch( srcFormat )
{
case Dali::Pixel::RGB565:
case Dali::Pixel::BGR565:
{
red = (red<<3) | (red & 0x07);
green = (green << 2) | (green & 0x03);
blue = (blue<<3) | (blue & 0x07);
break;
}
case Dali::Pixel::RGBA4444:
case Dali::Pixel::BGRA4444:
{
red = (red<<4) | (red&0x0F);
green = (green<<4) | (green&0x0F);
blue = (blue<<4) | (blue&0x0F);
break;
}
case Dali::Pixel::RGBA5551:
case Dali::Pixel::BGRA5551:
{
red = (red<<3) | (red&0x07);
green = (green<<3) | (green&0x07);
blue = (blue<<3) | (blue&0x07);
break;
}
default:
break;
}
WriteChannel(destPixel+destOffset, Dali::Pixel::RGBA8888, RED, red);
WriteChannel(destPixel+destOffset, Dali::Pixel::RGBA8888, GREEN, green);
WriteChannel(destPixel+destOffset, Dali::Pixel::RGBA8888, BLUE, blue);
}
int ConvertAlphaChannelToA8( unsigned char* srcPixel, int srcOffset, Dali::Pixel::Format srcFormat )
{
int alpha = ReadChannel(srcPixel+srcOffset, srcFormat, ALPHA );
int destAlpha = alpha;
switch( srcFormat )
{
case Pixel::RGBA5551:
case Pixel::BGRA5551:
{
destAlpha = (alpha==0)?0:255;
break;
}
case Pixel::RGBA4444:
case Pixel::BGRA4444:
{
destAlpha = (alpha<<4) | (alpha&0x0F);
break;
}
default:
break;
}
return destAlpha;
}
} // Adaptor
} // Internal
} // Dali
Reduced Cyclomatic Complexity of pixel-manipulation functions
Change-Id: Ic2ed1ecdc18a85240aebab45068e2c01e1764cf5
/*
* Copyright (c) 2020 Samsung Electronics Co., Ltd.
*
* 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.
*/
// CLASS HEADER
#include <dali/internal/imaging/common/pixel-manipulation.h>
// INTERNAL HEADERS
#include <dali/public-api/images/pixel.h>
#include <dali/integration-api/debug.h>
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
namespace
{
constexpr Channel ALPHA_CHANNEL_ONLY[] = {ALPHA};
constexpr Channel LUMINANCE_CHANNEL_ONLY[] = {LUMINANCE};
constexpr Channel LUMINANCE_ALPHA_CHANNELS[] = {ALPHA, LUMINANCE};
constexpr Channel RGB_CHANNELS[] = {RED, GREEN, BLUE};
constexpr Channel BGR_CHANNELS[] = {BLUE, GREEN, RED};
constexpr Channel RGBA_CHANNELS[] = {RED, GREEN, BLUE, ALPHA};
constexpr Channel BGRA_CHANNELS[] = {BLUE, GREEN, RED, ALPHA};
/**
* @brief Template to Read from a buffer with pixel formats that have one byte per channel.
*
* @tparam NumberOfChannels The number of channels to check
* @param pixelData The pixel data to retrieve the value from
* @param channel The channel we're after
* @param channels The array of channels in the pixel format
* @return The value of the required channel
*/
template<size_t NumberOfChannels>
unsigned int ReadChannel(unsigned char* pixelData, Channel channel, const Channel (&channels)[NumberOfChannels])
{
auto num = 0u;
auto retVal = 0u;
for(auto current : channels)
{
if( channel == current )
{
retVal = static_cast<unsigned int>(*(pixelData + num));
break;
}
++num;
}
return retVal;
}
/**
* @brief Template to Write to a buffer with pixel formats that have one byte per channel.
*
* @tparam NumberOfChannels The number of channels to check
* @param pixelData The pixel data to write the value to
* @param channel The channel we're after
* @param channelValue The value of the channel to set
* @param channels The array of channels in the pixel format
*/
template<size_t NumberOfChannels>
void WriteChannel(unsigned char* pixelData, Channel channel, unsigned int channelValue, const Channel (&channels)[NumberOfChannels])
{
auto num = 0u;
for( auto current : channels )
{
if( channel == current )
{
*(pixelData + num) = static_cast<unsigned char>( channelValue & 0xFF );
break;
}
++num;
}
}
/**
* @brief Reads from buffers with a pixel format of 565.
*
* @param pixelData The pixel data to read from
* @param channel The channel we're after
* @param one The first channel of the pixel format
* @param two The second channel of the pixel format
* @param three The third channel of the pixel format
* @return The value of the required channel
*/
unsigned int ReadChannel565(unsigned char* pixelData, Channel channel, Channel one, Channel two, Channel three)
{
if( channel == one )
{
return (static_cast<unsigned int>(*pixelData) & 0xF8) >> 3;
}
else if( channel == two )
{
return ((static_cast<unsigned int>(*pixelData) & 0x07) << 3) |
((static_cast<unsigned int>(*(pixelData+1)) & 0xE0) >> 5);
}
else if( channel == three )
{
return static_cast<unsigned int>(*(pixelData+1)) & 0x1F;
}
return 0u;
}
/**
* @brief Writes to the buffer with a pixel format of 565.
*
* @param pixelData The pixel data to write to
* @param channel The channel we're after
* @param channelValue The value to write
* @param one The first channel of the pixel format
* @param two The second channel of the pixel format
* @param three The third channel of the pixel format
*/
void WriteChannel565(unsigned char* pixelData, Channel channel, unsigned int channelValue, Channel one, Channel two, Channel three)
{
if( channel == one )
{
*pixelData &= static_cast<unsigned char>( ~0xF8 );
*pixelData |= static_cast<unsigned char>( (channelValue << 3) & 0xF8 );
}
else if( channel == two )
{
*pixelData &= static_cast<unsigned char>( ~0x07 );
*pixelData |= static_cast<unsigned char>( (channelValue >> 3) & 0x07 );
*(pixelData+1) &= static_cast<unsigned char>( ~0xE0 );
*(pixelData+1) |= static_cast<unsigned char>( (channelValue << 5) & 0xE0 );
}
else if( channel == three )
{
*(pixelData+1) &= static_cast<unsigned char>( ~0x1F );
*(pixelData+1) |= static_cast<unsigned char>( channelValue & 0x1F );
}
}
/**
* @brief Reads from buffers with a pixel format of 4444.
*
* @param pixelData The pixel data to read from
* @param channel The channel we're after
* @param one The first channel of the pixel format
* @param two The second channel of the pixel format
* @param three The third channel of the pixel format
* @param four The fourth channel of the pixel format
* @return
*/
unsigned int ReadChannel4444(unsigned char* pixelData, Channel channel, Channel one, Channel two, Channel three, Channel four)
{
if( channel == one )
{
return (static_cast<unsigned int>(*pixelData) & 0xF0) >> 4;
}
else if( channel == two )
{
return (static_cast<unsigned int>(*pixelData) & 0x0F);
}
else if( channel == three )
{
return (static_cast<unsigned int>(*(pixelData+1)) & 0xF0) >> 4;
}
else if( channel == four )
{
return (static_cast<unsigned int>(*(pixelData+1)) & 0x0F);
}
return 0u;
}
/**
* @brief Writes to the buffer with a pixel format of 565.
*
* @param pixelData The pixel data to write to
* @param channel The channel we're after
* @param channelValue The value to write
* @param one The first channel of the pixel format
* @param two The second channel of the pixel format
* @param three The third channel of the pixel format
* @param four The fourth channel of the pixel format
*/
void WriteChannel4444(unsigned char* pixelData, Channel channel, unsigned int channelValue, Channel one, Channel two, Channel three, Channel four)
{
if( channel == one )
{
*pixelData &= static_cast<unsigned char>( ~0xF0 );
*pixelData |= static_cast<unsigned char>( (channelValue << 4) & 0xF0 );
}
else if( channel == two )
{
*pixelData &= static_cast<unsigned char>( ~0x0F );
*pixelData |= static_cast<unsigned char>( channelValue & 0x0F );
}
else if( channel == three )
{
*(pixelData+1) &= static_cast<unsigned char>( ~0xF0 );
*(pixelData+1) |= static_cast<unsigned char>( (channelValue << 4) & 0xF0 );
}
else if( channel == four )
{
*(pixelData+1) &= static_cast<unsigned char>( ~0x0F );
*(pixelData+1) |= static_cast<unsigned char>( channelValue & 0x0F );
}
}
/**
* @brief Reads from buffers with a pixel format of 5551.
*
* @param pixelData The pixel data to read from
* @param channel The channel we're after
* @param one The first channel of the pixel format
* @param two The second channel of the pixel format
* @param three The third channel of the pixel format
* @param four The fourth channel of the pixel format
* @return
*/
unsigned int ReadChannel5551(unsigned char* pixelData, Channel channel, Channel one, Channel two, Channel three, Channel four)
{
if( channel == one )
{
return (static_cast<unsigned int>(*pixelData) & 0xF8) >> 3;
}
else if( channel == two )
{
return ((static_cast<unsigned int>(*pixelData) & 0x07) << 2) |
((static_cast<unsigned int>(*(pixelData+1)) & 0xC0) >> 6);
}
else if( channel == three )
{
return (static_cast<unsigned int>(*(pixelData+1)) & 0x3E) >> 1;
}
else if( channel == four )
{
return static_cast<unsigned int>(*(pixelData+1)) & 0x01;
}
return 0u;
}
/**
* @brief Writes to the buffer with a pixel format of 5551.
*
* @param pixelData The pixel data to write to
* @param channel The channel we're after
* @param channelValue The value to write
* @param one The first channel of the pixel format
* @param two The second channel of the pixel format
* @param three The third channel of the pixel format
* @param four The fourth channel of the pixel format
*/
void WriteChannel5551(unsigned char* pixelData, Channel channel, unsigned int channelValue, Channel one, Channel two, Channel three, Channel four)
{
// 11111222 22333334
// F8 7 C0 3E 1
if( channel == one )
{
*pixelData &= static_cast<unsigned char>( ~0xF8 );
*pixelData |= static_cast<unsigned char>( (channelValue << 3) & 0xF8 );
}
else if( channel == two )
{
*pixelData &= static_cast<unsigned char>( ~0x07 );
*pixelData |= static_cast<unsigned char>( (channelValue >> 2) & 0x07 );
*(pixelData+1) &= static_cast<unsigned char>( ~0xC0 );
*(pixelData+1) |= static_cast<unsigned char>( (channelValue << 6) & 0xC0 );
}
else if( channel == three )
{
*(pixelData+1) &= static_cast<unsigned char>( ~0x3E );
*(pixelData+1) |= static_cast<unsigned char>( (channelValue << 1) & 0x3E );
}
else if( channel == four )
{
*(pixelData+1) &= static_cast<unsigned char>( ~0x01 );
*(pixelData+1) |= static_cast<unsigned char>( channelValue & 0x01 );
}
}
} // unnamed namespace
struct Location
{
unsigned int bitShift;
unsigned int bitMask;
bool available;
};
struct Locations
{
Location luminance;
Location alpha;
Location red;
Location green;
Location blue;
};
bool HasChannel( Dali::Pixel::Format pixelFormat, Channel channel )
{
switch (pixelFormat)
{
case Dali::Pixel::A8:
{
return (channel == ALPHA);
}
case Dali::Pixel::L8:
{
return (channel == LUMINANCE);
}
case Dali::Pixel::LA88:
{
return ( channel == LUMINANCE || channel == ALPHA );
}
case Dali::Pixel::RGB565:
case Dali::Pixel::BGR565:
case Dali::Pixel::RGB888:
case Dali::Pixel::RGB8888:
case Dali::Pixel::BGR8888:
case Dali::Pixel::RGB16F:
case Dali::Pixel::RGB32F:
{
return ( channel == RED || channel == GREEN || channel == BLUE );
}
case Dali::Pixel::RGBA8888:
case Dali::Pixel::BGRA8888:
case Dali::Pixel::RGBA4444:
case Dali::Pixel::BGRA4444:
case Dali::Pixel::RGBA5551:
case Dali::Pixel::BGRA5551:
{
return ( channel == RED || channel == GREEN || channel == BLUE || channel == ALPHA );
}
case Dali::Pixel::DEPTH_UNSIGNED_INT:
case Dali::Pixel::DEPTH_FLOAT:
{
return ( channel == DEPTH );
}
case Dali::Pixel::DEPTH_STENCIL:
{
return ( channel == DEPTH || channel == STENCIL );
}
case Dali::Pixel::INVALID:
case Dali::Pixel::COMPRESSED_R11_EAC:
case Dali::Pixel::COMPRESSED_SIGNED_R11_EAC:
case Dali::Pixel::COMPRESSED_RG11_EAC:
case Dali::Pixel::COMPRESSED_SIGNED_RG11_EAC:
case Dali::Pixel::COMPRESSED_RGB8_ETC2:
case Dali::Pixel::COMPRESSED_SRGB8_ETC2:
case Dali::Pixel::COMPRESSED_RGB8_ETC1:
case Dali::Pixel::COMPRESSED_RGB_PVRTC_4BPPV1:
case Dali::Pixel::COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:
case Dali::Pixel::COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:
case Dali::Pixel::COMPRESSED_RGBA8_ETC2_EAC:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_4x4_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_5x4_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_5x5_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_6x5_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_6x6_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_8x5_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_8x6_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_8x8_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x5_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x6_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x8_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x10_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_12x10_KHR:
case Dali::Pixel::COMPRESSED_RGBA_ASTC_12x12_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:
case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:
{
DALI_LOG_ERROR("Pixel formats for compressed images are not compatible with simple channels.\n");
break;
}
}
return false;
}
unsigned int ReadChannel( unsigned char* pixelData,
Dali::Pixel::Format pixelFormat,
Channel channel )
{
switch (pixelFormat)
{
case Dali::Pixel::A8:
{
return ReadChannel(pixelData, channel, ALPHA_CHANNEL_ONLY);
}
case Dali::Pixel::L8:
{
return ReadChannel(pixelData, channel, LUMINANCE_CHANNEL_ONLY);
}
case Dali::Pixel::LA88:
{
return ReadChannel(pixelData, channel, LUMINANCE_ALPHA_CHANNELS);
}
case Dali::Pixel::RGB565:
{
return ReadChannel565(pixelData, channel, RED, GREEN, BLUE);
}
case Dali::Pixel::BGR565:
{
return ReadChannel565(pixelData, channel, BLUE, GREEN, RED);
}
case Dali::Pixel::RGB888:
case Dali::Pixel::RGB8888:
{
return ReadChannel(pixelData, channel, RGB_CHANNELS);
}
case Dali::Pixel::BGR8888:
{
return ReadChannel(pixelData, channel, BGR_CHANNELS);
}
case Dali::Pixel::RGBA8888:
{
return ReadChannel(pixelData, channel, RGBA_CHANNELS);
}
case Dali::Pixel::BGRA8888:
{
return ReadChannel(pixelData, channel, BGRA_CHANNELS);
}
case Dali::Pixel::RGBA4444:
{
return ReadChannel4444(pixelData, channel, RED, GREEN, BLUE, ALPHA);
}
case Dali::Pixel::BGRA4444:
{
return ReadChannel4444(pixelData, channel, BLUE, GREEN, RED, ALPHA);
}
case Dali::Pixel::RGBA5551:
{
return ReadChannel5551(pixelData, channel, RED, GREEN, BLUE, ALPHA);
}
case Dali::Pixel::BGRA5551:
{
return ReadChannel5551(pixelData, channel, BLUE, GREEN, RED, ALPHA);
}
case Dali::Pixel::DEPTH_UNSIGNED_INT:
case Dali::Pixel::DEPTH_FLOAT:
case Dali::Pixel::DEPTH_STENCIL:
{
return 0u;
}
default:
{
return 0u;
}
}
}
void WriteChannel( unsigned char* pixelData,
Dali::Pixel::Format pixelFormat,
Channel channel,
unsigned int channelValue )
{
switch (pixelFormat)
{
case Dali::Pixel::A8:
{
WriteChannel(pixelData, channel, channelValue, ALPHA_CHANNEL_ONLY);
break;
}
case Dali::Pixel::L8:
{
WriteChannel(pixelData, channel, channelValue, LUMINANCE_CHANNEL_ONLY);
break;
}
case Dali::Pixel::LA88:
{
WriteChannel(pixelData, channel, channelValue, LUMINANCE_ALPHA_CHANNELS);
break;
}
case Dali::Pixel::RGB565:
{
WriteChannel565(pixelData, channel, channelValue, RED, GREEN, BLUE);
break;
}
case Dali::Pixel::BGR565:
{
WriteChannel565(pixelData, channel, channelValue, BLUE, GREEN, RED);
break;
}
case Dali::Pixel::RGB888:
case Dali::Pixel::RGB8888:
{
WriteChannel(pixelData, channel, channelValue, RGB_CHANNELS);
break;
}
case Dali::Pixel::BGR8888:
{
WriteChannel(pixelData, channel, channelValue, BGR_CHANNELS);
break;
}
case Dali::Pixel::RGBA8888:
{
WriteChannel(pixelData, channel, channelValue, RGBA_CHANNELS);
break;
}
case Dali::Pixel::BGRA8888:
{
WriteChannel(pixelData, channel, channelValue, BGRA_CHANNELS);
break;
}
case Dali::Pixel::RGBA4444:
{
WriteChannel4444(pixelData, channel, channelValue, RED, GREEN, BLUE, ALPHA);
break;
}
case Dali::Pixel::BGRA4444:
{
WriteChannel4444(pixelData, channel, channelValue, BLUE, GREEN, RED, ALPHA);
break;
}
case Dali::Pixel::RGBA5551:
{
WriteChannel5551(pixelData, channel, channelValue, RED, GREEN, BLUE, ALPHA);
break;
}
case Dali::Pixel::BGRA5551:
{
WriteChannel5551(pixelData, channel, channelValue, BLUE, GREEN, RED, ALPHA);
break;
}
case Dali::Pixel::DEPTH_UNSIGNED_INT:
case Dali::Pixel::DEPTH_FLOAT:
case Dali::Pixel::DEPTH_STENCIL:
{
break;
}
default:
break;
}
}
void ConvertColorChannelsToRGBA8888(
unsigned char* srcPixel, int srcOffset, Dali::Pixel::Format srcFormat,
unsigned char* destPixel, int destOffset )
{
int red = ReadChannel(srcPixel+srcOffset, srcFormat, RED );
int green = ReadChannel(srcPixel+srcOffset, srcFormat, GREEN );
int blue = ReadChannel(srcPixel+srcOffset, srcFormat, BLUE );
switch( srcFormat )
{
case Dali::Pixel::RGB565:
case Dali::Pixel::BGR565:
{
red = (red<<3) | (red & 0x07);
green = (green << 2) | (green & 0x03);
blue = (blue<<3) | (blue & 0x07);
break;
}
case Dali::Pixel::RGBA4444:
case Dali::Pixel::BGRA4444:
{
red = (red<<4) | (red&0x0F);
green = (green<<4) | (green&0x0F);
blue = (blue<<4) | (blue&0x0F);
break;
}
case Dali::Pixel::RGBA5551:
case Dali::Pixel::BGRA5551:
{
red = (red<<3) | (red&0x07);
green = (green<<3) | (green&0x07);
blue = (blue<<3) | (blue&0x07);
break;
}
default:
break;
}
WriteChannel(destPixel+destOffset, Dali::Pixel::RGBA8888, RED, red);
WriteChannel(destPixel+destOffset, Dali::Pixel::RGBA8888, GREEN, green);
WriteChannel(destPixel+destOffset, Dali::Pixel::RGBA8888, BLUE, blue);
}
int ConvertAlphaChannelToA8( unsigned char* srcPixel, int srcOffset, Dali::Pixel::Format srcFormat )
{
int alpha = ReadChannel(srcPixel+srcOffset, srcFormat, ALPHA );
int destAlpha = alpha;
switch( srcFormat )
{
case Pixel::RGBA5551:
case Pixel::BGRA5551:
{
destAlpha = (alpha==0)?0:255;
break;
}
case Pixel::RGBA4444:
case Pixel::BGRA4444:
{
destAlpha = (alpha<<4) | (alpha&0x0F);
break;
}
default:
break;
}
return destAlpha;
}
} // Adaptor
} // Internal
} // Dali
|
#include "ms.h"
#include "pt.h"
#include <assert.h>
void ModelCheckerPG::dumpDOT( std::ofstream &outf )
{
propositionSet_it prp_it;
int pcount;
outf << "digraph G {\n \"\" [shape=none]" << std::endl;
outf << "\"\" -> \"" << this->initialVertex << "\"" << std::endl;
for (PGStateSet_it it_state = this->states.begin();
it_state != this->states.end(); it_state++) {
for (PGVertexSet_it it_vertex = (*it_state)->vertices.begin();
it_vertex != (*it_state)->vertices.end(); it_vertex++) {
outf << "\"" << *it_vertex << "\" [label=\"";
outf << *it_state << " {";
pcount = 0;
for (prp_it = (*it_state)->labeledPrp.begin();
prp_it != (*it_state)->labeledPrp.end(); prp_it++) {
if (pcount > 0)
outf << ", ";
outf << "p" << *prp_it;
pcount++;
}
outf << "}\\n";
printFormula( (*it_vertex)->subformula, outf );
outf << "\"]" << std::endl;
for (PGVertexSet_it it_vertex_succ = (*it_vertex)->succVertices.begin();
it_vertex_succ != (*it_vertex)->succVertices.end(); it_vertex_succ++) {
outf << "\"" << *it_vertex << "\" -> \"" << *it_vertex_succ << "\"" << std::endl;
}
}
}
outf << "}";
}
void ModelCheckerPG::optRewire( PGState *z_new )
{
double c_new;
bool updated;
for (PGVertexSet_it z_new_v_it = z_new->vertices.begin();
z_new_v_it != z_new->vertices.end(); z_new_v_it++) {
if ((*z_new_v_it)->subformula->parent != NULL
&& (*z_new_v_it)->subformula->parent->type == PT_SUC) {
// Like lines 21-28 of Algorithm 5 of the ACC 2012 paper
updated = false;
for (PGVertexSet_it rv_it = (*z_new_v_it)->RV.begin();
rv_it != (*z_new_v_it)->RV.end(); rv_it++) {
list<PGVertex *>key_existing;
key_existing.push_back( *rv_it );
key_existing.push_back( *z_new_v_it );
assert( Cost.find( key_existing ) != Cost.end() );
for (PGVertexSet_it pre_it = (*z_new_v_it)->predVertices.begin();
pre_it != (*z_new_v_it)->predVertices.end(); pre_it++) {
if ((*pre_it)->subformula->type != PT_SUC
|| *((*pre_it)->subformula->children.begin()) != (*z_new_v_it)->subformula)
continue;
list<PGVertex *> key;
key.push_back( *rv_it );
key.push_back( *pre_it );
assert( Cost.find( key ) != Cost.end() );
c_new = Cost[key] + ((*pre_it)->state == (*z_new_v_it)->state ? 0 : (*pre_it)->state->edgeCost[(*z_new_v_it)->state]);
if (c_new < Cost[key_existing]) {
Pr[key_existing] = *pre_it;
Cost[key_existing] = c_new;
updated = true;
}
}
}
if (updated)
propagateCost( *z_new_v_it );
} else if ((*z_new_v_it)->subformula->type == PT_SUC) {
// Like lines 29-36 of Algorithm 5 of the ACC 2012 paper
for (PGVertexSet_it post_it = (*z_new_v_it)->succVertices.begin();
post_it != (*z_new_v_it)->succVertices.end(); post_it++) {
if ((*post_it)->subformula != *((*z_new_v_it)->subformula->children.begin()))
continue;
updated = false;
for (PGVertexSet_it rv_it = (*post_it)->RV.begin();
rv_it != (*post_it)->RV.end(); rv_it++) {
if ((*z_new_v_it)->RV.find( *rv_it ) == (*z_new_v_it)->RV.end())
continue;
list<PGVertex *>key;
key.push_back( *rv_it );
key.push_back( *z_new_v_it );
assert( Cost.find( key ) != Cost.end() );
c_new = Cost[key] + ((*z_new_v_it)->state == (*post_it)->state ? 0 : (*z_new_v_it)->state->edgeCost[(*post_it)->state]);
list<PGVertex *> key_existing;
key_existing.push_back( *rv_it );
key_existing.push_back( *post_it );
assert( Cost.find( key_existing ) != Cost.end() );
if (c_new < Cost[key_existing]) {
Pr[key_existing] = *z_new_v_it;
Cost[key_existing] = c_new;
updated = true;
}
}
if (updated)
propagateCost( *post_it );
}
}
}
}
void ModelCheckerPG::propagateCost( PGVertex *changed_vertex )
{
PGVertexSet visited;
PGVertexSet current;
PGVertexSet next;
PGVertexSet_it it_current_v;
PGVertex *current_v;
double c_new;
for (PGStateSet_it it_state = this->states.begin();
it_state != this->states.end(); it_state++) {
for (PGVertexSet_it it_start_v = (*it_state)->vertices.begin();
it_start_v != (*it_state)->vertices.end(); it_start_v++) {
visited.clear();
visited.insert( changed_vertex );
current.clear();
next.clear();
next.insert( changed_vertex );
while (next.size() > 0) {
current.swap( next );
while (current.size() > 0) {
it_current_v = current.begin();
current_v = *it_current_v;
current.erase( it_current_v );
if (current_v->RV.find( *it_start_v ) == current_v->RV.end())
continue;
list <PGVertex *>key_existing;
key_existing.push_back( *it_start_v );
key_existing.push_back( current_v );
assert( Cost.find( key_existing ) != Cost.end() );
for (PGVertexSet_it it_predecessor_v = current_v->predVertices.begin();
it_predecessor_v != current_v->predVertices.end(); it_predecessor_v++) {
if ((*it_predecessor_v)->RV.find( *it_start_v ) == (*it_predecessor_v)->RV.end())
continue;
list <PGVertex *>key;
key.push_back( *it_start_v );
key.push_back( *it_predecessor_v );
assert( Cost.find( key ) != Cost.end() );
c_new = Cost[key] + ((*it_predecessor_v)->state == current_v->state ? 0 : (*it_predecessor_v)->state->edgeCost[current_v->state]);
if (c_new < Cost[key_existing]) {
Pr[key_existing] = *it_predecessor_v;
Cost[key_existing] = c_new;
}
}
for (PGVertexSet_it it_successor_v = current_v->succVertices.begin();
it_successor_v != current_v->succVertices.end(); it_successor_v++) {
if (visited.find( *it_successor_v ) != visited.end())
continue;
next.insert( *it_successor_v );
visited.insert( *it_successor_v );
}
}
}
}
}
}
int getColor( PGVertex *vertex )
{
if (vertex->subformula->type == PT_GFP) {
if (vertex->subformula->AD % 2 == 0) {
return vertex->subformula->AD;
} else {
return vertex->subformula->AD + 1;
}
} else if (vertex->subformula->type == PT_LFP) {
if (vertex->subformula->AD % 2 == 0) {
return vertex->subformula->AD + 1;
} else {
return vertex->subformula->AD;
}
}
return 0;
}
MS_state::MS_state()
: vertices(), successors(), predecessors(), labeledPrp()
{
this->data = 0;
this->identifier = -1;
this->labeledPrp.clear();
}
PGState::PGState()
: vertices(), successors(), predecessors(), labeledPrp()
{
this->data = 0;
this->labeledPrp.clear();
}
bool MS_state::addprop( int newprop )
{
this->labeledPrp.insert( newprop );
return true;
}
bool PGState::addprop( int newprop )
{
this->labeledPrp.insert( newprop );
return true;
}
ModelCheckerPG::ModelCheckerPG()
{
this->initialState = NULL;
this->initialVertex = NULL;
this->states.clear();
this->lV.clear();
this->nV.clear();
this->Pr.clear();
this->Cost.clear();
this->last_min_cost = -1.0;
}
rModelChecker::rModelChecker()
{
this->initialState = NULL;
this->initialVertex = NULL;
this->states.clear();
this->satVertices.clear();
this->num_local_updates = 0;
this->num_update_reachabilities = 0;
}
rModelChecker::~rModelChecker()
{ }
CT_vertex *
rModelChecker::addVertex( CT_vertex *parentVertex, MS_state *state,
PT_node *subformula )
{
#if !TRUST_ME
if (this->states.find (state) == this->states.end()) {
cout << "ERROR: rModelChecker::addVertex: state is not in this->states";
exit (1);
}
#endif
CT_vertex *vertexNew;
// Check whether the vertex already exists
bool vertexFound = false;
for (vertexSet_it iter = state->vertices.begin();
iter != state->vertices.end(); iter++) {
CT_vertex *vertexCurr = *iter;
if (vertexCurr->subformula == subformula){
vertexNew = vertexCurr;
vertexFound = true;
break;
}
}
// Create a new vertex if one does not exist
if (!vertexFound) {
vertexNew = new CT_vertex;
vertexNew->state = state;
vertexNew->subformula = subformula;
vertexNew->succVertices.clear();
vertexNew->predVertices.clear();
vertexNew->reachingVertices.clear();
PT_node *parentSubformula = parentVertex->subformula;
if ((parentSubformula->type == PT_GFP)
&& !(this->pt.compareFormulaSize( subformula, parentSubformula ))) {
// then place it to its own reachingVertices
vertexNew->reachingVertices.insert( parentVertex );
#if VERBOSE_DBG
cout << "Insert GFP to reachability" << endl;
#endif
}
state->vertices.insert (vertexNew);
}
// Update the predVertices and succVertices of both of the vertices
if (vertexNew->predVertices.find( parentVertex ) == vertexNew->predVertices.end() )
vertexNew->predVertices.insert( parentVertex );
if (parentVertex->succVertices.find( vertexNew ) == parentVertex->succVertices.end() )
parentVertex->succVertices.insert( vertexNew );
bool reachabilityUpdateOccurred = this->UpdateReachability( parentVertex, vertexNew );
if ((!vertexFound) || reachabilityUpdateOccurred)
return vertexNew;
return NULL;
}
bool // Returns true if a modification is made, it returns false otherwise
rModelChecker::UpdateReachability( CT_vertex *vertexFrom, CT_vertex *vertexTo )
{
bool addedNewReachingVertex = false;
this->num_update_reachabilities++;
// Compute vertexTo->reachingVertices =
// {vertex \in vertexFrom->reachingVertices : vertex->subformula >= vertexTo->subformula} \cup vertexTo->reachingVertices
// - The computation is done in linear time
vertexSet_it iterTo = vertexTo->reachingVertices.begin();
vertexSet_it iterToPrev = iterTo;
vertexSet_it iterToEnd = vertexTo->reachingVertices.end();
for (vertexSet_it iterFrom = vertexFrom->reachingVertices.begin();
iterFrom != vertexFrom->reachingVertices.end(); iterFrom++) {
while ((*iterTo < *iterFrom) && (iterTo != iterToEnd)) {
iterToPrev = iterTo;
iterTo++;
}
if ((*iterFrom == *iterTo) && (iterTo != iterToEnd)) {
//cout<< "yes" << endl;
continue;
}
if (this->pt.compareFormulaSize( vertexTo->subformula,
(*iterFrom)->subformula))
continue;
vertexTo->reachingVertices.insert (iterToPrev, *iterFrom);
addedNewReachingVertex = true;
}
// If vertexTo is a PT_VAR type subformula, then check if vertexTo is a sat node
if ((vertexTo->subformula->type == PT_VAR) ) {
// Check whether this node is reachable from a vertex = (state, BindingFormula(var))
PT_node *bindingSubformula = this->pt.getBoundFormula (vertexTo->subformula);
// Search the reaching vertices for vertex = (state, bindingSubformula)
bool gfpLoopFound = false;
for (vertexSet_it iter = vertexTo->reachingVertices.begin();
iter != vertexTo->reachingVertices.end(); iter++) {
CT_vertex *vertexCurr = *iter;
if ((vertexCurr->state == vertexTo->state)
&& (vertexCurr->subformula == bindingSubformula)) {
gfpLoopFound = true;
break;
}
}
if (gfpLoopFound) {
this->satVertices.insert (vertexTo);
}
}
// If added a new reaching vertex into reachingVertices in vertexTo,
// then run UpdateReachability for each successor vertex of vertexTo
if (addedNewReachingVertex) {
for (vertexSet_it iter = vertexTo->succVertices.begin();
iter != vertexTo->succVertices.end(); iter++) {
this->UpdateReachability (vertexTo,*iter);
}
}
return addedNewReachingVertex;
}
bool // Returns true if a witness is found, otherwise it returns false
rModelChecker::LocalUpdate( CT_vertex *vertex )
{
this->num_local_updates++;
MS_state *stateThis = vertex->state;
PT_node *subformulaThis = vertex->subformula;
#if VERBOSE_DBG
cout << "state : " << stateThis->identifier << " - subformula : " << subformulaThis->type << endl;
cout << " reachable states-subformula:" << endl;
for (vertexSet_it iter = vertex->reachingVertices.begin();
iter != vertex->reachingVertices.end(); iter++){
CT_vertex *reachingVertex = *iter;
cout << " - reaching state: " << reachingVertex->state->identifier << endl;
}
#endif
bool foundWitness = false;
// If subformulaThis is a suc-formula then make sure it is in the list of subformulae of this stateThis
if (subformulaThis->type == PT_SUC) {
if (stateThis->sucSubformulaeVertices.find (vertex) == stateThis->sucSubformulaeVertices.end()) {
stateThis->sucSubformulaeVertices.insert (vertex);
#if VERBOSE_DBG
cout << " --> added suc-subformula : " << stateThis->identifier << endl;
#endif
}
}
// 1. ATOMIC PROPOSITIONS
if (subformulaThis->type == PT_PRP || subformulaThis->type == PT_NPRP) {
// Check whether this literal is satisfied in this state
// if so, then we found a witness since this node is reachable from root
int prpCurr = ((PT_prp *)subformulaThis)->prp;
if (stateThis->labeledPrp.find ( prpCurr ) != stateThis->labeledPrp.end() ) {
if (subformulaThis->type == PT_PRP) {
cout << "FOUND A WITNESS: PRP" << endl;
this->satVertices.insert (vertex);
foundWitness = true;
}
} else if (subformulaThis->type == PT_NPRP) {
cout << "FOUND A WITNESS: NPRP" << endl;
this->satVertices.insert (vertex);
foundWitness = true;
}
}
// 2. VARIABLES
if (subformulaThis->type == PT_VAR) {
// Check whether this node is reachable from a vertex = (state, BindingFormula(var))
PT_node *bindingSubformula = this->pt.getBoundFormula (subformulaThis);
// Search the reaching vertices for vertex = (state, bindingSubformula)
bool gfpLoopFound = false;
for (vertexSet_it iter = vertex->reachingVertices.begin();
iter != vertex->reachingVertices.end(); iter++) {
CT_vertex *vertexCurr = *iter;
if ((vertexCurr->state == stateThis)
&& (vertexCurr->subformula == bindingSubformula)) {
gfpLoopFound = true;
break;
}
}
// If vertex = (state, bindingSubformula) if found to be reaching,
// then declare wictory
if (gfpLoopFound) {
this->satVertices.insert (vertex);
foundWitness = true;
}
// Create the new node with the bindingSubformula
CT_vertex *vertexNew = this->addVertex (vertex, stateThis, bindingSubformula);
if (vertexNew) {
if (this->LocalUpdate (vertexNew))
foundWitness = true;
}
}
// 3. AND OPERATOR
if (subformulaThis->type == PT_AND) {
#if !TRUST_ME
if ( ((PT_operator *)subformulaThis)->children.size() != 2) {
cout << "ERROR: rModelChecker::LocalUpdate: AND OPERATOR does not have 2 children" << endl;
exit (1);
}
#endif
subformulaeSet_it iter = ((PT_operator *)subformulaThis)->children.begin();
// Get left subformula
PT_node *subformulaLeft = *iter;
// Get right subformula
iter++;
PT_node *subformulaRight = *iter;
PT_node *subformulaChild = NULL;
if (subformulaLeft->type == PT_PRP) {
// Create a new node using subformulaRight
if (stateThis->labeledPrp.find( ((PT_prp *)subformulaLeft)->prp ) != stateThis->labeledPrp.end())
subformulaChild = subformulaRight;
} else if (subformulaRight->type == PT_PRP) {
// Create a new node using subformulaLeft
if (stateThis->labeledPrp.find( ((PT_prp *)subformulaRight)->prp ) != stateThis->labeledPrp.end())
subformulaChild = subformulaLeft;
} else if (subformulaLeft->type == PT_NPRP) {
// Create a new node using subformulaRight
if (stateThis->labeledPrp.find( ((PT_prp *)subformulaLeft)->prp ) == stateThis->labeledPrp.end())
subformulaChild = subformulaRight;
} else if (subformulaRight->type == PT_NPRP) {
// Create a new node using subformulaLeft
if (stateThis->labeledPrp.find( ((PT_prp *)subformulaRight)->prp ) == stateThis->labeledPrp.end())
subformulaChild = subformulaLeft;
} else {
cout << "ERROR: rModelChecker::LocalUpdate: No child of the AND OPERATOR is a literal" << endl;
exit (1);
}
/* If stateThis satisfies the proposition, then add the vertex and
update the reachability graph */
if (subformulaChild) {
CT_vertex *vertexNew = addVertex( vertex, stateThis, subformulaChild );
if (vertexNew)
if (this->LocalUpdate( vertexNew ))
foundWitness = true;
}
}
// 4. OR OPERATOR
if (subformulaThis->type == PT_OR) {
#if !TRUST_ME
if (((PT_operator *)subformulaThis)->children.size() != 2) {
cout << "ERROR: rModelChecker::LocalUpdate: OR OPERATOR does not have 2 children" << endl;
exit (1);
}
#endif
/* Add both of the child subformula to the model checker and update the
reachabilities */
for (subformulaeSet_it iter = ((PT_operator *)subformulaThis)->children.begin();
iter != ((PT_operator *)subformulaThis)->children.end(); iter++) {
PT_node *subformulaChild = *iter;
CT_vertex *vertexNew = this->addVertex (vertex, stateThis,subformulaChild);
if (vertexNew) {
if (this->LocalUpdate( vertexNew ))
foundWitness = true;
}
if (foundWitness)
break;
}
}
// 5. LFP OPERATOR
if (subformulaThis->type == PT_LFP) {
#if !TRUST_ME
if (((PT_operator *)subformulaThis)->children.size() != 1) {
cout << "ERROR: rModelChecker::LocalUpdate: LFP OPERATOR does not have 1 children" << endl;
exit (1);
}
#endif
subformulaeSet_it iter = ((PT_operator *)subformulaThis)->children.begin();
PT_node *subformulaChild = *iter;
CT_vertex *vertexNew = this->addVertex( vertex,stateThis, subformulaChild );
if (vertexNew) {
if (this->LocalUpdate (vertexNew))
foundWitness = true;
}
}
// 6. GFP OPEARATOR
if (subformulaThis->type == PT_GFP) {
#if !TRUST_ME
if (((PT_operator *)subformulaThis)->children.size() != 1) {
cout << "ERROR: rModelChecker::LocalUpdate: GFP OPERATOR does not have 1 children" << endl;
exit (1);
}
#endif
subformulaeSet_it iter = ((PT_operator *)subformulaThis)->children.begin();
PT_node *subformulaChild = *iter;
CT_vertex *vertexNew = this->addVertex (vertex,stateThis, subformulaChild);
if (vertexNew) {
if (this->LocalUpdate (vertexNew))
foundWitness = true;
}
}
// 7. SUC OPERATOR
if (subformulaThis->type == PT_SUC) {
#if !TRUST_ME
if ( ((PT_operator *)subformulaThis)->children.size() != 1) {
cout << "ERROR: rModelChecker::LocalUpdate: LFP OPERATOR does not have 1 children" << endl;
exit (1);
}
#endif
subformulaeSet_it iter = ((PT_operator *)subformulaThis)->children.begin();
PT_node *subformulaChild = *iter;
for (stateSet_it ssiter = stateThis->successors.begin();
ssiter != stateThis->successors.end(); ssiter++) {
MS_state *stateSucc = *ssiter;
CT_vertex *vertexNew = this->addVertex (vertex,stateSucc, subformulaChild);
if (vertexNew) {
if (this->LocalUpdate (vertexNew))
foundWitness = true;
}
if (foundWitness)
break;
}
}
return foundWitness;
}
bool
ModelCheckerPG::addState( PGState *state )
{
#if !TRUST_ME
for (PGStateSet_it iter = this->states.begin();
iter != this->states.end(); iter++)
if (*iter == state) {
cout << "ERROR: ModelCheckerPG::addState: state already exists" << endl;
exit(1);
}
#endif
if (this->initialState == NULL) {
this->initialState = state;
PGVertex *vertexNew = new PGVertex;
vertexNew->state = state;
vertexNew->subformula = this->pt.getRoot();
vertexNew->succVertices.clear();
vertexNew->predVertices.clear();
vertexNew->RV.clear();
vertexNew->color = getColor( vertexNew );
this->initialVertex = vertexNew;
/* Adding the initial vertex into the RV set of the initial vertex has
the same effect as the "dummy vertex" used in the ACC 2012 paper. */
vertexNew->RV.insert( this->initialVertex );
list<PGVertex *> key;
key.push_back( this->initialVertex );
key.push_back( this->initialVertex );
Cost[key] = 0.0;
state->vertices.clear();
state->successors.clear();
state->predecessors.clear();
state->vertices.insert( vertexNew );
#if !TRUSTME
this->states.insert( state );
#endif
// TODO: Check for witness upon this special first step
this->updateArena( NULL, this->initialVertex );
} else {
#if !TRUSTME
this->states.insert( state );
#endif
state->vertices.clear();
state->successors.clear();
state->predecessors.clear();
}
return false;
}
bool
rModelChecker::addState( MS_state *state )
{
#if !TRUST_ME
for (stateSet_it iter = this->states.begin();
iter != this->states.end(); iter++)
if (*iter == state) {
cout << "ERROR: rModelChecker::addState: state already exists" << endl;
exit(1);
}
#endif
if (this->initialState == NULL) {
this->initialState = state;
CT_vertex *vertexNew = new CT_vertex;
vertexNew->state = state;
vertexNew->subformula = this->pt.getRoot();
vertexNew->succVertices.clear();
vertexNew->predVertices.clear();
vertexNew->reachingVertices.clear();
// vertexNew->reachingVertices.insert (vertexNew);
this->initialVertex = vertexNew;
state->vertices.clear();
state->successors.clear();
state->predecessors.clear();
state->vertices.insert( vertexNew );
#if !TRUSTME
this->states.insert( state );
#endif
this->LocalUpdate( vertexNew );
} else {
// TODO: This block is redundant with the second part of the if-block above.
this->states.insert( state );
state->vertices.clear();
state->successors.clear();
state->predecessors.clear();
}
return false;
}
void
ModelCheckerPG::updateArena( PGVertex *vertex_from, PGVertex *vertex_to )
{
// If edge between these vertices already exists, do nothing.
if (vertex_from != NULL
&& vertex_from->succVertices.find( vertex_to ) != vertex_from->succVertices.end())
return;
// Remove if path cannot be winning for Player 1, hence not correct
PT_prp *conjunctPrp = NULL;
if (vertex_to->subformula->type == PT_AND)
conjunctPrp = this->pt.getConjunctPrp( (PT_operator *)(vertex_to->subformula) );
if ((vertex_to->subformula->type == PT_PRP
&& (vertex_to->state->labeledPrp.find( ((PT_prp *)vertex_to->subformula)->prp )
== vertex_to->state->labeledPrp.end()))
|| (vertex_to->subformula->type == PT_NPRP
&& (vertex_to->state->labeledPrp.find( ((PT_prp *)vertex_to->subformula)->prp )
!= vertex_to->state->labeledPrp.end()))
|| (vertex_to->subformula->type == PT_AND
&& ((conjunctPrp->type == PT_PRP && (vertex_to->state->labeledPrp.find( conjunctPrp->prp )
== vertex_to->state->labeledPrp.end()))
|| (conjunctPrp->type == PT_NPRP && (vertex_to->state->labeledPrp.find( conjunctPrp->prp )
!= vertex_to->state->labeledPrp.end()))))) {
// TODO: Like lines 3-7 of Algorithm 3 of the ACC 2012 paper
vertex_to->state->vertices.erase( vertex_to );
delete vertex_to;
return;
}
if (vertex_from != NULL
&& vertex_from->subformula->type == PT_GFP
&& this->nV.find( vertex_from ) == this->nV.end()) {
// TODO: && acceptVertex()
this->nV.insert( vertex_from );
}
if ((vertex_to->subformula->type == PT_PRP
|| vertex_to->subformula->type == PT_NPRP)
&& this->lV.find( vertex_to ) == this->lV.end()) {
this->lV.insert( vertex_to );
}
/* TODO: Add separately to V1 or V2 vertex sets corresponding to lines 13-16
in Algorithm 3 of the ACC 2012 paper, which may not be correct. */
// Create the edge
if (vertex_from != NULL) {
vertex_from->succVertices.insert( vertex_to );
vertex_to->predVertices.insert( vertex_from );
}
if (vertex_to->subformula->type == PT_AND
&& ((conjunctPrp->type == PT_PRP
&& (vertex_to->state->labeledPrp.find( conjunctPrp->prp )
!= vertex_to->state->labeledPrp.end()))
|| (conjunctPrp->type == PT_NPRP
&& (vertex_to->state->labeledPrp.find( conjunctPrp->prp )
== vertex_to->state->labeledPrp.end())))) {
subformulaeSet_it sf = vertex_to->subformula->children.begin();
if (*sf == conjunctPrp)
sf++;
PGVertex *vertex_to2 = NULL;
for (PGVertexSet_it v_to = vertex_to->state->vertices.begin();
v_to != vertex_to->state->vertices.end(); v_to++) {
if ((*v_to)->subformula == *sf) {
vertex_to2 = *v_to;
break;
}
}
if (vertex_to2 == NULL) {
vertex_to2 = new PGVertex;
vertex_to2->state = vertex_to->state;
vertex_to->state->vertices.insert( vertex_to2 );
vertex_to2->subformula = *sf;
vertex_to2->succVertices.clear();
vertex_to2->predVertices.clear();
vertex_to2->RV.clear();
vertex_to2->color = getColor( vertex_to2 );
}
updateArena( vertex_to, vertex_to2 );
}
if (vertex_to->subformula->type == PT_OR) {
subformulaeSet_it sf = vertex_to->subformula->children.begin();
PGVertex *vertex_to2 = NULL;
for (PGVertexSet_it v_to = vertex_to->state->vertices.begin();
v_to != vertex_to->state->vertices.end(); v_to++) {
if ((*v_to)->subformula == *sf) {
vertex_to2 = *v_to;
break;
}
}
if (vertex_to2 == NULL) {
vertex_to2 = new PGVertex;
vertex_to2->state = vertex_to->state;
vertex_to->state->vertices.insert( vertex_to2 );
vertex_to2->subformula = *sf;
vertex_to2->succVertices.clear();
vertex_to2->predVertices.clear();
vertex_to2->RV.clear();
vertex_to2->color = getColor( vertex_to2 );
}
sf++;
PGVertex *vertex_to3 = NULL;
for (PGVertexSet_it v_to = vertex_to->state->vertices.begin();
v_to != vertex_to->state->vertices.end(); v_to++) {
if ((*v_to)->subformula == *sf) {
vertex_to3 = *v_to;
break;
}
}
if (vertex_to3 == NULL) {
vertex_to3 = new PGVertex;
vertex_to3->state = vertex_to->state;
vertex_to->state->vertices.insert( vertex_to3 );
vertex_to3->subformula = *sf;
vertex_to3->succVertices.clear();
vertex_to3->predVertices.clear();
vertex_to3->RV.clear();
vertex_to3->color = getColor( vertex_to3 );
}
updateArena( vertex_to, vertex_to2 );
updateArena( vertex_to, vertex_to3 );
}
if (vertex_to->subformula->type == PT_SUC) {
for (PGStateSet_it next_state = vertex_to->state->successors.begin();
next_state != vertex_to->state->successors.end(); next_state++) {
PGVertex *vertex_to2 = NULL;
for (PGVertexSet_it v_to = (*next_state)->vertices.begin();
v_to != (*next_state)->vertices.end(); v_to++) {
if ((*v_to)->subformula == *(vertex_to->subformula->children.begin())) {
vertex_to2 = *v_to;
break;
}
}
if (vertex_to2 == NULL) {
vertex_to2 = new PGVertex;
vertex_to2->state = *next_state;
vertex_to2->state->vertices.insert( vertex_to2 );
vertex_to2->subformula = *(vertex_to->subformula->children.begin());
vertex_to2->succVertices.clear();
vertex_to2->predVertices.clear();
vertex_to2->RV.clear();
vertex_to2->color = getColor( vertex_to2 );
}
updateArena( vertex_to, vertex_to2 );
}
}
if (vertex_to->subformula->type == PT_VAR) {
PT_node *bf = this->pt.getBoundFormula( vertex_to->subformula );
PGVertex *vertex_to2 = NULL;
for (PGVertexSet_it v_to = vertex_to->state->vertices.begin();
v_to != vertex_to->state->vertices.end(); v_to++) {
if ((*v_to)->subformula == bf) {
vertex_to2 = *v_to;
break;
}
}
if (vertex_to2 == NULL) {
vertex_to2 = new PGVertex;
vertex_to2->state = vertex_to->state;
vertex_to->state->vertices.insert( vertex_to2 );
vertex_to2->subformula = bf;
vertex_to2->succVertices.clear();
vertex_to2->predVertices.clear();
vertex_to2->RV.clear();
vertex_to2->color = getColor( vertex_to2 );
}
updateArena( vertex_to, vertex_to2 );
}
if (vertex_to->subformula->type == PT_LFP
|| vertex_to->subformula->type == PT_GFP) {
subformulaeSet_it sf = vertex_to->subformula->children.begin();
PGVertex *vertex_to2 = NULL;
for (PGVertexSet_it v_to = vertex_to->state->vertices.begin();
v_to != vertex_to->state->vertices.end(); v_to++) {
if ((*v_to)->subformula == *sf) {
vertex_to2 = *v_to;
break;
}
}
if (vertex_to2 == NULL) {
vertex_to2 = new PGVertex;
vertex_to2->state = vertex_to->state;
vertex_to->state->vertices.insert( vertex_to2 );
vertex_to2->subformula = *sf;
vertex_to2->succVertices.clear();
vertex_to2->predVertices.clear();
vertex_to2->RV.clear();
vertex_to2->color = getColor( vertex_to2 );
}
updateArena( vertex_to, vertex_to2 );
}
if (vertex_from != NULL)
updateVertexSets( vertex_from, vertex_to );
}
void
ModelCheckerPG::updateVertexSets( PGVertex *vertex_from, PGVertex *vertex_to )
{
bool updatedVertexSet = false;
double edge_cost = vertex_from->state == vertex_to->state ? 0 : vertex_from->state->edgeCost[vertex_to->state];
for (PGVertexSet_it rv_it = vertex_from->RV.begin(); rv_it != vertex_from->RV.end(); rv_it++) {
if (vertex_to->RV.find( *rv_it ) == vertex_to->RV.end()
&& (vertex_to->color <= (*rv_it)->color || *rv_it == this->initialVertex)) {
vertex_to->RV.insert( *rv_it );
list<PGVertex *> key;
key.push_back( *rv_it );
key.push_back( vertex_to );
list<PGVertex *> key_base;
key_base.push_back( *rv_it );
key_base.push_back( vertex_from );
assert( Cost.find( key_base ) != Cost.end() );
assert( Pr.find( key ) == Pr.end() );
this->Pr[key] = vertex_from;
this->Cost[key] = Cost[key_base] + edge_cost;
updatedVertexSet = true;
}
}
if (this->nV.find( vertex_from ) != this->nV.end()) {
if (vertex_to->RV.find( vertex_from ) == vertex_to->RV.end()
&& (vertex_to->color <= vertex_from->color || vertex_from == this->initialVertex)) {
vertex_to->RV.insert( vertex_from );
list<PGVertex *> key;
key.push_back( vertex_from );
key.push_back( vertex_to );
this->Pr[key] = vertex_from;
this->Cost[key] = edge_cost;
updatedVertexSet = true;
}
}
if (updatedVertexSet) {
for (PGVertexSet_it next_v_to = vertex_to->succVertices.begin();
next_v_to != vertex_to->succVertices.end(); next_v_to++)
updateVertexSets( vertex_to, *next_v_to );
}
}
/* Version that restricts enumeration to only vertices that have been added to
the arena thus far and have associated formula of the form suc f. This is
different from AddTransition (page 739) in the ACC 2012 paper. */
bool
ModelCheckerPG::addTransition( PGState *state_from, PGState *state_to, double edge_cost )
{
bool foundWitness = false;
#if !TRUST_ME
if (state_from->successors.find (state_to) != state_from->successors.end()) {
cerr << "ERROR: ModelCheckerPG::addTransition: transition already exists" << endl;
exit (-1);
}
if (state_to->predecessors.find (state_from) != state_to->predecessors.end() ) {
cerr << "ERROR: ModelCheckerPG::addTransition: transition already exists" << endl;
exit (-1);
}
#endif
state_from->successors.insert( state_to );
state_to->predecessors.insert( state_from );
if (edge_cost >= 0)
state_from->edgeCost[state_to] = edge_cost;
for (PGVertexSet_it v_from = state_from->vertices.begin();
v_from != state_from->vertices.end(); v_from++) {
if ((*v_from)->subformula->type != PT_SUC)
continue;
// Create arena vertices if needed
PGVertex *vertex_to = NULL;
for (PGVertexSet_it v_to = state_to->vertices.begin();
v_to != state_to->vertices.end(); v_to++) {
if ((*v_to)->subformula->parent == (*v_from)->subformula) {
vertex_to = *v_to;
break;
}
}
if (vertex_to == NULL) {
vertex_to = new PGVertex;
vertex_to->state = state_to;
state_to->vertices.insert( vertex_to );
vertex_to->subformula = *((*v_from)->subformula->children.begin());
vertex_to->succVertices.clear();
vertex_to->predVertices.clear();
vertex_to->RV.clear();
vertex_to->color = getColor( vertex_to );
}
updateArena( *v_from, vertex_to );
if (this->lV.size() > 0) {
std::cerr << "nonempty lV" << std::endl;
foundWitness = true;
} else {
double min_loop_cost = -1;
for (PGVertexSet_it nuv = this->nV.begin(); nuv != this->nV.end();
nuv++) {
if ((*nuv)->RV.find( *nuv ) != (*nuv)->RV.end()) {
list<PGVertex *> key;
key.push_back( *nuv );
key.push_back( *nuv );
if (min_loop_cost < 0 || this->Cost[key] < min_loop_cost)
min_loop_cost = this->Cost[key];
foundWitness = true;
}
}
if (foundWitness) {
if (this->last_min_cost < 0 || min_loop_cost < this->last_min_cost) {
this->last_min_cost = min_loop_cost;
std::cerr << min_loop_cost << std::endl;
}
}
}
}
return foundWitness;
}
bool
rModelChecker::addTransition( MS_state *state_from, MS_state *state_to )
{
bool foundWitness = false;
#if !TRUST_ME
if (state_from->successors.find (state_to) != state_from->successors.end()) {
cerr << "ERROR: rModelChecker::addTransition: transition already exists" << endl;
exit (-1);
}
if (state_to->predecessors.find (state_from) != state_to->predecessors.end() ) {
cerr << "ERROR: rModelChecker::addTransition: transition already exists" << endl;
exit (-1);
}
#endif
state_from->successors.insert( state_to );
state_to->predecessors.insert( state_from );
for (vertexSet_it iter = state_from->sucSubformulaeVertices.begin();
iter != state_from->sucSubformulaeVertices.end(); iter++) {
CT_vertex *vertexCurr = *iter;
PT_node *subformulaCurr = vertexCurr->subformula;
#if !TRUST_ME
if (subformulaCurr->type != PT_SUC) {
cout << "ERROR: rModelChecker::addTransition: Successor vertex does not encode a succcesor type " << endl;
exit (1);
}
if (((PT_operator *)subformulaCurr)->children.size() != 1) {
cout << "ERROR: rModelChecker::addTransition: Successor operator does not have 1 child " << endl;
exit (1);
}
#endif
subformulaeSet_it sfiter = ((PT_operator *)subformulaCurr)->children.begin();
PT_node *subformulaChild = *sfiter;
CT_vertex *vertexNew = this->addVertex (vertexCurr, state_to, subformulaChild);
if (vertexNew) {
if (this->LocalUpdate (vertexNew))
foundWitness = true;
}
if (foundWitness)
break;
}
return foundWitness;
}
stateList
getStateTrajectoryBetweenVertices (CT_vertex *vertexInitial, CT_vertex *vertexFinal )
{
vertexList *solutionVertexList = NULL;
vertexListSet vertexListsCurr;
vertexList *vertexListFinal = new vertexList;
vertexListFinal->push_back (vertexFinal);
vertexListsCurr.insert (vertexListFinal);
// If the final formula is a PT_PRP type, then just trace back to the vertexInitial.
vertexSet verticesProcessed;
verticesProcessed.clear ();
verticesProcessed.insert (vertexFinal);
bool vertex_exists = true;
while (vertex_exists) {
vertex_exists = false;
bool solutionFound = false;
vertexListSet vertexListsNext;
for (vertexListSet_it iter = vertexListsCurr.begin(); iter != vertexListsCurr.end(); iter++) {
vertexList *vertexListThis = *iter;
CT_vertex *vertexLastInList = *(vertexListThis->rbegin());
if ( vertexLastInList == vertexInitial) {
// cout << "found initial vertex" << endl;
solutionVertexList = vertexListThis;
solutionFound = true;
break;
}
for (vertexSet_it iter2 = vertexLastInList->predVertices.begin();
iter2 != vertexLastInList->predVertices.end(); iter2++) {
CT_vertex *vertexPred = *iter2;
if (verticesProcessed.find (vertexPred) == verticesProcessed.end() ) {
vertexList *vertexListNew = new vertexList;
for (vertexList_it iter3 = vertexListThis->begin();
iter3 != vertexListThis->end(); iter3++) {
vertexListNew->push_back (*iter3);
}
vertexListNew->push_back (vertexPred);
vertexListsNext.insert (vertexListNew);
verticesProcessed.insert (vertexPred);
vertex_exists = true;
}
}
}
if (!solutionFound) {
for (vertexListSet_it iter = vertexListsCurr.begin();
iter != vertexListsCurr.end(); iter++) {
vertexList *vertexListThis = *iter;
delete vertexListThis;
}
vertexListsCurr.clear();
for (vertexListSet_it iter = vertexListsNext.begin();
iter != vertexListsNext.end(); iter++) {
vertexListsCurr.insert(*iter);
}
}
}
// revert back the stateList
// cout << "Solution vertex list size :" << solutionVertexList->size() << endl;
stateList trajectory;
trajectory.clear();
MS_state *stateLastInTrajectory = NULL;
for (vertexList_rit iter = solutionVertexList->rbegin();
iter != solutionVertexList->rend(); iter++) {
CT_vertex *vertexThis = *iter;
MS_state *stateThis = vertexThis->state;
if (stateThis != stateLastInTrajectory) {
trajectory.push_back (stateThis);
stateLastInTrajectory = stateThis;
}
}
return trajectory;
}
PGStateList
ModelCheckerPG::getTrajectory()
{
PGState *prev_state = NULL;
PGStateList trajectory;
if (this->lV.size() > 0) {
// TODO
assert( false );
} else {
PGVertex *loopv = NULL;
double min_loop_cost = -1; // Ignored until loopv != NULL
for (PGVertexSet_it nuv = this->nV.begin(); nuv != this->nV.end();
nuv++) {
if ((*nuv)->RV.find( *nuv ) != (*nuv)->RV.end()) {
list<PGVertex *> key;
key.push_back( *nuv );
key.push_back( *nuv );
assert( Cost.find( key ) != Cost.end() );
if (loopv == NULL || this->Cost[key] < min_loop_cost) {
loopv = *nuv;
min_loop_cost = this->Cost[key];
}
}
}
if (loopv == NULL) // No feasible nu-loop
return trajectory;
PGVertex *knotv = NULL;
double min_prefix_cost = -1;
PGVertex *curr = loopv;
do {
list<PGVertex *> key;
key.push_back( loopv );
key.push_back( curr );
assert( Pr.find( key ) != Pr.end() );
curr = Pr[key];
key.clear();
key.push_back( this->initialVertex );
key.push_back( curr );
assert( Cost.find( key ) != Cost.end() );
if (knotv == NULL || Cost[key] < min_prefix_cost) {
knotv = curr;
min_prefix_cost = Cost[key];
}
if (prev_state == NULL || prev_state != curr->state) {
trajectory.push_front( curr->state );
prev_state = curr->state;
}
} while (curr != loopv);
if (trajectory.front() == trajectory.back())
trajectory.pop_back();
while (trajectory.front() != knotv->state) {
PGState *front = trajectory.front();
trajectory.pop_front();
trajectory.push_back( front );
}
trajectory.push_back( knotv->state );
prev_state = trajectory.front();
curr = knotv;
do {
list<PGVertex *> key;
key.push_back( this->initialVertex );
key.push_back( curr );
assert( Pr.find( key ) != Pr.end() );
curr = Pr[key];
if (prev_state != curr->state) {
trajectory.push_front( curr->state );
prev_state = curr->state;
}
} while (curr != this->initialVertex);
std::cerr << "ModelCheckerPG::getTrajectory(): returned trajectory cost is "
<< min_prefix_cost << " + " << min_loop_cost
<< " = " << min_prefix_cost + min_loop_cost << std::endl;
}
return trajectory;
}
stateList
rModelChecker::getTrajectory()
{
stateList trajectory;
if (this->satVertices.empty())
return trajectory;
// Pick one of the sat vertices:
vertexSet_it iterVertexFinal = this->satVertices.begin();
CT_vertex *vertexFinal = *iterVertexFinal;
MS_state *stateFinal = vertexFinal->state;
PT_node *subformulaFinal = vertexFinal->subformula;
if (subformulaFinal->type == PT_PRP) {
trajectory = getStateTrajectoryBetweenVertices( this->initialVertex, vertexFinal );
// cout << "Trajectory num states :" << trajectory.size() << endl;
} else if (subformulaFinal->type == PT_VAR) {
// Get the loop
stateList trajectoryLoop;
CT_vertex *vertexInitial = NULL;
PT_node *subformulaInitial = this->pt.getBoundFormula( subformulaFinal );
for ( vertexSet_it iter = stateFinal->vertices.begin(); iter != stateFinal->vertices.end(); iter++ ) {
if ( (*iter)->subformula == subformulaInitial ) {
vertexInitial = *iter;
break;
}
}
if (vertexInitial == NULL) {
cout << "ERROR: rModelChecker::getTrajectory: no loop found even though claimed earlier" << endl;
exit (1);
}
trajectoryLoop = getStateTrajectoryBetweenVertices (vertexInitial, vertexFinal);
// Get the path that connects initialVertex to the loop
stateList trajectoryPath;
trajectoryPath = getStateTrajectoryBetweenVertices( this->initialVertex, vertexInitial );
// TODO: Only run loop if being verbose?
for (stateList_it iter = trajectoryPath.begin();
iter != trajectoryPath.end(); iter++) {
for (stateList_it iter2 = trajectoryPath.begin();
iter2 != iter; iter2++) {
// if (*iter2 == *iter)
// cout << "Path contains a minor loop" << endl;
}
}
// TODO: Only run loop if being verbose?
int k1 = 0;
for (stateList_it iter = trajectoryLoop.begin();
iter != trajectoryLoop.end(); iter++) {
int k2 = 0;
for (stateList_it iter2 = trajectoryLoop.begin();
iter2 != iter; iter2++) {
// if ( (*iter2 == *iter) && (iter2 != trajectoryLoop.begin()) )
// cout << "Loop contains a minor loop : " << k1 << " - " << k2 << endl;
k2++;
}
k1++;
}
// cout << "k1 : " << trajectoryLoop.size() << endl;
// Concatanate trajectoryPath and trajectoryLoop to form trajectory
// int k =0;
// for (stateList_it iter = trajectoryPath.begin(); iter != trajectoryPath.end(); iter++) {
// k++;
// if (k > 20)
// continue;
// trajectory.push_back (*iter);
// }
// int k = 0;
// for (stateList_it iter = trajectoryLoop.begin(); iter != trajectoryLoop.end(); iter++) {
// k++;
// if ( (k > 124) )
// continue;
// trajectory.push_back (*iter);
// }
// cout << "k :" << k << endl;
trajectoryPath.pop_back();
for (stateList_it iter = trajectoryPath.begin();
iter != trajectoryPath.end(); iter++)
trajectory.push_back (*iter);
for (stateList_it iter = trajectoryLoop.begin();
iter != trajectoryLoop.end(); iter++)
trajectory.push_back (*iter);
} else {
cout << "ERROR: rModelChecker::getTrajectory: final subformula type is neither PT_PRP nor PT_VAR" << endl;
exit(1);
}
return trajectory;
}
MS_state *
rModelChecker::findStateById( int id )
{
MS_state *state = NULL;
for (stateSet_it iter = this->states.begin();
iter != this->states.end(); iter++)
if ( (*iter)->identifier == id)
state = *iter;
return state;
}
bool
rModelChecker::addTransitionById( int id_from, int id_to )
{
MS_state *state_from = this->findStateById( id_from );
MS_state *state_to = this->findStateById( id_to );
#if !TRUST_ME
if ((state_from == NULL) || (state_to == NULL)) {
cout << "ERROR: rModelChecker::addTransitionbyID: state not found " << endl;
exit(1);
}
#endif
return this->addTransition (state_from, state_to);
}
Find minimum cost trajectory, instead of min loop then prefix
Before this changeset, a trajectory was found by searching for the
lowest cost loop (suffix), and then searching for the lowest cost
prefix that reaches it. Now a minimum cost trajectory is actually
found because comparison is made among entire trajectories (i.e.,
prefix and suffix pairs).
Also, include the prefix in the saved least cost found thus far.
#include "ms.h"
#include "pt.h"
#include <assert.h>
void ModelCheckerPG::dumpDOT( std::ofstream &outf )
{
propositionSet_it prp_it;
int pcount;
outf << "digraph G {\n \"\" [shape=none]" << std::endl;
outf << "\"\" -> \"" << this->initialVertex << "\"" << std::endl;
for (PGStateSet_it it_state = this->states.begin();
it_state != this->states.end(); it_state++) {
for (PGVertexSet_it it_vertex = (*it_state)->vertices.begin();
it_vertex != (*it_state)->vertices.end(); it_vertex++) {
outf << "\"" << *it_vertex << "\" [label=\"";
outf << *it_state << " {";
pcount = 0;
for (prp_it = (*it_state)->labeledPrp.begin();
prp_it != (*it_state)->labeledPrp.end(); prp_it++) {
if (pcount > 0)
outf << ", ";
outf << "p" << *prp_it;
pcount++;
}
outf << "}\\n";
printFormula( (*it_vertex)->subformula, outf );
outf << "\"]" << std::endl;
for (PGVertexSet_it it_vertex_succ = (*it_vertex)->succVertices.begin();
it_vertex_succ != (*it_vertex)->succVertices.end(); it_vertex_succ++) {
outf << "\"" << *it_vertex << "\" -> \"" << *it_vertex_succ << "\"" << std::endl;
}
}
}
outf << "}";
}
void ModelCheckerPG::optRewire( PGState *z_new )
{
double c_new;
bool updated;
for (PGVertexSet_it z_new_v_it = z_new->vertices.begin();
z_new_v_it != z_new->vertices.end(); z_new_v_it++) {
if ((*z_new_v_it)->subformula->parent != NULL
&& (*z_new_v_it)->subformula->parent->type == PT_SUC) {
// Like lines 21-28 of Algorithm 5 of the ACC 2012 paper
updated = false;
for (PGVertexSet_it rv_it = (*z_new_v_it)->RV.begin();
rv_it != (*z_new_v_it)->RV.end(); rv_it++) {
list<PGVertex *>key_existing;
key_existing.push_back( *rv_it );
key_existing.push_back( *z_new_v_it );
assert( Cost.find( key_existing ) != Cost.end() );
for (PGVertexSet_it pre_it = (*z_new_v_it)->predVertices.begin();
pre_it != (*z_new_v_it)->predVertices.end(); pre_it++) {
if ((*pre_it)->subformula->type != PT_SUC
|| *((*pre_it)->subformula->children.begin()) != (*z_new_v_it)->subformula)
continue;
list<PGVertex *> key;
key.push_back( *rv_it );
key.push_back( *pre_it );
assert( Cost.find( key ) != Cost.end() );
c_new = Cost[key] + ((*pre_it)->state == (*z_new_v_it)->state ? 0 : (*pre_it)->state->edgeCost[(*z_new_v_it)->state]);
if (c_new < Cost[key_existing]) {
Pr[key_existing] = *pre_it;
Cost[key_existing] = c_new;
updated = true;
}
}
}
if (updated)
propagateCost( *z_new_v_it );
} else if ((*z_new_v_it)->subformula->type == PT_SUC) {
// Like lines 29-36 of Algorithm 5 of the ACC 2012 paper
for (PGVertexSet_it post_it = (*z_new_v_it)->succVertices.begin();
post_it != (*z_new_v_it)->succVertices.end(); post_it++) {
if ((*post_it)->subformula != *((*z_new_v_it)->subformula->children.begin()))
continue;
updated = false;
for (PGVertexSet_it rv_it = (*post_it)->RV.begin();
rv_it != (*post_it)->RV.end(); rv_it++) {
if ((*z_new_v_it)->RV.find( *rv_it ) == (*z_new_v_it)->RV.end())
continue;
list<PGVertex *>key;
key.push_back( *rv_it );
key.push_back( *z_new_v_it );
assert( Cost.find( key ) != Cost.end() );
c_new = Cost[key] + ((*z_new_v_it)->state == (*post_it)->state ? 0 : (*z_new_v_it)->state->edgeCost[(*post_it)->state]);
list<PGVertex *> key_existing;
key_existing.push_back( *rv_it );
key_existing.push_back( *post_it );
assert( Cost.find( key_existing ) != Cost.end() );
if (c_new < Cost[key_existing]) {
Pr[key_existing] = *z_new_v_it;
Cost[key_existing] = c_new;
updated = true;
}
}
if (updated)
propagateCost( *post_it );
}
}
}
}
void ModelCheckerPG::propagateCost( PGVertex *changed_vertex )
{
PGVertexSet visited;
PGVertexSet current;
PGVertexSet next;
PGVertexSet_it it_current_v;
PGVertex *current_v;
double c_new;
for (PGStateSet_it it_state = this->states.begin();
it_state != this->states.end(); it_state++) {
for (PGVertexSet_it it_start_v = (*it_state)->vertices.begin();
it_start_v != (*it_state)->vertices.end(); it_start_v++) {
visited.clear();
visited.insert( changed_vertex );
current.clear();
next.clear();
next.insert( changed_vertex );
while (next.size() > 0) {
current.swap( next );
while (current.size() > 0) {
it_current_v = current.begin();
current_v = *it_current_v;
current.erase( it_current_v );
if (current_v->RV.find( *it_start_v ) == current_v->RV.end())
continue;
list <PGVertex *>key_existing;
key_existing.push_back( *it_start_v );
key_existing.push_back( current_v );
assert( Cost.find( key_existing ) != Cost.end() );
for (PGVertexSet_it it_predecessor_v = current_v->predVertices.begin();
it_predecessor_v != current_v->predVertices.end(); it_predecessor_v++) {
if ((*it_predecessor_v)->RV.find( *it_start_v ) == (*it_predecessor_v)->RV.end())
continue;
list <PGVertex *>key;
key.push_back( *it_start_v );
key.push_back( *it_predecessor_v );
assert( Cost.find( key ) != Cost.end() );
c_new = Cost[key] + ((*it_predecessor_v)->state == current_v->state ? 0 : (*it_predecessor_v)->state->edgeCost[current_v->state]);
if (c_new < Cost[key_existing]) {
Pr[key_existing] = *it_predecessor_v;
Cost[key_existing] = c_new;
}
}
for (PGVertexSet_it it_successor_v = current_v->succVertices.begin();
it_successor_v != current_v->succVertices.end(); it_successor_v++) {
if (visited.find( *it_successor_v ) != visited.end())
continue;
next.insert( *it_successor_v );
visited.insert( *it_successor_v );
}
}
}
}
}
}
int getColor( PGVertex *vertex )
{
if (vertex->subformula->type == PT_GFP) {
if (vertex->subformula->AD % 2 == 0) {
return vertex->subformula->AD;
} else {
return vertex->subformula->AD + 1;
}
} else if (vertex->subformula->type == PT_LFP) {
if (vertex->subformula->AD % 2 == 0) {
return vertex->subformula->AD + 1;
} else {
return vertex->subformula->AD;
}
}
return 0;
}
MS_state::MS_state()
: vertices(), successors(), predecessors(), labeledPrp()
{
this->data = 0;
this->identifier = -1;
this->labeledPrp.clear();
}
PGState::PGState()
: vertices(), successors(), predecessors(), labeledPrp()
{
this->data = 0;
this->labeledPrp.clear();
}
bool MS_state::addprop( int newprop )
{
this->labeledPrp.insert( newprop );
return true;
}
bool PGState::addprop( int newprop )
{
this->labeledPrp.insert( newprop );
return true;
}
ModelCheckerPG::ModelCheckerPG()
{
this->initialState = NULL;
this->initialVertex = NULL;
this->states.clear();
this->lV.clear();
this->nV.clear();
this->Pr.clear();
this->Cost.clear();
this->last_min_cost = -1.0;
}
rModelChecker::rModelChecker()
{
this->initialState = NULL;
this->initialVertex = NULL;
this->states.clear();
this->satVertices.clear();
this->num_local_updates = 0;
this->num_update_reachabilities = 0;
}
rModelChecker::~rModelChecker()
{ }
CT_vertex *
rModelChecker::addVertex( CT_vertex *parentVertex, MS_state *state,
PT_node *subformula )
{
#if !TRUST_ME
if (this->states.find (state) == this->states.end()) {
cout << "ERROR: rModelChecker::addVertex: state is not in this->states";
exit (1);
}
#endif
CT_vertex *vertexNew;
// Check whether the vertex already exists
bool vertexFound = false;
for (vertexSet_it iter = state->vertices.begin();
iter != state->vertices.end(); iter++) {
CT_vertex *vertexCurr = *iter;
if (vertexCurr->subformula == subformula){
vertexNew = vertexCurr;
vertexFound = true;
break;
}
}
// Create a new vertex if one does not exist
if (!vertexFound) {
vertexNew = new CT_vertex;
vertexNew->state = state;
vertexNew->subformula = subformula;
vertexNew->succVertices.clear();
vertexNew->predVertices.clear();
vertexNew->reachingVertices.clear();
PT_node *parentSubformula = parentVertex->subformula;
if ((parentSubformula->type == PT_GFP)
&& !(this->pt.compareFormulaSize( subformula, parentSubformula ))) {
// then place it to its own reachingVertices
vertexNew->reachingVertices.insert( parentVertex );
#if VERBOSE_DBG
cout << "Insert GFP to reachability" << endl;
#endif
}
state->vertices.insert (vertexNew);
}
// Update the predVertices and succVertices of both of the vertices
if (vertexNew->predVertices.find( parentVertex ) == vertexNew->predVertices.end() )
vertexNew->predVertices.insert( parentVertex );
if (parentVertex->succVertices.find( vertexNew ) == parentVertex->succVertices.end() )
parentVertex->succVertices.insert( vertexNew );
bool reachabilityUpdateOccurred = this->UpdateReachability( parentVertex, vertexNew );
if ((!vertexFound) || reachabilityUpdateOccurred)
return vertexNew;
return NULL;
}
bool // Returns true if a modification is made, it returns false otherwise
rModelChecker::UpdateReachability( CT_vertex *vertexFrom, CT_vertex *vertexTo )
{
bool addedNewReachingVertex = false;
this->num_update_reachabilities++;
// Compute vertexTo->reachingVertices =
// {vertex \in vertexFrom->reachingVertices : vertex->subformula >= vertexTo->subformula} \cup vertexTo->reachingVertices
// - The computation is done in linear time
vertexSet_it iterTo = vertexTo->reachingVertices.begin();
vertexSet_it iterToPrev = iterTo;
vertexSet_it iterToEnd = vertexTo->reachingVertices.end();
for (vertexSet_it iterFrom = vertexFrom->reachingVertices.begin();
iterFrom != vertexFrom->reachingVertices.end(); iterFrom++) {
while ((*iterTo < *iterFrom) && (iterTo != iterToEnd)) {
iterToPrev = iterTo;
iterTo++;
}
if ((*iterFrom == *iterTo) && (iterTo != iterToEnd)) {
//cout<< "yes" << endl;
continue;
}
if (this->pt.compareFormulaSize( vertexTo->subformula,
(*iterFrom)->subformula))
continue;
vertexTo->reachingVertices.insert (iterToPrev, *iterFrom);
addedNewReachingVertex = true;
}
// If vertexTo is a PT_VAR type subformula, then check if vertexTo is a sat node
if ((vertexTo->subformula->type == PT_VAR) ) {
// Check whether this node is reachable from a vertex = (state, BindingFormula(var))
PT_node *bindingSubformula = this->pt.getBoundFormula (vertexTo->subformula);
// Search the reaching vertices for vertex = (state, bindingSubformula)
bool gfpLoopFound = false;
for (vertexSet_it iter = vertexTo->reachingVertices.begin();
iter != vertexTo->reachingVertices.end(); iter++) {
CT_vertex *vertexCurr = *iter;
if ((vertexCurr->state == vertexTo->state)
&& (vertexCurr->subformula == bindingSubformula)) {
gfpLoopFound = true;
break;
}
}
if (gfpLoopFound) {
this->satVertices.insert (vertexTo);
}
}
// If added a new reaching vertex into reachingVertices in vertexTo,
// then run UpdateReachability for each successor vertex of vertexTo
if (addedNewReachingVertex) {
for (vertexSet_it iter = vertexTo->succVertices.begin();
iter != vertexTo->succVertices.end(); iter++) {
this->UpdateReachability (vertexTo,*iter);
}
}
return addedNewReachingVertex;
}
bool // Returns true if a witness is found, otherwise it returns false
rModelChecker::LocalUpdate( CT_vertex *vertex )
{
this->num_local_updates++;
MS_state *stateThis = vertex->state;
PT_node *subformulaThis = vertex->subformula;
#if VERBOSE_DBG
cout << "state : " << stateThis->identifier << " - subformula : " << subformulaThis->type << endl;
cout << " reachable states-subformula:" << endl;
for (vertexSet_it iter = vertex->reachingVertices.begin();
iter != vertex->reachingVertices.end(); iter++){
CT_vertex *reachingVertex = *iter;
cout << " - reaching state: " << reachingVertex->state->identifier << endl;
}
#endif
bool foundWitness = false;
// If subformulaThis is a suc-formula then make sure it is in the list of subformulae of this stateThis
if (subformulaThis->type == PT_SUC) {
if (stateThis->sucSubformulaeVertices.find (vertex) == stateThis->sucSubformulaeVertices.end()) {
stateThis->sucSubformulaeVertices.insert (vertex);
#if VERBOSE_DBG
cout << " --> added suc-subformula : " << stateThis->identifier << endl;
#endif
}
}
// 1. ATOMIC PROPOSITIONS
if (subformulaThis->type == PT_PRP || subformulaThis->type == PT_NPRP) {
// Check whether this literal is satisfied in this state
// if so, then we found a witness since this node is reachable from root
int prpCurr = ((PT_prp *)subformulaThis)->prp;
if (stateThis->labeledPrp.find ( prpCurr ) != stateThis->labeledPrp.end() ) {
if (subformulaThis->type == PT_PRP) {
cout << "FOUND A WITNESS: PRP" << endl;
this->satVertices.insert (vertex);
foundWitness = true;
}
} else if (subformulaThis->type == PT_NPRP) {
cout << "FOUND A WITNESS: NPRP" << endl;
this->satVertices.insert (vertex);
foundWitness = true;
}
}
// 2. VARIABLES
if (subformulaThis->type == PT_VAR) {
// Check whether this node is reachable from a vertex = (state, BindingFormula(var))
PT_node *bindingSubformula = this->pt.getBoundFormula (subformulaThis);
// Search the reaching vertices for vertex = (state, bindingSubformula)
bool gfpLoopFound = false;
for (vertexSet_it iter = vertex->reachingVertices.begin();
iter != vertex->reachingVertices.end(); iter++) {
CT_vertex *vertexCurr = *iter;
if ((vertexCurr->state == stateThis)
&& (vertexCurr->subformula == bindingSubformula)) {
gfpLoopFound = true;
break;
}
}
// If vertex = (state, bindingSubformula) if found to be reaching,
// then declare wictory
if (gfpLoopFound) {
this->satVertices.insert (vertex);
foundWitness = true;
}
// Create the new node with the bindingSubformula
CT_vertex *vertexNew = this->addVertex (vertex, stateThis, bindingSubformula);
if (vertexNew) {
if (this->LocalUpdate (vertexNew))
foundWitness = true;
}
}
// 3. AND OPERATOR
if (subformulaThis->type == PT_AND) {
#if !TRUST_ME
if ( ((PT_operator *)subformulaThis)->children.size() != 2) {
cout << "ERROR: rModelChecker::LocalUpdate: AND OPERATOR does not have 2 children" << endl;
exit (1);
}
#endif
subformulaeSet_it iter = ((PT_operator *)subformulaThis)->children.begin();
// Get left subformula
PT_node *subformulaLeft = *iter;
// Get right subformula
iter++;
PT_node *subformulaRight = *iter;
PT_node *subformulaChild = NULL;
if (subformulaLeft->type == PT_PRP) {
// Create a new node using subformulaRight
if (stateThis->labeledPrp.find( ((PT_prp *)subformulaLeft)->prp ) != stateThis->labeledPrp.end())
subformulaChild = subformulaRight;
} else if (subformulaRight->type == PT_PRP) {
// Create a new node using subformulaLeft
if (stateThis->labeledPrp.find( ((PT_prp *)subformulaRight)->prp ) != stateThis->labeledPrp.end())
subformulaChild = subformulaLeft;
} else if (subformulaLeft->type == PT_NPRP) {
// Create a new node using subformulaRight
if (stateThis->labeledPrp.find( ((PT_prp *)subformulaLeft)->prp ) == stateThis->labeledPrp.end())
subformulaChild = subformulaRight;
} else if (subformulaRight->type == PT_NPRP) {
// Create a new node using subformulaLeft
if (stateThis->labeledPrp.find( ((PT_prp *)subformulaRight)->prp ) == stateThis->labeledPrp.end())
subformulaChild = subformulaLeft;
} else {
cout << "ERROR: rModelChecker::LocalUpdate: No child of the AND OPERATOR is a literal" << endl;
exit (1);
}
/* If stateThis satisfies the proposition, then add the vertex and
update the reachability graph */
if (subformulaChild) {
CT_vertex *vertexNew = addVertex( vertex, stateThis, subformulaChild );
if (vertexNew)
if (this->LocalUpdate( vertexNew ))
foundWitness = true;
}
}
// 4. OR OPERATOR
if (subformulaThis->type == PT_OR) {
#if !TRUST_ME
if (((PT_operator *)subformulaThis)->children.size() != 2) {
cout << "ERROR: rModelChecker::LocalUpdate: OR OPERATOR does not have 2 children" << endl;
exit (1);
}
#endif
/* Add both of the child subformula to the model checker and update the
reachabilities */
for (subformulaeSet_it iter = ((PT_operator *)subformulaThis)->children.begin();
iter != ((PT_operator *)subformulaThis)->children.end(); iter++) {
PT_node *subformulaChild = *iter;
CT_vertex *vertexNew = this->addVertex (vertex, stateThis,subformulaChild);
if (vertexNew) {
if (this->LocalUpdate( vertexNew ))
foundWitness = true;
}
if (foundWitness)
break;
}
}
// 5. LFP OPERATOR
if (subformulaThis->type == PT_LFP) {
#if !TRUST_ME
if (((PT_operator *)subformulaThis)->children.size() != 1) {
cout << "ERROR: rModelChecker::LocalUpdate: LFP OPERATOR does not have 1 children" << endl;
exit (1);
}
#endif
subformulaeSet_it iter = ((PT_operator *)subformulaThis)->children.begin();
PT_node *subformulaChild = *iter;
CT_vertex *vertexNew = this->addVertex( vertex,stateThis, subformulaChild );
if (vertexNew) {
if (this->LocalUpdate (vertexNew))
foundWitness = true;
}
}
// 6. GFP OPEARATOR
if (subformulaThis->type == PT_GFP) {
#if !TRUST_ME
if (((PT_operator *)subformulaThis)->children.size() != 1) {
cout << "ERROR: rModelChecker::LocalUpdate: GFP OPERATOR does not have 1 children" << endl;
exit (1);
}
#endif
subformulaeSet_it iter = ((PT_operator *)subformulaThis)->children.begin();
PT_node *subformulaChild = *iter;
CT_vertex *vertexNew = this->addVertex (vertex,stateThis, subformulaChild);
if (vertexNew) {
if (this->LocalUpdate (vertexNew))
foundWitness = true;
}
}
// 7. SUC OPERATOR
if (subformulaThis->type == PT_SUC) {
#if !TRUST_ME
if ( ((PT_operator *)subformulaThis)->children.size() != 1) {
cout << "ERROR: rModelChecker::LocalUpdate: LFP OPERATOR does not have 1 children" << endl;
exit (1);
}
#endif
subformulaeSet_it iter = ((PT_operator *)subformulaThis)->children.begin();
PT_node *subformulaChild = *iter;
for (stateSet_it ssiter = stateThis->successors.begin();
ssiter != stateThis->successors.end(); ssiter++) {
MS_state *stateSucc = *ssiter;
CT_vertex *vertexNew = this->addVertex (vertex,stateSucc, subformulaChild);
if (vertexNew) {
if (this->LocalUpdate (vertexNew))
foundWitness = true;
}
if (foundWitness)
break;
}
}
return foundWitness;
}
bool
ModelCheckerPG::addState( PGState *state )
{
#if !TRUST_ME
for (PGStateSet_it iter = this->states.begin();
iter != this->states.end(); iter++)
if (*iter == state) {
cout << "ERROR: ModelCheckerPG::addState: state already exists" << endl;
exit(1);
}
#endif
if (this->initialState == NULL) {
this->initialState = state;
PGVertex *vertexNew = new PGVertex;
vertexNew->state = state;
vertexNew->subformula = this->pt.getRoot();
vertexNew->succVertices.clear();
vertexNew->predVertices.clear();
vertexNew->RV.clear();
vertexNew->color = getColor( vertexNew );
this->initialVertex = vertexNew;
/* Adding the initial vertex into the RV set of the initial vertex has
the same effect as the "dummy vertex" used in the ACC 2012 paper. */
vertexNew->RV.insert( this->initialVertex );
list<PGVertex *> key;
key.push_back( this->initialVertex );
key.push_back( this->initialVertex );
Cost[key] = 0.0;
state->vertices.clear();
state->successors.clear();
state->predecessors.clear();
state->vertices.insert( vertexNew );
#if !TRUSTME
this->states.insert( state );
#endif
// TODO: Check for witness upon this special first step
this->updateArena( NULL, this->initialVertex );
} else {
#if !TRUSTME
this->states.insert( state );
#endif
state->vertices.clear();
state->successors.clear();
state->predecessors.clear();
}
return false;
}
bool
rModelChecker::addState( MS_state *state )
{
#if !TRUST_ME
for (stateSet_it iter = this->states.begin();
iter != this->states.end(); iter++)
if (*iter == state) {
cout << "ERROR: rModelChecker::addState: state already exists" << endl;
exit(1);
}
#endif
if (this->initialState == NULL) {
this->initialState = state;
CT_vertex *vertexNew = new CT_vertex;
vertexNew->state = state;
vertexNew->subformula = this->pt.getRoot();
vertexNew->succVertices.clear();
vertexNew->predVertices.clear();
vertexNew->reachingVertices.clear();
// vertexNew->reachingVertices.insert (vertexNew);
this->initialVertex = vertexNew;
state->vertices.clear();
state->successors.clear();
state->predecessors.clear();
state->vertices.insert( vertexNew );
#if !TRUSTME
this->states.insert( state );
#endif
this->LocalUpdate( vertexNew );
} else {
// TODO: This block is redundant with the second part of the if-block above.
this->states.insert( state );
state->vertices.clear();
state->successors.clear();
state->predecessors.clear();
}
return false;
}
void
ModelCheckerPG::updateArena( PGVertex *vertex_from, PGVertex *vertex_to )
{
// If edge between these vertices already exists, do nothing.
if (vertex_from != NULL
&& vertex_from->succVertices.find( vertex_to ) != vertex_from->succVertices.end())
return;
// Remove if path cannot be winning for Player 1, hence not correct
PT_prp *conjunctPrp = NULL;
if (vertex_to->subformula->type == PT_AND)
conjunctPrp = this->pt.getConjunctPrp( (PT_operator *)(vertex_to->subformula) );
if ((vertex_to->subformula->type == PT_PRP
&& (vertex_to->state->labeledPrp.find( ((PT_prp *)vertex_to->subformula)->prp )
== vertex_to->state->labeledPrp.end()))
|| (vertex_to->subformula->type == PT_NPRP
&& (vertex_to->state->labeledPrp.find( ((PT_prp *)vertex_to->subformula)->prp )
!= vertex_to->state->labeledPrp.end()))
|| (vertex_to->subformula->type == PT_AND
&& ((conjunctPrp->type == PT_PRP && (vertex_to->state->labeledPrp.find( conjunctPrp->prp )
== vertex_to->state->labeledPrp.end()))
|| (conjunctPrp->type == PT_NPRP && (vertex_to->state->labeledPrp.find( conjunctPrp->prp )
!= vertex_to->state->labeledPrp.end()))))) {
// TODO: Like lines 3-7 of Algorithm 3 of the ACC 2012 paper
vertex_to->state->vertices.erase( vertex_to );
delete vertex_to;
return;
}
if (vertex_from != NULL
&& vertex_from->subformula->type == PT_GFP
&& this->nV.find( vertex_from ) == this->nV.end()) {
// TODO: && acceptVertex()
this->nV.insert( vertex_from );
}
if ((vertex_to->subformula->type == PT_PRP
|| vertex_to->subformula->type == PT_NPRP)
&& this->lV.find( vertex_to ) == this->lV.end()) {
this->lV.insert( vertex_to );
}
/* TODO: Add separately to V1 or V2 vertex sets corresponding to lines 13-16
in Algorithm 3 of the ACC 2012 paper, which may not be correct. */
// Create the edge
if (vertex_from != NULL) {
vertex_from->succVertices.insert( vertex_to );
vertex_to->predVertices.insert( vertex_from );
}
if (vertex_to->subformula->type == PT_AND
&& ((conjunctPrp->type == PT_PRP
&& (vertex_to->state->labeledPrp.find( conjunctPrp->prp )
!= vertex_to->state->labeledPrp.end()))
|| (conjunctPrp->type == PT_NPRP
&& (vertex_to->state->labeledPrp.find( conjunctPrp->prp )
== vertex_to->state->labeledPrp.end())))) {
subformulaeSet_it sf = vertex_to->subformula->children.begin();
if (*sf == conjunctPrp)
sf++;
PGVertex *vertex_to2 = NULL;
for (PGVertexSet_it v_to = vertex_to->state->vertices.begin();
v_to != vertex_to->state->vertices.end(); v_to++) {
if ((*v_to)->subformula == *sf) {
vertex_to2 = *v_to;
break;
}
}
if (vertex_to2 == NULL) {
vertex_to2 = new PGVertex;
vertex_to2->state = vertex_to->state;
vertex_to->state->vertices.insert( vertex_to2 );
vertex_to2->subformula = *sf;
vertex_to2->succVertices.clear();
vertex_to2->predVertices.clear();
vertex_to2->RV.clear();
vertex_to2->color = getColor( vertex_to2 );
}
updateArena( vertex_to, vertex_to2 );
}
if (vertex_to->subformula->type == PT_OR) {
subformulaeSet_it sf = vertex_to->subformula->children.begin();
PGVertex *vertex_to2 = NULL;
for (PGVertexSet_it v_to = vertex_to->state->vertices.begin();
v_to != vertex_to->state->vertices.end(); v_to++) {
if ((*v_to)->subformula == *sf) {
vertex_to2 = *v_to;
break;
}
}
if (vertex_to2 == NULL) {
vertex_to2 = new PGVertex;
vertex_to2->state = vertex_to->state;
vertex_to->state->vertices.insert( vertex_to2 );
vertex_to2->subformula = *sf;
vertex_to2->succVertices.clear();
vertex_to2->predVertices.clear();
vertex_to2->RV.clear();
vertex_to2->color = getColor( vertex_to2 );
}
sf++;
PGVertex *vertex_to3 = NULL;
for (PGVertexSet_it v_to = vertex_to->state->vertices.begin();
v_to != vertex_to->state->vertices.end(); v_to++) {
if ((*v_to)->subformula == *sf) {
vertex_to3 = *v_to;
break;
}
}
if (vertex_to3 == NULL) {
vertex_to3 = new PGVertex;
vertex_to3->state = vertex_to->state;
vertex_to->state->vertices.insert( vertex_to3 );
vertex_to3->subformula = *sf;
vertex_to3->succVertices.clear();
vertex_to3->predVertices.clear();
vertex_to3->RV.clear();
vertex_to3->color = getColor( vertex_to3 );
}
updateArena( vertex_to, vertex_to2 );
updateArena( vertex_to, vertex_to3 );
}
if (vertex_to->subformula->type == PT_SUC) {
for (PGStateSet_it next_state = vertex_to->state->successors.begin();
next_state != vertex_to->state->successors.end(); next_state++) {
PGVertex *vertex_to2 = NULL;
for (PGVertexSet_it v_to = (*next_state)->vertices.begin();
v_to != (*next_state)->vertices.end(); v_to++) {
if ((*v_to)->subformula == *(vertex_to->subformula->children.begin())) {
vertex_to2 = *v_to;
break;
}
}
if (vertex_to2 == NULL) {
vertex_to2 = new PGVertex;
vertex_to2->state = *next_state;
vertex_to2->state->vertices.insert( vertex_to2 );
vertex_to2->subformula = *(vertex_to->subformula->children.begin());
vertex_to2->succVertices.clear();
vertex_to2->predVertices.clear();
vertex_to2->RV.clear();
vertex_to2->color = getColor( vertex_to2 );
}
updateArena( vertex_to, vertex_to2 );
}
}
if (vertex_to->subformula->type == PT_VAR) {
PT_node *bf = this->pt.getBoundFormula( vertex_to->subformula );
PGVertex *vertex_to2 = NULL;
for (PGVertexSet_it v_to = vertex_to->state->vertices.begin();
v_to != vertex_to->state->vertices.end(); v_to++) {
if ((*v_to)->subformula == bf) {
vertex_to2 = *v_to;
break;
}
}
if (vertex_to2 == NULL) {
vertex_to2 = new PGVertex;
vertex_to2->state = vertex_to->state;
vertex_to->state->vertices.insert( vertex_to2 );
vertex_to2->subformula = bf;
vertex_to2->succVertices.clear();
vertex_to2->predVertices.clear();
vertex_to2->RV.clear();
vertex_to2->color = getColor( vertex_to2 );
}
updateArena( vertex_to, vertex_to2 );
}
if (vertex_to->subformula->type == PT_LFP
|| vertex_to->subformula->type == PT_GFP) {
subformulaeSet_it sf = vertex_to->subformula->children.begin();
PGVertex *vertex_to2 = NULL;
for (PGVertexSet_it v_to = vertex_to->state->vertices.begin();
v_to != vertex_to->state->vertices.end(); v_to++) {
if ((*v_to)->subformula == *sf) {
vertex_to2 = *v_to;
break;
}
}
if (vertex_to2 == NULL) {
vertex_to2 = new PGVertex;
vertex_to2->state = vertex_to->state;
vertex_to->state->vertices.insert( vertex_to2 );
vertex_to2->subformula = *sf;
vertex_to2->succVertices.clear();
vertex_to2->predVertices.clear();
vertex_to2->RV.clear();
vertex_to2->color = getColor( vertex_to2 );
}
updateArena( vertex_to, vertex_to2 );
}
if (vertex_from != NULL)
updateVertexSets( vertex_from, vertex_to );
}
void
ModelCheckerPG::updateVertexSets( PGVertex *vertex_from, PGVertex *vertex_to )
{
bool updatedVertexSet = false;
double edge_cost = vertex_from->state == vertex_to->state ? 0 : vertex_from->state->edgeCost[vertex_to->state];
for (PGVertexSet_it rv_it = vertex_from->RV.begin(); rv_it != vertex_from->RV.end(); rv_it++) {
if (vertex_to->RV.find( *rv_it ) == vertex_to->RV.end()
&& (vertex_to->color <= (*rv_it)->color || *rv_it == this->initialVertex)) {
vertex_to->RV.insert( *rv_it );
list<PGVertex *> key;
key.push_back( *rv_it );
key.push_back( vertex_to );
list<PGVertex *> key_base;
key_base.push_back( *rv_it );
key_base.push_back( vertex_from );
assert( Cost.find( key_base ) != Cost.end() );
assert( Pr.find( key ) == Pr.end() );
this->Pr[key] = vertex_from;
this->Cost[key] = Cost[key_base] + edge_cost;
updatedVertexSet = true;
}
}
if (this->nV.find( vertex_from ) != this->nV.end()) {
if (vertex_to->RV.find( vertex_from ) == vertex_to->RV.end()
&& (vertex_to->color <= vertex_from->color || vertex_from == this->initialVertex)) {
assert( !(vertex_to == vertex_from && edge_cost == 0) );
vertex_to->RV.insert( vertex_from );
list<PGVertex *> key;
key.push_back( vertex_from );
key.push_back( vertex_to );
this->Pr[key] = vertex_from;
this->Cost[key] = edge_cost;
updatedVertexSet = true;
}
}
if (updatedVertexSet) {
for (PGVertexSet_it next_v_to = vertex_to->succVertices.begin();
next_v_to != vertex_to->succVertices.end(); next_v_to++)
updateVertexSets( vertex_to, *next_v_to );
}
}
/* Version that restricts enumeration to only vertices that have been added to
the arena thus far and have associated formula of the form suc f. This is
different from AddTransition (page 739) in the ACC 2012 paper. */
bool
ModelCheckerPG::addTransition( PGState *state_from, PGState *state_to, double edge_cost )
{
bool foundWitness = false;
#if !TRUST_ME
if (state_from->successors.find (state_to) != state_from->successors.end()) {
cerr << "ERROR: ModelCheckerPG::addTransition: transition already exists" << endl;
exit (-1);
}
if (state_to->predecessors.find (state_from) != state_to->predecessors.end() ) {
cerr << "ERROR: ModelCheckerPG::addTransition: transition already exists" << endl;
exit (-1);
}
#endif
state_from->successors.insert( state_to );
state_to->predecessors.insert( state_from );
if (edge_cost >= 0)
state_from->edgeCost[state_to] = edge_cost;
for (PGVertexSet_it v_from = state_from->vertices.begin();
v_from != state_from->vertices.end(); v_from++) {
if ((*v_from)->subformula->type != PT_SUC)
continue;
// Create arena vertices if needed
PGVertex *vertex_to = NULL;
for (PGVertexSet_it v_to = state_to->vertices.begin();
v_to != state_to->vertices.end(); v_to++) {
if ((*v_to)->subformula->parent == (*v_from)->subformula) {
vertex_to = *v_to;
break;
}
}
if (vertex_to == NULL) {
vertex_to = new PGVertex;
vertex_to->state = state_to;
state_to->vertices.insert( vertex_to );
vertex_to->subformula = *((*v_from)->subformula->children.begin());
vertex_to->succVertices.clear();
vertex_to->predVertices.clear();
vertex_to->RV.clear();
vertex_to->color = getColor( vertex_to );
}
updateArena( *v_from, vertex_to );
if (this->lV.size() > 0) {
std::cerr << "nonempty lV" << std::endl;
foundWitness = true;
} else {
PGVertex *loopv;
PGVertex *curr;
double min_cost = -1;
double loop_cost, prefix_cost;
for (PGVertexSet_it nuv = this->nV.begin(); nuv != this->nV.end();
nuv++) {
if ((*nuv)->RV.find( *nuv ) != (*nuv)->RV.end()) {
list<PGVertex *> key;
key.push_back( *nuv );
key.push_back( *nuv );
assert( this->Cost.find( key ) != this->Cost.end() );
loop_cost = this->Cost[key];
if (loop_cost == 0)
continue;
loopv = *nuv;
curr = loopv;
prefix_cost = -1;
do {
key.clear();
key.push_back( loopv );
key.push_back( curr );
assert( Pr.find( key ) != Pr.end() );
curr = Pr[key];
key.clear();
key.push_back( this->initialVertex );
key.push_back( curr );
assert( Cost.find( key ) != Cost.end() );
if (prefix_cost < 0 || Cost[key] < prefix_cost) {
prefix_cost = Cost[key];
}
} while (curr != loopv);
if (min_cost < 0 || prefix_cost + loop_cost < min_cost) {
min_cost = prefix_cost + loop_cost;
foundWitness = true;
}
}
}
if (foundWitness) {
if (this->last_min_cost < 0 || min_cost < this->last_min_cost) {
this->last_min_cost = min_cost;
std::cerr << min_cost << std::endl;
}
}
}
}
return foundWitness;
}
bool
rModelChecker::addTransition( MS_state *state_from, MS_state *state_to )
{
bool foundWitness = false;
#if !TRUST_ME
if (state_from->successors.find (state_to) != state_from->successors.end()) {
cerr << "ERROR: rModelChecker::addTransition: transition already exists" << endl;
exit (-1);
}
if (state_to->predecessors.find (state_from) != state_to->predecessors.end() ) {
cerr << "ERROR: rModelChecker::addTransition: transition already exists" << endl;
exit (-1);
}
#endif
state_from->successors.insert( state_to );
state_to->predecessors.insert( state_from );
for (vertexSet_it iter = state_from->sucSubformulaeVertices.begin();
iter != state_from->sucSubformulaeVertices.end(); iter++) {
CT_vertex *vertexCurr = *iter;
PT_node *subformulaCurr = vertexCurr->subformula;
#if !TRUST_ME
if (subformulaCurr->type != PT_SUC) {
cout << "ERROR: rModelChecker::addTransition: Successor vertex does not encode a succcesor type " << endl;
exit (1);
}
if (((PT_operator *)subformulaCurr)->children.size() != 1) {
cout << "ERROR: rModelChecker::addTransition: Successor operator does not have 1 child " << endl;
exit (1);
}
#endif
subformulaeSet_it sfiter = ((PT_operator *)subformulaCurr)->children.begin();
PT_node *subformulaChild = *sfiter;
CT_vertex *vertexNew = this->addVertex (vertexCurr, state_to, subformulaChild);
if (vertexNew) {
if (this->LocalUpdate (vertexNew))
foundWitness = true;
}
if (foundWitness)
break;
}
return foundWitness;
}
stateList
getStateTrajectoryBetweenVertices (CT_vertex *vertexInitial, CT_vertex *vertexFinal )
{
vertexList *solutionVertexList = NULL;
vertexListSet vertexListsCurr;
vertexList *vertexListFinal = new vertexList;
vertexListFinal->push_back (vertexFinal);
vertexListsCurr.insert (vertexListFinal);
// If the final formula is a PT_PRP type, then just trace back to the vertexInitial.
vertexSet verticesProcessed;
verticesProcessed.clear ();
verticesProcessed.insert (vertexFinal);
bool vertex_exists = true;
while (vertex_exists) {
vertex_exists = false;
bool solutionFound = false;
vertexListSet vertexListsNext;
for (vertexListSet_it iter = vertexListsCurr.begin(); iter != vertexListsCurr.end(); iter++) {
vertexList *vertexListThis = *iter;
CT_vertex *vertexLastInList = *(vertexListThis->rbegin());
if ( vertexLastInList == vertexInitial) {
// cout << "found initial vertex" << endl;
solutionVertexList = vertexListThis;
solutionFound = true;
break;
}
for (vertexSet_it iter2 = vertexLastInList->predVertices.begin();
iter2 != vertexLastInList->predVertices.end(); iter2++) {
CT_vertex *vertexPred = *iter2;
if (verticesProcessed.find (vertexPred) == verticesProcessed.end() ) {
vertexList *vertexListNew = new vertexList;
for (vertexList_it iter3 = vertexListThis->begin();
iter3 != vertexListThis->end(); iter3++) {
vertexListNew->push_back (*iter3);
}
vertexListNew->push_back (vertexPred);
vertexListsNext.insert (vertexListNew);
verticesProcessed.insert (vertexPred);
vertex_exists = true;
}
}
}
if (!solutionFound) {
for (vertexListSet_it iter = vertexListsCurr.begin();
iter != vertexListsCurr.end(); iter++) {
vertexList *vertexListThis = *iter;
delete vertexListThis;
}
vertexListsCurr.clear();
for (vertexListSet_it iter = vertexListsNext.begin();
iter != vertexListsNext.end(); iter++) {
vertexListsCurr.insert(*iter);
}
}
}
// revert back the stateList
// cout << "Solution vertex list size :" << solutionVertexList->size() << endl;
stateList trajectory;
trajectory.clear();
MS_state *stateLastInTrajectory = NULL;
for (vertexList_rit iter = solutionVertexList->rbegin();
iter != solutionVertexList->rend(); iter++) {
CT_vertex *vertexThis = *iter;
MS_state *stateThis = vertexThis->state;
if (stateThis != stateLastInTrajectory) {
trajectory.push_back (stateThis);
stateLastInTrajectory = stateThis;
}
}
return trajectory;
}
PGStateList
ModelCheckerPG::getTrajectory()
{
PGState *prev_state = NULL;
PGStateList trajectory;
if (this->lV.size() > 0) {
// TODO
assert( false );
} else {
PGVertex *min_loopv = NULL, *min_knotv;
double min_cost = -1; // Ignored until min_loopv != NULL
PGVertex *curr;
PGVertex *loopv;
PGVertex *knotv;
double loop_cost, prefix_cost;
for (PGVertexSet_it nuv = this->nV.begin(); nuv != this->nV.end();
nuv++) {
if ((*nuv)->RV.find( *nuv ) != (*nuv)->RV.end()) {
list<PGVertex *> key;
key.push_back( *nuv );
key.push_back( *nuv );
assert( this->Cost.find( key ) != this->Cost.end() );
loop_cost = this->Cost[key];
if (loop_cost == 0)
continue;
loopv = *nuv;
curr = loopv;
prefix_cost = -1;
do {
key.clear();
key.push_back( loopv );
key.push_back( curr );
assert( Pr.find( key ) != Pr.end() );
curr = Pr[key];
key.clear();
key.push_back( this->initialVertex );
key.push_back( curr );
assert( Cost.find( key ) != Cost.end() );
if (prefix_cost < 0 || Cost[key] < prefix_cost) {
knotv = curr;
prefix_cost = Cost[key];
}
} while (curr != loopv);
if (min_cost < 0 || prefix_cost + loop_cost < min_cost) {
min_loopv = loopv;
min_knotv = knotv;
min_cost = prefix_cost + loop_cost;
}
}
}
if (min_loopv == NULL) // No feasible nu-loop
return trajectory;
curr = min_loopv;
do {
list<PGVertex *> key;
key.push_back( min_loopv );
key.push_back( curr );
assert( Pr.find( key ) != Pr.end() );
curr = Pr[key];
if (prev_state == NULL || prev_state != curr->state) {
trajectory.push_front( curr->state );
prev_state = curr->state;
}
} while (curr != min_loopv);
assert( trajectory.size() > 1 );
if (trajectory.front() == trajectory.back())
trajectory.pop_back();
while (trajectory.front() != min_knotv->state) {
PGState *front = trajectory.front();
trajectory.pop_front();
trajectory.push_back( front );
}
trajectory.push_back( min_knotv->state );
prev_state = trajectory.front();
curr = min_knotv;
do {
list<PGVertex *> key;
key.push_back( this->initialVertex );
key.push_back( curr );
assert( Pr.find( key ) != Pr.end() );
curr = Pr[key];
if (prev_state != curr->state) {
trajectory.push_front( curr->state );
prev_state = curr->state;
}
} while (curr != this->initialVertex);
std::cerr << "ModelCheckerPG::getTrajectory(): returned trajectory cost is "
<< min_cost << std::endl;
}
return trajectory;
}
stateList
rModelChecker::getTrajectory()
{
stateList trajectory;
if (this->satVertices.empty())
return trajectory;
// Pick one of the sat vertices:
vertexSet_it iterVertexFinal = this->satVertices.begin();
CT_vertex *vertexFinal = *iterVertexFinal;
MS_state *stateFinal = vertexFinal->state;
PT_node *subformulaFinal = vertexFinal->subformula;
if (subformulaFinal->type == PT_PRP) {
trajectory = getStateTrajectoryBetweenVertices( this->initialVertex, vertexFinal );
// cout << "Trajectory num states :" << trajectory.size() << endl;
} else if (subformulaFinal->type == PT_VAR) {
// Get the loop
stateList trajectoryLoop;
CT_vertex *vertexInitial = NULL;
PT_node *subformulaInitial = this->pt.getBoundFormula( subformulaFinal );
for ( vertexSet_it iter = stateFinal->vertices.begin(); iter != stateFinal->vertices.end(); iter++ ) {
if ( (*iter)->subformula == subformulaInitial ) {
vertexInitial = *iter;
break;
}
}
if (vertexInitial == NULL) {
cout << "ERROR: rModelChecker::getTrajectory: no loop found even though claimed earlier" << endl;
exit (1);
}
trajectoryLoop = getStateTrajectoryBetweenVertices (vertexInitial, vertexFinal);
// Get the path that connects initialVertex to the loop
stateList trajectoryPath;
trajectoryPath = getStateTrajectoryBetweenVertices( this->initialVertex, vertexInitial );
// TODO: Only run loop if being verbose?
for (stateList_it iter = trajectoryPath.begin();
iter != trajectoryPath.end(); iter++) {
for (stateList_it iter2 = trajectoryPath.begin();
iter2 != iter; iter2++) {
// if (*iter2 == *iter)
// cout << "Path contains a minor loop" << endl;
}
}
// TODO: Only run loop if being verbose?
int k1 = 0;
for (stateList_it iter = trajectoryLoop.begin();
iter != trajectoryLoop.end(); iter++) {
int k2 = 0;
for (stateList_it iter2 = trajectoryLoop.begin();
iter2 != iter; iter2++) {
// if ( (*iter2 == *iter) && (iter2 != trajectoryLoop.begin()) )
// cout << "Loop contains a minor loop : " << k1 << " - " << k2 << endl;
k2++;
}
k1++;
}
// cout << "k1 : " << trajectoryLoop.size() << endl;
// Concatanate trajectoryPath and trajectoryLoop to form trajectory
// int k =0;
// for (stateList_it iter = trajectoryPath.begin(); iter != trajectoryPath.end(); iter++) {
// k++;
// if (k > 20)
// continue;
// trajectory.push_back (*iter);
// }
// int k = 0;
// for (stateList_it iter = trajectoryLoop.begin(); iter != trajectoryLoop.end(); iter++) {
// k++;
// if ( (k > 124) )
// continue;
// trajectory.push_back (*iter);
// }
// cout << "k :" << k << endl;
trajectoryPath.pop_back();
for (stateList_it iter = trajectoryPath.begin();
iter != trajectoryPath.end(); iter++)
trajectory.push_back (*iter);
for (stateList_it iter = trajectoryLoop.begin();
iter != trajectoryLoop.end(); iter++)
trajectory.push_back (*iter);
} else {
cout << "ERROR: rModelChecker::getTrajectory: final subformula type is neither PT_PRP nor PT_VAR" << endl;
exit(1);
}
return trajectory;
}
MS_state *
rModelChecker::findStateById( int id )
{
MS_state *state = NULL;
for (stateSet_it iter = this->states.begin();
iter != this->states.end(); iter++)
if ( (*iter)->identifier == id)
state = *iter;
return state;
}
bool
rModelChecker::addTransitionById( int id_from, int id_to )
{
MS_state *state_from = this->findStateById( id_from );
MS_state *state_to = this->findStateById( id_to );
#if !TRUST_ME
if ((state_from == NULL) || (state_to == NULL)) {
cout << "ERROR: rModelChecker::addTransitionbyID: state not found " << endl;
exit(1);
}
#endif
return this->addTransition (state_from, state_to);
}
|
/** \copyright
* Copyright (c) 2015, Balazs Racz
* 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.
*
* 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.
*
* \file CpuLoad.hxx
* Class for maintining a CPU load indication.
*
* @author Balazs Racz
* @date 30 August 2015
*/
#include "CpuLoad.hxx"
#include "os/os.h"
#include "freertos_includes.h"
extern "C" {
/// The bits to shift to get multiples of 1.0
static constexpr uint32_t SHIFT_ONE = 24;
/// The bits to shift after a rate inclusing
static constexpr uint32_t SHIFT_RATE = 8;
/// The multiplication for the rate
static constexpr uint8_t AVG_RATE = 0xff;
/// If the last measurement was busy, we add this much weight
static constexpr uint32_t ADD_RATE = 0x1 << 24;
void CpuLoad::record_value(bool busy, uintptr_t key)
{
avg_ *= AVG_RATE;
++countSinceUpdate_;
if (busy)
{
avg_ += ADD_RATE;
}
avg_ >>= SHIFT_RATE;
// Check streak
if (busy)
{
if (consecutive_ < 255)
{
++consecutive_;
}
if (consecutive_ > maxConsecutive_)
{
maxConsecutive_ = consecutive_;
}
}
else
{
consecutive_ = 0;
}
// Check window of 16.
last16Bits_ <<= 1;
last16Bits_ |= (busy ? 1 : 0);
// sums up last 16 bits.
unsigned v = last16Bits_;
v = (v & 0x5555) + ((v & 0xaaaa) >> 1);
v = (v & 0x3333) + ((v & 0xcccc) >> 2);
v = (v & 0x0F0F) + ((v & 0xF0F0) >> 4);
v = (v & 0x00FF) + ((v & 0xFF00) >> 8);
if (v > peakOver16Counts_)
{
peakOver16Counts_ = v;
}
// Record per-key information
if (key == 0)
return;
bool found = false;
for (auto it = perKeyCost_.begin(); it != perKeyCost_.end(); ++it)
{
if (it->key == key)
{
found = true;
++it->rolling_count;
break;
}
}
if (!found && newKey_ == 0)
{
newKey_ = key;
}
}
uint8_t CpuLoad::get_load() {
return (avg_ * 100) >> SHIFT_ONE;
}
void cpuload_tick(unsigned irq)
{
if (!Singleton<CpuLoad>::exists())
return;
if (irq != 0)
{
Singleton<CpuLoad>::instance()->record_value(true, (uintptr_t)irq);
return;
}
#ifdef ESP32
auto hdl = xTaskGetCurrentTaskHandleForCPU(0);
bool is_idle = xTaskGetIdleTaskHandleForCPU(0) == hdl;
Singleton<CpuLoad>::instance()->record_value(!is_idle, (uintptr_t)hdl);
hdl = xTaskGetCurrentTaskHandleForCPU(1);
is_idle = xTaskGetIdleTaskHandleForCPU(1) == hdl;
Singleton<CpuLoad>::instance()->record_value(!is_idle, (uintptr_t)hdl);
#else
auto hdl = xTaskGetCurrentTaskHandle();
bool is_idle = xTaskGetIdleTaskHandle() == hdl;
Singleton<CpuLoad>::instance()->record_value(!is_idle, (uintptr_t)hdl);
#endif
}
}
DEFINE_SINGLETON_INSTANCE(CpuLoad);
Fixes load accounting for esp32 (#280)
This PR fixes a CPU accounting bug on the ESP32. When we were providing an executor pointer through the irq argument, we did not take a sample of what is being run on CPU1. This causes under-counting tasks that were scheduled to CPU1.
---
* cpuload: Handles the 'executor pointer' case against CPU0 for the ESP32.
* removes unnecessary return
/** \copyright
* Copyright (c) 2015, Balazs Racz
* 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.
*
* 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.
*
* \file CpuLoad.hxx
* Class for maintining a CPU load indication.
*
* @author Balazs Racz
* @date 30 August 2015
*/
#include "CpuLoad.hxx"
#include "os/os.h"
#include "freertos_includes.h"
extern "C" {
/// The bits to shift to get multiples of 1.0
static constexpr uint32_t SHIFT_ONE = 24;
/// The bits to shift after a rate inclusing
static constexpr uint32_t SHIFT_RATE = 8;
/// The multiplication for the rate
static constexpr uint8_t AVG_RATE = 0xff;
/// If the last measurement was busy, we add this much weight
static constexpr uint32_t ADD_RATE = 0x1 << 24;
void CpuLoad::record_value(bool busy, uintptr_t key)
{
avg_ *= AVG_RATE;
++countSinceUpdate_;
if (busy)
{
avg_ += ADD_RATE;
}
avg_ >>= SHIFT_RATE;
// Check streak
if (busy)
{
if (consecutive_ < 255)
{
++consecutive_;
}
if (consecutive_ > maxConsecutive_)
{
maxConsecutive_ = consecutive_;
}
}
else
{
consecutive_ = 0;
}
// Check window of 16.
last16Bits_ <<= 1;
last16Bits_ |= (busy ? 1 : 0);
// sums up last 16 bits.
unsigned v = last16Bits_;
v = (v & 0x5555) + ((v & 0xaaaa) >> 1);
v = (v & 0x3333) + ((v & 0xcccc) >> 2);
v = (v & 0x0F0F) + ((v & 0xF0F0) >> 4);
v = (v & 0x00FF) + ((v & 0xFF00) >> 8);
if (v > peakOver16Counts_)
{
peakOver16Counts_ = v;
}
// Record per-key information
if (key == 0)
return;
bool found = false;
for (auto it = perKeyCost_.begin(); it != perKeyCost_.end(); ++it)
{
if (it->key == key)
{
found = true;
++it->rolling_count;
break;
}
}
if (!found && newKey_ == 0)
{
newKey_ = key;
}
}
uint8_t CpuLoad::get_load() {
return (avg_ * 100) >> SHIFT_ONE;
}
void cpuload_tick(unsigned irq)
{
if (!Singleton<CpuLoad>::exists())
return;
#ifdef ESP32
if (irq != 0)
{
Singleton<CpuLoad>::instance()->record_value(true, (uintptr_t)irq);
}
else // assumes openmrn task is pinned to core 0
{
auto hdl = xTaskGetCurrentTaskHandleForCPU(0);
bool is_idle = xTaskGetIdleTaskHandleForCPU(0) == hdl;
Singleton<CpuLoad>::instance()->record_value(!is_idle, (uintptr_t)hdl);
}
// always records CPU 1 task.
auto hdl = xTaskGetCurrentTaskHandleForCPU(1);
bool is_idle = xTaskGetIdleTaskHandleForCPU(1) == hdl;
Singleton<CpuLoad>::instance()->record_value(!is_idle, (uintptr_t)hdl);
#else
if (irq != 0)
{
Singleton<CpuLoad>::instance()->record_value(true, (uintptr_t)irq);
return;
}
auto hdl = xTaskGetCurrentTaskHandle();
bool is_idle = xTaskGetIdleTaskHandle() == hdl;
Singleton<CpuLoad>::instance()->record_value(!is_idle, (uintptr_t)hdl);
#endif
}
}
DEFINE_SINGLETON_INSTANCE(CpuLoad);
|
// Copyright 2021 Google LLC
//
// 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 <functional>
#include <regex>
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Sequence.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FormatAdapters.h"
#include "llvm/Support/FormatCommon.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Record.h"
#include "llvm/TableGen/TableGenBackend.h"
#include "mlir/TableGen/Argument.h"
#include "mlir/TableGen/CodeGenHelpers.h"
#include "mlir/TableGen/Format.h"
#include "mlir/TableGen/Interfaces.h"
#include "mlir/TableGen/OpClass.h"
#include "mlir/TableGen/Operator.h"
#include "mlir/TableGen/Region.h"
#include "mlir/TableGen/SideEffects.h"
#include "mlir/TableGen/Trait.h"
namespace {
llvm::cl::opt<bool> ExplainMissing(
"explain-missing",
llvm::cl::desc("Print the reason for skipping operations from output"));
llvm::cl::opt<std::string> StripOpPrefix(
"strip-prefix", llvm::cl::desc("Prefix to strip from def names"),
llvm::cl::value_desc("prefix"));
llvm::cl::opt<std::string> DialectName(
"dialect-name", llvm::cl::desc("Override the inferred dialect name"),
llvm::cl::value_desc("dialect"));
template <class C>
llvm::iterator_range<typename C::const_iterator> make_range(const C& x) {
return llvm::make_range(x.begin(), x.end());
}
template <class C, class FunTy,
typename ResultTy = decltype(std::declval<FunTy>()(
std::declval<typename C::value_type>()))>
std::vector<ResultTy> map_vector(const C& container, FunTy f) {
std::vector<ResultTy> results;
for (const auto& v : container) {
results.push_back(f(v));
}
return results;
}
void warn(llvm::StringRef op_name, const std::string& reason) {
if (!ExplainMissing) return;
llvm::errs() << llvm::formatv(
"{0} {1}\n", llvm::fmt_align(op_name, llvm::AlignStyle::Left, 40),
reason);
}
void warn(const mlir::tblgen::Operator& op, const std::string& reason) {
warn(op.getOperationName(), reason);
}
struct AttrPatternTemplate {
const char* _pattern;
const char* _type;
std::vector<const char*> provided_constraints;
std::vector<const char*> type_var_defaults;
};
using attr_print_state = llvm::StringSet<>;
class AttrPattern {
public:
virtual ~AttrPattern() = default;
virtual std::string type() const = 0;
virtual std::string match(std::string name) const = 0;
virtual const std::vector<std::string>& provided_constraints() const = 0;
virtual void print(llvm::raw_ostream& os,
attr_print_state& optional_attr_defs) const = 0;
};
struct NameSource {
NameSource(const char* prefix) : prefix(prefix) {}
NameSource(const NameSource&) = delete;
std::string fresh() { return std::string(prefix) + std::to_string(suffix++); }
private:
const char* prefix;
int suffix = 0;
};
class SimpleAttrPattern : public AttrPattern {
public:
SimpleAttrPattern(const AttrPatternTemplate& tmpl, NameSource& gen)
: _type_var_defaults(tmpl.type_var_defaults) {
_pattern = tmpl._pattern;
if (tmpl.type_var_defaults.empty()) {
_type = tmpl._type;
_provided_constraints =
map_vector(tmpl.provided_constraints,
[](const char* c) { return std::string(c); });
} else if (tmpl.type_var_defaults.size() == 1) {
std::string var = gen.fresh();
_type_vars.push_back(var);
_type = llvm::formatv(tmpl._type, var);
_provided_constraints = map_vector(
tmpl.provided_constraints,
[&var](const char* c) { return llvm::formatv(c, var).str(); });
} else {
std::abort(); // Not sure how to splat arbitrary many vars into formatv.
}
}
std::string match(std::string name) const override { return llvm::formatv(_pattern, name); }
std::string type() const override { return _type; }
const std::vector<std::string>& provided_constraints() const override { return _provided_constraints; }
const std::vector<std::string>& type_vars() const { return _type_vars; }
const std::vector<const char*>& type_var_defaults() const { return _type_var_defaults; }
void print(llvm::raw_ostream& os,
attr_print_state& optional_attr_defs) const override {}
private:
const char* _pattern;
std::string _type;
std::vector<std::string> _provided_constraints;
std::vector<std::string> _type_vars;
const std::vector<const char*> _type_var_defaults;
};
class OptionalAttrPattern : public AttrPattern {
public:
OptionalAttrPattern(llvm::StringRef attr_kind, SimpleAttrPattern base)
: base(std::move(base)), attr_kind(attr_kind) {}
std::string type() const override {
return "Maybe " + base.type();
}
std::string match(std::string name) const override {
return llvm::formatv("Optional{0} {1}", attr_kind, name);
}
const std::vector<std::string>& provided_constraints() const override { return base.provided_constraints(); }
void print(llvm::raw_ostream& os,
attr_print_state& optional_attr_defs) const override {
if (!optional_attr_defs.contains(attr_kind)) {
if (base.provided_constraints().empty()) {
const char* kOptionalHandler = R"(
pattern Optional{0} :: Maybe {1} -> Maybe Attribute
pattern Optional{0} x <- ((\case Just ({2}) -> Just y; Nothing -> Nothing) -> x)
where Optional{0} x = case x of Just y -> Just ({2}); Nothing -> Nothing
)";
os << llvm::formatv(kOptionalHandler, attr_kind, base.type(),
base.match("y"));
} else {
const char *kOptionalHandlerConstr = R"(
data Maybe{0}Adapter = forall {4:$[ ]}. ({3:$[, ]}) => AdaptMaybe{0} (Maybe ({1}))
unwrapMaybe{0} :: Maybe Attribute -> Maybe{0}Adapter
unwrapMaybe{0} = \case
Just ({2}) -> AdaptMaybe{0} (Just y)
_ -> AdaptMaybe{0} {5:[]}Nothing
pattern Optional{0} :: () => ({3:$[, ]}) => Maybe {1} -> Maybe Attribute
pattern Optional{0} x <- (unwrapMaybe{0} -> AdaptMaybe{0} x)
where Optional{0} x = case x of Just y -> Just ({2}); Nothing -> Nothing
)";
std::vector<std::string> default_apps;
for (const char* d : base.type_var_defaults()) {
default_apps.push_back("@" + std::string(d) + " ");
}
os << llvm::formatv(kOptionalHandlerConstr,
attr_kind, // 0
base.type(), // 1
base.match("y"), // 2
make_range(base.provided_constraints()), // 3
make_range(base.type_vars()), // 4
make_range(default_apps)); // 5
}
optional_attr_defs.insert(attr_kind);
}
}
private:
SimpleAttrPattern base;
llvm::StringRef attr_kind;
};
using attr_pattern_map = llvm::StringMap<AttrPatternTemplate>;
const attr_pattern_map& getAttrPatternTemplates() {
static const attr_pattern_map* kAttrHandlers = new attr_pattern_map{
{"AnyAttr", {"{0}", "Attribute", {}, {}}},
{"AffineMapArrayAttr", {"PatternUtil.AffineMapArrayAttr {0}", "[Affine.Map]", {}, {}}},
{"AffineMapAttr", {"AffineMapAttr {0}", "Affine.Map", {}, {}}},
{"ArrayAttr", {"ArrayAttr {0}", "[Attribute]", {}, {}}},
{"BoolAttr", {"BoolAttr {0}", "Bool", {}, {}}},
{"DictionaryAttr", {"DictionaryAttr {0}", "(M.Map Name Attribute)", {}, {}}},
{"F32Attr", {"FloatAttr Float32Type {0}", "Double", {}, {}}},
{"F64Attr", {"FloatAttr Float64Type {0}", "Double", {}, {}}},
{"I32Attr", {"IntegerAttr (IntegerType Signless 32) {0}", "Int", {}, {}}},
{"I64Attr", {"IntegerAttr (IntegerType Signless 64) {0}", "Int", {}, {}}},
{"I64ArrayAttr", {"PatternUtil.I64ArrayAttr {0}", "[Int]", {}, {}}},
{"I64ElementsAttr", {"DenseElementsAttr (IntegerType Signless 64) (DenseInt64 {0})",
"(AST.IStorableArray {0} Int64)", {"Ix {0}", "Show {0}"}, {"PatternUtil.DummyIx"}}},
{"IndexAttr", {"IntegerAttr IndexType {0}", "Int", {}, {}}},
{"StrAttr", {"StringAttr {0}", "BS.ByteString", {}, {}}},
};
return *kAttrHandlers;
}
// Returns nullptr when the attribute pattern couldn't be constructed.
std::unique_ptr<AttrPattern> tryGetAttrPattern(
const mlir::tblgen::NamedAttribute& nattr, NameSource& gen) {
llvm::StringRef attr_kind = nattr.attr.getAttrDefName();
if (getAttrPatternTemplates().count(attr_kind) != 1) return nullptr;
const AttrPatternTemplate& tmpl = getAttrPatternTemplates().lookup(attr_kind);
if (!nattr.attr.isOptional()) {
return std::make_unique<SimpleAttrPattern>(tmpl, gen);
} else {
auto pat = std::make_unique<OptionalAttrPattern>(
attr_kind, SimpleAttrPattern(tmpl, gen));
return pat;
}
}
const std::string sanitizeName(llvm::StringRef name, llvm::Optional<int> idx = llvm::None) {
static const llvm::StringSet<>* kReservedNames = new llvm::StringSet<>{
// TODO(apaszke): Add more keywords
// Haskell keywords
"in", "data",
};
if (name.empty()) {
assert(idx);
return llvm::formatv("_unnamed{0}", *idx);
} else if (kReservedNames->contains(name)) {
auto new_name = name.str();
new_name.push_back('_');
return new_name;
} else {
return name.str();
}
}
std::string getDialectName(llvm::ArrayRef<llvm::Record*> op_defs) {
mlir::tblgen::Operator any_op(op_defs.front());
assert(
std::all_of(op_defs.begin(), op_defs.end(), [&any_op](llvm::Record* op) {
return mlir::tblgen::Operator(op).getDialectName() ==
any_op.getDialectName();
}));
std::string dialect_name;
if (DialectName.empty()) {
dialect_name = any_op.getDialectName().str();
dialect_name[0] = llvm::toUpper(dialect_name[0]);
} else {
dialect_name = DialectName;
}
return dialect_name;
}
class OpAttrPattern {
OpAttrPattern(std::string name, std::vector<std::string> binders,
std::vector<mlir::tblgen::NamedAttribute> attrs,
std::vector<std::unique_ptr<AttrPattern>> patterns)
: name(std::move(name)),
binders(std::move(binders)),
attrs(std::move(attrs)),
patterns(std::move(patterns)) {}
public:
static llvm::Optional<OpAttrPattern> buildFor(mlir::tblgen::Operator& op) {
if (op.getNumAttributes() == 0) return OpAttrPattern("NoAttrs", {}, {}, {});
NameSource gen("a");
std::vector<std::string> binders;
std::vector<mlir::tblgen::NamedAttribute> attrs;
std::vector<std::unique_ptr<AttrPattern>> patterns;
for (const auto& named_attr : op.getAttributes()) {
// Derived attributes are never materialized and don't have to be
// specified.
if (named_attr.attr.isDerivedAttr()) continue;
auto pattern = tryGetAttrPattern(named_attr, gen);
if (!pattern) {
if (named_attr.attr.hasDefaultValue()) {
warn(op, llvm::formatv("unsupported attr {0} (but has default value)",
named_attr.attr.getAttrDefName()));
continue;
}
if (named_attr.attr.isOptional()) {
warn(op, llvm::formatv("unsupported attr {0} (but is optional)",
named_attr.attr.getAttrDefName()));
continue;
}
warn(op, llvm::formatv("unsupported attr ({0})",
named_attr.attr.getAttrDefName()));
return llvm::None;
}
binders.push_back(sanitizeName(named_attr.name));
attrs.push_back(named_attr);
patterns.push_back(std::move(pattern));
}
if (binders.empty()) return OpAttrPattern("NoAttrs", {}, {}, {});
std::string name = "Internal" + op.getCppClassName().str() + "Attributes";
return OpAttrPattern(std::move(name), std::move(binders), std::move(attrs),
std::move(patterns));
}
void print(llvm::raw_ostream& os, attr_print_state& optional_attr_defs) {
if (name == "NoAttrs") return;
// `M.lookup "attr_name" m` for every attribute
std::vector<std::string> lookups;
// Patterns from handlers, but wrapped in "Just (...)" when non-optional
std::vector<std::string> lookup_patterns;
// `[("attr_name", attr_pattern)]` for every non-optional attribute
std::vector<std::string> singleton_pairs;
for (size_t i = 0; i < attrs.size(); ++i) {
const mlir::tblgen::NamedAttribute& nattr = attrs[i];
const AttrPattern& pattern = *patterns[i];
pattern.print(os, optional_attr_defs);
lookups.push_back(llvm::formatv("M.lookup \"{0}\" m", nattr.name));
std::string inst_pattern = pattern.match(binders[i]);
if (nattr.attr.isOptional()) {
lookup_patterns.push_back(inst_pattern);
singleton_pairs.push_back(llvm::formatv(
"(Data.Maybe.maybeToList $ (\"{0}\",) <$> {1})", nattr.name, inst_pattern));
} else {
lookup_patterns.push_back(llvm::formatv("Just ({0})", inst_pattern));
singleton_pairs.push_back(
llvm::formatv("[(\"{0}\", {1})]", nattr.name, inst_pattern));
}
}
const char* kAttributePattern = R"(
pattern {0} :: () => ({6:$[, ]}) => {1:$[ -> ]} -> NamedAttributes
pattern {0} {2:$[ ]} <- ((\m -> ({3:$[, ]})) -> ({4:$[, ]}))
where {0} {2:$[ ]} = M.fromList $ {5:$[ ++ ]}
)";
os << llvm::formatv(kAttributePattern,
name, // 0
make_range(types()), // 1
make_range(binders), // 2
make_range(lookups), // 3
make_range(lookup_patterns), // 4
make_range(singleton_pairs), // 5
make_range(provided_constraints())); // 6
}
std::vector<std::string> types() const {
return map_vector(patterns, [](const std::unique_ptr<AttrPattern>& p) {
return p->type();
});
}
std::vector<std::string> provided_constraints() const {
std::vector<std::string> result;
for (auto& p : patterns) {
for (auto& c : p->provided_constraints()) {
result.push_back(c);
}
}
return result;
}
std::string name;
std::vector<std::string> binders;
private:
std::vector<mlir::tblgen::NamedAttribute> attrs;
std::vector<std::unique_ptr<AttrPattern>> patterns;
};
llvm::Optional<std::string> buildOperation(
const llvm::Record* def, bool is_pattern, const std::string& what_for,
const std::string& location_expr,
const std::vector<std::string>& type_exprs,
const std::vector<std::string>& operand_exprs,
const std::vector<std::string>& region_exprs,
const OpAttrPattern& attr_pattern) {
mlir::tblgen::Operator op(def);
auto fail = [&op, &what_for](std::string reason) {
warn(op, llvm::formatv("couldn't construct {0}: {1}", what_for, reason));
return llvm::Optional<std::string>();
};
// Skip currently unsupported cases
if (op.getNumVariadicRegions() != 0) return fail("variadic regions");
if (op.getNumSuccessors() != 0) return fail("successors");
// Prepare results
std::string type_expr;
if (op.getNumResults() == 0) {
assert(type_exprs.size() == op.getNumResults());
type_expr = "[]";
} else if (op.getNumVariableLengthResults() == 0 &&
op.getTrait("::mlir::OpTrait::SameOperandsAndResultType")) {
assert(type_exprs.size() == 1);
type_expr = llvm::formatv("[{0:$[, ]}]",
make_range(std::vector<llvm::StringRef>(
op.getNumResults(), type_exprs.front())));
} else if (op.getNumVariableLengthResults() == 0) {
assert(type_exprs.size() == op.getNumResults());
type_expr = llvm::formatv("[{0:$[, ]}]", make_range(type_exprs));
} else if (!is_pattern) {
assert(type_exprs.size() == op.getNumResults());
std::vector<std::string> list_type_exprs;
for (int i = 0; i < op.getNumResults(); ++i) {
auto& result = op.getResult(i);
if (result.isOptional()) {
list_type_exprs.push_back("(Data.Maybe.maybeToList " + type_exprs[i] + ")");
} else if (result.isVariadic()) {
list_type_exprs.push_back(type_exprs[i]);
} else {
assert(!result.isVariableLength());
list_type_exprs.push_back("[" + type_exprs[i] + "]");
}
}
type_expr = llvm::formatv("({0:$[ ++ ]})", make_range(list_type_exprs));
} else {
return fail("unsupported variable length results");
}
// Prepare operands
std::string operand_expr;
assert(operand_exprs.size() == op.getNumOperands());
if (op.getNumOperands() == 1 && op.getOperand(0).isVariadic()) {
// Note that this expr already should represent a list
operand_expr = operand_exprs.front();
} else if (op.getNumVariableLengthOperands() == 0) {
operand_expr = llvm::formatv("[{0:$[, ]}]", make_range(operand_exprs));
} else if (!is_pattern) {
std::vector<std::string> operand_list_exprs;
for (int i = 0; i < op.getNumOperands(); ++i) {
auto& operand = op.getOperand(i);
if (operand.isOptional()) {
operand_list_exprs.push_back("(Data.Maybe.maybeToList " + operand_exprs[i] + ")");
} else if (operand.isVariadic()) {
operand_list_exprs.push_back(operand_exprs[i]);
} else {
assert(!operand.isVariableLength());
operand_list_exprs.push_back("[" + operand_exprs[i] + "]");
}
}
operand_expr =
llvm::formatv("({0:$[ ++ ]})", make_range(operand_list_exprs));
} else {
return fail("unsupported variable length operands");
}
std::string extra_attrs;
if (op.getTrait("::mlir::OpTrait::AttrSizedOperandSegments")) {
std::vector<std::string> segment_sizes;
for (int i = 0; i < op.getNumOperands(); ++i) {
auto& operand = op.getOperand(i);
if (operand.isOptional()) {
segment_sizes.push_back(llvm::formatv(
"case {0} of Just _ -> 1; Nothing -> 0", operand_exprs[i]));
} else if (operand.isVariadic()) {
segment_sizes.push_back("Prelude.length " + operand_exprs[i]);
} else {
assert(!operand.isVariableLength());
segment_sizes.push_back("1");
}
}
const char* kOperandSegmentsAttr = R"(
<> AST.namedAttribute "operand_segment_sizes"
(DenseElementsAttr (VectorType [{0}] $ IntegerType Unsigned 32) $
DenseUInt32 $ IArray.listArray (1 :: Int, {0}) $ Prelude.fromIntegral <$> [{1:$[, ]}])
)";
extra_attrs = llvm::formatv(kOperandSegmentsAttr,
segment_sizes.size(),
make_range(segment_sizes));
}
const char* kPatternExplicitType = R"(Operation
{ opName = "{0}"
, opLocation = {1}
, opResultTypes = Explicit {2}
, opOperands = {3}
, opRegions = [{4:$[ ]}]
, opSuccessors = []
, opAttributes = ({5}{6}{7:$[ ]}){8}
})";
return llvm::formatv(kPatternExplicitType,
op.getOperationName(), // 0
location_expr, // 1
type_expr, // 2
operand_expr, // 3
make_range(region_exprs), // 4
attr_pattern.name, // 5
attr_pattern.binders.empty() ? "" : " ", // 6
make_range(attr_pattern.binders), // 7
extra_attrs) // 8
.str();
}
// TODO(apaszke): Make this more reliable
std::string legalizeBuilderName(std::string name) {
for (size_t i = 0; i < name.size(); ++i) {
if (name[i] == '.') name[i] = '_';
}
return name;
}
std::string stripDialect(std::string name) {
size_t dialect_sep_loc = name.find('.');
assert(dialect_sep_loc != std::string::npos);
return name.substr(dialect_sep_loc + 1);
}
void emitBuilderMethod(mlir::tblgen::Operator& op,
const OpAttrPattern& attr_pattern, llvm::raw_ostream& os) {
auto fail = [&op](std::string reason) {
warn(op, "couldn't construct builder: " + reason);
};
if (op.getNumVariadicRegions() != 0) return fail("variadic regions");
if (op.getNumSuccessors() != 0) return fail("successors");
const char* result_type;
std::string prologue;
const char* continuation = "";
if (op.getNumResults() == 0) {
prologue = "Control.Monad.void ";
if (op.getTrait("::mlir::OpTrait::IsTerminator")) {
result_type = "EndOfBlock";
continuation = "\n AST.terminateBlock";
} else {
result_type = "()";
}
} else if (op.getNumResults() == 1) {
result_type = "Value";
prologue = "Control.Monad.liftM Prelude.head ";
} else {
result_type = "[Value]";
prologue = "";
}
std::string builder_name = legalizeBuilderName(stripDialect(op.getOperationName()));
std::vector<std::string> builder_arg_types;
// TODO(apaszke): Use inference (op.getSameTypeAsResult)
std::vector<std::string> type_exprs;
std::vector<std::string> type_binders;
if (op.getNumResults() == 0) {
// Nothing to do.
} else if (op.getNumVariableLengthResults() == 0 &&
op.getTrait("::mlir::OpTrait::SameOperandsAndResultType")) {
for (const mlir::tblgen::NamedTypeConstraint& operand : op.getOperands()) {
if (operand.isVariableLength()) continue;
type_exprs.push_back("(AST.typeOf " + sanitizeName(operand.name) + ")");
break;
}
if (type_exprs.empty()) return fail("type inference failed");
} else {
int result_nr = 0;
for (const mlir::tblgen::NamedTypeConstraint& result : op.getResults()) {
type_binders.push_back(llvm::formatv("ty{0}", result_nr++));
type_exprs.push_back(type_binders.back());
if (result.isOptional()) {
builder_arg_types.push_back("Maybe Type");
} else if (result.isVariadic()) {
builder_arg_types.push_back("[Type]");
} else {
assert(!result.isVariableLength());
builder_arg_types.push_back("Type");
}
}
}
std::vector<std::string> operand_binders;
std::vector<std::string> operand_name_exprs;
operand_name_exprs.reserve(op.getNumOperands());
for (int i = 0; i < op.getNumOperands(); ++i) {
const auto& operand = op.getOperand(i);
std::string operand_name = sanitizeName(operand.name, i);
operand_binders.push_back(operand_name);
if (operand.isOptional()) {
builder_arg_types.push_back("Maybe Value");
operand_name_exprs.push_back("(AST.operand <$> " + operand_name + ")");
} else if (operand.isVariadic()) {
builder_arg_types.push_back("[Value]");
operand_name_exprs.push_back("(AST.operands " + operand_name + ")");
} else {
assert(!operand.isVariableLength());
builder_arg_types.push_back("Value");
operand_name_exprs.push_back("(AST.operand " + operand_name + ")");
}
}
auto attr_types = attr_pattern.types();
builder_arg_types.insert(builder_arg_types.end(), attr_types.begin(),
attr_types.end());
std::vector<std::string> region_builder_binders;
std::vector<std::string> region_binders;
if (op.getNumRegions() > 0) {
std::string region_prologue;
for (const mlir::tblgen::NamedRegion& region : op.getRegions()) {
region_builder_binders.push_back(sanitizeName(region.name) + "Builder");
region_binders.push_back(sanitizeName(region.name));
builder_arg_types.push_back("RegionBuilderT m ()");
region_prologue += llvm::formatv(
"{0} <- AST.buildRegion {1}\n ",
region_binders.back(), region_builder_binders.back());
}
prologue = region_prologue + prologue;
}
builder_arg_types.push_back(""); // To add the arrow before m
llvm::Optional<std::string> operation =
buildOperation(&op.getDef(), false, "builder", "UnknownLocation",
type_exprs, operand_name_exprs, region_binders,
attr_pattern);
if (!operation) return;
const char* kBuilder = R"(
-- | A builder for @{10}@.
{0} :: ({11:$[, ]}) => MonadBlockBuilder m => {1:$[ -> ]}m {2}
{0} {3:$[ ]} {4:$[ ]} {5:$[ ]} {6:$[ ]} = do
{7}(AST.emitOp ({8})){9}
)";
os << llvm::formatv(kBuilder,
builder_name, // 0
make_range(builder_arg_types), // 1
result_type, // 2
make_range(type_binders), // 3
make_range(operand_binders), // 4
make_range(attr_pattern.binders), // 5
make_range(region_builder_binders), // 6
prologue, // 7
*operation, // 8
continuation, // 9
op.getOperationName(), // 10
make_range(attr_pattern.provided_constraints())); // 11
}
void emitPattern(const llvm::Record* def, const OpAttrPattern& attr_pattern,
llvm::raw_ostream& os) {
mlir::tblgen::Operator op(def);
auto fail = [&op](std::string reason) {
return warn(op, llvm::formatv("couldn't construct pattern: {0}", reason));
};
// Skip currently unsupported cases
if (op.getNumVariableLengthResults() != 0) return fail("variadic results");
if (op.getNumRegions() != 0) return fail("regions");
if (op.getNumSuccessors() != 0) return fail("successors");
if (!def->getName().endswith("Op")) return fail("unsupported name format");
if (!def->getName().startswith(StripOpPrefix)) return fail("missing prefix");
// Drop the stripped prefix and "Op" from the end.
llvm::StringRef pattern_name =
def->getName().drop_back(2).drop_front(StripOpPrefix.length());
std::vector<std::string> pattern_arg_types{"Location"};
// Prepare results
std::vector<std::string> type_binders;
if (op.getNumResults() > 0 &&
op.getTrait("::mlir::OpTrait::SameOperandsAndResultType")) {
assert(op.getNumVariableLengthResults() == 0);
pattern_arg_types.push_back("Type");
type_binders.push_back("ty");
} else {
size_t result_count = 0;
for (int i = 0; i < op.getNumResults(); ++i) {
pattern_arg_types.push_back("Type");
type_binders.push_back(llvm::formatv("ty{0}", result_count++));
}
}
// Prepare operands
std::vector<std::string> operand_binders;
if (op.getNumOperands() == 1 && op.getOperand(0).isVariadic()) {
// Single variadic arg is easy to handle
pattern_arg_types.push_back("[operand]");
operand_binders.push_back(sanitizeName(op.getOperand(0).name, 0));
} else {
// Non-variadic case
for (int i = 0; i < op.getNumOperands(); ++i) {
const auto& operand = op.getOperand(i);
if (operand.isVariableLength())
return fail("unsupported variable length operand");
pattern_arg_types.push_back("operand");
operand_binders.push_back(sanitizeName(operand.name, i));
}
}
// Prepare attribute pattern
auto attr_types = attr_pattern.types();
pattern_arg_types.insert(pattern_arg_types.end(), attr_types.begin(),
attr_types.end());
llvm::Optional<std::string> operation = buildOperation(
def, true, "pattern", "loc",
type_binders, operand_binders, {}, attr_pattern);
if (!operation) return;
const char* kPatternExplicitType = R"(
-- | A pattern for @{6}@.
pattern {0} :: () => ({7:$[, ]}) => {1:$[ -> ]} -> AbstractOperation operand
pattern {0} loc {2:$[ ]} {3:$[ ]} {4:$[ ]} = {5}
)";
os << llvm::formatv(kPatternExplicitType,
pattern_name, // 0
make_range(pattern_arg_types), // 1
make_range(type_binders), // 2
make_range(operand_binders), // 3
make_range(attr_pattern.binders), // 4
*operation, // 5
op.getOperationName(), // 6
make_range(attr_pattern.provided_constraints())); // 7
}
std::string formatDescription(mlir::tblgen::Operator op) {
std::string description;
description = "\n" + op.getDescription().str();
size_t pos = 0;
while (description[pos] == '\n') ++pos;
size_t leading_spaces = 0;
while (description[pos++] == ' ') ++leading_spaces;
if (leading_spaces) {
std::string leading_spaces_str;
for (size_t i = 0; i < leading_spaces; ++i) leading_spaces_str += "[ ]";
description = std::regex_replace(description, std::regex("\n" + leading_spaces_str), "\n");
}
description = std::regex_replace(description, std::regex("\\[(.*)\\]\\(.*\\)"), "$1");
description = std::regex_replace(description, std::regex("(['\"@<$#])"), "\\$1");
description = std::regex_replace(description, std::regex("```mlir"), "@");
description = std::regex_replace(description, std::regex("```"), "@");
description = std::regex_replace(description, std::regex("`"), "@");
description = std::regex_replace(description, std::regex("\n"), "\n-- ");
return description;
}
} // namespace
bool emitOpTableDefs(const llvm::RecordKeeper& recordKeeper,
llvm::raw_ostream& os) {
std::vector<llvm::Record*> defs = recordKeeper.getAllDerivedDefinitions("Op");
if (defs.empty()) return true;
// TODO(apaszke): Emit a module header to avoid leaking internal definitions.
auto dialect_name = getDialectName(defs);
os << "{-# OPTIONS_GHC -Wno-unused-imports #-}\n";
os << "{-# OPTIONS_HADDOCK hide, prune, not-home #-}\n\n";
os << "module MLIR.AST.Dialect.Generated." << dialect_name << " where\n";
os << R"(
import Prelude (Int, Double, Maybe(..), Bool(..), (++), (<$>), ($), (<>), Show)
import qualified Prelude
import Data.Int (Int64)
import qualified Data.Maybe
import Data.Array (Ix)
import qualified Data.Array.IArray as IArray
import qualified Data.ByteString as BS
import qualified Data.Map.Strict as M
import qualified Control.Monad
import MLIR.AST ( Attribute(..), Type(..), AbstractOperation(..), ResultTypes(..)
, Location(..), Signedness(..), DenseElements(..)
, NamedAttributes, Name
, pattern NoAttrs )
import qualified MLIR.AST as AST
import MLIR.AST.Builder (Value, EndOfBlock, MonadBlockBuilder, RegionBuilderT)
import qualified MLIR.AST.Builder as AST
import qualified MLIR.AST.IStorableArray as AST
import qualified MLIR.AST.PatternUtil as PatternUtil
import qualified MLIR.AST.Dialect.Affine as Affine
)";
attr_print_state attr_pattern_state;
for (const auto* def : defs) {
mlir::tblgen::Operator op(*def);
if (op.hasDescription()) {
os << llvm::formatv("\n-- * {0}\n-- ${0}", stripDialect(op.getOperationName()));
os << formatDescription(op);
os << "\n";
}
llvm::Optional<OpAttrPattern> attr_pattern = OpAttrPattern::buildFor(op);
if (!attr_pattern) continue;
attr_pattern->print(os, attr_pattern_state);
emitPattern(def, *attr_pattern, os);
emitBuilderMethod(op, *attr_pattern, os);
}
return false;
}
bool emitTestTableDefs(const llvm::RecordKeeper& recordKeeper,
llvm::raw_ostream& os) {
std::vector<llvm::Record*> defs = recordKeeper.getAllDerivedDefinitions("Op");
if (defs.empty()) return true;
auto dialect_name = getDialectName(defs);
os << "{-# OPTIONS_GHC -Wno-unused-imports #-}\n\n";
const char* module_header = R"(
module MLIR.AST.Dialect.Generated.{0}Spec where
import Prelude (IO, Maybe(..), ($), (<>))
import qualified Prelude
import Test.Hspec (Spec)
import qualified Test.Hspec as Hspec
import Test.QuickCheck ((===))
import qualified Test.QuickCheck as QC
import MLIR.AST (pattern NoAttrs)
import MLIR.AST.Dialect.{0}
import MLIR.Test.Generators ()
main :: IO ()
main = Hspec.hspec spec
spec :: Spec
spec = do
)";
os << llvm::formatv(module_header, dialect_name);
for (const auto* def : defs) {
mlir::tblgen::Operator op(*def);
llvm::Optional<OpAttrPattern> attr_pattern = OpAttrPattern::buildFor(op);
if (!attr_pattern) continue;
os << "\n Hspec.describe \"" << op.getOperationName() << "\" $ do";
const char* bidirectional_test_template = R"(
Hspec.it "has a bidirectional attr pattern" $ do
let wrapUnwrap ({1:$[, ]}) = case ({0} {1:$[ ]}) <> Prelude.mempty of
{0} {2:$[ ]} -> Just ({2:$[, ]})
_ -> Nothing
QC.property $ \args -> wrapUnwrap args === Just args
)";
os << llvm::formatv(
bidirectional_test_template, attr_pattern->name,
make_range(attr_pattern->binders),
make_range(map_vector(attr_pattern->binders, [](const std::string& b) {
return b + "_match";
})));
const char* pattern_extensibility_test_template = R"(
Hspec.it "accepts additional attributes" $ do
QC.property $ do
({1:$[, ]}) <- QC.arbitrary
extraAttrs <- QC.arbitrary
let match = case ({0} {1:$[ ]}) <> extraAttrs of
{0} {2:$[ ]} -> Just ({2:$[, ]})
_ -> Nothing
Prelude.return $ match === Just ({1:$[, ]})
)";
os << llvm::formatv(
pattern_extensibility_test_template, attr_pattern->name,
make_range(attr_pattern->binders),
make_range(map_vector(attr_pattern->binders, [](const std::string& b) {
return b + "_match";
})));
// TODO(apaszke): Test attr pattern matches with more attributes.
// TODO(apaszke): Test bidirectionality of op pattern.
// TODO(apaszke): Test op pattern matches with more attributes.
// TODO(apaszke): Test builder output matches op pattern.
// TODO(apaszke): Figure out how to do tests with translation.
}
return false;
}
Make hs-generator handle unnamed regions
// Copyright 2021 Google LLC
//
// 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 <functional>
#include <regex>
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Sequence.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FormatAdapters.h"
#include "llvm/Support/FormatCommon.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Record.h"
#include "llvm/TableGen/TableGenBackend.h"
#include "mlir/TableGen/Argument.h"
#include "mlir/TableGen/CodeGenHelpers.h"
#include "mlir/TableGen/Format.h"
#include "mlir/TableGen/Interfaces.h"
#include "mlir/TableGen/OpClass.h"
#include "mlir/TableGen/Operator.h"
#include "mlir/TableGen/Region.h"
#include "mlir/TableGen/SideEffects.h"
#include "mlir/TableGen/Trait.h"
namespace {
llvm::cl::opt<bool> ExplainMissing(
"explain-missing",
llvm::cl::desc("Print the reason for skipping operations from output"));
llvm::cl::opt<std::string> StripOpPrefix(
"strip-prefix", llvm::cl::desc("Prefix to strip from def names"),
llvm::cl::value_desc("prefix"));
llvm::cl::opt<std::string> DialectName(
"dialect-name", llvm::cl::desc("Override the inferred dialect name"),
llvm::cl::value_desc("dialect"));
template <class C>
llvm::iterator_range<typename C::const_iterator> make_range(const C& x) {
return llvm::make_range(x.begin(), x.end());
}
template <class C, class FunTy,
typename ResultTy = decltype(std::declval<FunTy>()(
std::declval<typename C::value_type>()))>
std::vector<ResultTy> map_vector(const C& container, FunTy f) {
std::vector<ResultTy> results;
for (const auto& v : container) {
results.push_back(f(v));
}
return results;
}
void warn(llvm::StringRef op_name, const std::string& reason) {
if (!ExplainMissing) return;
llvm::errs() << llvm::formatv(
"{0} {1}\n", llvm::fmt_align(op_name, llvm::AlignStyle::Left, 40),
reason);
}
void warn(const mlir::tblgen::Operator& op, const std::string& reason) {
warn(op.getOperationName(), reason);
}
struct AttrPatternTemplate {
const char* _pattern;
const char* _type;
std::vector<const char*> provided_constraints;
std::vector<const char*> type_var_defaults;
};
using attr_print_state = llvm::StringSet<>;
class AttrPattern {
public:
virtual ~AttrPattern() = default;
virtual std::string type() const = 0;
virtual std::string match(std::string name) const = 0;
virtual const std::vector<std::string>& provided_constraints() const = 0;
virtual void print(llvm::raw_ostream& os,
attr_print_state& optional_attr_defs) const = 0;
};
struct NameSource {
NameSource(const char* prefix) : prefix(prefix) {}
NameSource(const NameSource&) = delete;
std::string fresh() { return std::string(prefix) + std::to_string(suffix++); }
private:
const char* prefix;
int suffix = 0;
};
class SimpleAttrPattern : public AttrPattern {
public:
SimpleAttrPattern(const AttrPatternTemplate& tmpl, NameSource& gen)
: _type_var_defaults(tmpl.type_var_defaults) {
_pattern = tmpl._pattern;
if (tmpl.type_var_defaults.empty()) {
_type = tmpl._type;
_provided_constraints =
map_vector(tmpl.provided_constraints,
[](const char* c) { return std::string(c); });
} else if (tmpl.type_var_defaults.size() == 1) {
std::string var = gen.fresh();
_type_vars.push_back(var);
_type = llvm::formatv(tmpl._type, var);
_provided_constraints = map_vector(
tmpl.provided_constraints,
[&var](const char* c) { return llvm::formatv(c, var).str(); });
} else {
std::abort(); // Not sure how to splat arbitrary many vars into formatv.
}
}
std::string match(std::string name) const override { return llvm::formatv(_pattern, name); }
std::string type() const override { return _type; }
const std::vector<std::string>& provided_constraints() const override { return _provided_constraints; }
const std::vector<std::string>& type_vars() const { return _type_vars; }
const std::vector<const char*>& type_var_defaults() const { return _type_var_defaults; }
void print(llvm::raw_ostream& os,
attr_print_state& optional_attr_defs) const override {}
private:
const char* _pattern;
std::string _type;
std::vector<std::string> _provided_constraints;
std::vector<std::string> _type_vars;
const std::vector<const char*> _type_var_defaults;
};
class OptionalAttrPattern : public AttrPattern {
public:
OptionalAttrPattern(llvm::StringRef attr_kind, SimpleAttrPattern base)
: base(std::move(base)), attr_kind(attr_kind) {}
std::string type() const override {
return "Maybe " + base.type();
}
std::string match(std::string name) const override {
return llvm::formatv("Optional{0} {1}", attr_kind, name);
}
const std::vector<std::string>& provided_constraints() const override { return base.provided_constraints(); }
void print(llvm::raw_ostream& os,
attr_print_state& optional_attr_defs) const override {
if (!optional_attr_defs.contains(attr_kind)) {
if (base.provided_constraints().empty()) {
const char* kOptionalHandler = R"(
pattern Optional{0} :: Maybe {1} -> Maybe Attribute
pattern Optional{0} x <- ((\case Just ({2}) -> Just y; Nothing -> Nothing) -> x)
where Optional{0} x = case x of Just y -> Just ({2}); Nothing -> Nothing
)";
os << llvm::formatv(kOptionalHandler, attr_kind, base.type(),
base.match("y"));
} else {
const char *kOptionalHandlerConstr = R"(
data Maybe{0}Adapter = forall {4:$[ ]}. ({3:$[, ]}) => AdaptMaybe{0} (Maybe ({1}))
unwrapMaybe{0} :: Maybe Attribute -> Maybe{0}Adapter
unwrapMaybe{0} = \case
Just ({2}) -> AdaptMaybe{0} (Just y)
_ -> AdaptMaybe{0} {5:[]}Nothing
pattern Optional{0} :: () => ({3:$[, ]}) => Maybe {1} -> Maybe Attribute
pattern Optional{0} x <- (unwrapMaybe{0} -> AdaptMaybe{0} x)
where Optional{0} x = case x of Just y -> Just ({2}); Nothing -> Nothing
)";
std::vector<std::string> default_apps;
for (const char* d : base.type_var_defaults()) {
default_apps.push_back("@" + std::string(d) + " ");
}
os << llvm::formatv(kOptionalHandlerConstr,
attr_kind, // 0
base.type(), // 1
base.match("y"), // 2
make_range(base.provided_constraints()), // 3
make_range(base.type_vars()), // 4
make_range(default_apps)); // 5
}
optional_attr_defs.insert(attr_kind);
}
}
private:
SimpleAttrPattern base;
llvm::StringRef attr_kind;
};
using attr_pattern_map = llvm::StringMap<AttrPatternTemplate>;
const attr_pattern_map& getAttrPatternTemplates() {
static const attr_pattern_map* kAttrHandlers = new attr_pattern_map{
{"AnyAttr", {"{0}", "Attribute", {}, {}}},
{"AffineMapArrayAttr", {"PatternUtil.AffineMapArrayAttr {0}", "[Affine.Map]", {}, {}}},
{"AffineMapAttr", {"AffineMapAttr {0}", "Affine.Map", {}, {}}},
{"ArrayAttr", {"ArrayAttr {0}", "[Attribute]", {}, {}}},
{"BoolAttr", {"BoolAttr {0}", "Bool", {}, {}}},
{"DictionaryAttr", {"DictionaryAttr {0}", "(M.Map Name Attribute)", {}, {}}},
{"F32Attr", {"FloatAttr Float32Type {0}", "Double", {}, {}}},
{"F64Attr", {"FloatAttr Float64Type {0}", "Double", {}, {}}},
{"I32Attr", {"IntegerAttr (IntegerType Signless 32) {0}", "Int", {}, {}}},
{"I64Attr", {"IntegerAttr (IntegerType Signless 64) {0}", "Int", {}, {}}},
{"I64ArrayAttr", {"PatternUtil.I64ArrayAttr {0}", "[Int]", {}, {}}},
{"I64ElementsAttr", {"DenseElementsAttr (IntegerType Signless 64) (DenseInt64 {0})",
"(AST.IStorableArray {0} Int64)", {"Ix {0}", "Show {0}"}, {"PatternUtil.DummyIx"}}},
{"IndexAttr", {"IntegerAttr IndexType {0}", "Int", {}, {}}},
{"StrAttr", {"StringAttr {0}", "BS.ByteString", {}, {}}},
};
return *kAttrHandlers;
}
// Returns nullptr when the attribute pattern couldn't be constructed.
std::unique_ptr<AttrPattern> tryGetAttrPattern(
const mlir::tblgen::NamedAttribute& nattr, NameSource& gen) {
llvm::StringRef attr_kind = nattr.attr.getAttrDefName();
if (getAttrPatternTemplates().count(attr_kind) != 1) return nullptr;
const AttrPatternTemplate& tmpl = getAttrPatternTemplates().lookup(attr_kind);
if (!nattr.attr.isOptional()) {
return std::make_unique<SimpleAttrPattern>(tmpl, gen);
} else {
auto pat = std::make_unique<OptionalAttrPattern>(
attr_kind, SimpleAttrPattern(tmpl, gen));
return pat;
}
}
const std::string sanitizeName(llvm::StringRef name, llvm::Optional<int> idx = llvm::None) {
static const llvm::StringSet<>* kReservedNames = new llvm::StringSet<>{
// TODO(apaszke): Add more keywords
// Haskell keywords
"in", "data",
};
if (name.empty()) {
assert(idx);
return llvm::formatv("_unnamed{0}", *idx);
} else if (kReservedNames->contains(name)) {
auto new_name = name.str();
new_name.push_back('_');
return new_name;
} else {
return name.str();
}
}
std::string getDialectName(llvm::ArrayRef<llvm::Record*> op_defs) {
mlir::tblgen::Operator any_op(op_defs.front());
assert(
std::all_of(op_defs.begin(), op_defs.end(), [&any_op](llvm::Record* op) {
return mlir::tblgen::Operator(op).getDialectName() ==
any_op.getDialectName();
}));
std::string dialect_name;
if (DialectName.empty()) {
dialect_name = any_op.getDialectName().str();
dialect_name[0] = llvm::toUpper(dialect_name[0]);
} else {
dialect_name = DialectName;
}
return dialect_name;
}
class OpAttrPattern {
OpAttrPattern(std::string name, std::vector<std::string> binders,
std::vector<mlir::tblgen::NamedAttribute> attrs,
std::vector<std::unique_ptr<AttrPattern>> patterns)
: name(std::move(name)),
binders(std::move(binders)),
attrs(std::move(attrs)),
patterns(std::move(patterns)) {}
public:
static llvm::Optional<OpAttrPattern> buildFor(mlir::tblgen::Operator& op) {
if (op.getNumAttributes() == 0) return OpAttrPattern("NoAttrs", {}, {}, {});
NameSource gen("a");
std::vector<std::string> binders;
std::vector<mlir::tblgen::NamedAttribute> attrs;
std::vector<std::unique_ptr<AttrPattern>> patterns;
for (const auto& named_attr : op.getAttributes()) {
// Derived attributes are never materialized and don't have to be
// specified.
if (named_attr.attr.isDerivedAttr()) continue;
auto pattern = tryGetAttrPattern(named_attr, gen);
if (!pattern) {
if (named_attr.attr.hasDefaultValue()) {
warn(op, llvm::formatv("unsupported attr {0} (but has default value)",
named_attr.attr.getAttrDefName()));
continue;
}
if (named_attr.attr.isOptional()) {
warn(op, llvm::formatv("unsupported attr {0} (but is optional)",
named_attr.attr.getAttrDefName()));
continue;
}
warn(op, llvm::formatv("unsupported attr ({0})",
named_attr.attr.getAttrDefName()));
return llvm::None;
}
binders.push_back(sanitizeName(named_attr.name));
attrs.push_back(named_attr);
patterns.push_back(std::move(pattern));
}
if (binders.empty()) return OpAttrPattern("NoAttrs", {}, {}, {});
std::string name = "Internal" + op.getCppClassName().str() + "Attributes";
return OpAttrPattern(std::move(name), std::move(binders), std::move(attrs),
std::move(patterns));
}
void print(llvm::raw_ostream& os, attr_print_state& optional_attr_defs) {
if (name == "NoAttrs") return;
// `M.lookup "attr_name" m` for every attribute
std::vector<std::string> lookups;
// Patterns from handlers, but wrapped in "Just (...)" when non-optional
std::vector<std::string> lookup_patterns;
// `[("attr_name", attr_pattern)]` for every non-optional attribute
std::vector<std::string> singleton_pairs;
for (size_t i = 0; i < attrs.size(); ++i) {
const mlir::tblgen::NamedAttribute& nattr = attrs[i];
const AttrPattern& pattern = *patterns[i];
pattern.print(os, optional_attr_defs);
lookups.push_back(llvm::formatv("M.lookup \"{0}\" m", nattr.name));
std::string inst_pattern = pattern.match(binders[i]);
if (nattr.attr.isOptional()) {
lookup_patterns.push_back(inst_pattern);
singleton_pairs.push_back(llvm::formatv(
"(Data.Maybe.maybeToList $ (\"{0}\",) <$> {1})", nattr.name, inst_pattern));
} else {
lookup_patterns.push_back(llvm::formatv("Just ({0})", inst_pattern));
singleton_pairs.push_back(
llvm::formatv("[(\"{0}\", {1})]", nattr.name, inst_pattern));
}
}
const char* kAttributePattern = R"(
pattern {0} :: () => ({6:$[, ]}) => {1:$[ -> ]} -> NamedAttributes
pattern {0} {2:$[ ]} <- ((\m -> ({3:$[, ]})) -> ({4:$[, ]}))
where {0} {2:$[ ]} = M.fromList $ {5:$[ ++ ]}
)";
os << llvm::formatv(kAttributePattern,
name, // 0
make_range(types()), // 1
make_range(binders), // 2
make_range(lookups), // 3
make_range(lookup_patterns), // 4
make_range(singleton_pairs), // 5
make_range(provided_constraints())); // 6
}
std::vector<std::string> types() const {
return map_vector(patterns, [](const std::unique_ptr<AttrPattern>& p) {
return p->type();
});
}
std::vector<std::string> provided_constraints() const {
std::vector<std::string> result;
for (auto& p : patterns) {
for (auto& c : p->provided_constraints()) {
result.push_back(c);
}
}
return result;
}
std::string name;
std::vector<std::string> binders;
private:
std::vector<mlir::tblgen::NamedAttribute> attrs;
std::vector<std::unique_ptr<AttrPattern>> patterns;
};
llvm::Optional<std::string> buildOperation(
const llvm::Record* def, bool is_pattern, const std::string& what_for,
const std::string& location_expr,
const std::vector<std::string>& type_exprs,
const std::vector<std::string>& operand_exprs,
const std::vector<std::string>& region_exprs,
const OpAttrPattern& attr_pattern) {
mlir::tblgen::Operator op(def);
auto fail = [&op, &what_for](std::string reason) {
warn(op, llvm::formatv("couldn't construct {0}: {1}", what_for, reason));
return llvm::Optional<std::string>();
};
// Skip currently unsupported cases
if (op.getNumVariadicRegions() != 0) return fail("variadic regions");
if (op.getNumSuccessors() != 0) return fail("successors");
// Prepare results
std::string type_expr;
if (op.getNumResults() == 0) {
assert(type_exprs.size() == op.getNumResults());
type_expr = "[]";
} else if (op.getNumVariableLengthResults() == 0 &&
op.getTrait("::mlir::OpTrait::SameOperandsAndResultType")) {
assert(type_exprs.size() == 1);
type_expr = llvm::formatv("[{0:$[, ]}]",
make_range(std::vector<llvm::StringRef>(
op.getNumResults(), type_exprs.front())));
} else if (op.getNumVariableLengthResults() == 0) {
assert(type_exprs.size() == op.getNumResults());
type_expr = llvm::formatv("[{0:$[, ]}]", make_range(type_exprs));
} else if (!is_pattern) {
assert(type_exprs.size() == op.getNumResults());
std::vector<std::string> list_type_exprs;
for (int i = 0; i < op.getNumResults(); ++i) {
auto& result = op.getResult(i);
if (result.isOptional()) {
list_type_exprs.push_back("(Data.Maybe.maybeToList " + type_exprs[i] + ")");
} else if (result.isVariadic()) {
list_type_exprs.push_back(type_exprs[i]);
} else {
assert(!result.isVariableLength());
list_type_exprs.push_back("[" + type_exprs[i] + "]");
}
}
type_expr = llvm::formatv("({0:$[ ++ ]})", make_range(list_type_exprs));
} else {
return fail("unsupported variable length results");
}
// Prepare operands
std::string operand_expr;
assert(operand_exprs.size() == op.getNumOperands());
if (op.getNumOperands() == 1 && op.getOperand(0).isVariadic()) {
// Note that this expr already should represent a list
operand_expr = operand_exprs.front();
} else if (op.getNumVariableLengthOperands() == 0) {
operand_expr = llvm::formatv("[{0:$[, ]}]", make_range(operand_exprs));
} else if (!is_pattern) {
std::vector<std::string> operand_list_exprs;
for (int i = 0; i < op.getNumOperands(); ++i) {
auto& operand = op.getOperand(i);
if (operand.isOptional()) {
operand_list_exprs.push_back("(Data.Maybe.maybeToList " + operand_exprs[i] + ")");
} else if (operand.isVariadic()) {
operand_list_exprs.push_back(operand_exprs[i]);
} else {
assert(!operand.isVariableLength());
operand_list_exprs.push_back("[" + operand_exprs[i] + "]");
}
}
operand_expr =
llvm::formatv("({0:$[ ++ ]})", make_range(operand_list_exprs));
} else {
return fail("unsupported variable length operands");
}
std::string extra_attrs;
if (op.getTrait("::mlir::OpTrait::AttrSizedOperandSegments")) {
std::vector<std::string> segment_sizes;
for (int i = 0; i < op.getNumOperands(); ++i) {
auto& operand = op.getOperand(i);
if (operand.isOptional()) {
segment_sizes.push_back(llvm::formatv(
"case {0} of Just _ -> 1; Nothing -> 0", operand_exprs[i]));
} else if (operand.isVariadic()) {
segment_sizes.push_back("Prelude.length " + operand_exprs[i]);
} else {
assert(!operand.isVariableLength());
segment_sizes.push_back("1");
}
}
const char* kOperandSegmentsAttr = R"(
<> AST.namedAttribute "operand_segment_sizes"
(DenseElementsAttr (VectorType [{0}] $ IntegerType Unsigned 32) $
DenseUInt32 $ IArray.listArray (1 :: Int, {0}) $ Prelude.fromIntegral <$> [{1:$[, ]}])
)";
extra_attrs = llvm::formatv(kOperandSegmentsAttr,
segment_sizes.size(),
make_range(segment_sizes));
}
const char* kPatternExplicitType = R"(Operation
{ opName = "{0}"
, opLocation = {1}
, opResultTypes = Explicit {2}
, opOperands = {3}
, opRegions = [{4:$[ ]}]
, opSuccessors = []
, opAttributes = ({5}{6}{7:$[ ]}){8}
})";
return llvm::formatv(kPatternExplicitType,
op.getOperationName(), // 0
location_expr, // 1
type_expr, // 2
operand_expr, // 3
make_range(region_exprs), // 4
attr_pattern.name, // 5
attr_pattern.binders.empty() ? "" : " ", // 6
make_range(attr_pattern.binders), // 7
extra_attrs) // 8
.str();
}
// TODO(apaszke): Make this more reliable
std::string legalizeBuilderName(std::string name) {
for (size_t i = 0; i < name.size(); ++i) {
if (name[i] == '.') name[i] = '_';
}
return name;
}
std::string stripDialect(std::string name) {
size_t dialect_sep_loc = name.find('.');
assert(dialect_sep_loc != std::string::npos);
return name.substr(dialect_sep_loc + 1);
}
void emitBuilderMethod(mlir::tblgen::Operator& op,
const OpAttrPattern& attr_pattern, llvm::raw_ostream& os) {
auto fail = [&op](std::string reason) {
warn(op, "couldn't construct builder: " + reason);
};
if (op.getNumVariadicRegions() != 0) return fail("variadic regions");
if (op.getNumSuccessors() != 0) return fail("successors");
const char* result_type;
std::string prologue;
const char* continuation = "";
if (op.getNumResults() == 0) {
prologue = "Control.Monad.void ";
if (op.getTrait("::mlir::OpTrait::IsTerminator")) {
result_type = "EndOfBlock";
continuation = "\n AST.terminateBlock";
} else {
result_type = "()";
}
} else if (op.getNumResults() == 1) {
result_type = "Value";
prologue = "Control.Monad.liftM Prelude.head ";
} else {
result_type = "[Value]";
prologue = "";
}
std::string builder_name = legalizeBuilderName(stripDialect(op.getOperationName()));
std::vector<std::string> builder_arg_types;
// TODO(apaszke): Use inference (op.getSameTypeAsResult)
std::vector<std::string> type_exprs;
std::vector<std::string> type_binders;
if (op.getNumResults() == 0) {
// Nothing to do.
} else if (op.getNumVariableLengthResults() == 0 &&
op.getTrait("::mlir::OpTrait::SameOperandsAndResultType")) {
for (const mlir::tblgen::NamedTypeConstraint& operand : op.getOperands()) {
if (operand.isVariableLength()) continue;
type_exprs.push_back("(AST.typeOf " + sanitizeName(operand.name) + ")");
break;
}
if (type_exprs.empty()) return fail("type inference failed");
} else {
int result_nr = 0;
for (const mlir::tblgen::NamedTypeConstraint& result : op.getResults()) {
type_binders.push_back(llvm::formatv("ty{0}", result_nr++));
type_exprs.push_back(type_binders.back());
if (result.isOptional()) {
builder_arg_types.push_back("Maybe Type");
} else if (result.isVariadic()) {
builder_arg_types.push_back("[Type]");
} else {
assert(!result.isVariableLength());
builder_arg_types.push_back("Type");
}
}
}
std::vector<std::string> operand_binders;
std::vector<std::string> operand_name_exprs;
operand_name_exprs.reserve(op.getNumOperands());
for (int i = 0; i < op.getNumOperands(); ++i) {
const auto& operand = op.getOperand(i);
std::string operand_name = sanitizeName(operand.name, i);
operand_binders.push_back(operand_name);
if (operand.isOptional()) {
builder_arg_types.push_back("Maybe Value");
operand_name_exprs.push_back("(AST.operand <$> " + operand_name + ")");
} else if (operand.isVariadic()) {
builder_arg_types.push_back("[Value]");
operand_name_exprs.push_back("(AST.operands " + operand_name + ")");
} else {
assert(!operand.isVariableLength());
builder_arg_types.push_back("Value");
operand_name_exprs.push_back("(AST.operand " + operand_name + ")");
}
}
auto attr_types = attr_pattern.types();
builder_arg_types.insert(builder_arg_types.end(), attr_types.begin(),
attr_types.end());
std::vector<std::string> region_builder_binders;
std::vector<std::string> region_binders;
if (op.getNumRegions() > 0) {
std::string region_prologue;
NameSource gen("_unnamed_region");
for (const mlir::tblgen::NamedRegion& region : op.getRegions()) {
std::string name = region.name.empty() ? gen.fresh() : sanitizeName(region.name);
region_builder_binders.push_back(name + "Builder");
region_binders.push_back(name);
builder_arg_types.push_back("RegionBuilderT m ()");
region_prologue += llvm::formatv(
"{0} <- AST.buildRegion {1}\n ",
region_binders.back(), region_builder_binders.back());
}
prologue = region_prologue + prologue;
}
builder_arg_types.push_back(""); // To add the arrow before m
llvm::Optional<std::string> operation =
buildOperation(&op.getDef(), false, "builder", "UnknownLocation",
type_exprs, operand_name_exprs, region_binders,
attr_pattern);
if (!operation) return;
const char* kBuilder = R"(
-- | A builder for @{10}@.
{0} :: ({11:$[, ]}) => MonadBlockBuilder m => {1:$[ -> ]}m {2}
{0} {3:$[ ]} {4:$[ ]} {5:$[ ]} {6:$[ ]} = do
{7}(AST.emitOp ({8})){9}
)";
os << llvm::formatv(kBuilder,
builder_name, // 0
make_range(builder_arg_types), // 1
result_type, // 2
make_range(type_binders), // 3
make_range(operand_binders), // 4
make_range(attr_pattern.binders), // 5
make_range(region_builder_binders), // 6
prologue, // 7
*operation, // 8
continuation, // 9
op.getOperationName(), // 10
make_range(attr_pattern.provided_constraints())); // 11
}
void emitPattern(const llvm::Record* def, const OpAttrPattern& attr_pattern,
llvm::raw_ostream& os) {
mlir::tblgen::Operator op(def);
auto fail = [&op](std::string reason) {
return warn(op, llvm::formatv("couldn't construct pattern: {0}", reason));
};
// Skip currently unsupported cases
if (op.getNumVariableLengthResults() != 0) return fail("variadic results");
if (op.getNumRegions() != 0) return fail("regions");
if (op.getNumSuccessors() != 0) return fail("successors");
if (!def->getName().endswith("Op")) return fail("unsupported name format");
if (!def->getName().startswith(StripOpPrefix)) return fail("missing prefix");
// Drop the stripped prefix and "Op" from the end.
llvm::StringRef pattern_name =
def->getName().drop_back(2).drop_front(StripOpPrefix.length());
std::vector<std::string> pattern_arg_types{"Location"};
// Prepare results
std::vector<std::string> type_binders;
if (op.getNumResults() > 0 &&
op.getTrait("::mlir::OpTrait::SameOperandsAndResultType")) {
assert(op.getNumVariableLengthResults() == 0);
pattern_arg_types.push_back("Type");
type_binders.push_back("ty");
} else {
size_t result_count = 0;
for (int i = 0; i < op.getNumResults(); ++i) {
pattern_arg_types.push_back("Type");
type_binders.push_back(llvm::formatv("ty{0}", result_count++));
}
}
// Prepare operands
std::vector<std::string> operand_binders;
if (op.getNumOperands() == 1 && op.getOperand(0).isVariadic()) {
// Single variadic arg is easy to handle
pattern_arg_types.push_back("[operand]");
operand_binders.push_back(sanitizeName(op.getOperand(0).name, 0));
} else {
// Non-variadic case
for (int i = 0; i < op.getNumOperands(); ++i) {
const auto& operand = op.getOperand(i);
if (operand.isVariableLength())
return fail("unsupported variable length operand");
pattern_arg_types.push_back("operand");
operand_binders.push_back(sanitizeName(operand.name, i));
}
}
// Prepare attribute pattern
auto attr_types = attr_pattern.types();
pattern_arg_types.insert(pattern_arg_types.end(), attr_types.begin(),
attr_types.end());
llvm::Optional<std::string> operation = buildOperation(
def, true, "pattern", "loc",
type_binders, operand_binders, {}, attr_pattern);
if (!operation) return;
const char* kPatternExplicitType = R"(
-- | A pattern for @{6}@.
pattern {0} :: () => ({7:$[, ]}) => {1:$[ -> ]} -> AbstractOperation operand
pattern {0} loc {2:$[ ]} {3:$[ ]} {4:$[ ]} = {5}
)";
os << llvm::formatv(kPatternExplicitType,
pattern_name, // 0
make_range(pattern_arg_types), // 1
make_range(type_binders), // 2
make_range(operand_binders), // 3
make_range(attr_pattern.binders), // 4
*operation, // 5
op.getOperationName(), // 6
make_range(attr_pattern.provided_constraints())); // 7
}
std::string formatDescription(mlir::tblgen::Operator op) {
std::string description;
description = "\n" + op.getDescription().str();
size_t pos = 0;
while (description[pos] == '\n') ++pos;
size_t leading_spaces = 0;
while (description[pos++] == ' ') ++leading_spaces;
if (leading_spaces) {
std::string leading_spaces_str;
for (size_t i = 0; i < leading_spaces; ++i) leading_spaces_str += "[ ]";
description = std::regex_replace(description, std::regex("\n" + leading_spaces_str), "\n");
}
description = std::regex_replace(description, std::regex("\\[(.*)\\]\\(.*\\)"), "$1");
description = std::regex_replace(description, std::regex("(['\"@<$#])"), "\\$1");
description = std::regex_replace(description, std::regex("```mlir"), "@");
description = std::regex_replace(description, std::regex("```"), "@");
description = std::regex_replace(description, std::regex("`"), "@");
description = std::regex_replace(description, std::regex("\n"), "\n-- ");
return description;
}
} // namespace
bool emitOpTableDefs(const llvm::RecordKeeper& recordKeeper,
llvm::raw_ostream& os) {
std::vector<llvm::Record*> defs = recordKeeper.getAllDerivedDefinitions("Op");
if (defs.empty()) return true;
// TODO(apaszke): Emit a module header to avoid leaking internal definitions.
auto dialect_name = getDialectName(defs);
os << "{-# OPTIONS_GHC -Wno-unused-imports #-}\n";
os << "{-# OPTIONS_HADDOCK hide, prune, not-home #-}\n\n";
os << "module MLIR.AST.Dialect.Generated." << dialect_name << " where\n";
os << R"(
import Prelude (Int, Double, Maybe(..), Bool(..), (++), (<$>), ($), (<>), Show)
import qualified Prelude
import Data.Int (Int64)
import qualified Data.Maybe
import Data.Array (Ix)
import qualified Data.Array.IArray as IArray
import qualified Data.ByteString as BS
import qualified Data.Map.Strict as M
import qualified Control.Monad
import MLIR.AST ( Attribute(..), Type(..), AbstractOperation(..), ResultTypes(..)
, Location(..), Signedness(..), DenseElements(..)
, NamedAttributes, Name
, pattern NoAttrs )
import qualified MLIR.AST as AST
import MLIR.AST.Builder (Value, EndOfBlock, MonadBlockBuilder, RegionBuilderT)
import qualified MLIR.AST.Builder as AST
import qualified MLIR.AST.IStorableArray as AST
import qualified MLIR.AST.PatternUtil as PatternUtil
import qualified MLIR.AST.Dialect.Affine as Affine
)";
attr_print_state attr_pattern_state;
for (const auto* def : defs) {
mlir::tblgen::Operator op(*def);
if (op.hasDescription()) {
os << llvm::formatv("\n-- * {0}\n-- ${0}", stripDialect(op.getOperationName()));
os << formatDescription(op);
os << "\n";
}
llvm::Optional<OpAttrPattern> attr_pattern = OpAttrPattern::buildFor(op);
if (!attr_pattern) continue;
attr_pattern->print(os, attr_pattern_state);
emitPattern(def, *attr_pattern, os);
emitBuilderMethod(op, *attr_pattern, os);
}
return false;
}
bool emitTestTableDefs(const llvm::RecordKeeper& recordKeeper,
llvm::raw_ostream& os) {
std::vector<llvm::Record*> defs = recordKeeper.getAllDerivedDefinitions("Op");
if (defs.empty()) return true;
auto dialect_name = getDialectName(defs);
os << "{-# OPTIONS_GHC -Wno-unused-imports #-}\n\n";
const char* module_header = R"(
module MLIR.AST.Dialect.Generated.{0}Spec where
import Prelude (IO, Maybe(..), ($), (<>))
import qualified Prelude
import Test.Hspec (Spec)
import qualified Test.Hspec as Hspec
import Test.QuickCheck ((===))
import qualified Test.QuickCheck as QC
import MLIR.AST (pattern NoAttrs)
import MLIR.AST.Dialect.{0}
import MLIR.Test.Generators ()
main :: IO ()
main = Hspec.hspec spec
spec :: Spec
spec = do
)";
os << llvm::formatv(module_header, dialect_name);
for (const auto* def : defs) {
mlir::tblgen::Operator op(*def);
llvm::Optional<OpAttrPattern> attr_pattern = OpAttrPattern::buildFor(op);
if (!attr_pattern) continue;
os << "\n Hspec.describe \"" << op.getOperationName() << "\" $ do";
const char* bidirectional_test_template = R"(
Hspec.it "has a bidirectional attr pattern" $ do
let wrapUnwrap ({1:$[, ]}) = case ({0} {1:$[ ]}) <> Prelude.mempty of
{0} {2:$[ ]} -> Just ({2:$[, ]})
_ -> Nothing
QC.property $ \args -> wrapUnwrap args === Just args
)";
os << llvm::formatv(
bidirectional_test_template, attr_pattern->name,
make_range(attr_pattern->binders),
make_range(map_vector(attr_pattern->binders, [](const std::string& b) {
return b + "_match";
})));
const char* pattern_extensibility_test_template = R"(
Hspec.it "accepts additional attributes" $ do
QC.property $ do
({1:$[, ]}) <- QC.arbitrary
extraAttrs <- QC.arbitrary
let match = case ({0} {1:$[ ]}) <> extraAttrs of
{0} {2:$[ ]} -> Just ({2:$[, ]})
_ -> Nothing
Prelude.return $ match === Just ({1:$[, ]})
)";
os << llvm::formatv(
pattern_extensibility_test_template, attr_pattern->name,
make_range(attr_pattern->binders),
make_range(map_vector(attr_pattern->binders, [](const std::string& b) {
return b + "_match";
})));
// TODO(apaszke): Test attr pattern matches with more attributes.
// TODO(apaszke): Test bidirectionality of op pattern.
// TODO(apaszke): Test op pattern matches with more attributes.
// TODO(apaszke): Test builder output matches op pattern.
// TODO(apaszke): Figure out how to do tests with translation.
}
return false;
}
|
/***********************************************************************************
** MIT License **
** **
** Copyright (c) 2018 Victor DENIS (victordenis01@gmail.com) **
** **
** Permission is hereby granted, free of charge, to any person obtaining a copy **
** of this software and associated documentation files (the "Software"), to deal **
** in the Software without restriction, including without limitation the rights **
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell **
** copies of the Software, and to permit persons to whom the Software is **
** furnished to do so, subject to the following conditions: **
** **
** The above copyright notice and this permission notice shall be included in all **
** copies or substantial portions of the Software. **
** **
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR **
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, **
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE **
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER **
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, **
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE **
** SOFTWARE. **
***********************************************************************************/
#pragma once
#ifndef SIELOBROWSER_BOOKMARKSIMPORTER_HPP
#define SIELOBROWSER_BOOKMARKSIMPORTER_HPP
#include <QObject>
#include <QString>
namespace Sn
{
class BookmarkItem;
class BookmarksImporter: public QObject {
BookmarksImporter(QObject* parent = nullptr);
virtual ~BookmarksImporter();
bool error() const;
QString errorString() const;
virtual QString description() const = 0;
virtual QString standardPath() const = 0;
virtual QString getPath(QWidget* parent) = 0;
virtual bool prepareImport() = 0;
virtual BookmarkItem *importBookmarks() = 0;
protected:
// Empty error = no error
void setError(const QString& error);
private:
QString m_error{};
};
}
#endif //SIELOBROWSER_BOOKMARKSIMPORTER_HPP
[Update] Bookmarks importer
/***********************************************************************************
** MIT License **
** **
** Copyright (c) 2018 Victor DENIS (victordenis01@gmail.com) **
** **
** Permission is hereby granted, free of charge, to any person obtaining a copy **
** of this software and associated documentation files (the "Software"), to deal **
** in the Software without restriction, including without limitation the rights **
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell **
** copies of the Software, and to permit persons to whom the Software is **
** furnished to do so, subject to the following conditions: **
** **
** The above copyright notice and this permission notice shall be included in all **
** copies or substantial portions of the Software. **
** **
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR **
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, **
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE **
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER **
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, **
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE **
** SOFTWARE. **
***********************************************************************************/
#pragma once
#ifndef SIELOBROWSER_BOOKMARKSIMPORTER_HPP
#define SIELOBROWSER_BOOKMARKSIMPORTER_HPP
#include <QObject>
#include <QString>
namespace Sn
{
class BookmarkItem;
class BookmarksImporter: public QObject {
Q_OBJECT
public:
BookmarksImporter(QObject* parent = nullptr);
virtual ~BookmarksImporter();
bool error() const;
QString errorString() const;
virtual QString description() const = 0;
virtual QString standardPath() const = 0;
virtual QString getPath(QWidget* parent) = 0;
virtual bool prepareImport() = 0;
virtual BookmarkItem *importBookmarks() = 0;
protected:
// Empty error = no error
void setError(const QString& error);
private:
QString m_error{};
};
}
#endif //SIELOBROWSER_BOOKMARKSIMPORTER_HPP
|
//
// parser_tables.cpp
// Parse
//
// Created by Andrew Hunter on 07/05/2011.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#include <algorithm>
#include "parser_tables.h"
using namespace std;
using namespace contextfree;
using namespace lr;
/// \brief Ranks actions in the order they should appear in the final table
static inline int action_score(int action) {
switch (action) {
case lr_action::act_guard:
// Guard actions are always evaluated first, so we can substitute the guard symbol if it's matched
return 0;
case lr_action::act_weakreduce:
// Weak reduce actions come first as they should always be performed if their symbol will produce a shift
return 1;
case lr_action::act_shift:
case lr_action::act_divert:
// Shift actions are preferred if there's a conflict
return 2;
case lr_action::act_reduce:
// Reduce actions have the lowest priority
return 3;
case lr_action::act_goto:
// Gotos never actually produce a clash
return 4;
default:
return 5;
}
}
static inline bool compare_actions(const parser_tables::action& a, const parser_tables::action& b) {
// First, compare on symbol IDs
if (a.m_SymbolId < b.m_SymbolId) return true;
// Next, compare on action types
if (action_score(a.m_Type) < action_score(b.m_Type)) return true;
// Actions are equal
return false;
}
/// \brief Creates a parser from the result of the specified builder class
parser_tables::parser_tables(const lalr_builder& builder) {
// Allocate the tables
m_NumStates = builder.count_states();
m_NonterminalActions = new action*[m_NumStates];
m_TerminalActions = new action*[m_NumStates];
m_Counts = new action_count[m_NumStates];
contextfree::end_of_input eoi;
m_EndOfInput = builder.gram().identifier_for_item(eoi);
const grammar& gram = builder.gram();
map<int, int> ruleIds; // Maps their rule IDs to our rule IDs
// Build up the tables for each state
for (int stateId = 0; stateId < m_NumStates; stateId++) {
// Get the actions for this state
const lr_action_set& actions = builder.actions_for_state(stateId);
// Count the number of terminal and nonterminal actions
int termCount = 0;
int nontermCount = 0;
for (lr_action_set::const_iterator nextAction = actions.begin(); nextAction != actions.end(); nextAction++) {
if ((*nextAction)->item()->type() == item::terminal) {
termCount++;
} else {
nontermCount++;
}
}
// Allocate action tables of the appropriate size
action* termActions = new action[termCount];
action* nontermActions = new action[nontermCount];
int termPos = 0; // Current item in the terminal table
int nontermPos = 0; // Current item in the nonterminal table
// Fill up the actions (not in order)
for (lr_action_set::const_iterator nextAction = actions.begin(); nextAction != actions.end(); nextAction++) {
// Get the next state
int nextState = (*nextAction)->next_state();
int type = (*nextAction)->type();
// If the next action is a reduce action, then the next state should actually be the rule to reduce
if (type == lr_action::act_reduce || type == lr_action::act_weakreduce || type == lr_action::act_accept) {
// Look up the ID we assigned this rule
int ruleId = (*nextAction)->rule()->identifier(gram);
map<int, int>::iterator found = ruleIds.find(ruleId);
if (found == ruleIds.end()) {
nextState = (int)ruleIds.size();
ruleIds[ruleId] = nextState;
} else {
nextState = found->second;
}
}
if ((*nextAction)->item()->type() == item::terminal) {
// Add a new terminal action
termActions[termPos].m_Type = type;
termActions[termPos].m_NextState = nextState;
termActions[termPos].m_SymbolId = (*nextAction)->item()->symbol();
termPos++;
} else {
// Add a new nonterminal action
nontermActions[nontermPos].m_Type = type;
nontermActions[nontermPos].m_NextState = nextState;
nontermActions[nontermPos].m_SymbolId = gram.identifier_for_item((*nextAction)->item());
nontermPos++;
}
}
// Sort the actions for this state
std::sort(termActions, termActions + termCount, compare_actions);
std::sort(nontermActions, nontermActions + nontermCount, compare_actions);
// Store the actions in the table
m_TerminalActions[stateId] = termActions;
m_NonterminalActions[stateId] = nontermActions;
m_Counts[stateId].m_NumTerms = termCount;
m_Counts[stateId].m_NumNonterms = nontermCount;
}
// Fill in the rule table
m_NumRules = (int)ruleIds.size();
m_Rules = new reduce_rule[ruleIds.size()];
for (map<int, int>::iterator ruleId = ruleIds.begin(); ruleId != ruleIds.end(); ruleId++) {
const rule_container& rule = gram.rule_with_identifier(ruleId->first);
m_Rules[ruleId->second].m_Identifier = gram.identifier_for_item(rule->nonterminal());
m_Rules[ruleId->second].m_Length = (int)rule->items().size();
}
}
/// \brief Copy constructor
parser_tables::parser_tables(const parser_tables& copyFrom)
: m_NumStates(copyFrom.m_NumStates)
, m_NumRules(copyFrom.m_NumRules)
, m_EndOfInput(copyFrom.m_EndOfInput) {
// Allocate the action tables
m_TerminalActions = new action*[m_NumStates];
m_NonterminalActions = new action*[m_NumStates];
m_Counts = new action_count[m_NumStates];
// Copy the states
for (int stateId=0; stateId<m_NumStates; stateId++) {
// Copy the counts
m_Counts[stateId] = copyFrom.m_Counts[stateId];
// Allocate the array for this state
m_TerminalActions[stateId] = new action[m_Counts[stateId].m_NumTerms];
m_NonterminalActions[stateId] = new action[m_Counts[stateId].m_NumNonterms];
// Copy the terminals and nonterminals
for (int x=0; x<m_Counts[stateId].m_NumTerms; x++) {
m_TerminalActions[stateId][x] = copyFrom.m_TerminalActions[stateId][x];
}
for (int x=0; x<m_Counts[stateId].m_NumNonterms; x++) {
m_NonterminalActions[stateId][x] = copyFrom.m_NonterminalActions[stateId][x];
}
}
// Allocate the rule table
m_Rules = new reduce_rule[m_NumRules];
for (int ruleId=0; ruleId<m_NumRules; ruleId++) {
m_Rules[ruleId] = copyFrom.m_Rules[ruleId];
}
}
/// \brief Assignment
parser_tables& parser_tables::operator=(const parser_tables& copyFrom) {
if (©From == this) return *this;
// TODO
return *this;
}
/// \brief Destructor
parser_tables::~parser_tables() {
// Destroy each entry in the parser table
for (int x=0; x<m_NumStates; x++) {
delete[] m_NonterminalActions[x];
delete[] m_TerminalActions[x];
}
// Destroy the tables themselves
delete[] m_NonterminalActions;
delete[] m_TerminalActions;
delete[] m_Rules;
delete[] m_Counts;
}
Fixed very stupid bug with the way comparisons were done (if we want to compare < for something with multiple components, we need to make sure they're actually not equal before comparing the next item)
Might have this problem elsewhere as well
--HG--
branch : Parse
extra : convert_revision : svn%3A3666fe7e-a552-0410-bc3c-bd4e4c681ee0/trunk/Parse%401088
//
// parser_tables.cpp
// Parse
//
// Created by Andrew Hunter on 07/05/2011.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#include <algorithm>
#include "parser_tables.h"
using namespace std;
using namespace contextfree;
using namespace lr;
/// \brief Ranks actions in the order they should appear in the final table
static inline int action_score(int action) {
switch (action) {
case lr_action::act_guard:
// Guard actions are always evaluated first, so we can substitute the guard symbol if it's matched
return 0;
case lr_action::act_weakreduce:
// Weak reduce actions come first as they should always be performed if their symbol will produce a shift
return 1;
case lr_action::act_shift:
case lr_action::act_divert:
// Shift actions are preferred if there's a conflict
return 2;
case lr_action::act_reduce:
// Reduce actions have the lowest priority
return 3;
case lr_action::act_goto:
// Gotos never actually produce a clash
return 4;
default:
return 5;
}
}
static inline bool compare_actions(const parser_tables::action& a, const parser_tables::action& b) {
// First, compare on symbol IDs
if (a.m_SymbolId < b.m_SymbolId) return true;
if (a.m_SymbolId > b.m_SymbolId) return false;
// Next, compare on action types
int aScore = action_score(a.m_Type);
int bScore = action_score(b.m_Type);
if (aScore < bScore) return true;
if (aScore > bScore) return false;
// Actions are equal
return false;
}
/// \brief Creates a parser from the result of the specified builder class
parser_tables::parser_tables(const lalr_builder& builder) {
// Allocate the tables
m_NumStates = builder.count_states();
m_NonterminalActions = new action*[m_NumStates];
m_TerminalActions = new action*[m_NumStates];
m_Counts = new action_count[m_NumStates];
contextfree::end_of_input eoi;
m_EndOfInput = builder.gram().identifier_for_item(eoi);
const grammar& gram = builder.gram();
map<int, int> ruleIds; // Maps their rule IDs to our rule IDs
// Build up the tables for each state
for (int stateId = 0; stateId < m_NumStates; stateId++) {
// Get the actions for this state
const lr_action_set& actions = builder.actions_for_state(stateId);
// Count the number of terminal and nonterminal actions
int termCount = 0;
int nontermCount = 0;
for (lr_action_set::const_iterator nextAction = actions.begin(); nextAction != actions.end(); nextAction++) {
if ((*nextAction)->item()->type() == item::terminal) {
termCount++;
} else {
nontermCount++;
}
}
// Allocate action tables of the appropriate size
action* termActions = new action[termCount];
action* nontermActions = new action[nontermCount];
int termPos = 0; // Current item in the terminal table
int nontermPos = 0; // Current item in the nonterminal table
// Fill up the actions (not in order)
for (lr_action_set::const_iterator nextAction = actions.begin(); nextAction != actions.end(); nextAction++) {
// Get the next state
int nextState = (*nextAction)->next_state();
int type = (*nextAction)->type();
// If the next action is a reduce action, then the next state should actually be the rule to reduce
if (type == lr_action::act_reduce || type == lr_action::act_weakreduce || type == lr_action::act_accept) {
// Look up the ID we assigned this rule
int ruleId = (*nextAction)->rule()->identifier(gram);
map<int, int>::iterator found = ruleIds.find(ruleId);
if (found == ruleIds.end()) {
nextState = (int)ruleIds.size();
ruleIds[ruleId] = nextState;
} else {
nextState = found->second;
}
}
if ((*nextAction)->item()->type() == item::terminal) {
// Add a new terminal action
termActions[termPos].m_Type = type;
termActions[termPos].m_NextState = nextState;
termActions[termPos].m_SymbolId = (*nextAction)->item()->symbol();
termPos++;
} else {
// Add a new nonterminal action
nontermActions[nontermPos].m_Type = type;
nontermActions[nontermPos].m_NextState = nextState;
nontermActions[nontermPos].m_SymbolId = gram.identifier_for_item((*nextAction)->item());
nontermPos++;
}
}
// Sort the actions for this state
std::sort(termActions, termActions + termCount, compare_actions);
std::sort(nontermActions, nontermActions + nontermCount, compare_actions);
// Store the actions in the table
m_TerminalActions[stateId] = termActions;
m_NonterminalActions[stateId] = nontermActions;
m_Counts[stateId].m_NumTerms = termCount;
m_Counts[stateId].m_NumNonterms = nontermCount;
}
// Fill in the rule table
m_NumRules = (int)ruleIds.size();
m_Rules = new reduce_rule[ruleIds.size()];
for (map<int, int>::iterator ruleId = ruleIds.begin(); ruleId != ruleIds.end(); ruleId++) {
const rule_container& rule = gram.rule_with_identifier(ruleId->first);
m_Rules[ruleId->second].m_Identifier = gram.identifier_for_item(rule->nonterminal());
m_Rules[ruleId->second].m_Length = (int)rule->items().size();
}
}
/// \brief Copy constructor
parser_tables::parser_tables(const parser_tables& copyFrom)
: m_NumStates(copyFrom.m_NumStates)
, m_NumRules(copyFrom.m_NumRules)
, m_EndOfInput(copyFrom.m_EndOfInput) {
// Allocate the action tables
m_TerminalActions = new action*[m_NumStates];
m_NonterminalActions = new action*[m_NumStates];
m_Counts = new action_count[m_NumStates];
// Copy the states
for (int stateId=0; stateId<m_NumStates; stateId++) {
// Copy the counts
m_Counts[stateId] = copyFrom.m_Counts[stateId];
// Allocate the array for this state
m_TerminalActions[stateId] = new action[m_Counts[stateId].m_NumTerms];
m_NonterminalActions[stateId] = new action[m_Counts[stateId].m_NumNonterms];
// Copy the terminals and nonterminals
for (int x=0; x<m_Counts[stateId].m_NumTerms; x++) {
m_TerminalActions[stateId][x] = copyFrom.m_TerminalActions[stateId][x];
}
for (int x=0; x<m_Counts[stateId].m_NumNonterms; x++) {
m_NonterminalActions[stateId][x] = copyFrom.m_NonterminalActions[stateId][x];
}
}
// Allocate the rule table
m_Rules = new reduce_rule[m_NumRules];
for (int ruleId=0; ruleId<m_NumRules; ruleId++) {
m_Rules[ruleId] = copyFrom.m_Rules[ruleId];
}
}
/// \brief Assignment
parser_tables& parser_tables::operator=(const parser_tables& copyFrom) {
if (©From == this) return *this;
// TODO
return *this;
}
/// \brief Destructor
parser_tables::~parser_tables() {
// Destroy each entry in the parser table
for (int x=0; x<m_NumStates; x++) {
delete[] m_NonterminalActions[x];
delete[] m_TerminalActions[x];
}
// Destroy the tables themselves
delete[] m_NonterminalActions;
delete[] m_TerminalActions;
delete[] m_Rules;
delete[] m_Counts;
}
|
#ifndef LIB_PROPERTIES_HPP
#define LIB_PROPERTIES_HPP
#include "types.hpp"
namespace lib
{
template <typename T,class ACCESSOR>
class Property
{
public:
const T &get() const { return m_value; }
private:
Property() : m_value{} {}
Property(Property&&r) : m_value{ std::move(p); } {}
explicit Property(const T&iv) :m_value{ iv } {}
explicit Property(const T&&iv) :m_value{ std::move(iv); } {}
explicit Property(const Property &p) : m_value{ p } {}
T m_value;
void set(const T&nv) { m_value = nv; }
Property &operator=(const T&nv) { m_value = nv; return *this; }
Property &operator=(T&&nv) { m_value = nv; return *this; }
friend ACCESSOR;
};
template <typename T, class ACCESSOR> using PropertySptr = Property<sptr<T>,ACCESSOR>;
}
#endif
wip properties
#ifndef LIB_PROPERTIES_HPP
#define LIB_PROPERTIES_HPP
#include "types.hpp"
namespace lib
{
template <typename T>
class Property
{
public:
Property() : m_value{} {}
Property(Property&&r) : m_value{ std::move(p); } {}
explicit Property(const T&iv) :m_value{ iv } {}
explicit Property(const T&&iv) :m_value{ std::move(iv); } {}
explicit Property(const Property &p) : m_value{ p } {}
T m_value;
Property &operator=(const T&nv) { m_value = nv; return *this; }
Property &operator=(T&&nv) { m_value = nv; return *this; }
};
}
#endif
|
// -*- mode: c++; indent-tabs-mode: nil; tab-width: 2 -*-
// $Id$
// vim:tabstop=2
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include <string>
#include <boost/algorithm/string/predicate.hpp>
#include "moses/FF/Factory.h"
#include "TypeDef.h"
#include "moses/FF/WordPenaltyProducer.h"
#include "moses/FF/UnknownWordPenaltyProducer.h"
#include "moses/FF/InputFeature.h"
#include "moses/FF/DynamicCacheBasedLanguageModel.h"
#include "moses/TranslationModel/PhraseDictionaryDynamicCacheBased.h"
#include "DecodeStepTranslation.h"
#include "DecodeStepGeneration.h"
#include "GenerationDictionary.h"
#include "StaticData.h"
#include "Util.h"
#include "FactorCollection.h"
#include "Timer.h"
#include "TranslationOption.h"
#include "DecodeGraph.h"
#include "InputFileStream.h"
#include "ScoreComponentCollection.h"
#include "DecodeGraph.h"
#include "TranslationModel/PhraseDictionary.h"
#include "TranslationModel/PhraseDictionaryTreeAdaptor.h"
#ifdef WITH_THREADS
#include <boost/thread.hpp>
#endif
#ifdef HAVE_CMPH
#include "moses/TranslationModel/CompactPT/PhraseDictionaryCompact.h"
#endif
#if defined HAVE_CMPH
#include "moses/TranslationModel/CompactPT/LexicalReorderingTableCompact.h"
#endif
using namespace std;
using namespace boost::algorithm;
namespace Moses
{
StaticData StaticData::s_instance;
StaticData::StaticData()
: m_options(new AllOptions)
, m_requireSortingAfterSourceContext(false)
, m_currentWeightSetting("default")
, m_treeStructure(NULL)
, m_coordSpaceNextID(1)
{
Phrase::InitializeMemPool();
}
StaticData::~StaticData()
{
RemoveAllInColl(m_decodeGraphs);
Phrase::FinalizeMemPool();
}
bool StaticData::LoadDataStatic(Parameter *parameter, const std::string &execPath)
{
s_instance.SetExecPath(execPath);
return s_instance.LoadData(parameter);
}
void
StaticData
::initialize_features()
{
std::map<std::string, std::string> featureNameOverride = OverrideFeatureNames();
// all features
map<string, int> featureIndexMap;
const PARAM_VEC* params = m_parameter->GetParam("feature");
for (size_t i = 0; params && i < params->size(); ++i) {
const string &line = Trim(params->at(i));
VERBOSE(1,"line=" << line << endl);
if (line.empty())
continue;
vector<string> toks = Tokenize(line);
string &feature = toks[0];
std::map<std::string, std::string>::const_iterator iter
= featureNameOverride.find(feature);
if (iter == featureNameOverride.end()) {
// feature name not override
m_registry.Construct(feature, line);
} else {
// replace feature name with new name
string newName = iter->second;
feature = newName;
string newLine = Join(" ", toks);
m_registry.Construct(newName, newLine);
}
}
NoCache();
OverrideFeatures();
}
bool
StaticData
::ini_output_options()
{
// verbose level
m_parameter->SetParameter(m_verboseLevel, "verbose", (size_t) 1);
m_parameter->SetParameter<string>(m_outputUnknownsFile,
"output-unknowns", "");
return true;
}
// threads, timeouts, etc.
bool
StaticData
::ini_performance_options()
{
const PARAM_VEC *params;
m_threadCount = 1;
params = m_parameter->GetParam("threads");
if (params && params->size()) {
if (params->at(0) == "all") {
#ifdef WITH_THREADS
m_threadCount = boost::thread::hardware_concurrency();
if (!m_threadCount) {
std::cerr << "-threads all specified but Boost doesn't know how many cores there are";
return false;
}
#else
std::cerr << "-threads all specified but moses not built with thread support";
return false;
#endif
} else {
m_threadCount = Scan<int>(params->at(0));
if (m_threadCount < 1) {
std::cerr << "Specify at least one thread.";
return false;
}
#ifndef WITH_THREADS
if (m_threadCount > 1) {
std::cerr << "Error: Thread count of " << params->at(0)
<< " but moses not built with thread support";
return false;
}
#endif
}
}
return true;
}
bool StaticData::LoadData(Parameter *parameter)
{
m_parameter = parameter;
const PARAM_VEC *params;
m_options->init(*parameter);
if (is_syntax(m_options->search.algo))
m_options->syntax.LoadNonTerminals(*parameter, FactorCollection::Instance());
if (is_syntax(m_options->search.algo))
LoadChartDecodingParameters();
// ORDER HERE MATTERS, SO DON'T CHANGE IT UNLESS YOU KNOW WHAT YOU ARE DOING!
// input, output
m_parameter->SetParameter<string>(m_factorDelimiter, "factor-delimiter", "|");
m_parameter->SetParameter<size_t>(m_lmcache_cleanup_threshold, "clean-lm-cache", 1);
m_bookkeeping_options.init(*parameter);
if (!ini_output_options()) return false;
// threading etc.
if (!ini_performance_options()) return false;
// FEATURE FUNCTION INITIALIZATION HAPPENS HERE ===============================
// set class-specific default parameters
#if defined HAVE_CMPH
LexicalReorderingTableCompact::SetStaticDefaultParameters(*parameter);
PhraseDictionaryCompact::SetStaticDefaultParameters(*parameter);
#endif
initialize_features();
if (m_parameter->GetParam("show-weights") == NULL)
LoadFeatureFunctions();
LoadDecodeGraphs();
// sanity check that there are no weights without an associated FF
if (!CheckWeights()) return false;
//Load extra feature weights
string weightFile;
m_parameter->SetParameter<string>(weightFile, "weight-file", "");
if (!weightFile.empty()) {
ScoreComponentCollection extraWeights;
if (!extraWeights.Load(weightFile)) {
std::cerr << "Unable to load weights from " << weightFile;
return false;
}
m_allWeights.PlusEquals(extraWeights);
}
//Load sparse features from config (overrules weight file)
LoadSparseWeightsFromConfig();
// load alternate weight settings
//
// When and where are these used??? [UG]
//
// Update: Just checked the manual. The config file is NOT the right
// place to do this. [UG]
//
// <TODO>
// * Eliminate alternate-weight-setting. Alternate weight settings should
// be provided with the input, not in the config file.
// </TODO>
params = m_parameter->GetParam("alternate-weight-setting");
if (params && params->size() && !LoadAlternateWeightSettings())
return false;
return true;
}
void StaticData::SetWeight(const FeatureFunction* sp, float weight)
{
m_allWeights.Resize();
m_allWeights.Assign(sp,weight);
}
void StaticData::SetWeights(const FeatureFunction* sp,
const std::vector<float>& weights)
{
m_allWeights.Resize();
m_allWeights.Assign(sp,weights);
}
void StaticData::LoadNonTerminals()
{
string defaultNonTerminals;
m_parameter->SetParameter<string>(defaultNonTerminals, "non-terminals", "X");
FactorCollection &factorCollection = FactorCollection::Instance();
m_inputDefaultNonTerminal.SetIsNonTerminal(true);
const Factor *sourceFactor = factorCollection.AddFactor(Input, 0, defaultNonTerminals, true);
m_inputDefaultNonTerminal.SetFactor(0, sourceFactor);
m_outputDefaultNonTerminal.SetIsNonTerminal(true);
const Factor *targetFactor = factorCollection.AddFactor(Output, 0, defaultNonTerminals, true);
m_outputDefaultNonTerminal.SetFactor(0, targetFactor);
// for unknown words
const PARAM_VEC *params = m_parameter->GetParam("unknown-lhs");
if (params == NULL || params->size() == 0) {
UnknownLHSEntry entry(defaultNonTerminals, 0.0f);
m_unknownLHS.push_back(entry);
} else {
const string &filePath = params->at(0);
InputFileStream inStream(filePath);
string line;
while(getline(inStream, line)) {
vector<string> tokens = Tokenize(line);
UTIL_THROW_IF2(tokens.size() != 2,
"Incorrect unknown LHS format: " << line);
UnknownLHSEntry entry(tokens[0], Scan<float>(tokens[1]));
m_unknownLHS.push_back(entry);
// const Factor *targetFactor =
factorCollection.AddFactor(Output, 0, tokens[0], true);
}
}
}
void StaticData::LoadChartDecodingParameters()
{
LoadNonTerminals();
// source label overlap
m_parameter->SetParameter(m_sourceLabelOverlap, "source-label-overlap",
SourceLabelOverlapAdd);
}
void StaticData::LoadDecodeGraphs()
{
vector<string> mappingVector;
vector<size_t> maxChartSpans;
const PARAM_VEC *params;
params = m_parameter->GetParam("mapping");
if (params && params->size()) {
mappingVector = *params;
} else {
mappingVector.assign(1,"0 T 0");
}
params = m_parameter->GetParam("max-chart-span");
if (params && params->size()) {
maxChartSpans = Scan<size_t>(*params);
}
vector<string> toks = Tokenize(mappingVector[0]);
if (toks.size() == 3) {
// eg 0 T 0
LoadDecodeGraphsOld(mappingVector, maxChartSpans);
} else if (toks.size() == 2) {
if (toks[0] == "T" || toks[0] == "G") {
// eg. T 0
LoadDecodeGraphsOld(mappingVector, maxChartSpans);
} else {
// eg. 0 TM1
LoadDecodeGraphsNew(mappingVector, maxChartSpans);
}
} else {
UTIL_THROW(util::Exception, "Malformed mapping");
}
}
void
StaticData::
LoadDecodeGraphsOld(const vector<string> &mappingVector,
const vector<size_t> &maxChartSpans)
{
const vector<PhraseDictionary*>& pts = PhraseDictionary::GetColl();
const vector<GenerationDictionary*>& gens = GenerationDictionary::GetColl();
const std::vector<FeatureFunction*> *featuresRemaining
= &FeatureFunction::GetFeatureFunctions();
DecodeStep *prev = 0;
size_t prevDecodeGraphInd = 0;
for(size_t i=0; i<mappingVector.size(); i++) {
vector<string> token = Tokenize(mappingVector[i]);
size_t decodeGraphInd;
DecodeType decodeType;
size_t index;
if (token.size() == 2) {
// eg. T 0
decodeGraphInd = 0;
decodeType = token[0] == "T" ? Translate : Generate;
index = Scan<size_t>(token[1]);
} else if (token.size() == 3) {
// eg. 0 T 0
// For specifying multiple translation model
decodeGraphInd = Scan<size_t>(token[0]);
//the vectorList index can only increment by one
UTIL_THROW_IF2(decodeGraphInd != prevDecodeGraphInd
&& decodeGraphInd != prevDecodeGraphInd + 1,
"Malformed mapping");
if (decodeGraphInd > prevDecodeGraphInd) {
prev = NULL;
}
if (prevDecodeGraphInd < decodeGraphInd) {
featuresRemaining = &FeatureFunction::GetFeatureFunctions();
}
decodeType = token[1] == "T" ? Translate : Generate;
index = Scan<size_t>(token[2]);
} else {
UTIL_THROW(util::Exception, "Malformed mapping");
}
DecodeStep* decodeStep = NULL;
switch (decodeType) {
case Translate:
if(index>=pts.size()) {
util::StringStream strme;
strme << "No phrase dictionary with index "
<< index << " available!";
UTIL_THROW(util::Exception, strme.str());
}
decodeStep = new DecodeStepTranslation(pts[index], prev, *featuresRemaining);
break;
case Generate:
if(index>=gens.size()) {
util::StringStream strme;
strme << "No generation dictionary with index "
<< index << " available!";
UTIL_THROW(util::Exception, strme.str());
}
decodeStep = new DecodeStepGeneration(gens[index], prev, *featuresRemaining);
break;
default:
UTIL_THROW(util::Exception, "Unknown decode step");
break;
}
featuresRemaining = &decodeStep->GetFeaturesRemaining();
UTIL_THROW_IF2(decodeStep == NULL, "Null decode step");
if (m_decodeGraphs.size() < decodeGraphInd + 1) {
DecodeGraph *decodeGraph;
if (is_syntax(m_options->search.algo)) {
size_t maxChartSpan = (decodeGraphInd < maxChartSpans.size()) ? maxChartSpans[decodeGraphInd] : DEFAULT_MAX_CHART_SPAN;
VERBOSE(1,"max-chart-span: " << maxChartSpans[decodeGraphInd] << endl);
decodeGraph = new DecodeGraph(m_decodeGraphs.size(), maxChartSpan);
} else {
decodeGraph = new DecodeGraph(m_decodeGraphs.size());
}
m_decodeGraphs.push_back(decodeGraph); // TODO max chart span
}
m_decodeGraphs[decodeGraphInd]->Add(decodeStep);
prev = decodeStep;
prevDecodeGraphInd = decodeGraphInd;
}
// set maximum n-gram size for backoff approach to decoding paths
// default is always use subsequent paths (value = 0)
// if specified, record maxmimum unseen n-gram size
const vector<string> *backoffVector = m_parameter->GetParam("decoding-graph-backoff");
for(size_t i=0; i<m_decodeGraphs.size() && backoffVector && i<backoffVector->size(); i++) {
DecodeGraph &decodeGraph = *m_decodeGraphs[i];
if (i < backoffVector->size()) {
decodeGraph.SetBackoff(Scan<size_t>(backoffVector->at(i)));
}
}
}
void StaticData::LoadDecodeGraphsNew(const std::vector<std::string> &mappingVector, const std::vector<size_t> &maxChartSpans)
{
const std::vector<FeatureFunction*> *featuresRemaining = &FeatureFunction::GetFeatureFunctions();
DecodeStep *prev = 0;
size_t prevDecodeGraphInd = 0;
for(size_t i=0; i<mappingVector.size(); i++) {
vector<string> token = Tokenize(mappingVector[i]);
size_t decodeGraphInd;
decodeGraphInd = Scan<size_t>(token[0]);
//the vectorList index can only increment by one
UTIL_THROW_IF2(decodeGraphInd != prevDecodeGraphInd
&& decodeGraphInd != prevDecodeGraphInd + 1,
"Malformed mapping");
if (decodeGraphInd > prevDecodeGraphInd) {
prev = NULL;
}
if (prevDecodeGraphInd < decodeGraphInd) {
featuresRemaining = &FeatureFunction::GetFeatureFunctions();
}
FeatureFunction &ff = FeatureFunction::FindFeatureFunction(token[1]);
DecodeStep* decodeStep = NULL;
if (typeid(ff) == typeid(PhraseDictionary)) {
decodeStep = new DecodeStepTranslation(&static_cast<PhraseDictionary&>(ff), prev, *featuresRemaining);
} else if (typeid(ff) == typeid(GenerationDictionary)) {
decodeStep = new DecodeStepGeneration(&static_cast<GenerationDictionary&>(ff), prev, *featuresRemaining);
} else {
UTIL_THROW(util::Exception, "Unknown decode step");
}
featuresRemaining = &decodeStep->GetFeaturesRemaining();
UTIL_THROW_IF2(decodeStep == NULL, "Null decode step");
if (m_decodeGraphs.size() < decodeGraphInd + 1) {
DecodeGraph *decodeGraph;
if (is_syntax(m_options->search.algo)) {
size_t maxChartSpan = (decodeGraphInd < maxChartSpans.size()) ? maxChartSpans[decodeGraphInd] : DEFAULT_MAX_CHART_SPAN;
VERBOSE(1,"max-chart-span: " << maxChartSpans[decodeGraphInd] << endl);
decodeGraph = new DecodeGraph(m_decodeGraphs.size(), maxChartSpan);
} else {
decodeGraph = new DecodeGraph(m_decodeGraphs.size());
}
m_decodeGraphs.push_back(decodeGraph); // TODO max chart span
}
m_decodeGraphs[decodeGraphInd]->Add(decodeStep);
prev = decodeStep;
prevDecodeGraphInd = decodeGraphInd;
}
// set maximum n-gram size for backoff approach to decoding paths
// default is always use subsequent paths (value = 0)
// if specified, record maxmimum unseen n-gram size
const vector<string> *backoffVector = m_parameter->GetParam("decoding-graph-backoff");
for(size_t i=0; i<m_decodeGraphs.size() && backoffVector && i<backoffVector->size(); i++) {
DecodeGraph &decodeGraph = *m_decodeGraphs[i];
if (i < backoffVector->size()) {
decodeGraph.SetBackoff(Scan<size_t>(backoffVector->at(i)));
}
}
}
void StaticData::ReLoadBleuScoreFeatureParameter(float weight)
{
//loop over ScoreProducers to update weights of BleuScoreFeature
const std::vector<FeatureFunction*> &producers = FeatureFunction::GetFeatureFunctions();
for(size_t i=0; i<producers.size(); ++i) {
FeatureFunction *ff = producers[i];
std::string ffName = ff->GetScoreProducerDescription();
if (ffName == "BleuScoreFeature") {
SetWeight(ff, weight);
break;
}
}
}
// ScoreComponentCollection StaticData::GetAllWeightsScoreComponentCollection() const {}
// in ScoreComponentCollection.h
void StaticData::SetExecPath(const std::string &path)
{
// NOT TESTED
size_t pos = path.rfind("/");
if (pos != string::npos) {
m_binPath = path.substr(0, pos);
}
VERBOSE(1,m_binPath << endl);
}
const string &StaticData::GetBinDirectory() const
{
return m_binPath;
}
float StaticData::GetWeightWordPenalty() const
{
float weightWP = GetWeight(&WordPenaltyProducer::Instance());
return weightWP;
}
void
StaticData::
InitializeForInput(ttasksptr const& ttask) const
{
const std::vector<FeatureFunction*> &producers
= FeatureFunction::GetFeatureFunctions();
for(size_t i=0; i<producers.size(); ++i) {
FeatureFunction &ff = *producers[i];
if (! IsFeatureFunctionIgnored(ff)) {
Timer iTime;
iTime.start();
ff.InitializeForInput(ttask);
VERBOSE(3,"InitializeForInput( " << ff.GetScoreProducerDescription()
<< " )" << "= " << iTime << endl);
}
}
}
void
StaticData::
CleanUpAfterSentenceProcessing(ttasksptr const& ttask) const
{
const std::vector<FeatureFunction*> &producers
= FeatureFunction::GetFeatureFunctions();
for(size_t i=0; i<producers.size(); ++i) {
FeatureFunction &ff = *producers[i];
if (! IsFeatureFunctionIgnored(ff)) {
ff.CleanUpAfterSentenceProcessing(ttask);
}
}
}
void StaticData::LoadFeatureFunctions()
{
const std::vector<FeatureFunction*> &ffs = FeatureFunction::GetFeatureFunctions();
std::vector<FeatureFunction*>::const_iterator iter;
for (iter = ffs.begin(); iter != ffs.end(); ++iter) {
FeatureFunction *ff = *iter;
bool doLoad = true;
if (ff->RequireSortingAfterSourceContext()) {
m_requireSortingAfterSourceContext = true;
}
if (dynamic_cast<PhraseDictionary*>(ff)) {
doLoad = false;
}
if (doLoad) {
VERBOSE(1, "Loading " << ff->GetScoreProducerDescription() << endl);
ff->Load(options());
}
}
const std::vector<PhraseDictionary*> &pts = PhraseDictionary::GetColl();
for (size_t i = 0; i < pts.size(); ++i) {
PhraseDictionary *pt = pts[i];
VERBOSE(1, "Loading " << pt->GetScoreProducerDescription() << endl);
pt->Load(options());
}
CheckLEGACYPT();
}
bool StaticData::CheckWeights() const
{
set<string> weightNames = m_parameter->GetWeightNames();
set<string> featureNames;
const std::vector<FeatureFunction*> &ffs = FeatureFunction::GetFeatureFunctions();
for (size_t i = 0; i < ffs.size(); ++i) {
const FeatureFunction &ff = *ffs[i];
const string &descr = ff.GetScoreProducerDescription();
featureNames.insert(descr);
set<string>::iterator iter = weightNames.find(descr);
if (iter == weightNames.end()) {
cerr << "Can't find weights for feature function " << descr << endl;
} else {
weightNames.erase(iter);
}
}
//sparse features
if (!weightNames.empty()) {
set<string>::iterator iter;
for (iter = weightNames.begin(); iter != weightNames.end(); ) {
string fname = (*iter).substr(0, (*iter).find("_"));
VERBOSE(1,fname << "\n");
if (featureNames.find(fname) != featureNames.end()) {
weightNames.erase(iter++);
} else {
++iter;
}
}
}
if (!weightNames.empty()) {
cerr << "The following weights have no feature function. "
<< "Maybe incorrectly spelt weights: ";
set<string>::iterator iter;
for (iter = weightNames.begin(); iter != weightNames.end(); ++iter) {
cerr << *iter << ",";
}
return false;
}
return true;
}
void StaticData::LoadSparseWeightsFromConfig()
{
set<string> featureNames;
const std::vector<FeatureFunction*> &ffs = FeatureFunction::GetFeatureFunctions();
for (size_t i = 0; i < ffs.size(); ++i) {
const FeatureFunction &ff = *ffs[i];
const string &descr = ff.GetScoreProducerDescription();
featureNames.insert(descr);
}
std::map<std::string, std::vector<float> > weights = m_parameter->GetAllWeights();
std::map<std::string, std::vector<float> >::iterator iter;
for (iter = weights.begin(); iter != weights.end(); ++iter) {
// this indicates that it is sparse feature
if (featureNames.find(iter->first) == featureNames.end()) {
UTIL_THROW_IF2(iter->second.size() != 1, "ERROR: only one weight per sparse feature allowed: " << iter->first);
m_allWeights.Assign(iter->first, iter->second[0]);
}
}
}
/**! Read in settings for alternative weights */
bool StaticData::LoadAlternateWeightSettings()
{
if (m_threadCount > 1) {
cerr << "ERROR: alternative weight settings currently not supported with multi-threading.";
return false;
}
vector<string> weightSpecification;
const PARAM_VEC *params = m_parameter->GetParam("alternate-weight-setting");
if (params && params->size()) {
weightSpecification = *params;
}
// get mapping from feature names to feature functions
map<string,FeatureFunction*> nameToFF;
const std::vector<FeatureFunction*> &ffs = FeatureFunction::GetFeatureFunctions();
for (size_t i = 0; i < ffs.size(); ++i) {
nameToFF[ ffs[i]->GetScoreProducerDescription() ] = ffs[i];
}
// copy main weight setting as default
m_weightSetting["default"] = new ScoreComponentCollection( m_allWeights );
// go through specification in config file
string currentId = "";
bool hasErrors = false;
for (size_t i=0; i<weightSpecification.size(); ++i) {
// identifier line (with optional additional specifications)
if (weightSpecification[i].find("id=") == 0) {
vector<string> tokens = Tokenize(weightSpecification[i]);
vector<string> args = Tokenize(tokens[0], "=");
currentId = args[1];
VERBOSE(1,"alternate weight setting " << currentId << endl);
UTIL_THROW_IF2(m_weightSetting.find(currentId) != m_weightSetting.end(),
"Duplicate alternate weight id: " << currentId);
m_weightSetting[ currentId ] = new ScoreComponentCollection;
// other specifications
for(size_t j=1; j<tokens.size(); j++) {
vector<string> args = Tokenize(tokens[j], "=");
// sparse weights
if (args[0] == "weight-file") {
if (args.size() != 2) {
std::cerr << "One argument should be supplied for weight-file";
return false;
}
ScoreComponentCollection extraWeights;
if (!extraWeights.Load(args[1])) {
std::cerr << "Unable to load weights from " << args[1];
return false;
}
m_weightSetting[ currentId ]->PlusEquals(extraWeights);
}
// ignore feature functions
else if (args[0] == "ignore-ff") {
set< string > *ffNameSet = new set< string >;
m_weightSettingIgnoreFF[ currentId ] = *ffNameSet;
vector<string> featureFunctionName = Tokenize(args[1], ",");
for(size_t k=0; k<featureFunctionName.size(); k++) {
// check if a valid nane
map<string,FeatureFunction*>::iterator ffLookUp = nameToFF.find(featureFunctionName[k]);
if (ffLookUp == nameToFF.end()) {
cerr << "ERROR: alternate weight setting " << currentId
<< " specifies to ignore feature function " << featureFunctionName[k]
<< " but there is no such feature function" << endl;
hasErrors = true;
} else {
m_weightSettingIgnoreFF[ currentId ].insert( featureFunctionName[k] );
}
}
}
}
}
// weight lines
else {
UTIL_THROW_IF2(currentId.empty(), "No alternative weights specified");
vector<string> tokens = Tokenize(weightSpecification[i]);
UTIL_THROW_IF2(tokens.size() < 2
, "Incorrect format for alternate weights: " << weightSpecification[i]);
// get name and weight values
string name = tokens[0];
name = name.substr(0, name.size() - 1); // remove trailing "="
vector<float> weights(tokens.size() - 1);
for (size_t i = 1; i < tokens.size(); ++i) {
float weight = Scan<float>(tokens[i]);
weights[i - 1] = weight;
}
// check if a valid nane
map<string,FeatureFunction*>::iterator ffLookUp = nameToFF.find(name);
if (ffLookUp == nameToFF.end()) {
cerr << "ERROR: alternate weight setting " << currentId
<< " specifies weight(s) for " << name
<< " but there is no such feature function" << endl;
hasErrors = true;
} else {
m_weightSetting[ currentId ]->Assign( nameToFF[name], weights);
}
}
}
UTIL_THROW_IF2(hasErrors, "Errors loading alternate weights");
return true;
}
void StaticData::NoCache()
{
bool noCache;
m_parameter->SetParameter(noCache, "no-cache", false );
if (noCache) {
const std::vector<PhraseDictionary*> &pts = PhraseDictionary::GetColl();
for (size_t i = 0; i < pts.size(); ++i) {
PhraseDictionary &pt = *pts[i];
pt.SetParameter("cache-size", "0");
}
}
}
std::map<std::string, std::string>
StaticData
::OverrideFeatureNames()
{
std::map<std::string, std::string> ret;
const PARAM_VEC *params = m_parameter->GetParam("feature-name-overwrite");
if (params && params->size()) {
UTIL_THROW_IF2(params->size() != 1, "Only provide 1 line in the section [feature-name-overwrite]");
vector<string> toks = Tokenize(params->at(0));
UTIL_THROW_IF2(toks.size() % 2 != 0, "Format of -feature-name-overwrite must be [old-name new-name]*");
for (size_t i = 0; i < toks.size(); i += 2) {
const string &oldName = toks[i];
const string &newName = toks[i+1];
ret[oldName] = newName;
}
}
// FIXME Does this make sense for F2S? Perhaps it should be changed once
// FIXME the pipeline uses RuleTable consistently.
SearchAlgorithm algo = m_options->search.algo;
if (algo == SyntaxS2T || algo == SyntaxT2S ||
algo == SyntaxT2S_SCFG || algo == SyntaxF2S) {
// Automatically override PhraseDictionary{Memory,Scope3}. This will
// have to change if the FF parameters diverge too much in the future,
// but for now it makes switching between the old and new decoders much
// more convenient.
ret["PhraseDictionaryMemory"] = "RuleTable";
ret["PhraseDictionaryScope3"] = "RuleTable";
}
return ret;
}
void StaticData::OverrideFeatures()
{
const PARAM_VEC *params = m_parameter->GetParam("feature-overwrite");
for (size_t i = 0; params && i < params->size(); ++i) {
const string &str = params->at(i);
vector<string> toks = Tokenize(str);
UTIL_THROW_IF2(toks.size() <= 1, "Incorrect format for feature override: " << str);
FeatureFunction &ff = FeatureFunction::FindFeatureFunction(toks[0]);
for (size_t j = 1; j < toks.size(); ++j) {
const string &keyValStr = toks[j];
vector<string> keyVal = Tokenize(keyValStr, "=");
UTIL_THROW_IF2(keyVal.size() != 2, "Incorrect format for parameter override: " << keyValStr);
VERBOSE(1, "Override " << ff.GetScoreProducerDescription() << " "
<< keyVal[0] << "=" << keyVal[1] << endl);
ff.SetParameter(keyVal[0], keyVal[1]);
}
}
}
void StaticData::CheckLEGACYPT()
{
const std::vector<PhraseDictionary*> &pts = PhraseDictionary::GetColl();
for (size_t i = 0; i < pts.size(); ++i) {
const PhraseDictionary *phraseDictionary = pts[i];
if (dynamic_cast<const PhraseDictionaryTreeAdaptor*>(phraseDictionary) != NULL) {
m_useLegacyPT = true;
return;
}
}
m_useLegacyPT = false;
}
void StaticData::ResetWeights(const std::string &denseWeights, const std::string &sparseFile)
{
m_allWeights = ScoreComponentCollection();
// dense weights
string name("");
vector<float> weights;
vector<string> toks = Tokenize(denseWeights);
for (size_t i = 0; i < toks.size(); ++i) {
const string &tok = toks[i];
if (ends_with(tok, "=")) {
// start of new feature
if (name != "") {
// save previous ff
const FeatureFunction &ff = FeatureFunction::FindFeatureFunction(name);
m_allWeights.Assign(&ff, weights);
weights.clear();
}
name = tok.substr(0, tok.size() - 1);
} else {
// a weight for curr ff
float weight = Scan<float>(toks[i]);
weights.push_back(weight);
}
}
const FeatureFunction &ff = FeatureFunction::FindFeatureFunction(name);
m_allWeights.Assign(&ff, weights);
// sparse weights
InputFileStream sparseStrme(sparseFile);
string line;
while (getline(sparseStrme, line)) {
vector<string> toks = Tokenize(line);
UTIL_THROW_IF2(toks.size() != 2, "Incorrect sparse weight format. Should be FFName_spareseName weight");
vector<string> names = Tokenize(toks[0], "_");
UTIL_THROW_IF2(names.size() != 2, "Incorrect sparse weight name. Should be FFName_spareseName");
const FeatureFunction &ff = FeatureFunction::FindFeatureFunction(names[0]);
m_allWeights.Assign(&ff, names[1], Scan<float>(toks[1]));
}
}
size_t StaticData::GetCoordSpace(string space) const
{
map<string, size_t>::const_iterator m = m_coordSpaceMap.find(space);
if(m == m_coordSpaceMap.end()) {
return 0;
}
return m->second;
}
size_t StaticData::MapCoordSpace(string space)
{
map<string, size_t>::const_iterator m = m_coordSpaceMap.find(space);
if (m != m_coordSpaceMap.end()) {
return m->second;
}
size_t id = m_coordSpaceNextID;
m_coordSpaceNextID += 1;
m_coordSpaceMap[space] = id;
return id;
}
} // namespace
clang compile error
// -*- mode: c++; indent-tabs-mode: nil; tab-width: 2 -*-
// $Id$
// vim:tabstop=2
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include <string>
#include <boost/algorithm/string/predicate.hpp>
#include "moses/FF/Factory.h"
#include "TypeDef.h"
#include "moses/FF/WordPenaltyProducer.h"
#include "moses/FF/UnknownWordPenaltyProducer.h"
#include "moses/FF/InputFeature.h"
#include "moses/FF/DynamicCacheBasedLanguageModel.h"
#include "moses/TranslationModel/PhraseDictionaryDynamicCacheBased.h"
#include "DecodeStepTranslation.h"
#include "DecodeStepGeneration.h"
#include "GenerationDictionary.h"
#include "StaticData.h"
#include "Util.h"
#include "FactorCollection.h"
#include "Timer.h"
#include "TranslationOption.h"
#include "DecodeGraph.h"
#include "InputFileStream.h"
#include "ScoreComponentCollection.h"
#include "DecodeGraph.h"
#include "TranslationModel/PhraseDictionary.h"
#include "TranslationModel/PhraseDictionaryTreeAdaptor.h"
#ifdef WITH_THREADS
#include <boost/thread.hpp>
#endif
#ifdef HAVE_CMPH
#include "moses/TranslationModel/CompactPT/PhraseDictionaryCompact.h"
#endif
#if defined HAVE_CMPH
#include "moses/TranslationModel/CompactPT/LexicalReorderingTableCompact.h"
#endif
using namespace std;
using namespace boost::algorithm;
namespace Moses
{
StaticData StaticData::s_instance;
StaticData::StaticData()
: m_options(new AllOptions)
, m_requireSortingAfterSourceContext(false)
, m_currentWeightSetting("default")
, m_treeStructure(NULL)
, m_coordSpaceNextID(1)
{
Phrase::InitializeMemPool();
}
StaticData::~StaticData()
{
RemoveAllInColl(m_decodeGraphs);
Phrase::FinalizeMemPool();
}
bool StaticData::LoadDataStatic(Parameter *parameter, const std::string &execPath)
{
s_instance.SetExecPath(execPath);
return s_instance.LoadData(parameter);
}
void
StaticData
::initialize_features()
{
std::map<std::string, std::string> featureNameOverride = OverrideFeatureNames();
// all features
map<string, int> featureIndexMap;
const PARAM_VEC* params = m_parameter->GetParam("feature");
for (size_t i = 0; params && i < params->size(); ++i) {
const string &line = Trim(params->at(i));
VERBOSE(1,"line=" << line << endl);
if (line.empty())
continue;
vector<string> toks = Tokenize(line);
string &feature = toks[0];
std::map<std::string, std::string>::const_iterator iter
= featureNameOverride.find(feature);
if (iter == featureNameOverride.end()) {
// feature name not override
m_registry.Construct(feature, line);
} else {
// replace feature name with new name
string newName = iter->second;
feature = newName;
string newLine = Join(" ", toks);
m_registry.Construct(newName, newLine);
}
}
NoCache();
OverrideFeatures();
}
bool
StaticData
::ini_output_options()
{
// verbose level
m_parameter->SetParameter(m_verboseLevel, "verbose", (size_t) 1);
m_parameter->SetParameter<string>(m_outputUnknownsFile,
"output-unknowns", "");
return true;
}
// threads, timeouts, etc.
bool
StaticData
::ini_performance_options()
{
const PARAM_VEC *params;
m_threadCount = 1;
params = m_parameter->GetParam("threads");
if (params && params->size()) {
if (params->at(0) == "all") {
#ifdef WITH_THREADS
m_threadCount = boost::thread::hardware_concurrency();
if (!m_threadCount) {
std::cerr << "-threads all specified but Boost doesn't know how many cores there are";
return false;
}
#else
std::cerr << "-threads all specified but moses not built with thread support";
return false;
#endif
} else {
m_threadCount = Scan<int>(params->at(0));
if (m_threadCount < 1) {
std::cerr << "Specify at least one thread.";
return false;
}
#ifndef WITH_THREADS
if (m_threadCount > 1) {
std::cerr << "Error: Thread count of " << params->at(0)
<< " but moses not built with thread support";
return false;
}
#endif
}
}
return true;
}
bool StaticData::LoadData(Parameter *parameter)
{
m_parameter = parameter;
const PARAM_VEC *params;
m_options->init(*parameter);
if (is_syntax(m_options->search.algo))
m_options->syntax.LoadNonTerminals(*parameter, FactorCollection::Instance());
if (is_syntax(m_options->search.algo))
LoadChartDecodingParameters();
// ORDER HERE MATTERS, SO DON'T CHANGE IT UNLESS YOU KNOW WHAT YOU ARE DOING!
// input, output
m_parameter->SetParameter<string>(m_factorDelimiter, "factor-delimiter", "|");
m_parameter->SetParameter<size_t>(m_lmcache_cleanup_threshold, "clean-lm-cache", 1);
m_bookkeeping_options.init(*parameter);
if (!ini_output_options()) return false;
// threading etc.
if (!ini_performance_options()) return false;
// FEATURE FUNCTION INITIALIZATION HAPPENS HERE ===============================
// set class-specific default parameters
#if defined HAVE_CMPH
LexicalReorderingTableCompact::SetStaticDefaultParameters(*parameter);
PhraseDictionaryCompact::SetStaticDefaultParameters(*parameter);
#endif
initialize_features();
if (m_parameter->GetParam("show-weights") == NULL)
LoadFeatureFunctions();
LoadDecodeGraphs();
// sanity check that there are no weights without an associated FF
if (!CheckWeights()) return false;
//Load extra feature weights
string weightFile;
m_parameter->SetParameter<string>(weightFile, "weight-file", "");
if (!weightFile.empty()) {
ScoreComponentCollection extraWeights;
if (!extraWeights.Load(weightFile)) {
std::cerr << "Unable to load weights from " << weightFile;
return false;
}
m_allWeights.PlusEquals(extraWeights);
}
//Load sparse features from config (overrules weight file)
LoadSparseWeightsFromConfig();
// load alternate weight settings
//
// When and where are these used??? [UG]
//
// Update: Just checked the manual. The config file is NOT the right
// place to do this. [UG]
//
// <TODO>
// * Eliminate alternate-weight-setting. Alternate weight settings should
// be provided with the input, not in the config file.
// </TODO>
params = m_parameter->GetParam("alternate-weight-setting");
if (params && params->size() && !LoadAlternateWeightSettings())
return false;
return true;
}
void StaticData::SetWeight(const FeatureFunction* sp, float weight)
{
m_allWeights.Resize();
m_allWeights.Assign(sp,weight);
}
void StaticData::SetWeights(const FeatureFunction* sp,
const std::vector<float>& weights)
{
m_allWeights.Resize();
m_allWeights.Assign(sp,weights);
}
void StaticData::LoadNonTerminals()
{
string defaultNonTerminals;
m_parameter->SetParameter<string>(defaultNonTerminals, "non-terminals", "X");
FactorCollection &factorCollection = FactorCollection::Instance();
m_inputDefaultNonTerminal.SetIsNonTerminal(true);
const Factor *sourceFactor = factorCollection.AddFactor(Input, 0, defaultNonTerminals, true);
m_inputDefaultNonTerminal.SetFactor(0, sourceFactor);
m_outputDefaultNonTerminal.SetIsNonTerminal(true);
const Factor *targetFactor = factorCollection.AddFactor(Output, 0, defaultNonTerminals, true);
m_outputDefaultNonTerminal.SetFactor(0, targetFactor);
// for unknown words
const PARAM_VEC *params = m_parameter->GetParam("unknown-lhs");
if (params == NULL || params->size() == 0) {
UnknownLHSEntry entry(defaultNonTerminals, 0.0f);
m_unknownLHS.push_back(entry);
} else {
const string &filePath = params->at(0);
InputFileStream inStream(filePath);
string line;
while(getline(inStream, line)) {
vector<string> tokens = Tokenize(line);
UTIL_THROW_IF2(tokens.size() != 2,
"Incorrect unknown LHS format: " << line);
UnknownLHSEntry entry(tokens[0], Scan<float>(tokens[1]));
m_unknownLHS.push_back(entry);
// const Factor *targetFactor =
factorCollection.AddFactor(Output, 0, tokens[0], true);
}
}
}
void StaticData::LoadChartDecodingParameters()
{
LoadNonTerminals();
// source label overlap
m_parameter->SetParameter(m_sourceLabelOverlap, "source-label-overlap",
SourceLabelOverlapAdd);
}
void StaticData::LoadDecodeGraphs()
{
vector<string> mappingVector;
vector<size_t> maxChartSpans;
const PARAM_VEC *params;
params = m_parameter->GetParam("mapping");
if (params && params->size()) {
mappingVector = *params;
} else {
mappingVector.assign(1,"0 T 0");
}
params = m_parameter->GetParam("max-chart-span");
if (params && params->size()) {
maxChartSpans = Scan<size_t>(*params);
}
vector<string> toks = Tokenize(mappingVector[0]);
if (toks.size() == 3) {
// eg 0 T 0
LoadDecodeGraphsOld(mappingVector, maxChartSpans);
} else if (toks.size() == 2) {
if (toks[0] == "T" || toks[0] == "G") {
// eg. T 0
LoadDecodeGraphsOld(mappingVector, maxChartSpans);
} else {
// eg. 0 TM1
LoadDecodeGraphsNew(mappingVector, maxChartSpans);
}
} else {
UTIL_THROW(util::Exception, "Malformed mapping");
}
}
void
StaticData::
LoadDecodeGraphsOld(const vector<string> &mappingVector,
const vector<size_t> &maxChartSpans)
{
const vector<PhraseDictionary*>& pts = PhraseDictionary::GetColl();
const vector<GenerationDictionary*>& gens = GenerationDictionary::GetColl();
const std::vector<FeatureFunction*> *featuresRemaining
= &FeatureFunction::GetFeatureFunctions();
DecodeStep *prev = 0;
size_t prevDecodeGraphInd = 0;
for(size_t i=0; i<mappingVector.size(); i++) {
vector<string> token = Tokenize(mappingVector[i]);
size_t decodeGraphInd;
DecodeType decodeType;
size_t index;
if (token.size() == 2) {
// eg. T 0
decodeGraphInd = 0;
decodeType = token[0] == "T" ? Translate : Generate;
index = Scan<size_t>(token[1]);
} else if (token.size() == 3) {
// eg. 0 T 0
// For specifying multiple translation model
decodeGraphInd = Scan<size_t>(token[0]);
//the vectorList index can only increment by one
UTIL_THROW_IF2(decodeGraphInd != prevDecodeGraphInd
&& decodeGraphInd != prevDecodeGraphInd + 1,
"Malformed mapping");
if (decodeGraphInd > prevDecodeGraphInd) {
prev = NULL;
}
if (prevDecodeGraphInd < decodeGraphInd) {
featuresRemaining = &FeatureFunction::GetFeatureFunctions();
}
decodeType = token[1] == "T" ? Translate : Generate;
index = Scan<size_t>(token[2]);
} else {
UTIL_THROW(util::Exception, "Malformed mapping");
}
DecodeStep* decodeStep = NULL;
switch (decodeType) {
case Translate:
if(index>=pts.size()) {
util::StringStream strme;
strme << "No phrase dictionary with index "
<< index << " available!";
UTIL_THROW(util::Exception, strme.str());
}
decodeStep = new DecodeStepTranslation(pts[index], prev, *featuresRemaining);
break;
case Generate:
if(index>=gens.size()) {
util::StringStream strme;
strme << "No generation dictionary with index "
<< index << " available!";
UTIL_THROW(util::Exception, strme.str());
}
decodeStep = new DecodeStepGeneration(gens[index], prev, *featuresRemaining);
break;
default:
UTIL_THROW(util::Exception, "Unknown decode step");
break;
}
featuresRemaining = &decodeStep->GetFeaturesRemaining();
UTIL_THROW_IF2(decodeStep == NULL, "Null decode step");
if (m_decodeGraphs.size() < decodeGraphInd + 1) {
DecodeGraph *decodeGraph;
if (is_syntax(m_options->search.algo)) {
size_t maxChartSpan = (decodeGraphInd < maxChartSpans.size()) ? maxChartSpans[decodeGraphInd] : DEFAULT_MAX_CHART_SPAN;
VERBOSE(1,"max-chart-span: " << maxChartSpans[decodeGraphInd] << endl);
decodeGraph = new DecodeGraph(m_decodeGraphs.size(), maxChartSpan);
} else {
decodeGraph = new DecodeGraph(m_decodeGraphs.size());
}
m_decodeGraphs.push_back(decodeGraph); // TODO max chart span
}
m_decodeGraphs[decodeGraphInd]->Add(decodeStep);
prev = decodeStep;
prevDecodeGraphInd = decodeGraphInd;
}
// set maximum n-gram size for backoff approach to decoding paths
// default is always use subsequent paths (value = 0)
// if specified, record maxmimum unseen n-gram size
const vector<string> *backoffVector = m_parameter->GetParam("decoding-graph-backoff");
for(size_t i=0; i<m_decodeGraphs.size() && backoffVector && i<backoffVector->size(); i++) {
DecodeGraph &decodeGraph = *m_decodeGraphs[i];
if (i < backoffVector->size()) {
decodeGraph.SetBackoff(Scan<size_t>(backoffVector->at(i)));
}
}
}
void StaticData::LoadDecodeGraphsNew(const std::vector<std::string> &mappingVector, const std::vector<size_t> &maxChartSpans)
{
const std::vector<FeatureFunction*> *featuresRemaining = &FeatureFunction::GetFeatureFunctions();
DecodeStep *prev = 0;
size_t prevDecodeGraphInd = 0;
for(size_t i=0; i<mappingVector.size(); i++) {
vector<string> token = Tokenize(mappingVector[i]);
size_t decodeGraphInd;
decodeGraphInd = Scan<size_t>(token[0]);
//the vectorList index can only increment by one
UTIL_THROW_IF2(decodeGraphInd != prevDecodeGraphInd
&& decodeGraphInd != prevDecodeGraphInd + 1,
"Malformed mapping");
if (decodeGraphInd > prevDecodeGraphInd) {
prev = NULL;
}
if (prevDecodeGraphInd < decodeGraphInd) {
featuresRemaining = &FeatureFunction::GetFeatureFunctions();
}
FeatureFunction &ff = FeatureFunction::FindFeatureFunction(token[1]);
DecodeStep* decodeStep = NULL;
if (typeid(ff) == typeid(PhraseDictionary)) {
decodeStep = new DecodeStepTranslation(&static_cast<PhraseDictionary&>(ff), prev, *featuresRemaining);
} else if (typeid(ff) == typeid(GenerationDictionary)) {
decodeStep = new DecodeStepGeneration(&static_cast<GenerationDictionary&>(ff), prev, *featuresRemaining);
} else {
UTIL_THROW(util::Exception, "Unknown decode step");
}
featuresRemaining = &decodeStep->GetFeaturesRemaining();
UTIL_THROW_IF2(decodeStep == NULL, "Null decode step");
if (m_decodeGraphs.size() < decodeGraphInd + 1) {
DecodeGraph *decodeGraph;
if (is_syntax(m_options->search.algo)) {
size_t maxChartSpan = (decodeGraphInd < maxChartSpans.size()) ? maxChartSpans[decodeGraphInd] : DEFAULT_MAX_CHART_SPAN;
VERBOSE(1,"max-chart-span: " << maxChartSpans[decodeGraphInd] << endl);
decodeGraph = new DecodeGraph(m_decodeGraphs.size(), maxChartSpan);
} else {
decodeGraph = new DecodeGraph(m_decodeGraphs.size());
}
m_decodeGraphs.push_back(decodeGraph); // TODO max chart span
}
m_decodeGraphs[decodeGraphInd]->Add(decodeStep);
prev = decodeStep;
prevDecodeGraphInd = decodeGraphInd;
}
// set maximum n-gram size for backoff approach to decoding paths
// default is always use subsequent paths (value = 0)
// if specified, record maxmimum unseen n-gram size
const vector<string> *backoffVector = m_parameter->GetParam("decoding-graph-backoff");
for(size_t i=0; i<m_decodeGraphs.size() && backoffVector && i<backoffVector->size(); i++) {
DecodeGraph &decodeGraph = *m_decodeGraphs[i];
if (i < backoffVector->size()) {
decodeGraph.SetBackoff(Scan<size_t>(backoffVector->at(i)));
}
}
}
void StaticData::ReLoadBleuScoreFeatureParameter(float weight)
{
//loop over ScoreProducers to update weights of BleuScoreFeature
const std::vector<FeatureFunction*> &producers = FeatureFunction::GetFeatureFunctions();
for(size_t i=0; i<producers.size(); ++i) {
FeatureFunction *ff = producers[i];
std::string ffName = ff->GetScoreProducerDescription();
if (ffName == "BleuScoreFeature") {
SetWeight(ff, weight);
break;
}
}
}
// ScoreComponentCollection StaticData::GetAllWeightsScoreComponentCollection() const {}
// in ScoreComponentCollection.h
void StaticData::SetExecPath(const std::string &path)
{
// NOT TESTED
size_t pos = path.rfind("/");
if (pos != string::npos) {
m_binPath = path.substr(0, pos);
}
VERBOSE(1,m_binPath << endl);
}
const string &StaticData::GetBinDirectory() const
{
return m_binPath;
}
float StaticData::GetWeightWordPenalty() const
{
float weightWP = GetWeight(&WordPenaltyProducer::Instance());
return weightWP;
}
void
StaticData::
InitializeForInput(ttasksptr const& ttask) const
{
const std::vector<FeatureFunction*> &producers
= FeatureFunction::GetFeatureFunctions();
for(size_t i=0; i<producers.size(); ++i) {
FeatureFunction &ff = *producers[i];
if (! IsFeatureFunctionIgnored(ff)) {
Timer iTime;
iTime.start();
ff.InitializeForInput(ttask);
VERBOSE(3,"InitializeForInput( " << ff.GetScoreProducerDescription()
<< " )" << "= " << iTime << endl);
}
}
}
void
StaticData::
CleanUpAfterSentenceProcessing(ttasksptr const& ttask) const
{
const std::vector<FeatureFunction*> &producers
= FeatureFunction::GetFeatureFunctions();
for(size_t i=0; i<producers.size(); ++i) {
FeatureFunction &ff = *producers[i];
if (! IsFeatureFunctionIgnored(ff)) {
ff.CleanUpAfterSentenceProcessing(ttask);
}
}
}
void StaticData::LoadFeatureFunctions()
{
const std::vector<FeatureFunction*> &ffs = FeatureFunction::GetFeatureFunctions();
std::vector<FeatureFunction*>::const_iterator iter;
for (iter = ffs.begin(); iter != ffs.end(); ++iter) {
FeatureFunction *ff = *iter;
bool doLoad = true;
if (ff->RequireSortingAfterSourceContext()) {
m_requireSortingAfterSourceContext = true;
}
if (dynamic_cast<PhraseDictionary*>(ff)) {
doLoad = false;
}
if (doLoad) {
VERBOSE(1, "Loading " << ff->GetScoreProducerDescription() << endl);
ff->Load(options());
}
}
const std::vector<PhraseDictionary*> &pts = PhraseDictionary::GetColl();
for (size_t i = 0; i < pts.size(); ++i) {
PhraseDictionary *pt = pts[i];
VERBOSE(1, "Loading " << pt->GetScoreProducerDescription() << endl);
pt->Load(options());
}
CheckLEGACYPT();
}
bool StaticData::CheckWeights() const
{
set<string> weightNames = m_parameter->GetWeightNames();
set<string> featureNames;
const std::vector<FeatureFunction*> &ffs = FeatureFunction::GetFeatureFunctions();
for (size_t i = 0; i < ffs.size(); ++i) {
const FeatureFunction &ff = *ffs[i];
const string &descr = ff.GetScoreProducerDescription();
featureNames.insert(descr);
set<string>::iterator iter = weightNames.find(descr);
if (iter == weightNames.end()) {
cerr << "Can't find weights for feature function " << descr << endl;
} else {
weightNames.erase(iter);
}
}
//sparse features
if (!weightNames.empty()) {
set<string>::iterator iter;
for (iter = weightNames.begin(); iter != weightNames.end(); ) {
string fname = (*iter).substr(0, (*iter).find("_"));
VERBOSE(1,fname << "\n");
if (featureNames.find(fname) != featureNames.end()) {
weightNames.erase(iter++);
} else {
++iter;
}
}
}
if (!weightNames.empty()) {
cerr << "The following weights have no feature function. "
<< "Maybe incorrectly spelt weights: ";
set<string>::iterator iter;
for (iter = weightNames.begin(); iter != weightNames.end(); ++iter) {
cerr << *iter << ",";
}
return false;
}
return true;
}
void StaticData::LoadSparseWeightsFromConfig()
{
set<string> featureNames;
const std::vector<FeatureFunction*> &ffs = FeatureFunction::GetFeatureFunctions();
for (size_t i = 0; i < ffs.size(); ++i) {
const FeatureFunction &ff = *ffs[i];
const string &descr = ff.GetScoreProducerDescription();
featureNames.insert(descr);
}
std::map<std::string, std::vector<float> > weights = m_parameter->GetAllWeights();
std::map<std::string, std::vector<float> >::iterator iter;
for (iter = weights.begin(); iter != weights.end(); ++iter) {
// this indicates that it is sparse feature
if (featureNames.find(iter->first) == featureNames.end()) {
UTIL_THROW_IF2(iter->second.size() != 1, "ERROR: only one weight per sparse feature allowed: " << iter->first);
m_allWeights.Assign(iter->first, iter->second[0]);
}
}
}
/**! Read in settings for alternative weights */
bool StaticData::LoadAlternateWeightSettings()
{
if (m_threadCount > 1) {
cerr << "ERROR: alternative weight settings currently not supported with multi-threading.";
return false;
}
vector<string> weightSpecification;
const PARAM_VEC *params = m_parameter->GetParam("alternate-weight-setting");
if (params && params->size()) {
weightSpecification = *params;
}
// get mapping from feature names to feature functions
map<string,FeatureFunction*> nameToFF;
const std::vector<FeatureFunction*> &ffs = FeatureFunction::GetFeatureFunctions();
for (size_t i = 0; i < ffs.size(); ++i) {
nameToFF[ ffs[i]->GetScoreProducerDescription() ] = ffs[i];
}
// copy main weight setting as default
m_weightSetting["default"] = new ScoreComponentCollection( m_allWeights );
// go through specification in config file
string currentId = "";
bool hasErrors = false;
for (size_t i=0; i<weightSpecification.size(); ++i) {
// identifier line (with optional additional specifications)
if (weightSpecification[i].find("id=") == 0) {
vector<string> tokens = Tokenize(weightSpecification[i]);
vector<string> args = Tokenize(tokens[0], "=");
currentId = args[1];
VERBOSE(1,"alternate weight setting " << currentId << endl);
UTIL_THROW_IF2(m_weightSetting.find(currentId) != m_weightSetting.end(),
"Duplicate alternate weight id: " << currentId);
m_weightSetting[ currentId ] = new ScoreComponentCollection;
// other specifications
for(size_t j=1; j<tokens.size(); j++) {
vector<string> args = Tokenize(tokens[j], "=");
// sparse weights
if (args[0] == "weight-file") {
if (args.size() != 2) {
std::cerr << "One argument should be supplied for weight-file";
return false;
}
ScoreComponentCollection extraWeights;
if (!extraWeights.Load(args[1])) {
std::cerr << "Unable to load weights from " << args[1];
return false;
}
m_weightSetting[ currentId ]->PlusEquals(extraWeights);
}
// ignore feature functions
else if (args[0] == "ignore-ff") {
set< string > *ffNameSet = new set< string >;
m_weightSettingIgnoreFF[ currentId ] = *ffNameSet;
vector<string> featureFunctionName = Tokenize(args[1], ",");
for(size_t k=0; k<featureFunctionName.size(); k++) {
// check if a valid nane
map<string,FeatureFunction*>::iterator ffLookUp = nameToFF.find(featureFunctionName[k]);
if (ffLookUp == nameToFF.end()) {
cerr << "ERROR: alternate weight setting " << currentId
<< " specifies to ignore feature function " << featureFunctionName[k]
<< " but there is no such feature function" << endl;
hasErrors = true;
} else {
m_weightSettingIgnoreFF[ currentId ].insert( featureFunctionName[k] );
}
}
}
}
}
// weight lines
else {
UTIL_THROW_IF2(currentId.empty(), "No alternative weights specified");
vector<string> tokens = Tokenize(weightSpecification[i]);
UTIL_THROW_IF2(tokens.size() < 2
, "Incorrect format for alternate weights: " << weightSpecification[i]);
// get name and weight values
string name = tokens[0];
name = name.substr(0, name.size() - 1); // remove trailing "="
vector<float> weights(tokens.size() - 1);
for (size_t i = 1; i < tokens.size(); ++i) {
float weight = Scan<float>(tokens[i]);
weights[i - 1] = weight;
}
// check if a valid nane
map<string,FeatureFunction*>::iterator ffLookUp = nameToFF.find(name);
if (ffLookUp == nameToFF.end()) {
cerr << "ERROR: alternate weight setting " << currentId
<< " specifies weight(s) for " << name
<< " but there is no such feature function" << endl;
hasErrors = true;
} else {
m_weightSetting[ currentId ]->Assign( nameToFF[name], weights);
}
}
}
UTIL_THROW_IF2(hasErrors, "Errors loading alternate weights");
return true;
}
void StaticData::NoCache()
{
bool noCache;
m_parameter->SetParameter(noCache, "no-cache", false );
if (noCache) {
const std::vector<PhraseDictionary*> &pts = PhraseDictionary::GetColl();
for (size_t i = 0; i < pts.size(); ++i) {
PhraseDictionary &pt = *pts[i];
pt.SetParameter("cache-size", "0");
}
}
}
std::map<std::string, std::string>
StaticData
::OverrideFeatureNames()
{
std::map<std::string, std::string> ret;
const PARAM_VEC *params = m_parameter->GetParam("feature-name-overwrite");
if (params && params->size()) {
UTIL_THROW_IF2(params->size() != 1, "Only provide 1 line in the section [feature-name-overwrite]");
vector<string> toks = Tokenize(params->at(0));
UTIL_THROW_IF2(toks.size() % 2 != 0, "Format of -feature-name-overwrite must be [old-name new-name]*");
for (size_t i = 0; i < toks.size(); i += 2) {
const string &oldName = toks[i];
const string &newName = toks[i+1];
ret[oldName] = newName;
}
}
// FIXME Does this make sense for F2S? Perhaps it should be changed once
// FIXME the pipeline uses RuleTable consistently.
SearchAlgorithm algo = m_options->search.algo;
if (algo == SyntaxS2T || algo == SyntaxT2S ||
algo == SyntaxT2S_SCFG || algo == SyntaxF2S) {
// Automatically override PhraseDictionary{Memory,Scope3}. This will
// have to change if the FF parameters diverge too much in the future,
// but for now it makes switching between the old and new decoders much
// more convenient.
ret["PhraseDictionaryMemory"] = "RuleTable";
ret["PhraseDictionaryScope3"] = "RuleTable";
}
return ret;
}
void StaticData::OverrideFeatures()
{
const PARAM_VEC *params = m_parameter->GetParam("feature-overwrite");
for (size_t i = 0; params && i < params->size(); ++i) {
const string &str = params->at(i);
vector<string> toks = Tokenize(str);
UTIL_THROW_IF2(toks.size() <= 1, "Incorrect format for feature override: " << str);
FeatureFunction &ff = FeatureFunction::FindFeatureFunction(toks[0]);
for (size_t j = 1; j < toks.size(); ++j) {
const string &keyValStr = toks[j];
vector<string> keyVal = Tokenize(keyValStr, "=");
UTIL_THROW_IF2(keyVal.size() != 2, "Incorrect format for parameter override: " << keyValStr);
VERBOSE(1, "Override " << ff.GetScoreProducerDescription() << " "
<< keyVal[0] << "=" << keyVal[1] << endl);
ff.SetParameter(keyVal[0], keyVal[1]);
}
}
}
void StaticData::CheckLEGACYPT()
{
const std::vector<PhraseDictionary*> &pts = PhraseDictionary::GetColl();
for (size_t i = 0; i < pts.size(); ++i) {
const PhraseDictionary *phraseDictionary = pts[i];
if (dynamic_cast<const PhraseDictionaryTreeAdaptor*>(phraseDictionary) != NULL) {
m_useLegacyPT = true;
return;
}
}
m_useLegacyPT = false;
}
void StaticData::ResetWeights(const std::string &denseWeights, const std::string &sparseFile)
{
m_allWeights = ScoreComponentCollection();
// dense weights
string name("");
vector<float> weights;
vector<string> toks = Tokenize(denseWeights);
for (size_t i = 0; i < toks.size(); ++i) {
const string &tok = toks[i];
if (ends_with(tok, "=")) {
// start of new feature
if (name != "") {
// save previous ff
const FeatureFunction &ff = FeatureFunction::FindFeatureFunction(name);
m_allWeights.Assign(&ff, weights);
weights.clear();
}
name = tok.substr(0, tok.size() - 1);
} else {
// a weight for curr ff
float weight = Scan<float>(toks[i]);
weights.push_back(weight);
}
}
const FeatureFunction &ff = FeatureFunction::FindFeatureFunction(name);
m_allWeights.Assign(&ff, weights);
// sparse weights
InputFileStream sparseStrme(sparseFile);
string line;
while (getline(sparseStrme, line)) {
vector<string> toks = Tokenize(line);
UTIL_THROW_IF2(toks.size() != 2, "Incorrect sparse weight format. Should be FFName_spareseName weight");
vector<string> names = Tokenize(toks[0], "_");
UTIL_THROW_IF2(names.size() != 2, "Incorrect sparse weight name. Should be FFName_spareseName");
const FeatureFunction &ff = FeatureFunction::FindFeatureFunction(names[0]);
m_allWeights.Assign(&ff, names[1], Scan<float>(toks[1]));
}
}
size_t StaticData::GetCoordSpace(string space) const
{
map<string const, size_t>::const_iterator m = m_coordSpaceMap.find(space);
if(m == m_coordSpaceMap.end()) {
return 0;
}
return m->second;
}
size_t StaticData::MapCoordSpace(string space)
{
map<string const, size_t>::const_iterator m = m_coordSpaceMap.find(space);
if (m != m_coordSpaceMap.end()) {
return m->second;
}
size_t id = m_coordSpaceNextID;
m_coordSpaceNextID += 1;
m_coordSpaceMap[space] = id;
return id;
}
} // namespace
|
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ViewElementListProvider.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-08 00:20:24 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "ViewElementListProvider.hxx"
#include "DrawModelWrapper.hxx"
#include "chartview/NumberFormatterWrapper.hxx"
#include "chartview/DataPointSymbolSupplier.hxx"
#include "macros.hxx"
/*
#ifndef _SVDMODEL_HXX
#include <svx/svdmodel.hxx>
#endif
*/
//------------
//oldChartModelWrapper
/*
// header for class SfxPrinter
#ifndef _SFX_PRINTER_HXX
#include <sfx2/printer.hxx>
#endif
*/
// header for class FontList
#ifndef _CTRLTOOL_HXX
#include <svtools/ctrltool.hxx>
#endif
// header for class Application
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
//------------
// header for class SvxShape
#ifndef _SVX_UNOSHAPE_HXX
#include <svx/unoshape.hxx>
#endif
// header for class SdrObject
#ifndef _SVDOBJ_HXX
#include <svx/svdobj.hxx>
#endif
//---------------
//for creation of a symbol Graphic
// header for class VirtualDevice
#ifndef _SV_VIRDEV_HXX
#include <vcl/virdev.hxx>
#endif
// header for class SdrView
#ifndef _SVDVIEW_HXX
#include <svx/svdview.hxx>
#endif
//---------------
/*
//for creation of own number formatter
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
*/
#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGESSUPPLIER_HPP_
#include <com/sun/star/drawing/XDrawPagesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
//using namespace ::com::sun::star::chart2;
ViewElementListProvider::ViewElementListProvider( DrawModelWrapper* pDrawModelWrapper
, NumberFormatterWrapper* pNumberFormatterWrapper )
: m_pDrawModelWrapper( pDrawModelWrapper )
, m_pFontList(NULL)
, m_pNumberFormatterWrapper(pNumberFormatterWrapper)
{
DBG_ASSERT(m_pDrawModelWrapper,"A DrawModelWrapper is missing - maybe not all services can be provided");
DBG_ASSERT(m_pNumberFormatterWrapper,"A Numberformatter is missing - maybe not all services can be provided");
}
ViewElementListProvider::~ViewElementListProvider()
{
if(m_pFontList)
delete m_pFontList;
}
XColorTable* ViewElementListProvider::GetColorTable() const
{
if(m_pDrawModelWrapper)
return m_pDrawModelWrapper->GetColorTable();
return NULL;
}
XDashList* ViewElementListProvider::GetDashList() const
{
if(m_pDrawModelWrapper)
return m_pDrawModelWrapper->GetDashList();
return NULL;
}
XLineEndList* ViewElementListProvider::GetLineEndList() const
{
if(m_pDrawModelWrapper)
return m_pDrawModelWrapper->GetLineEndList();
return NULL;
}
XGradientList* ViewElementListProvider::GetGradientList() const
{
if(m_pDrawModelWrapper)
return m_pDrawModelWrapper->GetGradientList();
return NULL;
}
XHatchList* ViewElementListProvider::GetHatchList() const
{
if(m_pDrawModelWrapper)
return m_pDrawModelWrapper->GetHatchList();
return NULL;
}
XBitmapList* ViewElementListProvider::GetBitmapList() const
{
if(m_pDrawModelWrapper)
return m_pDrawModelWrapper->GetBitmapList();
return NULL;
}
//create chartspecific symbols for linecharts
SdrObjList* ViewElementListProvider::GetSymbolList() const
{
static SdrObjList* m_pSymbolList = NULL;
static uno::Reference< drawing::XShapes > m_xSymbols(NULL);//@todo this keeps the first drawinglayer alive ...
try
{
if(!m_pSymbolList || !m_pSymbolList->GetObjCount())
{
//@todo use mutex
//get factory from draw model
uno::Reference< drawing::XDrawPagesSupplier > xDrawPagesSuplier( m_pDrawModelWrapper->getUnoModel(), uno::UNO_QUERY );
uno::Reference< lang::XMultiServiceFactory > xShapeFactory( xDrawPagesSuplier, uno::UNO_QUERY );
//create hidden draw page (target):
uno::Reference< drawing::XDrawPages > xDrawPages( xDrawPagesSuplier->getDrawPages () );
uno::Reference< drawing::XDrawPage > xDrawPage( xDrawPages->insertNewByIndex ( 1 ) );
uno::Reference<drawing::XShapes> xTarget( xDrawPage, uno::UNO_QUERY );
//create symbols via uno and convert to native sdr objects
drawing::Direction3D aSymbolSize(1000,1000,1000);//this size is somehow arbitrary - nneds only to be big thus the dialog restricts the symbols to its own maximum value
m_xSymbols = DataPointSymbolSupplier::create2DSymbolList( xShapeFactory, xTarget, aSymbolSize );
uno::Reference< lang::XUnoTunnel > xUnoTunnel( m_xSymbols, uno::UNO_QUERY );
uno::Reference< lang::XTypeProvider > xTypeProvider( m_xSymbols, uno::UNO_QUERY );
if(xUnoTunnel.is()&&xTypeProvider.is())
{
SvxShape* pSvxShape = reinterpret_cast<SvxShape*>(xUnoTunnel->getSomething( SvxShape::getUnoTunnelId() ));
if(pSvxShape)
{
SdrObject* pSdrObject = pSvxShape->GetSdrObject();
if(pSdrObject)
m_pSymbolList = pSdrObject->GetSubList();
}
}
}
}
catch( uno::Exception& e )
{
ASSERT_EXCEPTION( e );
}
return m_pSymbolList;
}
Graphic ViewElementListProvider::GetSymbolGraphic( sal_Int32 nStandardSymbol, const SfxItemSet* pSymbolShapeProperties ) const
{
SdrObjList* pSymbolList = this->GetSymbolList();
if( !pSymbolList->GetObjCount() )
return Graphic();
if(nStandardSymbol<0)
nStandardSymbol*=-1;
if( nStandardSymbol >= static_cast<sal_Int32>(pSymbolList->GetObjCount()) )
nStandardSymbol %= pSymbolList->GetObjCount();
SdrObject* pObj = pSymbolList->GetObj(nStandardSymbol);
VirtualDevice aVDev;
aVDev.SetMapMode(MapMode(MAP_100TH_MM));
SdrModel* pModel = new SdrModel();
pModel->GetItemPool().FreezeIdRanges();
SdrPage* pPage = new SdrPage( *pModel, FALSE );
pPage->SetSize(Size(1000,1000));
pModel->InsertPage( pPage, 0 );
SdrView* pView = new SdrView( pModel, &aVDev );
pView->SetMarkHdlHidden( TRUE );
SdrPageView* pPageView = pView->ShowPage(pPage, Point());
pObj=pObj->Clone();
pPage->NbcInsertObject(pObj);
pView->MarkObj(pObj,pPageView);
if( pSymbolShapeProperties )
pObj->SetMergedItemSet(*pSymbolShapeProperties);
GDIMetaFile aMeta(pView->GetAllMarkedMetaFile());
Graphic aGraph(aMeta);
Size aSize = pObj->GetSnapRect().GetSize();
aGraph.SetPrefSize(aSize);
aGraph.SetPrefMapMode(MAP_100TH_MM);
pView->UnmarkAll();
pObj=pPage->RemoveObject(0);
if(pObj)
delete pObj;
delete pView;
delete pModel;
return aGraph;
}
FontList* ViewElementListProvider::getFontList() const
{
//was old chart:
//SvxFontListItem* SfxObjectShell::.GetItem(SID_ATTR_CHAR_FONTLIST)
if(!m_pFontList)
{
OutputDevice* pPrinter = NULL;//getPrinter();
OutputDevice* pDefaultOut = Application::GetDefaultDevice(); // #67730#
m_pFontList = new FontList( pPrinter ? pPrinter : pDefaultOut
, pPrinter ? pDefaultOut : NULL
, FALSE );
}
return m_pFontList;
}
/*
SfxPrinter* ObjectPropertiesDialogParameter::getPrinter()
{
//was old chart:
//SfxPrinter* SchChartDocShell::GetPrinter()
// OLE-Objekt: kein Printer anlegen ??? see old chart: :UpdateTablePointers
//@todo get printer from calc or other container
//return NULL;
SfxPrinter* pPrinter = NULL;
bool bOwnPrinter = true;
if (!pPrinter)
{
SfxBoolItem aItem(SID_PRINTER_NOTFOUND_WARN, TRUE);
// ItemSet mit speziellem Poolbereich anlegen
SfxItemSet* pSet = new SfxItemSet(GetPool(),
SID_PRINTER_NOTFOUND_WARN,
SID_PRINTER_NOTFOUND_WARN, 0);
pSet->Put(aItem);
pPrinter = new SfxPrinter(pSet); //@todo ->need to remember and delete
bOwnPrinter = TRUE;
MapMode aMapMode = pPrinter->GetMapMode();
aMapMode.SetMapUnit(MAP_100TH_MM);
pPrinter->SetMapMode(aMapMode);
if (pChDoc)
{
if (pPrinter != pChDoc->GetRefDevice())
pChDoc->SetRefDevice(pPrinter);
if (pPrinter != pChDoc->GetOutliner()->GetRefDevice())
pChDoc->GetOutliner()->SetRefDevice(pPrinter);
}
}
return pPrinter;
}
*/
SvNumberFormatter* ViewElementListProvider::GetOwnNumberFormatter() const
{
if( m_pNumberFormatterWrapper )
return m_pNumberFormatterWrapper->getSvNumberFormatter();
return NULL;
/*
static SvNumberFormatter aNumberFormatter = SvNumberFormatter(
::comphelper::getProcessServiceFactory(),
LANGUAGE_SYSTEM );
return &aNumberFormatter;
*/
}
SvNumberFormatter* ViewElementListProvider::GetNumFormatter() const
{
//@todo
return GetOwnNumberFormatter();
}
//.............................................................................
} //namespace chart
//.............................................................................
INTEGRATION: CWS pchfix02 (1.7.78); FILE MERGED
2006/09/01 17:18:36 kaib 1.7.78.1: #i68856# Added header markers and pch files
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ViewElementListProvider.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-09-17 13:01:03 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "ViewElementListProvider.hxx"
#include "DrawModelWrapper.hxx"
#include "chartview/NumberFormatterWrapper.hxx"
#include "chartview/DataPointSymbolSupplier.hxx"
#include "macros.hxx"
/*
#ifndef _SVDMODEL_HXX
#include <svx/svdmodel.hxx>
#endif
*/
//------------
//oldChartModelWrapper
/*
// header for class SfxPrinter
#ifndef _SFX_PRINTER_HXX
#include <sfx2/printer.hxx>
#endif
*/
// header for class FontList
#ifndef _CTRLTOOL_HXX
#include <svtools/ctrltool.hxx>
#endif
// header for class Application
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
//------------
// header for class SvxShape
#ifndef _SVX_UNOSHAPE_HXX
#include <svx/unoshape.hxx>
#endif
// header for class SdrObject
#ifndef _SVDOBJ_HXX
#include <svx/svdobj.hxx>
#endif
//---------------
//for creation of a symbol Graphic
// header for class VirtualDevice
#ifndef _SV_VIRDEV_HXX
#include <vcl/virdev.hxx>
#endif
// header for class SdrView
#ifndef _SVDVIEW_HXX
#include <svx/svdview.hxx>
#endif
//---------------
/*
//for creation of own number formatter
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
*/
#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGESSUPPLIER_HPP_
#include <com/sun/star/drawing/XDrawPagesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
//using namespace ::com::sun::star::chart2;
ViewElementListProvider::ViewElementListProvider( DrawModelWrapper* pDrawModelWrapper
, NumberFormatterWrapper* pNumberFormatterWrapper )
: m_pDrawModelWrapper( pDrawModelWrapper )
, m_pFontList(NULL)
, m_pNumberFormatterWrapper(pNumberFormatterWrapper)
{
DBG_ASSERT(m_pDrawModelWrapper,"A DrawModelWrapper is missing - maybe not all services can be provided");
DBG_ASSERT(m_pNumberFormatterWrapper,"A Numberformatter is missing - maybe not all services can be provided");
}
ViewElementListProvider::~ViewElementListProvider()
{
if(m_pFontList)
delete m_pFontList;
}
XColorTable* ViewElementListProvider::GetColorTable() const
{
if(m_pDrawModelWrapper)
return m_pDrawModelWrapper->GetColorTable();
return NULL;
}
XDashList* ViewElementListProvider::GetDashList() const
{
if(m_pDrawModelWrapper)
return m_pDrawModelWrapper->GetDashList();
return NULL;
}
XLineEndList* ViewElementListProvider::GetLineEndList() const
{
if(m_pDrawModelWrapper)
return m_pDrawModelWrapper->GetLineEndList();
return NULL;
}
XGradientList* ViewElementListProvider::GetGradientList() const
{
if(m_pDrawModelWrapper)
return m_pDrawModelWrapper->GetGradientList();
return NULL;
}
XHatchList* ViewElementListProvider::GetHatchList() const
{
if(m_pDrawModelWrapper)
return m_pDrawModelWrapper->GetHatchList();
return NULL;
}
XBitmapList* ViewElementListProvider::GetBitmapList() const
{
if(m_pDrawModelWrapper)
return m_pDrawModelWrapper->GetBitmapList();
return NULL;
}
//create chartspecific symbols for linecharts
SdrObjList* ViewElementListProvider::GetSymbolList() const
{
static SdrObjList* m_pSymbolList = NULL;
static uno::Reference< drawing::XShapes > m_xSymbols(NULL);//@todo this keeps the first drawinglayer alive ...
try
{
if(!m_pSymbolList || !m_pSymbolList->GetObjCount())
{
//@todo use mutex
//get factory from draw model
uno::Reference< drawing::XDrawPagesSupplier > xDrawPagesSuplier( m_pDrawModelWrapper->getUnoModel(), uno::UNO_QUERY );
uno::Reference< lang::XMultiServiceFactory > xShapeFactory( xDrawPagesSuplier, uno::UNO_QUERY );
//create hidden draw page (target):
uno::Reference< drawing::XDrawPages > xDrawPages( xDrawPagesSuplier->getDrawPages () );
uno::Reference< drawing::XDrawPage > xDrawPage( xDrawPages->insertNewByIndex ( 1 ) );
uno::Reference<drawing::XShapes> xTarget( xDrawPage, uno::UNO_QUERY );
//create symbols via uno and convert to native sdr objects
drawing::Direction3D aSymbolSize(1000,1000,1000);//this size is somehow arbitrary - nneds only to be big thus the dialog restricts the symbols to its own maximum value
m_xSymbols = DataPointSymbolSupplier::create2DSymbolList( xShapeFactory, xTarget, aSymbolSize );
uno::Reference< lang::XUnoTunnel > xUnoTunnel( m_xSymbols, uno::UNO_QUERY );
uno::Reference< lang::XTypeProvider > xTypeProvider( m_xSymbols, uno::UNO_QUERY );
if(xUnoTunnel.is()&&xTypeProvider.is())
{
SvxShape* pSvxShape = reinterpret_cast<SvxShape*>(xUnoTunnel->getSomething( SvxShape::getUnoTunnelId() ));
if(pSvxShape)
{
SdrObject* pSdrObject = pSvxShape->GetSdrObject();
if(pSdrObject)
m_pSymbolList = pSdrObject->GetSubList();
}
}
}
}
catch( uno::Exception& e )
{
ASSERT_EXCEPTION( e );
}
return m_pSymbolList;
}
Graphic ViewElementListProvider::GetSymbolGraphic( sal_Int32 nStandardSymbol, const SfxItemSet* pSymbolShapeProperties ) const
{
SdrObjList* pSymbolList = this->GetSymbolList();
if( !pSymbolList->GetObjCount() )
return Graphic();
if(nStandardSymbol<0)
nStandardSymbol*=-1;
if( nStandardSymbol >= static_cast<sal_Int32>(pSymbolList->GetObjCount()) )
nStandardSymbol %= pSymbolList->GetObjCount();
SdrObject* pObj = pSymbolList->GetObj(nStandardSymbol);
VirtualDevice aVDev;
aVDev.SetMapMode(MapMode(MAP_100TH_MM));
SdrModel* pModel = new SdrModel();
pModel->GetItemPool().FreezeIdRanges();
SdrPage* pPage = new SdrPage( *pModel, FALSE );
pPage->SetSize(Size(1000,1000));
pModel->InsertPage( pPage, 0 );
SdrView* pView = new SdrView( pModel, &aVDev );
pView->SetMarkHdlHidden( TRUE );
SdrPageView* pPageView = pView->ShowPage(pPage, Point());
pObj=pObj->Clone();
pPage->NbcInsertObject(pObj);
pView->MarkObj(pObj,pPageView);
if( pSymbolShapeProperties )
pObj->SetMergedItemSet(*pSymbolShapeProperties);
GDIMetaFile aMeta(pView->GetAllMarkedMetaFile());
Graphic aGraph(aMeta);
Size aSize = pObj->GetSnapRect().GetSize();
aGraph.SetPrefSize(aSize);
aGraph.SetPrefMapMode(MAP_100TH_MM);
pView->UnmarkAll();
pObj=pPage->RemoveObject(0);
if(pObj)
delete pObj;
delete pView;
delete pModel;
return aGraph;
}
FontList* ViewElementListProvider::getFontList() const
{
//was old chart:
//SvxFontListItem* SfxObjectShell::.GetItem(SID_ATTR_CHAR_FONTLIST)
if(!m_pFontList)
{
OutputDevice* pPrinter = NULL;//getPrinter();
OutputDevice* pDefaultOut = Application::GetDefaultDevice(); // #67730#
m_pFontList = new FontList( pPrinter ? pPrinter : pDefaultOut
, pPrinter ? pDefaultOut : NULL
, FALSE );
}
return m_pFontList;
}
/*
SfxPrinter* ObjectPropertiesDialogParameter::getPrinter()
{
//was old chart:
//SfxPrinter* SchChartDocShell::GetPrinter()
// OLE-Objekt: kein Printer anlegen ??? see old chart: :UpdateTablePointers
//@todo get printer from calc or other container
//return NULL;
SfxPrinter* pPrinter = NULL;
bool bOwnPrinter = true;
if (!pPrinter)
{
SfxBoolItem aItem(SID_PRINTER_NOTFOUND_WARN, TRUE);
// ItemSet mit speziellem Poolbereich anlegen
SfxItemSet* pSet = new SfxItemSet(GetPool(),
SID_PRINTER_NOTFOUND_WARN,
SID_PRINTER_NOTFOUND_WARN, 0);
pSet->Put(aItem);
pPrinter = new SfxPrinter(pSet); //@todo ->need to remember and delete
bOwnPrinter = TRUE;
MapMode aMapMode = pPrinter->GetMapMode();
aMapMode.SetMapUnit(MAP_100TH_MM);
pPrinter->SetMapMode(aMapMode);
if (pChDoc)
{
if (pPrinter != pChDoc->GetRefDevice())
pChDoc->SetRefDevice(pPrinter);
if (pPrinter != pChDoc->GetOutliner()->GetRefDevice())
pChDoc->GetOutliner()->SetRefDevice(pPrinter);
}
}
return pPrinter;
}
*/
SvNumberFormatter* ViewElementListProvider::GetOwnNumberFormatter() const
{
if( m_pNumberFormatterWrapper )
return m_pNumberFormatterWrapper->getSvNumberFormatter();
return NULL;
/*
static SvNumberFormatter aNumberFormatter = SvNumberFormatter(
::comphelper::getProcessServiceFactory(),
LANGUAGE_SYSTEM );
return &aNumberFormatter;
*/
}
SvNumberFormatter* ViewElementListProvider::GetNumFormatter() const
{
//@todo
return GetOwnNumberFormatter();
}
//.............................................................................
} //namespace chart
//.............................................................................
|
#include "points_calculator.h"
#include "wait_and_win_test.h"
#include <assert.h>
#include <stddef.h>
#include <string.h>
//#define STRICT_98_RULE
namespace mahjong {
static bool seperate_2(const TILE *tiles, long tile_cnt, long fixed_set_cnt, SET (*output_sets)[5], long *separation_cnt) {
if (tile_cnt == 2 && tiles[0] == tiles[1]) { // 划分成功
// 这2张作为将
output_sets[*separation_cnt][4].is_melded = false;
output_sets[*separation_cnt][4].mid_tile = tiles[0];
output_sets[*separation_cnt][4].set_type = SET_TYPE::PAIR;
// 拷贝一份当前的划分出来的面子,并排序
SET temp[5];
memcpy(temp, output_sets[*separation_cnt], 5 * sizeof(SET));
std::sort(temp + fixed_set_cnt, temp + 4, &set_cmp);
// 检查这种划分是否已经存在了
bool has_found = false;
long i = *separation_cnt;
while (i--) {
if (std::equal(std::begin(temp), std::end(temp), output_sets[i], [](const SET &set1, const SET &set2) {
return set1.mid_tile == set2.mid_tile && set1.set_type == set2.set_type;
})) {
has_found = true;
break;
}
}
if (!has_found) {
// 如果不存在,那么得到一种新的划分
memcpy(output_sets[*separation_cnt + 1], output_sets[*separation_cnt], 5 * sizeof(SET));
++(*separation_cnt);
}
return true;
}
return false;
}
static bool seperate_N(const TILE *tiles, long tile_cnt, long fixed_set_cnt, SET (*output_sets)[5], long *separation_cnt) {
if (tile_cnt < 3) {
return seperate_2(tiles, tile_cnt, fixed_set_cnt, output_sets, separation_cnt);
}
bool ret = false;
long i = 0;
while (i < tile_cnt) {
TILE tile_i = tiles[i];
long j = i + 1;
while (j < tile_cnt) {
TILE tile_j = tiles[j];
if (tile_j - tile_i >= 3) break; // 这已经不可能再构成面子了
long k = j + 1;
while (k < tile_cnt) {
TILE tile_k = tiles[k];
if (tile_k - tile_i >= 3) break; // 这已经不可能再构成面子了
if (is_concealed_set_completed(tile_i, tile_j, tile_k)) {
long current = (14 - tile_cnt) / 3;
output_sets[*separation_cnt][current].is_melded = false;
output_sets[*separation_cnt][current].mid_tile = tile_j;
output_sets[*separation_cnt][current].set_type = (tile_i == tile_j) ? SET_TYPE::PUNG : SET_TYPE::CHOW;
// 削减面子
TILE remains[14];
for (int n = 0, c = 0; n < tile_cnt; ++n) {
if (n == i || n == j || n == k) {
continue;
}
remains[c++] = tiles[n];
}
// 递归
if (seperate_N(remains, tile_cnt - 3, fixed_set_cnt, output_sets, separation_cnt)) {
ret = true;
}
}
do ++k; while (k < tile_cnt && tiles[k] == tile_k); // 快速跳过相同的case
}
do ++j; while (j < tile_cnt && tiles[j] == tile_j); // 快速跳过相同的case
}
do ++i; while (i < tile_cnt && tiles[i] == tile_i); // 快速跳过相同的case
}
return ret;
}
// 从一组一组的牌恢复成一张一张的牌
void recovery_tiles_from_sets(const SET *sets, long set_cnt, TILE *tiles, long *tile_cnt) {
assert(tiles != nullptr && tile_cnt != nullptr);
*tile_cnt = 0;
for (int i = 0; i < set_cnt; ++i) {
switch (sets[i].set_type) {
case SET_TYPE::CHOW:
tiles[(*tile_cnt)++] = sets[i].mid_tile - 1;
tiles[(*tile_cnt)++] = sets[i].mid_tile;
tiles[(*tile_cnt)++] = sets[i].mid_tile + 1;
break;
case SET_TYPE::PUNG:
tiles[(*tile_cnt)++] = sets[i].mid_tile;
tiles[(*tile_cnt)++] = sets[i].mid_tile;
tiles[(*tile_cnt)++] = sets[i].mid_tile;
break;
case SET_TYPE::KONG:
tiles[(*tile_cnt)++] = sets[i].mid_tile;
tiles[(*tile_cnt)++] = sets[i].mid_tile;
tiles[(*tile_cnt)++] = sets[i].mid_tile;
tiles[(*tile_cnt)++] = sets[i].mid_tile;
break;
case SET_TYPE::PAIR:
tiles[(*tile_cnt)++] = sets[i].mid_tile;
tiles[(*tile_cnt)++] = sets[i].mid_tile;
break;
default:
assert(0);
break;
}
}
}
// 一色四同顺
static bool is_quadruple_chow(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2, TILE mid_tile3) {
return (mid_tile0 == mid_tile1 && mid_tile0 == mid_tile2 && mid_tile0 == mid_tile3);
}
// 一色四节高
static bool is_four_pure_shifted_pungs(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2, TILE mid_tile3) {
if (is_numbered_suit_quick(mid_tile0)) {
return (mid_tile0 + 1 == mid_tile1 && mid_tile1 + 1 == mid_tile2 && mid_tile2 + 1 == mid_tile3);
}
return false;
}
// 一色四步高
static bool is_four_pure_shifted_chows(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2, TILE mid_tile3) {
// 递增2的必然是:123 345 567 789
// 递增1的最小为:123 234 345 456 最大为:456 567 678 789
return ((mid_tile0 + 2 == mid_tile1 && mid_tile1 + 2 == mid_tile2 && mid_tile2 + 2 == mid_tile3)
|| (mid_tile0 + 1 == mid_tile1 && mid_tile1 + 1 == mid_tile2 && mid_tile2 + 1 == mid_tile3));
}
// 一色三同顺
static bool is_pure_triple_chow(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2) {
return (mid_tile0 == mid_tile1 && mid_tile0 == mid_tile2);
}
// 一色三节高
static bool is_pure_shifted_pungs(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2) {
if (is_numbered_suit_quick(mid_tile0)) {
return (mid_tile0 + 1 == mid_tile1 && mid_tile1 + 1 == mid_tile2);
}
return false;
}
// 清龙
static bool is_pure_straight(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2) {
if (tile_rank(mid_tile0) == 2) {
return (mid_tile0 + 3 == mid_tile1 && mid_tile1 + 3 == mid_tile2);
}
return false;
}
// 一色三步高
static bool is_pure_shifted_chows(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2) {
return ((mid_tile0 + 2 == mid_tile1 && mid_tile1 + 2 == mid_tile2)
|| (mid_tile0 + 1 == mid_tile1 && mid_tile1 + 1 == mid_tile2));
}
// 花龙
static bool is_mixed_straight(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2) {
SUIT_TYPE suit0 = tile_suit(mid_tile0);
SUIT_TYPE suit1 = tile_suit(mid_tile1);
SUIT_TYPE suit2 = tile_suit(mid_tile2);
if (suit0 != suit1 && suit0 != suit2 && suit1 != suit2) {
RANK_TYPE rank0 = tile_rank(mid_tile0);
RANK_TYPE rank1 = tile_rank(mid_tile1);
RANK_TYPE rank2 = tile_rank(mid_tile2);
return ((rank0 == 2 && rank1 == 5 && rank2 == 8)
|| (rank0 == 2 && rank1 == 8 && rank2 == 5)
|| (rank0 == 5 && rank1 == 2 && rank2 == 8)
|| (rank0 == 5 && rank1 == 8 && rank2 == 2)
|| (rank0 == 8 && rank1 == 2 && rank2 == 5)
|| (rank0 == 8 && rank1 == 5 && rank2 == 2));
}
return false;
}
// 三色三同顺或者三同刻
static bool is_mixed_triple_chow_or_pung(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2) {
if (!is_numbered_suit_quick(mid_tile0) || !is_numbered_suit_quick(mid_tile1) || !is_numbered_suit_quick(mid_tile2)) {
return false;
}
SUIT_TYPE suit0 = tile_suit(mid_tile0);
SUIT_TYPE suit1 = tile_suit(mid_tile1);
SUIT_TYPE suit2 = tile_suit(mid_tile2);
if (suit0 != suit1 && suit0 != suit2 && suit1 != suit2) {
RANK_TYPE rank0 = tile_rank(mid_tile0);
RANK_TYPE rank1 = tile_rank(mid_tile1);
RANK_TYPE rank2 = tile_rank(mid_tile2);
return (rank0 == rank1 && rank0 == rank2);
}
return false;
}
// 三色三节高或者三色三步高
static bool is_mixed_shifted_chow_or_pung(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2) {
if (!is_numbered_suit_quick(mid_tile0) || !is_numbered_suit_quick(mid_tile1) || !is_numbered_suit_quick(mid_tile2)) {
return false;
}
SUIT_TYPE suit0 = tile_suit(mid_tile0);
SUIT_TYPE suit1 = tile_suit(mid_tile1);
SUIT_TYPE suit2 = tile_suit(mid_tile2);
if (suit0 != suit1 && suit0 != suit2 && suit1 != suit2) {
RANK_TYPE rank0 = tile_rank(mid_tile0);
RANK_TYPE rank1 = tile_rank(mid_tile1);
RANK_TYPE rank2 = tile_rank(mid_tile2);
return ((rank1 + 1 == rank0 && rank0 + 1 == rank2)
|| (rank2 + 1 == rank0 && rank0 + 1 == rank1)
|| (rank0 + 1 == rank1 && rank1 + 1 == rank2)
|| (rank2 + 1 == rank1 && rank1 + 1 == rank0)
|| (rank0 + 1 == rank2 && rank2 + 1 == rank1)
|| (rank1 + 1 == rank2 && rank2 + 1 == rank0));
}
return false;
}
// 一般高
static bool is_pure_double_chow(TILE mid_tile0, TILE mid_tile1) {
return mid_tile0 == mid_tile1;
}
// 喜相逢
static bool is_mixed_double_chow(TILE mid_tile0, TILE mid_tile1) {
return (is_rank_equal_quick(mid_tile0, mid_tile1) && !is_suit_equal_quick(mid_tile0, mid_tile1));
}
// 连六
static bool is_short_straight(TILE mid_tile0, TILE mid_tile1) {
return (mid_tile0 + 3 == mid_tile1 || mid_tile1 + 3 == mid_tile0);
}
// 老少副
static bool is_two_terminal_chows(TILE mid_tile0, TILE mid_tile1) {
if (is_suit_equal_quick(mid_tile0, mid_tile1)) {
RANK_TYPE rank0 = tile_rank(mid_tile0);
RANK_TYPE rank1 = tile_rank(mid_tile1);
return ((rank0 == 2 && rank1 == 8) || (rank0 == 8 && rank1 == 2));
}
return false;
}
// 4组顺子的番
static POINT_TYPE get_4_chows_points(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2, TILE mid_tile3) {
if (is_quadruple_chow(mid_tile0, mid_tile1, mid_tile2, mid_tile3)) {
return QUADRUPLE_CHOW;
}
if (is_four_pure_shifted_chows(mid_tile0, mid_tile1, mid_tile2, mid_tile3)) {
return FOUR_PURE_SHIFTED_CHOWS;
}
return NONE;
}
// 3组顺子的番
static POINT_TYPE get_3_chows_points(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2) {
if (is_mixed_shifted_chow_or_pung(mid_tile0, mid_tile1, mid_tile2)) {
return MIXED_SHIFTED_CHOWS;
}
if (is_mixed_straight(mid_tile0, mid_tile1, mid_tile2)) {
return MIXED_STRAIGHT;
}
if (is_mixed_triple_chow_or_pung(mid_tile0, mid_tile1, mid_tile2)) {
return MIXED_TRIPLE_CHOW;
}
if (is_pure_straight(mid_tile0, mid_tile1, mid_tile2)) {
return PURE_STRAIGHT;
}
if (is_pure_shifted_chows(mid_tile0, mid_tile1, mid_tile2)) {
return PURE_SHIFTED_CHOWS;
}
if (is_pure_triple_chow(mid_tile0, mid_tile1, mid_tile2)) {
return PURE_TRIPLE_CHOW;
}
return NONE;
}
// 2组顺子的番
static POINT_TYPE get_2_chows_points(TILE mid_tile0, TILE mid_tile1) {
if (is_pure_double_chow(mid_tile0, mid_tile1)) {
return PURE_DOUBLE_CHOW;
}
if (is_mixed_double_chow(mid_tile0, mid_tile1)) {
return MIXED_DOUBLE_CHOW;
}
if (is_short_straight(mid_tile0, mid_tile1)) {
return SHORT_STRAIGHT;
}
if (is_two_terminal_chows(mid_tile0, mid_tile1)) {
return TWO_TERMINAL_CHOWS;
}
return NONE;
}
// 4组刻子的番
static POINT_TYPE get_4_pungs_points(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2, TILE mid_tile3) {
if (is_four_pure_shifted_pungs(mid_tile0, mid_tile1, mid_tile2, mid_tile3)) {
return FOUR_PURE_SHIFTED_PUNGS;
}
if (is_winds(mid_tile0) && is_winds(mid_tile1) && is_winds(mid_tile2) && is_winds(mid_tile3)) {
return BIG_FOUR_WINDS;
}
return NONE;
}
// 3组刻子的番
static POINT_TYPE get_3_pungs_points(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2) {
if (is_mixed_shifted_chow_or_pung(mid_tile0, mid_tile1, mid_tile2)) {
return MIXED_SHIFTED_PUNGS;
}
if (is_mixed_triple_chow_or_pung(mid_tile0, mid_tile1, mid_tile2)) {
return TRIPLE_PUNG;
}
if (is_pure_shifted_pungs(mid_tile0, mid_tile1, mid_tile2)) {
return PURE_SHIFTED_PUNGS;
}
if (is_dragons(mid_tile0) && is_dragons(mid_tile1) && is_dragons(mid_tile2)) {
return BIG_THREE_DRAGONS;
}
if (is_winds(mid_tile0) && is_winds(mid_tile1) && is_winds(mid_tile2)) {
return BIG_THREE_WINDS;
}
return NONE;
}
// 2组刻子的番
static POINT_TYPE get_2_pungs_points(TILE mid_tile0, TILE mid_tile1) {
if (is_numbered_suit_quick(mid_tile0) && is_numbered_suit_quick(mid_tile1) && is_rank_equal_quick(mid_tile0, mid_tile1)) {
return DOUBLE_PUNG;
}
if (is_dragons(mid_tile0) && is_dragons(mid_tile1)) {
return TWO_DRAGONS_PUNGS;
}
return NONE;
}
// 1组刻子的番
static POINT_TYPE get_1_pung_points(TILE mid_tile) {
if (is_terminal(mid_tile) || is_winds(mid_tile)) {
return PUNG_OF_TERMINALS_OR_HONORS;
}
if (is_dragons(mid_tile)) {
return DRAGON_PUNG;
}
return NONE;
}
template <long _Size>
static POINT_TYPE *pairwise_test_chows(const SET (&chows_sets)[_Size], POINT_TYPE *selected_points) {
POINT_TYPE all_points[_Size][_Size] = { { NONE } };
// 初始化矩阵
for (int i = 0; i < _Size; ++i) {
for (int j = 0; j < i - 1; ++j) { // 这是对称矩阵
all_points[i][j] = all_points[j][i];
}
for (int j = i + 1; j < _Size; ++j) {
all_points[i][j] = get_2_chows_points(chows_sets[i].mid_tile, chows_sets[j].mid_tile);
}
}
// 套算一次原则:
// 如果有尚未组合过的一副牌,只可同已组合过的相应的一副牌套算一次
//
// 不得相同原则:
// 凡已经合过某一番种的牌,不能再同其他一副牌组成相同的番种计分
//
// 根据套算一次原则,234567s234567p,只能计为“喜相逢*2 连六*1”或者“喜相逢*1 连六*2”,而不是“喜相逢*2 连六*2”
// 根据以上两点,234s223344567p,只能计为:“喜相逢、一般高、连六”,而不是“喜相逢*2、连六”
unsigned used_flag[_Size] = { 0 };
for (int i = 0; i < _Size; ++i) {
for (int j = 0; j < _Size; ++j) {
if (i == j) {
continue;
}
// 套算一次原则
if (used_flag[i] && used_flag[j]) {
continue;
}
if (all_points[i][j] != NONE) {
// 不得相同原则
int idx = all_points[i][j] - PURE_DOUBLE_CHOW;
if ((used_flag[i] & (1 << idx)) == 0 && (used_flag[j] & (1 << idx)) == 0) {
used_flag[i] |= (1 << (all_points[i][j] - PURE_DOUBLE_CHOW));
used_flag[j] |= (1 << (all_points[i][j] - PURE_DOUBLE_CHOW));
*selected_points = all_points[i][j];
++selected_points;
}
}
}
}
return selected_points;
}
// 4组顺子算番
static void calculate_4_chows(const SET chow_sets[4], long (&points_table)[POINT_TYPE_COUNT]) {
// 复制并排序
SET sets[4];
memcpy(sets, chow_sets, sizeof(sets));
std::sort(std::begin(sets), std::end(sets), [](const SET &set1, const SET &set2) {
return set1.mid_tile < set2.mid_tile;
});
POINT_TYPE points;
// 有4组顺子的番种(四同顺 四步高),不再检测其他的了
if ((points = get_4_chows_points(sets[0].mid_tile, sets[1].mid_tile, sets[2].mid_tile, sets[3].mid_tile))) {
points_table[points] = 1;
return;
}
// 3组顺子判断
bool _3_chows_has_points = false;
long free_set_idx = -1;
if ((points = get_3_chows_points(sets[0].mid_tile, sets[1].mid_tile, sets[2].mid_tile)) != NONE) {
points_table[points] = 1;
free_set_idx = 3;
_3_chows_has_points = true;
}
else if ((points = get_3_chows_points(sets[0].mid_tile, sets[1].mid_tile, sets[3].mid_tile)) != NONE) {
points_table[points] = 1;
free_set_idx = 2;
_3_chows_has_points = true;
}
else if ((points = get_3_chows_points(sets[0].mid_tile, sets[2].mid_tile, sets[3].mid_tile)) != NONE) {
points_table[points] = 1;
free_set_idx = 1;
_3_chows_has_points = true;
}
else if ((points = get_3_chows_points(sets[1].mid_tile, sets[2].mid_tile, sets[3].mid_tile)) != NONE) {
points_table[points] = 1;
free_set_idx = 0;
_3_chows_has_points = true;
}
// 有3组顺子的番种(三同顺 三步高 清龙 花龙)时,余下的第4组顺子最多1番
if (_3_chows_has_points) {
for (long i = 0; i < 4; ++i) {
if (i == free_set_idx) {
continue;
}
if ((points = get_2_chows_points(sets[i].mid_tile, sets[free_set_idx].mid_tile)) != NONE) {
++points_table[points];
break;
}
}
return;
}
// 没有上述番种时,4组顺子最多3番
POINT_TYPE selected_points[3] = { NONE };
pairwise_test_chows(sets, selected_points);
for (long i = 0; i < 3; ++i) {
if (selected_points[i] != NONE) {
++points_table[selected_points[i]];
}
}
}
// 3组顺子算番
static void calculate_3_chows(const SET chow_sets[3], long (&points_table)[POINT_TYPE_COUNT]) {
// 复制并排序
SET sets[3];
memcpy(sets, chow_sets, sizeof(sets));
std::sort(std::begin(sets), std::end(sets), [](const SET &set1, const SET &set2) {
return set1.mid_tile < set2.mid_tile;
});
POINT_TYPE points;
// 有3组顺子的番种(三同顺 三步高 清龙 花龙)时,不再检测其他的
if ((points = get_3_chows_points(sets[0].mid_tile, sets[1].mid_tile, sets[2].mid_tile)) != NONE) {
points_table[points] = 1;
return;
}
// 没有上述番种时,3组顺子最多2番
POINT_TYPE selected_points[2] = { NONE };
pairwise_test_chows(sets, selected_points);
for (long i = 0; i < 2; ++i) {
if (selected_points[i] != NONE) {
++points_table[selected_points[i]];
}
}
}
// 2组顺子算番
static void calculate_2_chows(const SET chow_sets[2], long (&points_table)[POINT_TYPE_COUNT]) {
const SET *sets = chow_sets;
POINT_TYPE points;
if ((points = get_2_chows_points(sets[0].mid_tile, sets[1].mid_tile)) != NONE) {
++points_table[points];
}
}
// 刻子(杠)算番
static void calculate_kongs(const SET *pung_sets, long pung_cnt, long (&points_table)[POINT_TYPE_COUNT]) {
// 统计明杠 暗杠 明刻 暗刻
int melded_kong_cnt = 0;
int concealed_kong_cnt = 0;
int concealed_pung_cnt = 0;
for (long i = 0; i < pung_cnt; ++i) {
if (pung_sets[i].is_melded) {
if (pung_sets[i].set_type == SET_TYPE::KONG) {
++melded_kong_cnt;
}
}
else {
if (pung_sets[i].set_type == SET_TYPE::KONG) {
++concealed_kong_cnt;
}
else {
++concealed_pung_cnt;
}
}
}
// 规则
// 三杠
// 明杠 明杠 暗杠 暗刻 -> 三杠+暗杠+双暗刻+碰碰和
// 明杠 暗杠 暗杠 明刻 -> 三杠+双暗杠+碰碰和
// 明杠 暗杠 暗杠 暗刻 -> 三杠+三暗刻+双暗杠+碰碰和
// 暗杠 暗杠 暗杠 明刻 -> 三杠+三暗刻+碰碰和
// 暗杠 暗杠 暗杠 暗刻 -> 三杠+四暗刻
//
// 四杠
// 暗杠 明杠 明杠 明杠 -> 四杠+暗杠
// 暗杠 暗杠 明杠 明杠 -> 四杠+双暗杠
// 暗杠 暗杠 暗杠 明杠 -> 四杠+三暗刻
// 暗杠 暗杠 暗杠 暗杠 -> 四杠+四暗刻
//
int kong_cnt = melded_kong_cnt + concealed_kong_cnt;
switch (kong_cnt) {
case 0: // 0个杠
switch (concealed_pung_cnt) { // 暗刻的个数
case 0: break;
case 1: break;
case 2: points_table[TWO_CONCEALED_PUNGS] = 1; break;
case 3: points_table[THREE_CONCEALED_PUNGS] = 1; break;
case 4: points_table[FOUR_CONCEALED_PUNGS] = 1; break;
default: assert(0); break;
}
break;
case 1: // 1个杠
if (melded_kong_cnt == 1) { // 明杠
points_table[MELDED_KONG] = 1;
switch (concealed_pung_cnt) { // 暗刻的个数
case 0: break;
case 1: break;
case 2: points_table[TWO_CONCEALED_PUNGS] = 1; break;
case 3: points_table[THREE_CONCEALED_PUNGS] = 1; break;
default: assert(0); break;
}
}
else { // 暗杠
points_table[CONCEALED_KONG] = 1;
switch (concealed_pung_cnt) { // 暗刻的个数
case 0: break;
case 1: points_table[TWO_CONCEALED_PUNGS] = 1; break;
case 2: points_table[THREE_CONCEALED_PUNGS] = 1; break;
case 3: points_table[FOUR_CONCEALED_PUNGS] = 1; break;
default: assert(0); break;
}
}
break;
case 2: // 2个杠
switch (concealed_kong_cnt) {
case 0: // 双明杠
points_table[TWO_MELDED_KONGS] = 1;
switch (concealed_pung_cnt) { // 暗刻的个数
case 0: break;
case 1: break;
case 2: points_table[TWO_CONCEALED_PUNGS] = 1; break;
default: assert(0); break;
}
break;
case 1: // 明暗杠
#if HAS_CONCEALED_KONG_AND_MELDED_KONG
points_table[CONCEALED_KONG_AND_MELDED_KONG] = 1;
#else
points_table[MELDED_KONG] = 1;
points_table[CONCEALED_KONG] = 1;
#endif
switch (concealed_pung_cnt) { // 暗刻的个数
case 0: break;
case 1: points_table[TWO_CONCEALED_PUNGS] = 1; break;
case 2: points_table[THREE_CONCEALED_PUNGS] = 1; break;
default: assert(0); break;
}
break;
case 2: // 双暗杠
points_table[TWO_CONCEALED_KONGS] = 1;
switch (concealed_pung_cnt) { // 暗刻的个数
case 0: break;
case 1: points_table[THREE_CONCEALED_PUNGS] = 1; break;
case 2: points_table[FOUR_CONCEALED_PUNGS] = 1; break;
default: assert(0); break;
}
break;
default:
assert(0);
break;
}
break;
case 3: // 3个杠
points_table[THREE_KONGS] = 1;
switch (concealed_kong_cnt) { // 暗刻的个数
case 0: break;
case 1:
if (concealed_pung_cnt == 0) {
points_table[CONCEALED_KONG] = 1;
}
else {
points_table[CONCEALED_KONG] = 1;
points_table[TWO_CONCEALED_PUNGS] = 1;
}
break;
case 2:
if (concealed_pung_cnt == 0) {
points_table[TWO_CONCEALED_KONGS] = 1;
}
else {
points_table[THREE_CONCEALED_PUNGS] = 1;
points_table[TWO_CONCEALED_KONGS] = 1;
}
break;
case 3:
if (concealed_pung_cnt == 0) {
points_table[THREE_CONCEALED_PUNGS] = 1;
}
else {
points_table[FOUR_CONCEALED_PUNGS] = 1;
}
break;
default:
assert(0);
break;
}
break;
case 4: // 4个杠
points_table[FOUR_KONGS] = 1;
switch (concealed_kong_cnt) {
case 0: break;
case 1: points_table[CONCEALED_KONG] = 1; break;
case 2: points_table[TWO_CONCEALED_KONGS] = 1; break;
case 3: points_table[THREE_CONCEALED_PUNGS] = 1; break;
case 4: points_table[FOUR_CONCEALED_PUNGS] = 1; break;
default: assert(0); break;
}
break;
default:
assert(0);
break;
}
// 四杠和四暗刻不计碰碰和,其他先加上碰碰和的番
if (pung_cnt == 4) {
if (points_table[FOUR_KONGS] == 0 && points_table[FOUR_CONCEALED_PUNGS] == 0) {
points_table[ALL_PUNGS] = 1;
}
}
for (long i = 0; i < pung_cnt; ++i) {
POINT_TYPE points = get_1_pung_points(pung_sets[i].mid_tile);
if (points != NONE) {
++points_table[points];
}
}
}
// 4组刻子算番
static void calculate_4_pungs(const SET pung_sets[4], long (&points_table)[POINT_TYPE_COUNT]) {
SET sets[4];
memcpy(sets, pung_sets, sizeof(sets));
std::sort(std::begin(sets), std::end(sets), [](const SET &set1, const SET &set2) {
return set1.mid_tile < set2.mid_tile;
});
calculate_kongs(sets, 4, points_table);
POINT_TYPE points;
if ((points = get_4_pungs_points(sets[0].mid_tile, sets[1].mid_tile, sets[2].mid_tile, sets[3].mid_tile)) != NONE) {
points_table[points] = 1;
return;
}
bool _3_pungs_has_points = false;
long free_set_idx = -1;
if ((points = get_3_pungs_points(sets[0].mid_tile, sets[1].mid_tile, sets[2].mid_tile)) != NONE) {
points_table[points] = 1;
free_set_idx = 3;
_3_pungs_has_points = true;
}
else if ((points = get_3_pungs_points(sets[0].mid_tile, sets[1].mid_tile, sets[3].mid_tile)) != NONE) {
points_table[points] = 1;
free_set_idx = 2;
_3_pungs_has_points = true;
}
else if ((points = get_3_pungs_points(sets[0].mid_tile, sets[2].mid_tile, sets[3].mid_tile)) != NONE) {
points_table[points] = 1;
free_set_idx = 1;
_3_pungs_has_points = true;
}
else if ((points = get_3_pungs_points(sets[1].mid_tile, sets[2].mid_tile, sets[3].mid_tile)) != NONE) {
points_table[points] = 1;
free_set_idx = 0;
_3_pungs_has_points = true;
}
if (_3_pungs_has_points) {
for (long i = 0; i < 4; ++i) {
if (i == free_set_idx) {
continue;
}
if ((points = get_2_pungs_points(sets[i].mid_tile, sets[free_set_idx].mid_tile)) != NONE) {
++points_table[points];
break;
}
}
}
else {
if ((points = get_2_pungs_points(sets[0].mid_tile, sets[1].mid_tile)) != NONE) {
++points_table[points];
}
if ((points = get_2_pungs_points(sets[0].mid_tile, sets[2].mid_tile)) != NONE) {
++points_table[points];
}
if ((points = get_2_pungs_points(sets[0].mid_tile, sets[3].mid_tile)) != NONE) {
++points_table[points];
}
if ((points = get_2_pungs_points(sets[1].mid_tile, sets[2].mid_tile)) != NONE) {
++points_table[points];
}
if ((points = get_2_pungs_points(sets[1].mid_tile, sets[3].mid_tile)) != NONE) {
++points_table[points];
}
if ((points = get_2_pungs_points(sets[2].mid_tile, sets[3].mid_tile)) != NONE) {
++points_table[points];
}
}
}
// 3组刻子算番
static void calculate_3_pungs(const SET pung_sets[3], long (&points_table)[POINT_TYPE_COUNT]) {
SET sets[3];
memcpy(sets, pung_sets, sizeof(sets));
std::sort(std::begin(sets), std::end(sets), [](const SET &set1, const SET &set2) {
return set1.mid_tile < set2.mid_tile;
});
calculate_kongs(sets, 3, points_table);
POINT_TYPE points;
if ((points = get_3_pungs_points(sets[0].mid_tile, sets[1].mid_tile, sets[2].mid_tile)) != NONE) {
points_table[points] = 1;
return;
}
if ((points = get_2_pungs_points(sets[0].mid_tile, sets[1].mid_tile)) != NONE) {
++points_table[points];
}
if ((points = get_2_pungs_points(sets[0].mid_tile, sets[2].mid_tile)) != NONE) {
++points_table[points];
}
if ((points = get_2_pungs_points(sets[1].mid_tile, sets[2].mid_tile)) != NONE) {
++points_table[points];
}
}
// 2组刻子算番
static void calculate_2_pungs(const SET pung_sets[2], long (&points_table)[POINT_TYPE_COUNT]) {
calculate_kongs(pung_sets, 2, points_table);
POINT_TYPE points = get_2_pungs_points(pung_sets[0].mid_tile, pung_sets[1].mid_tile);
if (points != NONE) {
++points_table[points];
}
}
// 1组刻子算番
static void calculate_1_pung(const SET &pung_set, long (&points_table)[POINT_TYPE_COUNT]) {
calculate_kongs(&pung_set, 1, points_table);
}
// 九莲宝灯
static bool is_nine_gates(const TILE tiles[14], TILE win_tile) {
TILE hand_tiles[13];
copy_exclude(tiles, tiles + 14, &win_tile, (&win_tile) + 1, hand_tiles);
sort_tiles(hand_tiles, 13);
switch (hand_tiles[0]) {
case 0x11: return (memcmp(hand_tiles, standard_nine_gates[0], sizeof(hand_tiles)) == 0);
case 0x21: return (memcmp(hand_tiles, standard_nine_gates[1], sizeof(hand_tiles)) == 0);
case 0x31: return (memcmp(hand_tiles, standard_nine_gates[2], sizeof(hand_tiles)) == 0);
default: return false;
}
}
// 一色双龙会
static bool is_pure_terminal_chows(const SET (&chow_sets)[4], const SET &pair_set) {
if (tile_rank(pair_set.mid_tile) != 5) {
return false;
}
int _123_cnt = 0, _789_cnt = 0;
SUIT_TYPE pair_suit = tile_suit(pair_set.mid_tile);
for (long i = 0; i < 4; ++i) {
SUIT_TYPE suit = tile_suit(chow_sets[i].mid_tile);
if (suit != pair_suit) {
return false;
}
RANK_TYPE rank = tile_rank(chow_sets[i].mid_tile);
switch (rank) {
case 2: ++_123_cnt; break;
case 8: ++_789_cnt; break;
default: return false;
}
}
return (_123_cnt == 2 && _789_cnt == 2);
}
// 三色双龙会
static bool is_three_suited_terminal_chows(const SET (&chow_sets)[4], const SET &pair_set) {
if (tile_rank(pair_set.mid_tile) != 5) {
return false;
}
int _123_suit_table[4] = { 0 };
int _789_suit_table[4] = { 0 };
SUIT_TYPE pair_suit = tile_suit(pair_set.mid_tile);
for (long i = 0; i < 4; ++i) {
SUIT_TYPE suit = tile_suit(chow_sets[i].mid_tile);
if (suit == pair_suit) {
return false;
}
RANK_TYPE rank = tile_rank(chow_sets[i].mid_tile);
switch (rank) {
case 2: ++_123_suit_table[suit]; break;
case 8: ++_789_suit_table[suit]; break;
default: return false;
}
}
switch (pair_suit) {
case 1: return (_123_suit_table[2] && _123_suit_table[3] && _789_suit_table[2] && _789_suit_table[3]);
case 2: return (_123_suit_table[1] && _123_suit_table[3] && _789_suit_table[1] && _789_suit_table[3]);
case 3: return (_123_suit_table[1] && _123_suit_table[2] && _789_suit_table[1] && _789_suit_table[2]);
default: assert(0); return false;
}
}
// 检测不求人、全求人
static void check_melded_or_concealed_hand(const SET (&sets)[5], long fixed_cnt, bool self_drawn, long (&points_table)[POINT_TYPE_COUNT]) {
long melded_cnt = 0;
for (long i = 0; i < fixed_cnt; ++i) {
if (sets[i].is_melded) {
++melded_cnt;
}
}
switch (melded_cnt) {
case 0: points_table[self_drawn ? FULLY_CONCEALED_HAND : CONCEALED_HAND] = 1; break;
case 4: points_table[self_drawn ? SELF_DRAWN : MELDED_HAND] = 1; break;
default:
if (self_drawn) {
points_table[SELF_DRAWN] = 1;
}
break;
}
}
// 检测平和、小三元、小四喜
static void check_pair_tile(TILE pair_tile, long chow_cnt, long (&points_table)[POINT_TYPE_COUNT]) {
if (chow_cnt == 4) {
if (is_numbered_suit_quick(pair_tile)) {
points_table[ALL_CHOWS] = 1;
}
}
else {
if (points_table[TWO_DRAGONS_PUNGS]) {
if (is_dragons(pair_tile)) {
points_table[LITTLE_THREE_DRAGONS] = 1;
points_table[TWO_DRAGONS_PUNGS] = 0;
}
}
else if (points_table[BIG_THREE_WINDS]) {
if (is_winds(pair_tile)) {
points_table[LITTLE_FOUR_WINDS] = 1;
points_table[BIG_THREE_WINDS] = 0;
}
}
}
}
// 检测序数牌和字牌
static void check_tiles_suits(const TILE *tiles, long tile_cnt, long (&points_table)[POINT_TYPE_COUNT]) {
bool has_characters = false;
bool has_bamboo = false;
bool has_dots = false;
bool has_winds = false;
bool has_dragons = false;
for (long i = 0; i < tile_cnt; ++i) {
SUIT_TYPE suit = tile_suit(tiles[i]);
switch (suit) {
case TILE_SUIT_CHARACTERS: has_characters = true; break;
case TILE_SUIT_BAMBOO: has_bamboo = true; break;
case TILE_SUIT_DOTS: has_dots = true; break;
case TILE_SUIT_WINDS: has_winds = true; break;
case TILE_SUIT_DRAGONS: has_dragons = true; break;
}
}
if (has_characters && has_bamboo && has_dots && has_winds && has_dragons) {
points_table[ALL_TYPES] = 1;
return;
}
if (!has_winds && !has_dragons) {
points_table[NO_HONORS] = 1;
}
if (!has_characters) {
++points_table[ONE_VOIDED_SUIT];
}
if (!has_bamboo) {
++points_table[ONE_VOIDED_SUIT];
}
if (!has_dots) {
++points_table[ONE_VOIDED_SUIT];
}
if (points_table[ONE_VOIDED_SUIT] == 2) {
points_table[ONE_VOIDED_SUIT] = 0;
points_table[points_table[NO_HONORS] == 0 ? HALF_FLUSH : FULL_FLUSH] = 1;
}
}
// 检测大于五、小于五、全大、全中、全小
static void check_tiles_rank_range(const TILE *tiles, long tile_cnt, long (&points_table)[POINT_TYPE_COUNT]) {
#ifdef STRICT_98_RULE
if (points_table[SEVEN_PAIRS]) {
return;
}
#endif
// 打表
uint16_t rank_flag = 0;
for (long i = 0; i < tile_cnt; ++i) {
SUIT_TYPE suit = tile_suit(tiles[i]);
if (suit == TILE_SUIT_WINDS || suit == TILE_SUIT_DRAGONS) {
return; // 不允许字牌
}
rank_flag |= (1 << tile_rank(tiles[i]));
}
// 1111 1111 1110 0001
// 检测是否缺少56789
if (!(rank_flag & 0xFFE1)) {
points_table[rank_flag & 0x0010 ? LOWER_FOUR : LOWER_TILES] = 1;
}
// 1111 1100 0011 1111
// 检测是否缺少12345
else if (!(rank_flag & 0xFC3F)) {
// no 6 ?
points_table[rank_flag & 0x0040 ? UPPER_FOUR : UPPER_TILES] = 1;
}
// 1111 1111 1000 1111
// 检测是否缺少2478
else if (!(rank_flag & 0xFF8F)) {
points_table[MIDDLE_TILES] = 1;
}
}
// 检测全带幺、全带五、全双刻
static void check_tiles_rank_by_set(const SET (&sets)[5], long (&points_table)[POINT_TYPE_COUNT]) {
int terminal_cnt = 0;
int honor_cnt = 0;
int _5_cnt = 0;
int even_pung_cnt = 0;
for (long i = 0; i < 5; ++i) {
if (is_set_contains_tile(sets[i], 0x11) ||
is_set_contains_tile(sets[i], 0x19) ||
is_set_contains_tile(sets[i], 0x21) ||
is_set_contains_tile(sets[i], 0x29) ||
is_set_contains_tile(sets[i], 0x31) ||
is_set_contains_tile(sets[i], 0x39)) {
++terminal_cnt;
}
else if (is_set_contains_tile(sets[i], 0x41) ||
is_set_contains_tile(sets[i], 0x42) ||
is_set_contains_tile(sets[i], 0x43) ||
is_set_contains_tile(sets[i], 0x44) ||
is_set_contains_tile(sets[i], 0x51) ||
is_set_contains_tile(sets[i], 0x52) ||
is_set_contains_tile(sets[i], 0x53)) {
++honor_cnt;
}
else if (is_set_contains_tile(sets[i], 0x15) ||
is_set_contains_tile(sets[i], 0x25) ||
is_set_contains_tile(sets[i], 0x35)) {
++_5_cnt;
}
else if (sets[i].set_type == SET_TYPE::PUNG ||
sets[i].set_type == SET_TYPE::KONG ||
sets[i].set_type == SET_TYPE::PAIR) {
if (is_numbered_suit_quick(sets[i].mid_tile) && sets[i].mid_tile % 2 == 0) {
++even_pung_cnt;
}
}
}
if (terminal_cnt + honor_cnt == 5) {
points_table[OUTSIDE_HAND] = 1;
}
else if (_5_cnt == 5) {
points_table[ALL_FIVE] = 1;
}
else if (even_pung_cnt == 5) {
points_table[ALL_EVEN_PUNGS] = 1;
}
}
// 检测断幺、推不倒、绿一色、清幺九、混幺九
static void check_tiles_traits(const TILE *tiles, long tile_cnt, long (&points_table)[POINT_TYPE_COUNT]) {
if (!std::any_of(tiles, tiles + tile_cnt, &is_terminal_or_honor)) {
points_table[ALL_SIMPLES] = 1;
}
if (std::all_of(tiles, tiles + tile_cnt, &is_reversible_tile)) {
points_table[REVERSIBLE_TILES] = 1;
}
#ifdef STRICT_98_RULE
if (points_table[SEVEN_PAIRS]) {
return;
}
#endif
if (std::all_of(tiles, tiles + tile_cnt, &is_green)) {
points_table[ALL_GREEN] = 1;
}
if (points_table[ALL_SIMPLES] != 0) {
return;
}
if (std::all_of(tiles, tiles + tile_cnt, &is_honor)) {
points_table[ALL_HONORS] = 1;
return;
}
if (std::all_of(tiles, tiles + tile_cnt, &is_terminal)) {
points_table[ALL_TERMINALS] = 1;
return;
}
if (std::all_of(tiles, tiles + tile_cnt, &is_terminal_or_honor)) {
points_table[ALL_TERMINALS_AND_HONORS] = 1;
}
}
// 检测四归一
static void check_tiles_hog(const TILE *tiles, long tile_cnt, long (&points_table)[POINT_TYPE_COUNT]) {
long kong_cnt = tile_cnt - 14;
int cnt_table[0x54] = { 0 };
for (long i = 0; i < tile_cnt; ++i) {
++cnt_table[tiles[i]];
}
long _4_cnt = std::count(std::begin(cnt_table), std::end(cnt_table), 4);
points_table[TILE_HOG] = _4_cnt - kong_cnt;
}
// 检测边坎钓
static void check_edge_closed_single_wait(const SET *concealed_sets, long set_cnt, TILE win_tile, long (&points_table)[POINT_TYPE_COUNT]) {
TILE concealed_tiles[14];
long concealed_tile_cnt;
recovery_tiles_from_sets(concealed_sets, set_cnt, concealed_tiles, &concealed_tile_cnt);
sort_tiles(concealed_tiles, concealed_tile_cnt);
copy_exclude(concealed_tiles, concealed_tiles + concealed_tile_cnt, &win_tile, (&win_tile) + 1, concealed_tiles);
bool waiting_table[6][10] = { { 0 } };
long waiting_cnt = 0;
TILE waiting_seven_pairs = 0;
switch (set_cnt) {
case 5:
is_basic_type_13_wait(concealed_tiles, waiting_table);
if (is_seven_pairs_wait((const TILE (&)[13])concealed_tiles, &waiting_seven_pairs)) {
waiting_table[tile_suit(waiting_seven_pairs)][tile_rank(waiting_seven_pairs)] = true;
}
break;
case 4:
is_basic_type_10_wait(concealed_tiles, waiting_table);
break;
case 3:
is_basic_type_7_wait(concealed_tiles, waiting_table);
break;
case 2:
is_basic_type_4_wait(concealed_tiles, waiting_table);
break;
case 1:
waiting_table[tile_suit(win_tile)][tile_rank(win_tile)] = true;
break;
default:
break;
}
for (int i = 1; i < 6; ++i) {
for (int j = 1; j < 10; ++j) {
if (waiting_table[i][j]) {
++waiting_cnt;
}
}
}
// 听牌数大于1张,或者是全求人,不计边坎钓
if (waiting_cnt != 1 || points_table[MELDED_HAND]) {
return;
}
bool maybe_edge = false;
bool maybe_closed = false;
bool maybe_single = false;
for (long i = 0; i < set_cnt; ++i) {
switch (concealed_sets[i].set_type) {
case SET_TYPE::CHOW:
if (concealed_sets[i].mid_tile == win_tile) {
maybe_closed = true;
}
else if (concealed_sets[i].mid_tile + 1 == win_tile
|| concealed_sets[i].mid_tile - 1 == win_tile) {
maybe_edge = true;
}
break;
case SET_TYPE::PAIR:
if (concealed_sets[i].mid_tile == win_tile) {
maybe_single = true;
}
break;
default:
break;
}
}
if (maybe_edge) {
points_table[EDGE_WAIT] = 1;
return;
}
if (maybe_closed) {
points_table[CLOSED_WAIT] = 1;
return;
}
if (maybe_single) {
points_table[SINGLE_WAIT] = 1;
return;
}
}
// 检测圈风刻、门风刻
static void check_wind_pungs(const SET &sets, WIND_TYPE prevalent_wind, WIND_TYPE seat_wind, long (&points_table)[POINT_TYPE_COUNT]) {
if (sets.set_type == SET_TYPE::PUNG || sets.set_type == SET_TYPE::KONG) {
RANK_TYPE delta = sets.mid_tile - 0x41;
if (delta == (int)prevalent_wind - (int)WIND_TYPE::EAST) {
points_table[PREVALENT_WIND] = 1;
}
if (delta == (int)seat_wind - (int)WIND_TYPE::EAST) {
points_table[SEAT_WIND] = 1;
}
}
}
// 统一校正
static void correction_points_table(long (&points_table)[POINT_TYPE_COUNT], bool prevalent_eq_seat) {
if (points_table[BIG_FOUR_WINDS]) {
points_table[BIG_THREE_WINDS] = 0;
points_table[ALL_PUNGS] = 0;
points_table[PREVALENT_WIND] = 0;
points_table[SEAT_WIND] = 0;
points_table[PUNG_OF_TERMINALS_OR_HONORS] = 0;
}
if (points_table[BIG_THREE_DRAGONS]) {
points_table[TWO_DRAGONS_PUNGS] = 0;
points_table[DRAGON_PUNG] = 0;
#ifdef STRICT_98_RULE
points_table[ONE_VOIDED_SUIT] = 0;
#endif
}
if (points_table[ALL_GREEN]) {
points_table[HALF_FLUSH] = 0;
points_table[ONE_VOIDED_SUIT] = 0;
}
if (points_table[NINE_GATES]) {
points_table[FULL_FLUSH] = 0;
points_table[CONCEALED_HAND] = 0;
--points_table[PUNG_OF_TERMINALS_OR_HONORS];
points_table[ONE_VOIDED_SUIT] = 0;
points_table[NO_HONORS] = 0;
if (points_table[FULLY_CONCEALED_HAND]) {
points_table[FULLY_CONCEALED_HAND] = 0;
points_table[SELF_DRAWN] = 1;
}
}
if (points_table[FOUR_KONGS]) {
points_table[SINGLE_WAIT] = 0;
}
if (points_table[SEVEN_SHIFTED_PAIRS]) {
points_table[SEVEN_PAIRS] = 0;
points_table[FULL_FLUSH] = 0;
points_table[CONCEALED_HAND] = 0;
points_table[ONE_VOIDED_SUIT] = 0;
points_table[NO_HONORS] = 0;
}
if (points_table[THIRTEEN_ORPHANS]) {
points_table[ALL_TYPES] = 0;
points_table[CONCEALED_HAND] = 0;
points_table[SINGLE_WAIT] = 0;
}
if (points_table[ALL_TERMINALS]) {
points_table[ALL_TERMINALS_AND_HONORS] = 0;
points_table[ALL_PUNGS] = 0;
points_table[OUTSIDE_HAND] = 0;
points_table[PUNG_OF_TERMINALS_OR_HONORS] = 0;
points_table[NO_HONORS] = 0;
#ifdef STRICT_98_RULE
points_table[TRIPLE_PUNG] = 0;
points_table[DOUBLE_PUNG] = 0;
#endif
}
if (points_table[LITTLE_FOUR_WINDS]) {
points_table[BIG_THREE_WINDS] = 0;
}
if (points_table[LITTLE_THREE_DRAGONS]) {
points_table[TWO_DRAGONS_PUNGS] = 0;
points_table[DRAGON_PUNG] = 0;
#ifdef STRICT_98_RULE
points_table[ONE_VOIDED_SUIT] = 0;
#endif
}
if (points_table[ALL_HONORS]) {
points_table[ALL_TERMINALS_AND_HONORS] = 0;
points_table[ALL_PUNGS] = 0;
points_table[OUTSIDE_HAND] = 0;
points_table[PUNG_OF_TERMINALS_OR_HONORS] = 0;
points_table[ONE_VOIDED_SUIT] = 0;
}
if (points_table[FOUR_CONCEALED_PUNGS]) {
points_table[ALL_PUNGS] = 0;
points_table[CONCEALED_HAND] = 0;
if (points_table[FULLY_CONCEALED_HAND]) {
points_table[FULLY_CONCEALED_HAND] = 0;
points_table[SELF_DRAWN] = 1;
}
}
if (points_table[PURE_TERMINAL_CHOWS]) {
points_table[SEVEN_PAIRS] = 0;
points_table[FULL_FLUSH] = 0;
points_table[ALL_CHOWS] = 0;
points_table[PURE_DOUBLE_CHOW] = 0;
points_table[TWO_TERMINAL_CHOWS] = 0;
points_table[ONE_VOIDED_SUIT] = 0;
points_table[NO_HONORS] = 0;
}
if (points_table[QUADRUPLE_CHOW]) {
points_table[PURE_SHIFTED_PUNGS] = 0;
points_table[TILE_HOG] = 0;
points_table[PURE_DOUBLE_CHOW] = 0;
#ifdef STRICT_98_RULE
points_table[ONE_VOIDED_SUIT] = 0;
#endif
}
if (points_table[FOUR_PURE_SHIFTED_PUNGS]) {
points_table[PURE_TRIPLE_CHOW] = 0;
points_table[ALL_PUNGS] = 0;
#ifdef STRICT_98_RULE
points_table[ONE_VOIDED_SUIT] = 0;
#endif
}
if (points_table[FOUR_PURE_SHIFTED_CHOWS]) {
points_table[TWO_TERMINAL_CHOWS] = 0;
points_table[SHORT_STRAIGHT] = 0;
#ifdef STRICT_98_RULE
points_table[ONE_VOIDED_SUIT] = 0;
#endif
}
if (points_table[ALL_TERMINALS_AND_HONORS]) {
points_table[ALL_PUNGS] = 0;
points_table[OUTSIDE_HAND] = 0;
points_table[PUNG_OF_TERMINALS_OR_HONORS] = 0;
}
if (points_table[SEVEN_PAIRS]) {
points_table[CONCEALED_HAND] = 0;
points_table[SINGLE_WAIT] = 0;
}
if (points_table[GREATER_HONORS_AND_KNITTED_TILES]) {
points_table[CONCEALED_HAND] = 0;
points_table[ALL_TYPES] = 0;
}
if (points_table[ALL_EVEN_PUNGS]) {
points_table[ALL_PUNGS] = 0;
points_table[ALL_SIMPLES] = 0;
points_table[NO_HONORS] = 0;
}
if (points_table[FULL_FLUSH]) {
points_table[ONE_VOIDED_SUIT] = 0;
points_table[NO_HONORS] = 0;
}
if (points_table[PURE_TRIPLE_CHOW]) {
points_table[PURE_SHIFTED_PUNGS] = 0;
points_table[PURE_DOUBLE_CHOW] = 0;
}
if (points_table[PURE_SHIFTED_PUNGS]) {
points_table[PURE_TRIPLE_CHOW] = 0;
}
if (points_table[UPPER_TILES]) {
points_table[UPPER_FOUR] = 0;
points_table[NO_HONORS] = 0;
}
if (points_table[MIDDLE_TILES]) {
points_table[ALL_SIMPLES] = 0;
points_table[NO_HONORS] = 0;
}
if (points_table[LOWER_TILES]) {
points_table[LOWER_FOUR] = 0;
points_table[NO_HONORS] = 0;
}
if (points_table[THREE_SUITED_TERMINAL_CHOWS]) {
points_table[ALL_CHOWS] = 0;
points_table[NO_HONORS] = 0;
points_table[MIXED_DOUBLE_CHOW] = 0;
points_table[TWO_TERMINAL_CHOWS] = 0;
}
if (points_table[ALL_FIVE]) {
points_table[ALL_SIMPLES] = 0;
points_table[NO_HONORS] = 0;
}
if (points_table[LESSER_HONORS_AND_KNITTED_TILES]) {
points_table[CONCEALED_HAND] = 0;
points_table[ALL_TYPES] = 0;
}
if (points_table[UPPER_FOUR]) {
points_table[NO_HONORS] = 0;
}
if (points_table[LOWER_FOUR]) {
points_table[NO_HONORS] = 0;
}
if (points_table[BIG_THREE_WINDS]) {
if (!points_table[ALL_HONORS] && !points_table[ALL_TERMINALS_AND_HONORS]) {
assert(points_table[PUNG_OF_TERMINALS_OR_HONORS] >= 3);
points_table[PUNG_OF_TERMINALS_OR_HONORS] -= 3;
}
#ifdef STRICT_98_RULE
points_table[ONE_VOIDED_SUIT] = 0;
#endif
}
if (points_table[REVERSIBLE_TILES]) {
points_table[ONE_VOIDED_SUIT] = 0;
}
if (points_table[LAST_TILE_DRAW]) {
points_table[SELF_DRAWN] = 0;
}
if (points_table[OUT_WITH_REPLACEMENT_TILE]) {
points_table[SELF_DRAWN] = 0;
}
if (points_table[ROBBING_THE_KONG]) {
points_table[LAST_TILE] = 0;
}
if (points_table[TWO_CONCEALED_KONGS]) {
points_table[CONCEALED_KONG] = 0;
}
if (points_table[HALF_FLUSH]) {
points_table[ONE_VOIDED_SUIT] = 0;
}
if (points_table[MELDED_HAND]) {
points_table[SINGLE_WAIT] = 0;
}
if (points_table[TWO_DRAGONS_PUNGS]) {
points_table[DRAGON_PUNG] = 0;
}
if (points_table[FULLY_CONCEALED_HAND]) {
points_table[SELF_DRAWN] = 0;
}
if (points_table[TWO_MELDED_KONGS]) {
points_table[MELDED_KONG] = 0;
}
if (points_table[PREVALENT_WIND]) {
if (!points_table[BIG_THREE_WINDS] && !points_table[LITTLE_FOUR_WINDS]
&& !points_table[ALL_HONORS] && !points_table[ALL_TERMINALS_AND_HONORS]) {
assert(points_table[PUNG_OF_TERMINALS_OR_HONORS] > 0);
--points_table[PUNG_OF_TERMINALS_OR_HONORS];
}
}
if (points_table[SEAT_WIND]) {
if (!prevalent_eq_seat && !points_table[BIG_THREE_WINDS] && !points_table[LITTLE_FOUR_WINDS]
&& !points_table[ALL_HONORS] && !points_table[ALL_TERMINALS_AND_HONORS]) {
assert(points_table[PUNG_OF_TERMINALS_OR_HONORS] > 0);
--points_table[PUNG_OF_TERMINALS_OR_HONORS];
}
}
if (points_table[ALL_CHOWS]) {
points_table[NO_HONORS] = 0;
}
if (points_table[ALL_SIMPLES]) {
points_table[NO_HONORS] = 0;
}
}
static void check_win_type(WIN_TYPE win_type, long (&points_table)[POINT_TYPE_COUNT]) {
if (win_type & WIN_TYPE_4TH_TILE) {
points_table[LAST_TILE] = 1;
}
if (win_type & WIN_TYPE_WALL_LAST) {
points_table[win_type & WIN_TYPE_SELF_DRAWN ? LAST_TILE_DRAW : LAST_TILE_CLAIM] = 1;
}
if (win_type & WIN_TYPE_ABOUT_KONG) {
points_table[win_type & WIN_TYPE_SELF_DRAWN ? OUT_WITH_REPLACEMENT_TILE : ROBBING_THE_KONG] = 1;
}
if (win_type & WIN_TYPE_SELF_DRAWN) {
points_table[SELF_DRAWN] = 1;
}
}
static void calculate_basic_type_points(const SET (&sets)[5], long fixed_cnt, TILE win_tile, WIN_TYPE win_type,
WIND_TYPE prevalent_wind, WIND_TYPE seat_wind, long (&points_table)[POINT_TYPE_COUNT]) {
SET pair_set;
SET chow_sets[4];
SET pung_sets[4];
long chow_cnt = 0;
long pung_cnt = 0;
for (long i = 0; i < 5; ++i) {
switch (sets[i].set_type) {
case SET_TYPE::CHOW: chow_sets[chow_cnt++] = sets[i]; break;
case SET_TYPE::PUNG:
case SET_TYPE::KONG: pung_sets[pung_cnt++] = sets[i]; break;
case SET_TYPE::PAIR: pair_set = sets[i]; break;
default: assert(0); break;
}
}
TILE tiles[18];
long tile_cnt = 0;
recovery_tiles_from_sets(sets, 5, tiles, &tile_cnt);
if (fixed_cnt == 0 && tile_cnt == 14) {
if (is_nine_gates(tiles, win_tile)) {
points_table[NINE_GATES] = 1;
}
}
check_win_type(win_type, points_table);
// 点和的明刻
if ((win_type & WIN_TYPE_SELF_DRAWN) == 0) {
if (std::none_of(chow_sets, chow_sets + chow_cnt, [win_tile](const SET &chow_set) {
return (chow_set.mid_tile - 1 == win_tile || chow_set.mid_tile == win_tile || chow_set.mid_tile + 1 == win_tile);
})) {
for (long i = 0; i < pung_cnt; ++i) {
if (pung_sets[i].mid_tile == win_tile && !pung_sets[i].is_melded) {
pung_sets[i].is_melded = true;
}
}
}
}
switch (chow_cnt) {
case 4:
if (is_pure_terminal_chows(chow_sets, pair_set)) {
points_table[PURE_TERMINAL_CHOWS] = 1;
break;
}
if (is_three_suited_terminal_chows(chow_sets, pair_set)) {
points_table[THREE_SUITED_TERMINAL_CHOWS] = 1;
break;
}
calculate_4_chows(chow_sets, points_table);
break;
case 3:
calculate_3_chows(chow_sets, points_table);
calculate_1_pung(pung_sets[0], points_table);
break;
case 2:
calculate_2_chows(chow_sets, points_table);
calculate_2_pungs(pung_sets, points_table);
break;
case 1:
calculate_3_pungs(pung_sets, points_table);
break;
case 0:
calculate_4_pungs(pung_sets, points_table);
break;
default:
break;
}
check_melded_or_concealed_hand(sets, fixed_cnt, win_type & WIN_TYPE_SELF_DRAWN, points_table);
check_pair_tile(pair_set.mid_tile, chow_cnt, points_table);
check_tiles_rank_by_set(sets, points_table);
check_tiles_suits(tiles, tile_cnt, points_table);
check_tiles_traits(tiles, tile_cnt, points_table);
check_tiles_rank_range(tiles, tile_cnt, points_table);
check_tiles_hog(tiles, tile_cnt, points_table);
check_edge_closed_single_wait(sets + fixed_cnt, 5 - fixed_cnt, win_tile, points_table);
for (int i = 0; i < 5; ++i) {
check_wind_pungs(sets[i], prevalent_wind, seat_wind, points_table);
}
correction_points_table(points_table, prevalent_wind == seat_wind);
if (std::all_of(std::begin(points_table), std::end(points_table), [](int p) { return p == 0; })) {
points_table[CHICKEN_HAND] = 1;
}
}
static bool calculate_special_type_points(const TILE (&concealed_tiles)[14], WIN_TYPE win_type, long (&points_table)[POINT_TYPE_COUNT]) {
if (concealed_tiles[0] == concealed_tiles[1]
&& concealed_tiles[2] == concealed_tiles[3]
&& concealed_tiles[4] == concealed_tiles[5]
&& concealed_tiles[6] == concealed_tiles[7]
&& concealed_tiles[8] == concealed_tiles[9]
&& concealed_tiles[10] == concealed_tiles[11]
&& concealed_tiles[12] == concealed_tiles[13]) {
if (concealed_tiles[0] + 1 == concealed_tiles[2]
&& concealed_tiles[2] + 1 == concealed_tiles[4]
&& concealed_tiles[4] + 1 == concealed_tiles[6]
&& concealed_tiles[6] + 1 == concealed_tiles[8]
&& concealed_tiles[8] + 1 == concealed_tiles[10]
&& concealed_tiles[10] + 1 == concealed_tiles[12]) {
points_table[SEVEN_SHIFTED_PAIRS] = 1;
check_tiles_traits(concealed_tiles, 14, points_table);
}
else {
points_table[SEVEN_PAIRS] = 1;
check_tiles_suits(concealed_tiles, 14, points_table);
check_tiles_traits(concealed_tiles, 14, points_table);
check_tiles_rank_range(concealed_tiles, 14, points_table);
check_tiles_hog(concealed_tiles, 14, points_table);
}
}
else if (std::includes(std::begin(concealed_tiles), std::end(concealed_tiles),
std::begin(standard_thirteen_orphans), std::end(standard_thirteen_orphans))) {
points_table[THIRTEEN_ORPHANS] = 1;
}
else {
const TILE *it = std::find_if(std::begin(concealed_tiles), std::end(concealed_tiles), &is_honor);
long numbered_cnt = it - concealed_tiles;
// 序数牌张数大于9或者小于7必然不可能是全不靠
if (numbered_cnt > 9 || numbered_cnt < 7) {
return false;
}
const TILE *matched_seq = nullptr;
for (int i = 0; i < 6; ++i) {
if (std::includes(std::begin(standard_knitted_straight[i]), std::end(standard_knitted_straight[i]),
std::begin(concealed_tiles), it)) {
matched_seq = standard_knitted_straight[i]; // 匹配到一个组合龙
break;
}
}
if (matched_seq == nullptr) {
return false;
}
// standard_thirteen_orphans + 6是字牌,即ESWNCFP
if (numbered_cnt == 7 && memcmp(standard_thirteen_orphans + 6, concealed_tiles + 7, 7 * sizeof(TILE)) == 0) {
points_table[GREATER_HONORS_AND_KNITTED_TILES] = 1;
}
else if (std::includes(standard_thirteen_orphans + 6, standard_thirteen_orphans + 13, it, std::end(concealed_tiles))) {
points_table[LESSER_HONORS_AND_KNITTED_TILES] = 1;
if (numbered_cnt == 9) {
points_table[KNITTED_STRAIGHT] = 1;
}
}
}
check_win_type(win_type, points_table);
correction_points_table(points_table, false);
return true;
}
static bool calculate_knitted_straight_in_basic_type_points(SET &fourth_set, const TILE *concealed_tiles, long concealed_cnt,
TILE win_tile, WIN_TYPE win_type, WIND_TYPE prevalent_wind, WIND_TYPE seat_wind, long (&points_table)[POINT_TYPE_COUNT]) {
assert(concealed_cnt == 14 || concealed_cnt == 11);
const TILE *matched_seq = nullptr;
for (int i = 0; i < 6; ++i) {
if (std::includes(concealed_tiles, concealed_tiles + concealed_cnt,
std::begin(standard_knitted_straight[i]), std::end(standard_knitted_straight[i]))) {
matched_seq = standard_knitted_straight[i]; // 匹配到一个组合龙
break;
}
}
if (matched_seq == nullptr) {
return false;
}
TILE pair_tile = 0;
TILE remains[5];
TILE *end = copy_exclude(concealed_tiles, concealed_tiles + concealed_cnt, matched_seq, matched_seq + 9, remains);
long remain_cnt = end - remains;
if (remain_cnt == 5) { // 如果第4组面子是手上的,那么手牌去除组合龙后会剩下14-9=5张,这5张包含一组面子和一对将
TILE *it = std::adjacent_find(std::begin(remains), std::end(remains)); // 将牌
while (it != std::end(remains)) {
pair_tile = *it; // 记录将(平和判断要用到)
TILE pair[2] = { pair_tile, pair_tile };
TILE temp[3]; // 去除将牌后余下3张
copy_exclude(std::begin(remains), std::end(remains), std::begin(pair), std::end(pair), temp);
if (is_chow(temp[0], temp[1], temp[2])) { // 去除将牌后余下3张是顺子
fourth_set.is_melded = false;
fourth_set.mid_tile = temp[1];
fourth_set.set_type = SET_TYPE::CHOW;
break;
}
else if (is_pung(temp[0], temp[1], temp[2])) { // 去除将牌后余下3张是刻子
fourth_set.is_melded = false;
fourth_set.mid_tile = temp[1];
fourth_set.set_type = SET_TYPE::PUNG;
break;
}
// 去除将牌后余下3张不能组成面子
do ++it; while (it != std::end(remains) && *it == pair_tile);
it = std::adjacent_find(it, std::end(remains));
pair_tile = 0;
}
if (pair_tile == 0) {
return false;
}
}
else {
// 如果第4组面子是吃碰杠的,那么手牌去除组合龙后会剩下11-9=2张,这2张必然是一对将
assert(remain_cnt == 2);
if (remains[0] != remains[1]) {
return false;
}
pair_tile = remains[0];
if (fourth_set.set_type != SET_TYPE::CHOW
&& fourth_set.set_type != SET_TYPE::PUNG
&& fourth_set.set_type != SET_TYPE::KONG) {
return false;
}
}
points_table[KNITTED_STRAIGHT] = 1;
if (fourth_set.set_type == SET_TYPE::CHOW) {
if (is_numbered_suit_quick(pair_tile)) {
points_table[ALL_CHOWS] = 1;
}
}
else {
POINT_TYPE points = get_1_pung_points(fourth_set.mid_tile);
if (points != NONE) {
++points_table[points];
}
}
check_win_type(win_type, points_table);
if (win_type & WIN_TYPE_SELF_DRAWN) {
points_table[FULLY_CONCEALED_HAND] = 1;
}
else {
points_table[CONCEALED_HAND] = 1;
}
check_tiles_suits(concealed_tiles, 14, points_table);
check_tiles_traits(concealed_tiles, 14, points_table);
check_tiles_rank_range(concealed_tiles, 14, points_table);
check_tiles_hog(concealed_tiles, 14, points_table);
// 和组合龙范围的牌,不算边坎钓
if (std::find(matched_seq, matched_seq + 9, win_tile) == matched_seq + 9) {
if (remain_cnt == 5) {
SET sets[2];
sets[0].is_melded = fourth_set.is_melded;
sets[0].set_type = fourth_set.set_type;
sets[0].mid_tile = fourth_set.mid_tile;
sets[1].is_melded = false;
sets[1].set_type = SET_TYPE::PAIR;
sets[1].mid_tile = pair_tile;
check_edge_closed_single_wait(sets, 2, win_tile, points_table);
}
else {
assert(remain_cnt == 2);
points_table[SINGLE_WAIT] = 1;
}
}
check_wind_pungs(fourth_set, prevalent_wind, seat_wind, points_table);
correction_points_table(points_table, prevalent_wind == seat_wind);
return true;
}
static int get_points_by_table(const long (&points_table)[POINT_TYPE_COUNT]) {
int points = 0;
for (int i = 1; i < FLOWER_TILES; ++i) {
if (points_table[i] == 0) {
continue;
}
points += points_value_table[i] * points_table[i];
if (points_table[i] == 1) {
printf("%s %d\n", points_name[i], points_value_table[i]);
}
else {
printf("%s %d*%ld\n", points_name[i], points_value_table[i], points_table[i]);
}
}
return points;
}
const char *parse_tiles(const char *str, TILE *tiles, long *out_tile_cnt) {
//std::regex reg("[1-9]+[mps]|[ESWNCFP]");
//if (std::regex_match(str, reg)) {
// std::cout << "cannot parse the string" << std::endl;
// return;
//}
long tile_cnt = 0;
TILE temp[14];
long temp_cnt = 0;
const char *p = str;
for (; temp_cnt < 14 && tile_cnt < 14 && *p != '\0'; ++p) {
char c = *p;
switch (c) {
case '1': temp[temp_cnt++] = 1; break;
case '2': temp[temp_cnt++] = 2; break;
case '3': temp[temp_cnt++] = 3; break;
case '4': temp[temp_cnt++] = 4; break;
case '5': temp[temp_cnt++] = 5; break;
case '6': temp[temp_cnt++] = 6; break;
case '7': temp[temp_cnt++] = 7; break;
case '8': temp[temp_cnt++] = 8; break;
case '9': temp[temp_cnt++] = 9; break;
case 'm':
for (long i = 0; i < temp_cnt && tile_cnt < 14; ++i) {
tiles[tile_cnt++] = temp[i] | 0x10;
}
temp_cnt = 0;
break;
case 's':
for (long i = 0; i < temp_cnt && tile_cnt < 14; ++i) {
tiles[tile_cnt++] = temp[i] | 0x20;
}
temp_cnt = 0;
break;
case 'p':
for (long i = 0; i < temp_cnt && tile_cnt < 14; ++i) {
tiles[tile_cnt++] = temp[i] | 0x30;
}
temp_cnt = 0;
break;
case 'E': tiles[tile_cnt++] = 0x41; break;
case 'S': tiles[tile_cnt++] = 0x42; break;
case 'W': tiles[tile_cnt++] = 0x43; break;
case 'N': tiles[tile_cnt++] = 0x44; break;
case 'C': tiles[tile_cnt++] = 0x51; break;
case 'F': tiles[tile_cnt++] = 0x52; break;
case 'P': tiles[tile_cnt++] = 0x53; break;
default: goto end;
}
}
end:
if (temp_cnt != 0) {
puts("Expect m/s/p to finish a series of numbers");
return nullptr;
}
if (out_tile_cnt != nullptr) {
*out_tile_cnt = tile_cnt;
}
return p;
}
bool string_to_tiles(const char *str, SET *fixed_sets, long *fixed_set_cnt, TILE *concealed_tiles, long *concealed_cnt) {
SET sets[5];
long set_cnt = 0;
bool has_fixed_set = false, is_concealed_kong = false;
TILE tiles[14];
long tile_cnt = 0;
const char *p = str;
while (char c = *p) {
const char *q;
switch (c) {
case '[':
q = ++p;
is_concealed_kong = false;
has_fixed_set = true;
break;
case ']':
if (!has_fixed_set) {
puts("Closing bracket ] does not match");
return false;
}
if (tile_cnt != 3 && tile_cnt != 4) {
puts("Only 3 or 4 tiles allowed in a fixed set between [ ]");
return false;
}
if (tile_cnt == 3) {
if (is_concealed_kong) {
puts("Concealed kong need 4 same tiles");
return false;
}
if (tiles[0] + 1 == tiles[1] && tiles[1] + 1 == tiles[2]) {
sets[set_cnt].mid_tile = tiles[1];
sets[set_cnt].set_type = SET_TYPE::CHOW;
sets[set_cnt].is_melded = true;
}
else if (tiles[0] == tiles[1] && tiles[1] == tiles[2]) {
sets[set_cnt].mid_tile = tiles[1];
sets[set_cnt].set_type = SET_TYPE::PUNG;
sets[set_cnt].is_melded = true;
}
else {
puts("Cannot make a chow or pung");
return false;
}
}
else {
if (tiles[0] != tiles[1] || tiles[1] != tiles[2] || tiles[2] != tiles[3]) {
puts("Kong need 4 same tiles");
}
sets[set_cnt].mid_tile = tiles[0];
sets[set_cnt].set_type = SET_TYPE::KONG;
sets[set_cnt].is_melded = true;
}
q = ++p;
has_fixed_set = false;
++set_cnt;
tile_cnt = 0;
break;
case '{':
q = ++p;
is_concealed_kong = true;
has_fixed_set = true;
break;
case '}':
if (!has_fixed_set) {
puts("Closing bracket } does not match");
return false;
}
if (!is_concealed_kong) {
puts("{} is only for concealed kong");
return false;
}
if (tile_cnt != 4) {
puts("Concealed kong need 4 same tiles");
return false;
}
q = ++p;
sets[set_cnt].mid_tile = tiles[0];
sets[set_cnt].set_type = SET_TYPE::KONG;
sets[set_cnt].is_melded = false;
has_fixed_set = false;
++set_cnt;
tile_cnt = 0;
break;
default:
q = parse_tiles(p, tiles, &tile_cnt);
if (q == p || q == nullptr) {
puts("Unexpect character");
return false;
}
break;
}
p = q;
}
if (has_fixed_set) {
puts("Expect closing bracket!");
return false;
}
//for (long i = 0; i < set_cnt; ++i) {
// printf("[%d %s %x] ", sets[i].is_melded, set_type_name[(int)sets[i].set_type], sets[i].mid_tile);
//}
//for (long i = 0; i < tile_cnt; ++i) {
// printf("%x ", tiles[i]);
//}
//puts("");
if (fixed_sets != nullptr) {
memcpy(fixed_sets, sets, set_cnt * sizeof(SET));
}
if (fixed_set_cnt != nullptr) {
*fixed_set_cnt = set_cnt;
}
memcpy(concealed_tiles, tiles, tile_cnt * sizeof(TILE));
if (concealed_cnt != nullptr) {
*concealed_cnt = tile_cnt;
}
return true;
}
int calculate_points(const SET *fixed_set, long fixed_cnt, const TILE *concealed_tiles, long concealed_cnt, TILE win_tile, WIN_TYPE win_type,
WIND_TYPE prevalent_wind, WIND_TYPE seat_wind, long (&points_table)[POINT_TYPE_COUNT]) {
if (fixed_set == nullptr) {
fixed_cnt = 0;
}
if (concealed_tiles == nullptr || concealed_cnt <= 0 || fixed_cnt < 0 || fixed_cnt > 4
|| fixed_cnt * 3 + concealed_cnt != 13) {
return ERROR_WRONG_TILES_COUNT;
}
TILE _concealed_tiles[14];
SET _separation_sets[MAX_SEPARAION_CNT][5];
long _separation_cnt;
// 合并得到14张牌
memcpy(_concealed_tiles, concealed_tiles, sizeof(TILE) * concealed_cnt);
_concealed_tiles[concealed_cnt] = win_tile;
sort_tiles(_concealed_tiles, concealed_cnt + 1);
memcpy(_separation_sets[0], fixed_set, fixed_cnt * sizeof(SET));
for (long i = 0; i < fixed_cnt; ++i) {
if (fixed_set[i].set_type != SET_TYPE::KONG) {
_separation_sets[0][i].is_melded = true;
}
}
_separation_cnt = 0;
seperate_N(_concealed_tiles, concealed_cnt + 1, fixed_cnt, _separation_sets, &_separation_cnt);
for (long i = 0; i < _separation_cnt; ++i) {
std::sort(&_separation_sets[i][fixed_cnt], &_separation_sets[i][4], &set_cmp);
}
long points_tables[MAX_SEPARAION_CNT][POINT_TYPE_COUNT] = { 0 };
int max_points = 0;
long max_idx = -1;
if (fixed_cnt == 0) { // 门清状态,有可能是基本和型组合龙
if (calculate_knitted_straight_in_basic_type_points(_separation_sets[_separation_cnt][0], _concealed_tiles, 14,
win_tile, win_type, prevalent_wind, seat_wind, points_tables[_separation_cnt])) {
int current_points = get_points_by_table(points_tables[_separation_cnt]);
if (current_points > max_points) {
max_points = current_points;
max_idx = _separation_cnt;
}
printf("points = %d\n\n", current_points);
}
else if (calculate_special_type_points(_concealed_tiles, win_type, points_tables[_separation_cnt])) {
int current_points = get_points_by_table(points_tables[_separation_cnt]);
if (current_points > max_points) {
max_points = current_points;
max_idx = _separation_cnt;
}
printf("points = %d\n\n", current_points);
if (points_tables[_separation_cnt][SEVEN_SHIFTED_PAIRS]) {
_separation_cnt = 0;
}
}
}
else if (fixed_cnt == 1 && _separation_cnt == 0) {
// 1副露状态,有可能是基本和型组合龙
if (calculate_knitted_straight_in_basic_type_points(_separation_sets[0][0], _concealed_tiles, 14,
win_tile, win_type, prevalent_wind, seat_wind, points_tables[0])) {
int current_points = get_points_by_table(points_tables[0]);
if (current_points > max_points) {
max_points = current_points;
max_idx = _separation_cnt;
}
printf("points = %d\n\n", current_points);
}
}
// 遍历各种划分方式,分别算番,找出最大的番的划分方式
for (long i = 0; i < _separation_cnt; ++i) {
for (int j = 0; j < 5; ++j) {
//printf("[%d %s %x]", _separation_sets[i][j].is_melded,
// set_type_name[(int)_separation_sets[i][j].set_type], _separation_sets[i][j].mid_tile);
TILE mid_tile = _separation_sets[i][j].mid_tile;
switch (_separation_sets[i][j].set_type) {
case SET_TYPE::CHOW:
printf(_separation_sets[i][j].is_melded ? "[%s%s%s]" : "{%s%s%s}",
stringify_table[mid_tile - 1], stringify_table[mid_tile], stringify_table[mid_tile + 1]);
break;
case SET_TYPE::PUNG:
printf(_separation_sets[i][j].is_melded ? "[%s%s%s]" : "{%s%s%s}",
stringify_table[mid_tile], stringify_table[mid_tile], stringify_table[mid_tile]);
break;
case SET_TYPE::KONG:
printf(_separation_sets[i][j].is_melded ? "[%s%s%s%s]" : "{%s%s%s%s}",
stringify_table[mid_tile], stringify_table[mid_tile], stringify_table[mid_tile], stringify_table[mid_tile]);
break;
case SET_TYPE::PAIR:
printf(_separation_sets[i][j].is_melded ? "[%s%s]" : "{%s%s}",
stringify_table[mid_tile], stringify_table[mid_tile]);
break;
default:
break;
}
}
puts("");
calculate_basic_type_points(_separation_sets[i], fixed_cnt, win_tile, win_type, prevalent_wind, seat_wind, points_tables[i]);
int current_points = get_points_by_table(points_tables[i]);
if (current_points > max_points) {
max_points = current_points;
max_idx = i;
}
printf("points = %d\n\n", current_points);
}
if (max_idx == -1) {
return ERROR_NOT_WIN;
}
memcpy(points_table, points_tables[max_idx], sizeof(points_table));
return max_points;
}
}
修复暗刻计算错误的bug
#include "points_calculator.h"
#include "wait_and_win_test.h"
#include <assert.h>
#include <stddef.h>
#include <string.h>
//#define STRICT_98_RULE
namespace mahjong {
static bool seperate_2(const TILE *tiles, long tile_cnt, long fixed_set_cnt, SET (*output_sets)[5], long *separation_cnt) {
if (tile_cnt == 2 && tiles[0] == tiles[1]) { // 划分成功
// 这2张作为将
output_sets[*separation_cnt][4].is_melded = false;
output_sets[*separation_cnt][4].mid_tile = tiles[0];
output_sets[*separation_cnt][4].set_type = SET_TYPE::PAIR;
// 拷贝一份当前的划分出来的面子,并排序
SET temp[5];
memcpy(temp, output_sets[*separation_cnt], 5 * sizeof(SET));
std::sort(temp + fixed_set_cnt, temp + 4, &set_cmp);
// 检查这种划分是否已经存在了
bool has_found = false;
long i = *separation_cnt;
while (i--) {
if (std::equal(std::begin(temp), std::end(temp), output_sets[i], [](const SET &set1, const SET &set2) {
return set1.mid_tile == set2.mid_tile && set1.set_type == set2.set_type;
})) {
has_found = true;
break;
}
}
if (!has_found) {
// 如果不存在,那么得到一种新的划分
memcpy(output_sets[*separation_cnt + 1], output_sets[*separation_cnt], 5 * sizeof(SET));
++(*separation_cnt);
}
return true;
}
return false;
}
static bool seperate_N(const TILE *tiles, long tile_cnt, long fixed_set_cnt, SET (*output_sets)[5], long *separation_cnt) {
if (tile_cnt < 3) {
return seperate_2(tiles, tile_cnt, fixed_set_cnt, output_sets, separation_cnt);
}
bool ret = false;
long i = 0;
while (i < tile_cnt) {
TILE tile_i = tiles[i];
long j = i + 1;
while (j < tile_cnt) {
TILE tile_j = tiles[j];
if (tile_j - tile_i >= 3) break; // 这已经不可能再构成面子了
long k = j + 1;
while (k < tile_cnt) {
TILE tile_k = tiles[k];
if (tile_k - tile_i >= 3) break; // 这已经不可能再构成面子了
if (is_concealed_set_completed(tile_i, tile_j, tile_k)) {
long current = (14 - tile_cnt) / 3;
output_sets[*separation_cnt][current].is_melded = false;
output_sets[*separation_cnt][current].mid_tile = tile_j;
output_sets[*separation_cnt][current].set_type = (tile_i == tile_j) ? SET_TYPE::PUNG : SET_TYPE::CHOW;
// 削减面子
TILE remains[14];
for (int n = 0, c = 0; n < tile_cnt; ++n) {
if (n == i || n == j || n == k) {
continue;
}
remains[c++] = tiles[n];
}
// 递归
if (seperate_N(remains, tile_cnt - 3, fixed_set_cnt, output_sets, separation_cnt)) {
ret = true;
}
}
do ++k; while (k < tile_cnt && tiles[k] == tile_k); // 快速跳过相同的case
}
do ++j; while (j < tile_cnt && tiles[j] == tile_j); // 快速跳过相同的case
}
do ++i; while (i < tile_cnt && tiles[i] == tile_i); // 快速跳过相同的case
}
return ret;
}
// 从一组一组的牌恢复成一张一张的牌
void recovery_tiles_from_sets(const SET *sets, long set_cnt, TILE *tiles, long *tile_cnt) {
assert(tiles != nullptr && tile_cnt != nullptr);
*tile_cnt = 0;
for (int i = 0; i < set_cnt; ++i) {
switch (sets[i].set_type) {
case SET_TYPE::CHOW:
tiles[(*tile_cnt)++] = sets[i].mid_tile - 1;
tiles[(*tile_cnt)++] = sets[i].mid_tile;
tiles[(*tile_cnt)++] = sets[i].mid_tile + 1;
break;
case SET_TYPE::PUNG:
tiles[(*tile_cnt)++] = sets[i].mid_tile;
tiles[(*tile_cnt)++] = sets[i].mid_tile;
tiles[(*tile_cnt)++] = sets[i].mid_tile;
break;
case SET_TYPE::KONG:
tiles[(*tile_cnt)++] = sets[i].mid_tile;
tiles[(*tile_cnt)++] = sets[i].mid_tile;
tiles[(*tile_cnt)++] = sets[i].mid_tile;
tiles[(*tile_cnt)++] = sets[i].mid_tile;
break;
case SET_TYPE::PAIR:
tiles[(*tile_cnt)++] = sets[i].mid_tile;
tiles[(*tile_cnt)++] = sets[i].mid_tile;
break;
default:
assert(0);
break;
}
}
}
// 一色四同顺
static bool is_quadruple_chow(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2, TILE mid_tile3) {
return (mid_tile0 == mid_tile1 && mid_tile0 == mid_tile2 && mid_tile0 == mid_tile3);
}
// 一色四节高
static bool is_four_pure_shifted_pungs(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2, TILE mid_tile3) {
if (is_numbered_suit_quick(mid_tile0)) {
return (mid_tile0 + 1 == mid_tile1 && mid_tile1 + 1 == mid_tile2 && mid_tile2 + 1 == mid_tile3);
}
return false;
}
// 一色四步高
static bool is_four_pure_shifted_chows(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2, TILE mid_tile3) {
// 递增2的必然是:123 345 567 789
// 递增1的最小为:123 234 345 456 最大为:456 567 678 789
return ((mid_tile0 + 2 == mid_tile1 && mid_tile1 + 2 == mid_tile2 && mid_tile2 + 2 == mid_tile3)
|| (mid_tile0 + 1 == mid_tile1 && mid_tile1 + 1 == mid_tile2 && mid_tile2 + 1 == mid_tile3));
}
// 一色三同顺
static bool is_pure_triple_chow(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2) {
return (mid_tile0 == mid_tile1 && mid_tile0 == mid_tile2);
}
// 一色三节高
static bool is_pure_shifted_pungs(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2) {
if (is_numbered_suit_quick(mid_tile0)) {
return (mid_tile0 + 1 == mid_tile1 && mid_tile1 + 1 == mid_tile2);
}
return false;
}
// 清龙
static bool is_pure_straight(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2) {
if (tile_rank(mid_tile0) == 2) {
return (mid_tile0 + 3 == mid_tile1 && mid_tile1 + 3 == mid_tile2);
}
return false;
}
// 一色三步高
static bool is_pure_shifted_chows(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2) {
return ((mid_tile0 + 2 == mid_tile1 && mid_tile1 + 2 == mid_tile2)
|| (mid_tile0 + 1 == mid_tile1 && mid_tile1 + 1 == mid_tile2));
}
// 花龙
static bool is_mixed_straight(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2) {
SUIT_TYPE suit0 = tile_suit(mid_tile0);
SUIT_TYPE suit1 = tile_suit(mid_tile1);
SUIT_TYPE suit2 = tile_suit(mid_tile2);
if (suit0 != suit1 && suit0 != suit2 && suit1 != suit2) {
RANK_TYPE rank0 = tile_rank(mid_tile0);
RANK_TYPE rank1 = tile_rank(mid_tile1);
RANK_TYPE rank2 = tile_rank(mid_tile2);
return ((rank0 == 2 && rank1 == 5 && rank2 == 8)
|| (rank0 == 2 && rank1 == 8 && rank2 == 5)
|| (rank0 == 5 && rank1 == 2 && rank2 == 8)
|| (rank0 == 5 && rank1 == 8 && rank2 == 2)
|| (rank0 == 8 && rank1 == 2 && rank2 == 5)
|| (rank0 == 8 && rank1 == 5 && rank2 == 2));
}
return false;
}
// 三色三同顺或者三同刻
static bool is_mixed_triple_chow_or_pung(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2) {
if (!is_numbered_suit_quick(mid_tile0) || !is_numbered_suit_quick(mid_tile1) || !is_numbered_suit_quick(mid_tile2)) {
return false;
}
SUIT_TYPE suit0 = tile_suit(mid_tile0);
SUIT_TYPE suit1 = tile_suit(mid_tile1);
SUIT_TYPE suit2 = tile_suit(mid_tile2);
if (suit0 != suit1 && suit0 != suit2 && suit1 != suit2) {
RANK_TYPE rank0 = tile_rank(mid_tile0);
RANK_TYPE rank1 = tile_rank(mid_tile1);
RANK_TYPE rank2 = tile_rank(mid_tile2);
return (rank0 == rank1 && rank0 == rank2);
}
return false;
}
// 三色三节高或者三色三步高
static bool is_mixed_shifted_chow_or_pung(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2) {
if (!is_numbered_suit_quick(mid_tile0) || !is_numbered_suit_quick(mid_tile1) || !is_numbered_suit_quick(mid_tile2)) {
return false;
}
SUIT_TYPE suit0 = tile_suit(mid_tile0);
SUIT_TYPE suit1 = tile_suit(mid_tile1);
SUIT_TYPE suit2 = tile_suit(mid_tile2);
if (suit0 != suit1 && suit0 != suit2 && suit1 != suit2) {
RANK_TYPE rank0 = tile_rank(mid_tile0);
RANK_TYPE rank1 = tile_rank(mid_tile1);
RANK_TYPE rank2 = tile_rank(mid_tile2);
return ((rank1 + 1 == rank0 && rank0 + 1 == rank2)
|| (rank2 + 1 == rank0 && rank0 + 1 == rank1)
|| (rank0 + 1 == rank1 && rank1 + 1 == rank2)
|| (rank2 + 1 == rank1 && rank1 + 1 == rank0)
|| (rank0 + 1 == rank2 && rank2 + 1 == rank1)
|| (rank1 + 1 == rank2 && rank2 + 1 == rank0));
}
return false;
}
// 一般高
static bool is_pure_double_chow(TILE mid_tile0, TILE mid_tile1) {
return mid_tile0 == mid_tile1;
}
// 喜相逢
static bool is_mixed_double_chow(TILE mid_tile0, TILE mid_tile1) {
return (is_rank_equal_quick(mid_tile0, mid_tile1) && !is_suit_equal_quick(mid_tile0, mid_tile1));
}
// 连六
static bool is_short_straight(TILE mid_tile0, TILE mid_tile1) {
return (mid_tile0 + 3 == mid_tile1 || mid_tile1 + 3 == mid_tile0);
}
// 老少副
static bool is_two_terminal_chows(TILE mid_tile0, TILE mid_tile1) {
if (is_suit_equal_quick(mid_tile0, mid_tile1)) {
RANK_TYPE rank0 = tile_rank(mid_tile0);
RANK_TYPE rank1 = tile_rank(mid_tile1);
return ((rank0 == 2 && rank1 == 8) || (rank0 == 8 && rank1 == 2));
}
return false;
}
// 4组顺子的番
static POINT_TYPE get_4_chows_points(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2, TILE mid_tile3) {
if (is_quadruple_chow(mid_tile0, mid_tile1, mid_tile2, mid_tile3)) {
return QUADRUPLE_CHOW;
}
if (is_four_pure_shifted_chows(mid_tile0, mid_tile1, mid_tile2, mid_tile3)) {
return FOUR_PURE_SHIFTED_CHOWS;
}
return NONE;
}
// 3组顺子的番
static POINT_TYPE get_3_chows_points(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2) {
if (is_mixed_shifted_chow_or_pung(mid_tile0, mid_tile1, mid_tile2)) {
return MIXED_SHIFTED_CHOWS;
}
if (is_mixed_straight(mid_tile0, mid_tile1, mid_tile2)) {
return MIXED_STRAIGHT;
}
if (is_mixed_triple_chow_or_pung(mid_tile0, mid_tile1, mid_tile2)) {
return MIXED_TRIPLE_CHOW;
}
if (is_pure_straight(mid_tile0, mid_tile1, mid_tile2)) {
return PURE_STRAIGHT;
}
if (is_pure_shifted_chows(mid_tile0, mid_tile1, mid_tile2)) {
return PURE_SHIFTED_CHOWS;
}
if (is_pure_triple_chow(mid_tile0, mid_tile1, mid_tile2)) {
return PURE_TRIPLE_CHOW;
}
return NONE;
}
// 2组顺子的番
static POINT_TYPE get_2_chows_points(TILE mid_tile0, TILE mid_tile1) {
if (is_pure_double_chow(mid_tile0, mid_tile1)) {
return PURE_DOUBLE_CHOW;
}
if (is_mixed_double_chow(mid_tile0, mid_tile1)) {
return MIXED_DOUBLE_CHOW;
}
if (is_short_straight(mid_tile0, mid_tile1)) {
return SHORT_STRAIGHT;
}
if (is_two_terminal_chows(mid_tile0, mid_tile1)) {
return TWO_TERMINAL_CHOWS;
}
return NONE;
}
// 4组刻子的番
static POINT_TYPE get_4_pungs_points(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2, TILE mid_tile3) {
if (is_four_pure_shifted_pungs(mid_tile0, mid_tile1, mid_tile2, mid_tile3)) {
return FOUR_PURE_SHIFTED_PUNGS;
}
if (is_winds(mid_tile0) && is_winds(mid_tile1) && is_winds(mid_tile2) && is_winds(mid_tile3)) {
return BIG_FOUR_WINDS;
}
return NONE;
}
// 3组刻子的番
static POINT_TYPE get_3_pungs_points(TILE mid_tile0, TILE mid_tile1, TILE mid_tile2) {
if (is_mixed_shifted_chow_or_pung(mid_tile0, mid_tile1, mid_tile2)) {
return MIXED_SHIFTED_PUNGS;
}
if (is_mixed_triple_chow_or_pung(mid_tile0, mid_tile1, mid_tile2)) {
return TRIPLE_PUNG;
}
if (is_pure_shifted_pungs(mid_tile0, mid_tile1, mid_tile2)) {
return PURE_SHIFTED_PUNGS;
}
if (is_dragons(mid_tile0) && is_dragons(mid_tile1) && is_dragons(mid_tile2)) {
return BIG_THREE_DRAGONS;
}
if (is_winds(mid_tile0) && is_winds(mid_tile1) && is_winds(mid_tile2)) {
return BIG_THREE_WINDS;
}
return NONE;
}
// 2组刻子的番
static POINT_TYPE get_2_pungs_points(TILE mid_tile0, TILE mid_tile1) {
if (is_numbered_suit_quick(mid_tile0) && is_numbered_suit_quick(mid_tile1) && is_rank_equal_quick(mid_tile0, mid_tile1)) {
return DOUBLE_PUNG;
}
if (is_dragons(mid_tile0) && is_dragons(mid_tile1)) {
return TWO_DRAGONS_PUNGS;
}
return NONE;
}
// 1组刻子的番
static POINT_TYPE get_1_pung_points(TILE mid_tile) {
if (is_terminal(mid_tile) || is_winds(mid_tile)) {
return PUNG_OF_TERMINALS_OR_HONORS;
}
if (is_dragons(mid_tile)) {
return DRAGON_PUNG;
}
return NONE;
}
template <long _Size>
static POINT_TYPE *pairwise_test_chows(const SET (&chows_sets)[_Size], POINT_TYPE *selected_points) {
POINT_TYPE all_points[_Size][_Size] = { { NONE } };
// 初始化矩阵
for (int i = 0; i < _Size; ++i) {
for (int j = 0; j < i - 1; ++j) { // 这是对称矩阵
all_points[i][j] = all_points[j][i];
}
for (int j = i + 1; j < _Size; ++j) {
all_points[i][j] = get_2_chows_points(chows_sets[i].mid_tile, chows_sets[j].mid_tile);
}
}
// 套算一次原则:
// 如果有尚未组合过的一副牌,只可同已组合过的相应的一副牌套算一次
//
// 不得相同原则:
// 凡已经合过某一番种的牌,不能再同其他一副牌组成相同的番种计分
//
// 根据套算一次原则,234567s234567p,只能计为“喜相逢*2 连六*1”或者“喜相逢*1 连六*2”,而不是“喜相逢*2 连六*2”
// 根据以上两点,234s223344567p,只能计为:“喜相逢、一般高、连六”,而不是“喜相逢*2、连六”
unsigned used_flag[_Size] = { 0 };
for (int i = 0; i < _Size; ++i) {
for (int j = 0; j < _Size; ++j) {
if (i == j) {
continue;
}
// 套算一次原则
if (used_flag[i] && used_flag[j]) {
continue;
}
if (all_points[i][j] != NONE) {
// 不得相同原则
int idx = all_points[i][j] - PURE_DOUBLE_CHOW;
if ((used_flag[i] & (1 << idx)) == 0 && (used_flag[j] & (1 << idx)) == 0) {
used_flag[i] |= (1 << (all_points[i][j] - PURE_DOUBLE_CHOW));
used_flag[j] |= (1 << (all_points[i][j] - PURE_DOUBLE_CHOW));
*selected_points = all_points[i][j];
++selected_points;
}
}
}
}
return selected_points;
}
// 4组顺子算番
static void calculate_4_chows(const SET chow_sets[4], long (&points_table)[POINT_TYPE_COUNT]) {
// 复制并排序
SET sets[4];
memcpy(sets, chow_sets, sizeof(sets));
std::sort(std::begin(sets), std::end(sets), [](const SET &set1, const SET &set2) {
return set1.mid_tile < set2.mid_tile;
});
POINT_TYPE points;
// 有4组顺子的番种(四同顺 四步高),不再检测其他的了
if ((points = get_4_chows_points(sets[0].mid_tile, sets[1].mid_tile, sets[2].mid_tile, sets[3].mid_tile))) {
points_table[points] = 1;
return;
}
// 3组顺子判断
bool _3_chows_has_points = false;
long free_set_idx = -1;
if ((points = get_3_chows_points(sets[0].mid_tile, sets[1].mid_tile, sets[2].mid_tile)) != NONE) {
points_table[points] = 1;
free_set_idx = 3;
_3_chows_has_points = true;
}
else if ((points = get_3_chows_points(sets[0].mid_tile, sets[1].mid_tile, sets[3].mid_tile)) != NONE) {
points_table[points] = 1;
free_set_idx = 2;
_3_chows_has_points = true;
}
else if ((points = get_3_chows_points(sets[0].mid_tile, sets[2].mid_tile, sets[3].mid_tile)) != NONE) {
points_table[points] = 1;
free_set_idx = 1;
_3_chows_has_points = true;
}
else if ((points = get_3_chows_points(sets[1].mid_tile, sets[2].mid_tile, sets[3].mid_tile)) != NONE) {
points_table[points] = 1;
free_set_idx = 0;
_3_chows_has_points = true;
}
// 有3组顺子的番种(三同顺 三步高 清龙 花龙)时,余下的第4组顺子最多1番
if (_3_chows_has_points) {
for (long i = 0; i < 4; ++i) {
if (i == free_set_idx) {
continue;
}
if ((points = get_2_chows_points(sets[i].mid_tile, sets[free_set_idx].mid_tile)) != NONE) {
++points_table[points];
break;
}
}
return;
}
// 没有上述番种时,4组顺子最多3番
POINT_TYPE selected_points[3] = { NONE };
pairwise_test_chows(sets, selected_points);
for (long i = 0; i < 3; ++i) {
if (selected_points[i] != NONE) {
++points_table[selected_points[i]];
}
}
}
// 3组顺子算番
static void calculate_3_chows(const SET chow_sets[3], long (&points_table)[POINT_TYPE_COUNT]) {
// 复制并排序
SET sets[3];
memcpy(sets, chow_sets, sizeof(sets));
std::sort(std::begin(sets), std::end(sets), [](const SET &set1, const SET &set2) {
return set1.mid_tile < set2.mid_tile;
});
POINT_TYPE points;
// 有3组顺子的番种(三同顺 三步高 清龙 花龙)时,不再检测其他的
if ((points = get_3_chows_points(sets[0].mid_tile, sets[1].mid_tile, sets[2].mid_tile)) != NONE) {
points_table[points] = 1;
return;
}
// 没有上述番种时,3组顺子最多2番
POINT_TYPE selected_points[2] = { NONE };
pairwise_test_chows(sets, selected_points);
for (long i = 0; i < 2; ++i) {
if (selected_points[i] != NONE) {
++points_table[selected_points[i]];
}
}
}
// 2组顺子算番
static void calculate_2_chows(const SET chow_sets[2], long (&points_table)[POINT_TYPE_COUNT]) {
const SET *sets = chow_sets;
POINT_TYPE points;
if ((points = get_2_chows_points(sets[0].mid_tile, sets[1].mid_tile)) != NONE) {
++points_table[points];
}
}
// 刻子(杠)算番
static void calculate_kongs(const SET *pung_sets, long pung_cnt, long (&points_table)[POINT_TYPE_COUNT]) {
// 统计明杠 暗杠 明刻 暗刻
int melded_kong_cnt = 0;
int concealed_kong_cnt = 0;
int concealed_pung_cnt = 0;
for (long i = 0; i < pung_cnt; ++i) {
if (pung_sets[i].is_melded) {
if (pung_sets[i].set_type == SET_TYPE::KONG) {
++melded_kong_cnt;
}
}
else {
if (pung_sets[i].set_type == SET_TYPE::KONG) {
++concealed_kong_cnt;
}
else {
++concealed_pung_cnt;
}
}
}
// 规则
// 三杠
// 明杠 明杠 暗杠 暗刻 -> 三杠+暗杠+双暗刻+碰碰和
// 明杠 暗杠 暗杠 明刻 -> 三杠+双暗杠+碰碰和
// 明杠 暗杠 暗杠 暗刻 -> 三杠+三暗刻+双暗杠+碰碰和
// 暗杠 暗杠 暗杠 明刻 -> 三杠+三暗刻+碰碰和
// 暗杠 暗杠 暗杠 暗刻 -> 三杠+四暗刻
//
// 四杠
// 暗杠 明杠 明杠 明杠 -> 四杠+暗杠
// 暗杠 暗杠 明杠 明杠 -> 四杠+双暗杠
// 暗杠 暗杠 暗杠 明杠 -> 四杠+三暗刻
// 暗杠 暗杠 暗杠 暗杠 -> 四杠+四暗刻
//
int kong_cnt = melded_kong_cnt + concealed_kong_cnt;
switch (kong_cnt) {
case 0: // 0个杠
switch (concealed_pung_cnt) { // 暗刻的个数
case 0: break;
case 1: break;
case 2: points_table[TWO_CONCEALED_PUNGS] = 1; break;
case 3: points_table[THREE_CONCEALED_PUNGS] = 1; break;
case 4: points_table[FOUR_CONCEALED_PUNGS] = 1; break;
default: assert(0); break;
}
break;
case 1: // 1个杠
if (melded_kong_cnt == 1) { // 明杠
points_table[MELDED_KONG] = 1;
switch (concealed_pung_cnt) { // 暗刻的个数
case 0: break;
case 1: break;
case 2: points_table[TWO_CONCEALED_PUNGS] = 1; break;
case 3: points_table[THREE_CONCEALED_PUNGS] = 1; break;
default: assert(0); break;
}
}
else { // 暗杠
points_table[CONCEALED_KONG] = 1;
switch (concealed_pung_cnt) { // 暗刻的个数
case 0: break;
case 1: points_table[TWO_CONCEALED_PUNGS] = 1; break;
case 2: points_table[THREE_CONCEALED_PUNGS] = 1; break;
case 3: points_table[FOUR_CONCEALED_PUNGS] = 1; break;
default: assert(0); break;
}
}
break;
case 2: // 2个杠
switch (concealed_kong_cnt) {
case 0: // 双明杠
points_table[TWO_MELDED_KONGS] = 1;
switch (concealed_pung_cnt) { // 暗刻的个数
case 0: break;
case 1: break;
case 2: points_table[TWO_CONCEALED_PUNGS] = 1; break;
default: assert(0); break;
}
break;
case 1: // 明暗杠
#if HAS_CONCEALED_KONG_AND_MELDED_KONG
points_table[CONCEALED_KONG_AND_MELDED_KONG] = 1;
#else
points_table[MELDED_KONG] = 1;
points_table[CONCEALED_KONG] = 1;
#endif
switch (concealed_pung_cnt) { // 暗刻的个数
case 0: break;
case 1: points_table[TWO_CONCEALED_PUNGS] = 1; break;
case 2: points_table[THREE_CONCEALED_PUNGS] = 1; break;
default: assert(0); break;
}
break;
case 2: // 双暗杠
points_table[TWO_CONCEALED_KONGS] = 1;
switch (concealed_pung_cnt) { // 暗刻的个数
case 0: break;
case 1: points_table[THREE_CONCEALED_PUNGS] = 1; break;
case 2: points_table[FOUR_CONCEALED_PUNGS] = 1; break;
default: assert(0); break;
}
break;
default:
assert(0);
break;
}
break;
case 3: // 3个杠
points_table[THREE_KONGS] = 1;
switch (concealed_kong_cnt) { // 暗刻的个数
case 0: break;
case 1:
if (concealed_pung_cnt == 0) {
points_table[CONCEALED_KONG] = 1;
}
else {
points_table[CONCEALED_KONG] = 1;
points_table[TWO_CONCEALED_PUNGS] = 1;
}
break;
case 2:
if (concealed_pung_cnt == 0) {
points_table[TWO_CONCEALED_KONGS] = 1;
}
else {
points_table[THREE_CONCEALED_PUNGS] = 1;
points_table[TWO_CONCEALED_KONGS] = 1;
}
break;
case 3:
if (concealed_pung_cnt == 0) {
points_table[THREE_CONCEALED_PUNGS] = 1;
}
else {
points_table[FOUR_CONCEALED_PUNGS] = 1;
}
break;
default:
assert(0);
break;
}
break;
case 4: // 4个杠
points_table[FOUR_KONGS] = 1;
switch (concealed_kong_cnt) {
case 0: break;
case 1: points_table[CONCEALED_KONG] = 1; break;
case 2: points_table[TWO_CONCEALED_KONGS] = 1; break;
case 3: points_table[THREE_CONCEALED_PUNGS] = 1; break;
case 4: points_table[FOUR_CONCEALED_PUNGS] = 1; break;
default: assert(0); break;
}
break;
default:
assert(0);
break;
}
// 四杠和四暗刻不计碰碰和,其他先加上碰碰和的番
if (pung_cnt == 4) {
if (points_table[FOUR_KONGS] == 0 && points_table[FOUR_CONCEALED_PUNGS] == 0) {
points_table[ALL_PUNGS] = 1;
}
}
for (long i = 0; i < pung_cnt; ++i) {
POINT_TYPE points = get_1_pung_points(pung_sets[i].mid_tile);
if (points != NONE) {
++points_table[points];
}
}
}
// 4组刻子算番
static void calculate_4_pungs(const SET pung_sets[4], long (&points_table)[POINT_TYPE_COUNT]) {
SET sets[4];
memcpy(sets, pung_sets, sizeof(sets));
std::sort(std::begin(sets), std::end(sets), [](const SET &set1, const SET &set2) {
return set1.mid_tile < set2.mid_tile;
});
calculate_kongs(sets, 4, points_table);
POINT_TYPE points;
if ((points = get_4_pungs_points(sets[0].mid_tile, sets[1].mid_tile, sets[2].mid_tile, sets[3].mid_tile)) != NONE) {
points_table[points] = 1;
return;
}
bool _3_pungs_has_points = false;
long free_set_idx = -1;
if ((points = get_3_pungs_points(sets[0].mid_tile, sets[1].mid_tile, sets[2].mid_tile)) != NONE) {
points_table[points] = 1;
free_set_idx = 3;
_3_pungs_has_points = true;
}
else if ((points = get_3_pungs_points(sets[0].mid_tile, sets[1].mid_tile, sets[3].mid_tile)) != NONE) {
points_table[points] = 1;
free_set_idx = 2;
_3_pungs_has_points = true;
}
else if ((points = get_3_pungs_points(sets[0].mid_tile, sets[2].mid_tile, sets[3].mid_tile)) != NONE) {
points_table[points] = 1;
free_set_idx = 1;
_3_pungs_has_points = true;
}
else if ((points = get_3_pungs_points(sets[1].mid_tile, sets[2].mid_tile, sets[3].mid_tile)) != NONE) {
points_table[points] = 1;
free_set_idx = 0;
_3_pungs_has_points = true;
}
if (_3_pungs_has_points) {
for (long i = 0; i < 4; ++i) {
if (i == free_set_idx) {
continue;
}
if ((points = get_2_pungs_points(sets[i].mid_tile, sets[free_set_idx].mid_tile)) != NONE) {
++points_table[points];
break;
}
}
}
else {
if ((points = get_2_pungs_points(sets[0].mid_tile, sets[1].mid_tile)) != NONE) {
++points_table[points];
}
if ((points = get_2_pungs_points(sets[0].mid_tile, sets[2].mid_tile)) != NONE) {
++points_table[points];
}
if ((points = get_2_pungs_points(sets[0].mid_tile, sets[3].mid_tile)) != NONE) {
++points_table[points];
}
if ((points = get_2_pungs_points(sets[1].mid_tile, sets[2].mid_tile)) != NONE) {
++points_table[points];
}
if ((points = get_2_pungs_points(sets[1].mid_tile, sets[3].mid_tile)) != NONE) {
++points_table[points];
}
if ((points = get_2_pungs_points(sets[2].mid_tile, sets[3].mid_tile)) != NONE) {
++points_table[points];
}
}
}
// 3组刻子算番
static void calculate_3_pungs(const SET pung_sets[3], long (&points_table)[POINT_TYPE_COUNT]) {
SET sets[3];
memcpy(sets, pung_sets, sizeof(sets));
std::sort(std::begin(sets), std::end(sets), [](const SET &set1, const SET &set2) {
return set1.mid_tile < set2.mid_tile;
});
calculate_kongs(sets, 3, points_table);
POINT_TYPE points;
if ((points = get_3_pungs_points(sets[0].mid_tile, sets[1].mid_tile, sets[2].mid_tile)) != NONE) {
points_table[points] = 1;
return;
}
if ((points = get_2_pungs_points(sets[0].mid_tile, sets[1].mid_tile)) != NONE) {
++points_table[points];
}
if ((points = get_2_pungs_points(sets[0].mid_tile, sets[2].mid_tile)) != NONE) {
++points_table[points];
}
if ((points = get_2_pungs_points(sets[1].mid_tile, sets[2].mid_tile)) != NONE) {
++points_table[points];
}
}
// 2组刻子算番
static void calculate_2_pungs(const SET pung_sets[2], long (&points_table)[POINT_TYPE_COUNT]) {
calculate_kongs(pung_sets, 2, points_table);
POINT_TYPE points = get_2_pungs_points(pung_sets[0].mid_tile, pung_sets[1].mid_tile);
if (points != NONE) {
++points_table[points];
}
}
// 1组刻子算番
static void calculate_1_pung(const SET &pung_set, long (&points_table)[POINT_TYPE_COUNT]) {
calculate_kongs(&pung_set, 1, points_table);
}
// 九莲宝灯
static bool is_nine_gates(const TILE tiles[14], TILE win_tile) {
TILE hand_tiles[13];
copy_exclude(tiles, tiles + 14, &win_tile, (&win_tile) + 1, hand_tiles);
sort_tiles(hand_tiles, 13);
switch (hand_tiles[0]) {
case 0x11: return (memcmp(hand_tiles, standard_nine_gates[0], sizeof(hand_tiles)) == 0);
case 0x21: return (memcmp(hand_tiles, standard_nine_gates[1], sizeof(hand_tiles)) == 0);
case 0x31: return (memcmp(hand_tiles, standard_nine_gates[2], sizeof(hand_tiles)) == 0);
default: return false;
}
}
// 一色双龙会
static bool is_pure_terminal_chows(const SET (&chow_sets)[4], const SET &pair_set) {
if (tile_rank(pair_set.mid_tile) != 5) {
return false;
}
int _123_cnt = 0, _789_cnt = 0;
SUIT_TYPE pair_suit = tile_suit(pair_set.mid_tile);
for (long i = 0; i < 4; ++i) {
SUIT_TYPE suit = tile_suit(chow_sets[i].mid_tile);
if (suit != pair_suit) {
return false;
}
RANK_TYPE rank = tile_rank(chow_sets[i].mid_tile);
switch (rank) {
case 2: ++_123_cnt; break;
case 8: ++_789_cnt; break;
default: return false;
}
}
return (_123_cnt == 2 && _789_cnt == 2);
}
// 三色双龙会
static bool is_three_suited_terminal_chows(const SET (&chow_sets)[4], const SET &pair_set) {
if (tile_rank(pair_set.mid_tile) != 5) {
return false;
}
int _123_suit_table[4] = { 0 };
int _789_suit_table[4] = { 0 };
SUIT_TYPE pair_suit = tile_suit(pair_set.mid_tile);
for (long i = 0; i < 4; ++i) {
SUIT_TYPE suit = tile_suit(chow_sets[i].mid_tile);
if (suit == pair_suit) {
return false;
}
RANK_TYPE rank = tile_rank(chow_sets[i].mid_tile);
switch (rank) {
case 2: ++_123_suit_table[suit]; break;
case 8: ++_789_suit_table[suit]; break;
default: return false;
}
}
switch (pair_suit) {
case 1: return (_123_suit_table[2] && _123_suit_table[3] && _789_suit_table[2] && _789_suit_table[3]);
case 2: return (_123_suit_table[1] && _123_suit_table[3] && _789_suit_table[1] && _789_suit_table[3]);
case 3: return (_123_suit_table[1] && _123_suit_table[2] && _789_suit_table[1] && _789_suit_table[2]);
default: assert(0); return false;
}
}
// 检测不求人、全求人
static void check_melded_or_concealed_hand(const SET (&sets)[5], long fixed_cnt, bool self_drawn, long (&points_table)[POINT_TYPE_COUNT]) {
long melded_cnt = 0;
for (long i = 0; i < fixed_cnt; ++i) {
if (sets[i].is_melded) {
++melded_cnt;
}
}
switch (melded_cnt) {
case 0: points_table[self_drawn ? FULLY_CONCEALED_HAND : CONCEALED_HAND] = 1; break;
case 4: points_table[self_drawn ? SELF_DRAWN : MELDED_HAND] = 1; break;
default:
if (self_drawn) {
points_table[SELF_DRAWN] = 1;
}
break;
}
}
// 检测平和、小三元、小四喜
static void check_pair_tile(TILE pair_tile, long chow_cnt, long (&points_table)[POINT_TYPE_COUNT]) {
if (chow_cnt == 4) {
if (is_numbered_suit_quick(pair_tile)) {
points_table[ALL_CHOWS] = 1;
}
}
else {
if (points_table[TWO_DRAGONS_PUNGS]) {
if (is_dragons(pair_tile)) {
points_table[LITTLE_THREE_DRAGONS] = 1;
points_table[TWO_DRAGONS_PUNGS] = 0;
}
}
else if (points_table[BIG_THREE_WINDS]) {
if (is_winds(pair_tile)) {
points_table[LITTLE_FOUR_WINDS] = 1;
points_table[BIG_THREE_WINDS] = 0;
}
}
}
}
// 检测序数牌和字牌
static void check_tiles_suits(const TILE *tiles, long tile_cnt, long (&points_table)[POINT_TYPE_COUNT]) {
bool has_characters = false;
bool has_bamboo = false;
bool has_dots = false;
bool has_winds = false;
bool has_dragons = false;
for (long i = 0; i < tile_cnt; ++i) {
SUIT_TYPE suit = tile_suit(tiles[i]);
switch (suit) {
case TILE_SUIT_CHARACTERS: has_characters = true; break;
case TILE_SUIT_BAMBOO: has_bamboo = true; break;
case TILE_SUIT_DOTS: has_dots = true; break;
case TILE_SUIT_WINDS: has_winds = true; break;
case TILE_SUIT_DRAGONS: has_dragons = true; break;
}
}
if (has_characters && has_bamboo && has_dots && has_winds && has_dragons) {
points_table[ALL_TYPES] = 1;
return;
}
if (!has_winds && !has_dragons) {
points_table[NO_HONORS] = 1;
}
if (!has_characters) {
++points_table[ONE_VOIDED_SUIT];
}
if (!has_bamboo) {
++points_table[ONE_VOIDED_SUIT];
}
if (!has_dots) {
++points_table[ONE_VOIDED_SUIT];
}
if (points_table[ONE_VOIDED_SUIT] == 2) {
points_table[ONE_VOIDED_SUIT] = 0;
points_table[points_table[NO_HONORS] == 0 ? HALF_FLUSH : FULL_FLUSH] = 1;
}
}
// 检测大于五、小于五、全大、全中、全小
static void check_tiles_rank_range(const TILE *tiles, long tile_cnt, long (&points_table)[POINT_TYPE_COUNT]) {
#ifdef STRICT_98_RULE
if (points_table[SEVEN_PAIRS]) {
return;
}
#endif
// 打表
uint16_t rank_flag = 0;
for (long i = 0; i < tile_cnt; ++i) {
SUIT_TYPE suit = tile_suit(tiles[i]);
if (suit == TILE_SUIT_WINDS || suit == TILE_SUIT_DRAGONS) {
return; // 不允许字牌
}
rank_flag |= (1 << tile_rank(tiles[i]));
}
// 1111 1111 1110 0001
// 检测是否缺少56789
if (!(rank_flag & 0xFFE1)) {
points_table[rank_flag & 0x0010 ? LOWER_FOUR : LOWER_TILES] = 1;
}
// 1111 1100 0011 1111
// 检测是否缺少12345
else if (!(rank_flag & 0xFC3F)) {
// no 6 ?
points_table[rank_flag & 0x0040 ? UPPER_FOUR : UPPER_TILES] = 1;
}
// 1111 1111 1000 1111
// 检测是否缺少2478
else if (!(rank_flag & 0xFF8F)) {
points_table[MIDDLE_TILES] = 1;
}
}
// 检测全带幺、全带五、全双刻
static void check_tiles_rank_by_set(const SET (&sets)[5], long (&points_table)[POINT_TYPE_COUNT]) {
int terminal_cnt = 0;
int honor_cnt = 0;
int _5_cnt = 0;
int even_pung_cnt = 0;
for (long i = 0; i < 5; ++i) {
if (is_set_contains_tile(sets[i], 0x11) ||
is_set_contains_tile(sets[i], 0x19) ||
is_set_contains_tile(sets[i], 0x21) ||
is_set_contains_tile(sets[i], 0x29) ||
is_set_contains_tile(sets[i], 0x31) ||
is_set_contains_tile(sets[i], 0x39)) {
++terminal_cnt;
}
else if (is_set_contains_tile(sets[i], 0x41) ||
is_set_contains_tile(sets[i], 0x42) ||
is_set_contains_tile(sets[i], 0x43) ||
is_set_contains_tile(sets[i], 0x44) ||
is_set_contains_tile(sets[i], 0x51) ||
is_set_contains_tile(sets[i], 0x52) ||
is_set_contains_tile(sets[i], 0x53)) {
++honor_cnt;
}
else if (is_set_contains_tile(sets[i], 0x15) ||
is_set_contains_tile(sets[i], 0x25) ||
is_set_contains_tile(sets[i], 0x35)) {
++_5_cnt;
}
else if (sets[i].set_type == SET_TYPE::PUNG ||
sets[i].set_type == SET_TYPE::KONG ||
sets[i].set_type == SET_TYPE::PAIR) {
if (is_numbered_suit_quick(sets[i].mid_tile) && sets[i].mid_tile % 2 == 0) {
++even_pung_cnt;
}
}
}
if (terminal_cnt + honor_cnt == 5) {
points_table[OUTSIDE_HAND] = 1;
}
else if (_5_cnt == 5) {
points_table[ALL_FIVE] = 1;
}
else if (even_pung_cnt == 5) {
points_table[ALL_EVEN_PUNGS] = 1;
}
}
// 检测断幺、推不倒、绿一色、清幺九、混幺九
static void check_tiles_traits(const TILE *tiles, long tile_cnt, long (&points_table)[POINT_TYPE_COUNT]) {
if (!std::any_of(tiles, tiles + tile_cnt, &is_terminal_or_honor)) {
points_table[ALL_SIMPLES] = 1;
}
if (std::all_of(tiles, tiles + tile_cnt, &is_reversible_tile)) {
points_table[REVERSIBLE_TILES] = 1;
}
#ifdef STRICT_98_RULE
if (points_table[SEVEN_PAIRS]) {
return;
}
#endif
if (std::all_of(tiles, tiles + tile_cnt, &is_green)) {
points_table[ALL_GREEN] = 1;
}
if (points_table[ALL_SIMPLES] != 0) {
return;
}
if (std::all_of(tiles, tiles + tile_cnt, &is_honor)) {
points_table[ALL_HONORS] = 1;
return;
}
if (std::all_of(tiles, tiles + tile_cnt, &is_terminal)) {
points_table[ALL_TERMINALS] = 1;
return;
}
if (std::all_of(tiles, tiles + tile_cnt, &is_terminal_or_honor)) {
points_table[ALL_TERMINALS_AND_HONORS] = 1;
}
}
// 检测四归一
static void check_tiles_hog(const TILE *tiles, long tile_cnt, long (&points_table)[POINT_TYPE_COUNT]) {
long kong_cnt = tile_cnt - 14;
int cnt_table[0x54] = { 0 };
for (long i = 0; i < tile_cnt; ++i) {
++cnt_table[tiles[i]];
}
long _4_cnt = std::count(std::begin(cnt_table), std::end(cnt_table), 4);
points_table[TILE_HOG] = _4_cnt - kong_cnt;
}
// 检测边坎钓
static void check_edge_closed_single_wait(const SET *concealed_sets, long set_cnt, TILE win_tile, long (&points_table)[POINT_TYPE_COUNT]) {
TILE concealed_tiles[14];
long concealed_tile_cnt;
recovery_tiles_from_sets(concealed_sets, set_cnt, concealed_tiles, &concealed_tile_cnt);
sort_tiles(concealed_tiles, concealed_tile_cnt);
copy_exclude(concealed_tiles, concealed_tiles + concealed_tile_cnt, &win_tile, (&win_tile) + 1, concealed_tiles);
bool waiting_table[6][10] = { { 0 } };
long waiting_cnt = 0;
TILE waiting_seven_pairs = 0;
switch (set_cnt) {
case 5:
is_basic_type_13_wait(concealed_tiles, waiting_table);
if (is_seven_pairs_wait((const TILE (&)[13])concealed_tiles, &waiting_seven_pairs)) {
waiting_table[tile_suit(waiting_seven_pairs)][tile_rank(waiting_seven_pairs)] = true;
}
break;
case 4:
is_basic_type_10_wait(concealed_tiles, waiting_table);
break;
case 3:
is_basic_type_7_wait(concealed_tiles, waiting_table);
break;
case 2:
is_basic_type_4_wait(concealed_tiles, waiting_table);
break;
case 1:
waiting_table[tile_suit(win_tile)][tile_rank(win_tile)] = true;
break;
default:
break;
}
for (int i = 1; i < 6; ++i) {
for (int j = 1; j < 10; ++j) {
if (waiting_table[i][j]) {
++waiting_cnt;
}
}
}
// 听牌数大于1张,或者是全求人,不计边坎钓
if (waiting_cnt != 1 || points_table[MELDED_HAND]) {
return;
}
bool maybe_edge = false;
bool maybe_closed = false;
bool maybe_single = false;
for (long i = 0; i < set_cnt; ++i) {
switch (concealed_sets[i].set_type) {
case SET_TYPE::CHOW:
if (concealed_sets[i].mid_tile == win_tile) {
maybe_closed = true;
}
else if (concealed_sets[i].mid_tile + 1 == win_tile
|| concealed_sets[i].mid_tile - 1 == win_tile) {
maybe_edge = true;
}
break;
case SET_TYPE::PAIR:
if (concealed_sets[i].mid_tile == win_tile) {
maybe_single = true;
}
break;
default:
break;
}
}
if (maybe_edge) {
points_table[EDGE_WAIT] = 1;
return;
}
if (maybe_closed) {
points_table[CLOSED_WAIT] = 1;
return;
}
if (maybe_single) {
points_table[SINGLE_WAIT] = 1;
return;
}
}
// 检测圈风刻、门风刻
static void check_wind_pungs(const SET &sets, WIND_TYPE prevalent_wind, WIND_TYPE seat_wind, long (&points_table)[POINT_TYPE_COUNT]) {
if (sets.set_type == SET_TYPE::PUNG || sets.set_type == SET_TYPE::KONG) {
RANK_TYPE delta = sets.mid_tile - 0x41;
if (delta == (int)prevalent_wind - (int)WIND_TYPE::EAST) {
points_table[PREVALENT_WIND] = 1;
}
if (delta == (int)seat_wind - (int)WIND_TYPE::EAST) {
points_table[SEAT_WIND] = 1;
}
}
}
// 统一校正
static void correction_points_table(long (&points_table)[POINT_TYPE_COUNT], bool prevalent_eq_seat) {
if (points_table[BIG_FOUR_WINDS]) {
points_table[BIG_THREE_WINDS] = 0;
points_table[ALL_PUNGS] = 0;
points_table[PREVALENT_WIND] = 0;
points_table[SEAT_WIND] = 0;
points_table[PUNG_OF_TERMINALS_OR_HONORS] = 0;
}
if (points_table[BIG_THREE_DRAGONS]) {
points_table[TWO_DRAGONS_PUNGS] = 0;
points_table[DRAGON_PUNG] = 0;
#ifdef STRICT_98_RULE
points_table[ONE_VOIDED_SUIT] = 0;
#endif
}
if (points_table[ALL_GREEN]) {
points_table[HALF_FLUSH] = 0;
points_table[ONE_VOIDED_SUIT] = 0;
}
if (points_table[NINE_GATES]) {
points_table[FULL_FLUSH] = 0;
points_table[CONCEALED_HAND] = 0;
--points_table[PUNG_OF_TERMINALS_OR_HONORS];
points_table[ONE_VOIDED_SUIT] = 0;
points_table[NO_HONORS] = 0;
if (points_table[FULLY_CONCEALED_HAND]) {
points_table[FULLY_CONCEALED_HAND] = 0;
points_table[SELF_DRAWN] = 1;
}
}
if (points_table[FOUR_KONGS]) {
points_table[SINGLE_WAIT] = 0;
}
if (points_table[SEVEN_SHIFTED_PAIRS]) {
points_table[SEVEN_PAIRS] = 0;
points_table[FULL_FLUSH] = 0;
points_table[CONCEALED_HAND] = 0;
points_table[ONE_VOIDED_SUIT] = 0;
points_table[NO_HONORS] = 0;
}
if (points_table[THIRTEEN_ORPHANS]) {
points_table[ALL_TYPES] = 0;
points_table[CONCEALED_HAND] = 0;
points_table[SINGLE_WAIT] = 0;
}
if (points_table[ALL_TERMINALS]) {
points_table[ALL_TERMINALS_AND_HONORS] = 0;
points_table[ALL_PUNGS] = 0;
points_table[OUTSIDE_HAND] = 0;
points_table[PUNG_OF_TERMINALS_OR_HONORS] = 0;
points_table[NO_HONORS] = 0;
#ifdef STRICT_98_RULE
points_table[TRIPLE_PUNG] = 0;
points_table[DOUBLE_PUNG] = 0;
#endif
}
if (points_table[LITTLE_FOUR_WINDS]) {
points_table[BIG_THREE_WINDS] = 0;
}
if (points_table[LITTLE_THREE_DRAGONS]) {
points_table[TWO_DRAGONS_PUNGS] = 0;
points_table[DRAGON_PUNG] = 0;
#ifdef STRICT_98_RULE
points_table[ONE_VOIDED_SUIT] = 0;
#endif
}
if (points_table[ALL_HONORS]) {
points_table[ALL_TERMINALS_AND_HONORS] = 0;
points_table[ALL_PUNGS] = 0;
points_table[OUTSIDE_HAND] = 0;
points_table[PUNG_OF_TERMINALS_OR_HONORS] = 0;
points_table[ONE_VOIDED_SUIT] = 0;
}
if (points_table[FOUR_CONCEALED_PUNGS]) {
points_table[ALL_PUNGS] = 0;
points_table[CONCEALED_HAND] = 0;
if (points_table[FULLY_CONCEALED_HAND]) {
points_table[FULLY_CONCEALED_HAND] = 0;
points_table[SELF_DRAWN] = 1;
}
}
if (points_table[PURE_TERMINAL_CHOWS]) {
points_table[SEVEN_PAIRS] = 0;
points_table[FULL_FLUSH] = 0;
points_table[ALL_CHOWS] = 0;
points_table[PURE_DOUBLE_CHOW] = 0;
points_table[TWO_TERMINAL_CHOWS] = 0;
points_table[ONE_VOIDED_SUIT] = 0;
points_table[NO_HONORS] = 0;
}
if (points_table[QUADRUPLE_CHOW]) {
points_table[PURE_SHIFTED_PUNGS] = 0;
points_table[TILE_HOG] = 0;
points_table[PURE_DOUBLE_CHOW] = 0;
#ifdef STRICT_98_RULE
points_table[ONE_VOIDED_SUIT] = 0;
#endif
}
if (points_table[FOUR_PURE_SHIFTED_PUNGS]) {
points_table[PURE_TRIPLE_CHOW] = 0;
points_table[ALL_PUNGS] = 0;
#ifdef STRICT_98_RULE
points_table[ONE_VOIDED_SUIT] = 0;
#endif
}
if (points_table[FOUR_PURE_SHIFTED_CHOWS]) {
points_table[TWO_TERMINAL_CHOWS] = 0;
points_table[SHORT_STRAIGHT] = 0;
#ifdef STRICT_98_RULE
points_table[ONE_VOIDED_SUIT] = 0;
#endif
}
if (points_table[ALL_TERMINALS_AND_HONORS]) {
points_table[ALL_PUNGS] = 0;
points_table[OUTSIDE_HAND] = 0;
points_table[PUNG_OF_TERMINALS_OR_HONORS] = 0;
}
if (points_table[SEVEN_PAIRS]) {
points_table[CONCEALED_HAND] = 0;
points_table[SINGLE_WAIT] = 0;
}
if (points_table[GREATER_HONORS_AND_KNITTED_TILES]) {
points_table[CONCEALED_HAND] = 0;
points_table[ALL_TYPES] = 0;
}
if (points_table[ALL_EVEN_PUNGS]) {
points_table[ALL_PUNGS] = 0;
points_table[ALL_SIMPLES] = 0;
points_table[NO_HONORS] = 0;
}
if (points_table[FULL_FLUSH]) {
points_table[ONE_VOIDED_SUIT] = 0;
points_table[NO_HONORS] = 0;
}
if (points_table[PURE_TRIPLE_CHOW]) {
points_table[PURE_SHIFTED_PUNGS] = 0;
points_table[PURE_DOUBLE_CHOW] = 0;
}
if (points_table[PURE_SHIFTED_PUNGS]) {
points_table[PURE_TRIPLE_CHOW] = 0;
}
if (points_table[UPPER_TILES]) {
points_table[UPPER_FOUR] = 0;
points_table[NO_HONORS] = 0;
}
if (points_table[MIDDLE_TILES]) {
points_table[ALL_SIMPLES] = 0;
points_table[NO_HONORS] = 0;
}
if (points_table[LOWER_TILES]) {
points_table[LOWER_FOUR] = 0;
points_table[NO_HONORS] = 0;
}
if (points_table[THREE_SUITED_TERMINAL_CHOWS]) {
points_table[ALL_CHOWS] = 0;
points_table[NO_HONORS] = 0;
points_table[MIXED_DOUBLE_CHOW] = 0;
points_table[TWO_TERMINAL_CHOWS] = 0;
}
if (points_table[ALL_FIVE]) {
points_table[ALL_SIMPLES] = 0;
points_table[NO_HONORS] = 0;
}
if (points_table[LESSER_HONORS_AND_KNITTED_TILES]) {
points_table[CONCEALED_HAND] = 0;
points_table[ALL_TYPES] = 0;
}
if (points_table[UPPER_FOUR]) {
points_table[NO_HONORS] = 0;
}
if (points_table[LOWER_FOUR]) {
points_table[NO_HONORS] = 0;
}
if (points_table[BIG_THREE_WINDS]) {
if (!points_table[ALL_HONORS] && !points_table[ALL_TERMINALS_AND_HONORS]) {
assert(points_table[PUNG_OF_TERMINALS_OR_HONORS] >= 3);
points_table[PUNG_OF_TERMINALS_OR_HONORS] -= 3;
}
#ifdef STRICT_98_RULE
points_table[ONE_VOIDED_SUIT] = 0;
#endif
}
if (points_table[REVERSIBLE_TILES]) {
points_table[ONE_VOIDED_SUIT] = 0;
}
if (points_table[LAST_TILE_DRAW]) {
points_table[SELF_DRAWN] = 0;
}
if (points_table[OUT_WITH_REPLACEMENT_TILE]) {
points_table[SELF_DRAWN] = 0;
}
if (points_table[ROBBING_THE_KONG]) {
points_table[LAST_TILE] = 0;
}
if (points_table[TWO_CONCEALED_KONGS]) {
points_table[CONCEALED_KONG] = 0;
}
if (points_table[HALF_FLUSH]) {
points_table[ONE_VOIDED_SUIT] = 0;
}
if (points_table[MELDED_HAND]) {
points_table[SINGLE_WAIT] = 0;
}
if (points_table[TWO_DRAGONS_PUNGS]) {
points_table[DRAGON_PUNG] = 0;
}
if (points_table[FULLY_CONCEALED_HAND]) {
points_table[SELF_DRAWN] = 0;
}
if (points_table[TWO_MELDED_KONGS]) {
points_table[MELDED_KONG] = 0;
}
if (points_table[PREVALENT_WIND]) {
if (!points_table[BIG_THREE_WINDS] && !points_table[LITTLE_FOUR_WINDS]
&& !points_table[ALL_HONORS] && !points_table[ALL_TERMINALS_AND_HONORS]) {
assert(points_table[PUNG_OF_TERMINALS_OR_HONORS] > 0);
--points_table[PUNG_OF_TERMINALS_OR_HONORS];
}
}
if (points_table[SEAT_WIND]) {
if (!prevalent_eq_seat && !points_table[BIG_THREE_WINDS] && !points_table[LITTLE_FOUR_WINDS]
&& !points_table[ALL_HONORS] && !points_table[ALL_TERMINALS_AND_HONORS]) {
assert(points_table[PUNG_OF_TERMINALS_OR_HONORS] > 0);
--points_table[PUNG_OF_TERMINALS_OR_HONORS];
}
}
if (points_table[ALL_CHOWS]) {
points_table[NO_HONORS] = 0;
}
if (points_table[ALL_SIMPLES]) {
points_table[NO_HONORS] = 0;
}
}
static void check_win_type(WIN_TYPE win_type, long (&points_table)[POINT_TYPE_COUNT]) {
if (win_type & WIN_TYPE_4TH_TILE) {
points_table[LAST_TILE] = 1;
}
if (win_type & WIN_TYPE_WALL_LAST) {
points_table[win_type & WIN_TYPE_SELF_DRAWN ? LAST_TILE_DRAW : LAST_TILE_CLAIM] = 1;
}
if (win_type & WIN_TYPE_ABOUT_KONG) {
points_table[win_type & WIN_TYPE_SELF_DRAWN ? OUT_WITH_REPLACEMENT_TILE : ROBBING_THE_KONG] = 1;
}
if (win_type & WIN_TYPE_SELF_DRAWN) {
points_table[SELF_DRAWN] = 1;
}
}
static bool is_win_tile_in_concealed_chow_sets(const SET *chow_sets, long chow_cnt, TILE win_tile) {
return std::any_of(chow_sets, chow_sets + chow_cnt, [win_tile](const SET &chow_set) {
return !chow_set.is_melded && (chow_set.mid_tile - 1 == win_tile || chow_set.mid_tile == win_tile || chow_set.mid_tile + 1 == win_tile);
});
}
static void calculate_basic_type_points(const SET (&sets)[5], long fixed_cnt, TILE win_tile, WIN_TYPE win_type,
WIND_TYPE prevalent_wind, WIND_TYPE seat_wind, long (&points_table)[POINT_TYPE_COUNT]) {
SET pair_set;
SET chow_sets[4];
SET pung_sets[4];
long chow_cnt = 0;
long pung_cnt = 0;
for (long i = 0; i < 5; ++i) {
switch (sets[i].set_type) {
case SET_TYPE::CHOW: chow_sets[chow_cnt++] = sets[i]; break;
case SET_TYPE::PUNG:
case SET_TYPE::KONG: pung_sets[pung_cnt++] = sets[i]; break;
case SET_TYPE::PAIR: pair_set = sets[i]; break;
default: assert(0); break;
}
}
TILE tiles[18];
long tile_cnt = 0;
recovery_tiles_from_sets(sets, 5, tiles, &tile_cnt);
if (fixed_cnt == 0 && tile_cnt == 14) {
if (is_nine_gates(tiles, win_tile)) {
points_table[NINE_GATES] = 1;
}
}
check_win_type(win_type, points_table);
// 点和的明刻
if ((win_type & WIN_TYPE_SELF_DRAWN) == 0) {
if (!is_win_tile_in_concealed_chow_sets(chow_sets, chow_cnt, win_tile)) {
for (long i = 0; i < pung_cnt; ++i) {
if (pung_sets[i].mid_tile == win_tile && !pung_sets[i].is_melded) {
pung_sets[i].is_melded = true;
}
}
}
}
switch (chow_cnt) {
case 4:
if (is_pure_terminal_chows(chow_sets, pair_set)) {
points_table[PURE_TERMINAL_CHOWS] = 1;
break;
}
if (is_three_suited_terminal_chows(chow_sets, pair_set)) {
points_table[THREE_SUITED_TERMINAL_CHOWS] = 1;
break;
}
calculate_4_chows(chow_sets, points_table);
break;
case 3:
calculate_3_chows(chow_sets, points_table);
calculate_1_pung(pung_sets[0], points_table);
break;
case 2:
calculate_2_chows(chow_sets, points_table);
calculate_2_pungs(pung_sets, points_table);
break;
case 1:
calculate_3_pungs(pung_sets, points_table);
break;
case 0:
calculate_4_pungs(pung_sets, points_table);
break;
default:
break;
}
check_melded_or_concealed_hand(sets, fixed_cnt, win_type & WIN_TYPE_SELF_DRAWN, points_table);
check_pair_tile(pair_set.mid_tile, chow_cnt, points_table);
check_tiles_rank_by_set(sets, points_table);
check_tiles_suits(tiles, tile_cnt, points_table);
check_tiles_traits(tiles, tile_cnt, points_table);
check_tiles_rank_range(tiles, tile_cnt, points_table);
check_tiles_hog(tiles, tile_cnt, points_table);
check_edge_closed_single_wait(sets + fixed_cnt, 5 - fixed_cnt, win_tile, points_table);
for (int i = 0; i < 5; ++i) {
check_wind_pungs(sets[i], prevalent_wind, seat_wind, points_table);
}
correction_points_table(points_table, prevalent_wind == seat_wind);
if (std::all_of(std::begin(points_table), std::end(points_table), [](int p) { return p == 0; })) {
points_table[CHICKEN_HAND] = 1;
}
}
static bool calculate_special_type_points(const TILE (&concealed_tiles)[14], WIN_TYPE win_type, long (&points_table)[POINT_TYPE_COUNT]) {
if (concealed_tiles[0] == concealed_tiles[1]
&& concealed_tiles[2] == concealed_tiles[3]
&& concealed_tiles[4] == concealed_tiles[5]
&& concealed_tiles[6] == concealed_tiles[7]
&& concealed_tiles[8] == concealed_tiles[9]
&& concealed_tiles[10] == concealed_tiles[11]
&& concealed_tiles[12] == concealed_tiles[13]) {
if (concealed_tiles[0] + 1 == concealed_tiles[2]
&& concealed_tiles[2] + 1 == concealed_tiles[4]
&& concealed_tiles[4] + 1 == concealed_tiles[6]
&& concealed_tiles[6] + 1 == concealed_tiles[8]
&& concealed_tiles[8] + 1 == concealed_tiles[10]
&& concealed_tiles[10] + 1 == concealed_tiles[12]) {
points_table[SEVEN_SHIFTED_PAIRS] = 1;
check_tiles_traits(concealed_tiles, 14, points_table);
}
else {
points_table[SEVEN_PAIRS] = 1;
check_tiles_suits(concealed_tiles, 14, points_table);
check_tiles_traits(concealed_tiles, 14, points_table);
check_tiles_rank_range(concealed_tiles, 14, points_table);
check_tiles_hog(concealed_tiles, 14, points_table);
}
}
else if (std::includes(std::begin(concealed_tiles), std::end(concealed_tiles),
std::begin(standard_thirteen_orphans), std::end(standard_thirteen_orphans))) {
points_table[THIRTEEN_ORPHANS] = 1;
}
else {
const TILE *it = std::find_if(std::begin(concealed_tiles), std::end(concealed_tiles), &is_honor);
long numbered_cnt = it - concealed_tiles;
// 序数牌张数大于9或者小于7必然不可能是全不靠
if (numbered_cnt > 9 || numbered_cnt < 7) {
return false;
}
const TILE *matched_seq = nullptr;
for (int i = 0; i < 6; ++i) {
if (std::includes(std::begin(standard_knitted_straight[i]), std::end(standard_knitted_straight[i]),
std::begin(concealed_tiles), it)) {
matched_seq = standard_knitted_straight[i]; // 匹配到一个组合龙
break;
}
}
if (matched_seq == nullptr) {
return false;
}
// standard_thirteen_orphans + 6是字牌,即ESWNCFP
if (numbered_cnt == 7 && memcmp(standard_thirteen_orphans + 6, concealed_tiles + 7, 7 * sizeof(TILE)) == 0) {
points_table[GREATER_HONORS_AND_KNITTED_TILES] = 1;
}
else if (std::includes(standard_thirteen_orphans + 6, standard_thirteen_orphans + 13, it, std::end(concealed_tiles))) {
points_table[LESSER_HONORS_AND_KNITTED_TILES] = 1;
if (numbered_cnt == 9) {
points_table[KNITTED_STRAIGHT] = 1;
}
}
}
check_win_type(win_type, points_table);
correction_points_table(points_table, false);
return true;
}
static bool calculate_knitted_straight_in_basic_type_points(SET &fourth_set, const TILE *concealed_tiles, long concealed_cnt,
TILE win_tile, WIN_TYPE win_type, WIND_TYPE prevalent_wind, WIND_TYPE seat_wind, long (&points_table)[POINT_TYPE_COUNT]) {
assert(concealed_cnt == 14 || concealed_cnt == 11);
const TILE *matched_seq = nullptr;
for (int i = 0; i < 6; ++i) {
if (std::includes(concealed_tiles, concealed_tiles + concealed_cnt,
std::begin(standard_knitted_straight[i]), std::end(standard_knitted_straight[i]))) {
matched_seq = standard_knitted_straight[i]; // 匹配到一个组合龙
break;
}
}
if (matched_seq == nullptr) {
return false;
}
TILE pair_tile = 0;
TILE remains[5];
TILE *end = copy_exclude(concealed_tiles, concealed_tiles + concealed_cnt, matched_seq, matched_seq + 9, remains);
long remain_cnt = end - remains;
if (remain_cnt == 5) { // 如果第4组面子是手上的,那么手牌去除组合龙后会剩下14-9=5张,这5张包含一组面子和一对将
TILE *it = std::adjacent_find(std::begin(remains), std::end(remains)); // 将牌
while (it != std::end(remains)) {
pair_tile = *it; // 记录将(平和判断要用到)
TILE pair[2] = { pair_tile, pair_tile };
TILE temp[3]; // 去除将牌后余下3张
copy_exclude(std::begin(remains), std::end(remains), std::begin(pair), std::end(pair), temp);
if (is_chow(temp[0], temp[1], temp[2])) { // 去除将牌后余下3张是顺子
fourth_set.is_melded = false;
fourth_set.mid_tile = temp[1];
fourth_set.set_type = SET_TYPE::CHOW;
break;
}
else if (is_pung(temp[0], temp[1], temp[2])) { // 去除将牌后余下3张是刻子
fourth_set.is_melded = false;
fourth_set.mid_tile = temp[1];
fourth_set.set_type = SET_TYPE::PUNG;
break;
}
// 去除将牌后余下3张不能组成面子
do ++it; while (it != std::end(remains) && *it == pair_tile);
it = std::adjacent_find(it, std::end(remains));
pair_tile = 0;
}
if (pair_tile == 0) {
return false;
}
}
else {
// 如果第4组面子是吃碰杠的,那么手牌去除组合龙后会剩下11-9=2张,这2张必然是一对将
assert(remain_cnt == 2);
if (remains[0] != remains[1]) {
return false;
}
pair_tile = remains[0];
if (fourth_set.set_type != SET_TYPE::CHOW
&& fourth_set.set_type != SET_TYPE::PUNG
&& fourth_set.set_type != SET_TYPE::KONG) {
return false;
}
}
points_table[KNITTED_STRAIGHT] = 1;
if (fourth_set.set_type == SET_TYPE::CHOW) {
if (is_numbered_suit_quick(pair_tile)) {
points_table[ALL_CHOWS] = 1;
}
}
else {
POINT_TYPE points = get_1_pung_points(fourth_set.mid_tile);
if (points != NONE) {
++points_table[points];
}
}
check_win_type(win_type, points_table);
if (win_type & WIN_TYPE_SELF_DRAWN) {
points_table[FULLY_CONCEALED_HAND] = 1;
}
else {
points_table[CONCEALED_HAND] = 1;
}
check_tiles_suits(concealed_tiles, 14, points_table);
check_tiles_traits(concealed_tiles, 14, points_table);
check_tiles_rank_range(concealed_tiles, 14, points_table);
check_tiles_hog(concealed_tiles, 14, points_table);
// 和组合龙范围的牌,不算边坎钓
if (std::find(matched_seq, matched_seq + 9, win_tile) == matched_seq + 9) {
if (remain_cnt == 5) {
SET sets[2];
sets[0].is_melded = fourth_set.is_melded;
sets[0].set_type = fourth_set.set_type;
sets[0].mid_tile = fourth_set.mid_tile;
sets[1].is_melded = false;
sets[1].set_type = SET_TYPE::PAIR;
sets[1].mid_tile = pair_tile;
check_edge_closed_single_wait(sets, 2, win_tile, points_table);
}
else {
assert(remain_cnt == 2);
points_table[SINGLE_WAIT] = 1;
}
}
check_wind_pungs(fourth_set, prevalent_wind, seat_wind, points_table);
correction_points_table(points_table, prevalent_wind == seat_wind);
return true;
}
static int get_points_by_table(const long (&points_table)[POINT_TYPE_COUNT]) {
int points = 0;
for (int i = 1; i < FLOWER_TILES; ++i) {
if (points_table[i] == 0) {
continue;
}
points += points_value_table[i] * points_table[i];
if (points_table[i] == 1) {
printf("%s %d\n", points_name[i], points_value_table[i]);
}
else {
printf("%s %d*%ld\n", points_name[i], points_value_table[i], points_table[i]);
}
}
return points;
}
const char *parse_tiles(const char *str, TILE *tiles, long *out_tile_cnt) {
//std::regex reg("[1-9]+[mps]|[ESWNCFP]");
//if (std::regex_match(str, reg)) {
// std::cout << "cannot parse the string" << std::endl;
// return;
//}
long tile_cnt = 0;
TILE temp[14];
long temp_cnt = 0;
const char *p = str;
for (; temp_cnt < 14 && tile_cnt < 14 && *p != '\0'; ++p) {
char c = *p;
switch (c) {
case '1': temp[temp_cnt++] = 1; break;
case '2': temp[temp_cnt++] = 2; break;
case '3': temp[temp_cnt++] = 3; break;
case '4': temp[temp_cnt++] = 4; break;
case '5': temp[temp_cnt++] = 5; break;
case '6': temp[temp_cnt++] = 6; break;
case '7': temp[temp_cnt++] = 7; break;
case '8': temp[temp_cnt++] = 8; break;
case '9': temp[temp_cnt++] = 9; break;
case 'm':
for (long i = 0; i < temp_cnt && tile_cnt < 14; ++i) {
tiles[tile_cnt++] = temp[i] | 0x10;
}
temp_cnt = 0;
break;
case 's':
for (long i = 0; i < temp_cnt && tile_cnt < 14; ++i) {
tiles[tile_cnt++] = temp[i] | 0x20;
}
temp_cnt = 0;
break;
case 'p':
for (long i = 0; i < temp_cnt && tile_cnt < 14; ++i) {
tiles[tile_cnt++] = temp[i] | 0x30;
}
temp_cnt = 0;
break;
case 'E': tiles[tile_cnt++] = 0x41; break;
case 'S': tiles[tile_cnt++] = 0x42; break;
case 'W': tiles[tile_cnt++] = 0x43; break;
case 'N': tiles[tile_cnt++] = 0x44; break;
case 'C': tiles[tile_cnt++] = 0x51; break;
case 'F': tiles[tile_cnt++] = 0x52; break;
case 'P': tiles[tile_cnt++] = 0x53; break;
default: goto end;
}
}
end:
if (temp_cnt != 0) {
puts("Expect m/s/p to finish a series of numbers");
return nullptr;
}
if (out_tile_cnt != nullptr) {
*out_tile_cnt = tile_cnt;
}
return p;
}
bool string_to_tiles(const char *str, SET *fixed_sets, long *fixed_set_cnt, TILE *concealed_tiles, long *concealed_cnt) {
SET sets[5];
long set_cnt = 0;
bool has_fixed_set = false, is_concealed_kong = false;
TILE tiles[14];
long tile_cnt = 0;
const char *p = str;
while (char c = *p) {
const char *q;
switch (c) {
case '[':
q = ++p;
is_concealed_kong = false;
has_fixed_set = true;
break;
case ']':
if (!has_fixed_set) {
puts("Closing bracket ] does not match");
return false;
}
if (tile_cnt != 3 && tile_cnt != 4) {
puts("Only 3 or 4 tiles allowed in a fixed set between [ ]");
return false;
}
if (tile_cnt == 3) {
if (is_concealed_kong) {
puts("Concealed kong need 4 same tiles");
return false;
}
if (tiles[0] + 1 == tiles[1] && tiles[1] + 1 == tiles[2]) {
sets[set_cnt].mid_tile = tiles[1];
sets[set_cnt].set_type = SET_TYPE::CHOW;
sets[set_cnt].is_melded = true;
}
else if (tiles[0] == tiles[1] && tiles[1] == tiles[2]) {
sets[set_cnt].mid_tile = tiles[1];
sets[set_cnt].set_type = SET_TYPE::PUNG;
sets[set_cnt].is_melded = true;
}
else {
puts("Cannot make a chow or pung");
return false;
}
}
else {
if (tiles[0] != tiles[1] || tiles[1] != tiles[2] || tiles[2] != tiles[3]) {
puts("Kong need 4 same tiles");
}
sets[set_cnt].mid_tile = tiles[0];
sets[set_cnt].set_type = SET_TYPE::KONG;
sets[set_cnt].is_melded = true;
}
q = ++p;
has_fixed_set = false;
++set_cnt;
tile_cnt = 0;
break;
case '{':
q = ++p;
is_concealed_kong = true;
has_fixed_set = true;
break;
case '}':
if (!has_fixed_set) {
puts("Closing bracket } does not match");
return false;
}
if (!is_concealed_kong) {
puts("{} is only for concealed kong");
return false;
}
if (tile_cnt != 4) {
puts("Concealed kong need 4 same tiles");
return false;
}
q = ++p;
sets[set_cnt].mid_tile = tiles[0];
sets[set_cnt].set_type = SET_TYPE::KONG;
sets[set_cnt].is_melded = false;
has_fixed_set = false;
++set_cnt;
tile_cnt = 0;
break;
default:
q = parse_tiles(p, tiles, &tile_cnt);
if (q == p || q == nullptr) {
puts("Unexpect character");
return false;
}
break;
}
p = q;
}
if (has_fixed_set) {
puts("Expect closing bracket!");
return false;
}
//for (long i = 0; i < set_cnt; ++i) {
// printf("[%d %s %x] ", sets[i].is_melded, set_type_name[(int)sets[i].set_type], sets[i].mid_tile);
//}
//for (long i = 0; i < tile_cnt; ++i) {
// printf("%x ", tiles[i]);
//}
//puts("");
if (fixed_sets != nullptr) {
memcpy(fixed_sets, sets, set_cnt * sizeof(SET));
}
if (fixed_set_cnt != nullptr) {
*fixed_set_cnt = set_cnt;
}
memcpy(concealed_tiles, tiles, tile_cnt * sizeof(TILE));
if (concealed_cnt != nullptr) {
*concealed_cnt = tile_cnt;
}
return true;
}
int calculate_points(const SET *fixed_set, long fixed_cnt, const TILE *concealed_tiles, long concealed_cnt, TILE win_tile, WIN_TYPE win_type,
WIND_TYPE prevalent_wind, WIND_TYPE seat_wind, long (&points_table)[POINT_TYPE_COUNT]) {
if (fixed_set == nullptr) {
fixed_cnt = 0;
}
if (concealed_tiles == nullptr || concealed_cnt <= 0 || fixed_cnt < 0 || fixed_cnt > 4
|| fixed_cnt * 3 + concealed_cnt != 13) {
return ERROR_WRONG_TILES_COUNT;
}
TILE _concealed_tiles[14];
SET _separation_sets[MAX_SEPARAION_CNT][5];
long _separation_cnt;
// 合并得到14张牌
memcpy(_concealed_tiles, concealed_tiles, sizeof(TILE) * concealed_cnt);
_concealed_tiles[concealed_cnt] = win_tile;
sort_tiles(_concealed_tiles, concealed_cnt + 1);
memcpy(_separation_sets[0], fixed_set, fixed_cnt * sizeof(SET));
for (long i = 0; i < fixed_cnt; ++i) {
if (fixed_set[i].set_type != SET_TYPE::KONG) {
_separation_sets[0][i].is_melded = true;
}
}
_separation_cnt = 0;
seperate_N(_concealed_tiles, concealed_cnt + 1, fixed_cnt, _separation_sets, &_separation_cnt);
for (long i = 0; i < _separation_cnt; ++i) {
std::sort(&_separation_sets[i][fixed_cnt], &_separation_sets[i][4], &set_cmp);
}
long points_tables[MAX_SEPARAION_CNT][POINT_TYPE_COUNT] = { 0 };
int max_points = 0;
long max_idx = -1;
if (fixed_cnt == 0) { // 门清状态,有可能是基本和型组合龙
if (calculate_knitted_straight_in_basic_type_points(_separation_sets[_separation_cnt][0], _concealed_tiles, 14,
win_tile, win_type, prevalent_wind, seat_wind, points_tables[_separation_cnt])) {
int current_points = get_points_by_table(points_tables[_separation_cnt]);
if (current_points > max_points) {
max_points = current_points;
max_idx = _separation_cnt;
}
printf("points = %d\n\n", current_points);
}
else if (calculate_special_type_points(_concealed_tiles, win_type, points_tables[_separation_cnt])) {
int current_points = get_points_by_table(points_tables[_separation_cnt]);
if (current_points > max_points) {
max_points = current_points;
max_idx = _separation_cnt;
}
printf("points = %d\n\n", current_points);
if (points_tables[_separation_cnt][SEVEN_SHIFTED_PAIRS]) {
_separation_cnt = 0;
}
}
}
else if (fixed_cnt == 1 && _separation_cnt == 0) {
// 1副露状态,有可能是基本和型组合龙
if (calculate_knitted_straight_in_basic_type_points(_separation_sets[0][0], _concealed_tiles, 14,
win_tile, win_type, prevalent_wind, seat_wind, points_tables[0])) {
int current_points = get_points_by_table(points_tables[0]);
if (current_points > max_points) {
max_points = current_points;
max_idx = _separation_cnt;
}
printf("points = %d\n\n", current_points);
}
}
// 遍历各种划分方式,分别算番,找出最大的番的划分方式
for (long i = 0; i < _separation_cnt; ++i) {
for (int j = 0; j < 5; ++j) {
//printf("[%d %s %x]", _separation_sets[i][j].is_melded,
// set_type_name[(int)_separation_sets[i][j].set_type], _separation_sets[i][j].mid_tile);
TILE mid_tile = _separation_sets[i][j].mid_tile;
switch (_separation_sets[i][j].set_type) {
case SET_TYPE::CHOW:
printf(_separation_sets[i][j].is_melded ? "[%s%s%s]" : "{%s%s%s}",
stringify_table[mid_tile - 1], stringify_table[mid_tile], stringify_table[mid_tile + 1]);
break;
case SET_TYPE::PUNG:
printf(_separation_sets[i][j].is_melded ? "[%s%s%s]" : "{%s%s%s}",
stringify_table[mid_tile], stringify_table[mid_tile], stringify_table[mid_tile]);
break;
case SET_TYPE::KONG:
printf(_separation_sets[i][j].is_melded ? "[%s%s%s%s]" : "{%s%s%s%s}",
stringify_table[mid_tile], stringify_table[mid_tile], stringify_table[mid_tile], stringify_table[mid_tile]);
break;
case SET_TYPE::PAIR:
printf(_separation_sets[i][j].is_melded ? "[%s%s]" : "{%s%s}",
stringify_table[mid_tile], stringify_table[mid_tile]);
break;
default:
break;
}
}
puts("");
calculate_basic_type_points(_separation_sets[i], fixed_cnt, win_tile, win_type, prevalent_wind, seat_wind, points_tables[i]);
int current_points = get_points_by_table(points_tables[i]);
if (current_points > max_points) {
max_points = current_points;
max_idx = i;
}
printf("points = %d\n\n", current_points);
}
if (max_idx == -1) {
return ERROR_NOT_WIN;
}
memcpy(points_table, points_tables[max_idx], sizeof(points_table));
return max_points;
}
}
|
// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#include "bsesequencer.hh"
#include <bse/bseengine.hh>
#include <bse/bsecxxplugin.hh>
enum {
PARAM_0,
PARAM_NOTES,
PARAM_LENGTH,
PARAM_TRANSPOSE,
PARAM_COUNTER
};
/* --- prototypes --- */
static void bse_sequencer_init (BseSequencer *sequencer);
static void bse_sequencer_class_init (BseSequencerClass *klass);
static void bse_sequencer_finalize (GObject *object);
static void bse_sequencer_set_property (BseSequencer *sequencer,
guint param_id,
GValue *value,
GParamSpec *pspec);
static void bse_sequencer_get_property (BseSequencer *sequencer,
guint param_id,
GValue *value,
GParamSpec *pspec);
static void bse_sequencer_prepare (BseSource *source);
static void bse_sequencer_context_create (BseSource *source,
guint context_handle,
BseTrans *trans);
static void bse_sequencer_reset (BseSource *source);
static void bse_sequencer_update_modules (BseSequencer *seq);
// == Type Registration ==
#include "./icons/sequencer.c"
BSE_RESIDENT_SOURCE_DEF (BseSequencer, bse_sequencer, N_("Other Sources/Sequencer"),
"The Sequencer produces a frequency signal according to a sequence of notes",
sequencer_icon);
/* --- variables --- */
static gpointer parent_class = NULL;
/* --- functions --- */
static void
bse_sequencer_class_init (BseSequencerClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
BseObjectClass *object_class = BSE_OBJECT_CLASS (klass);
BseSourceClass *source_class = BSE_SOURCE_CLASS (klass);
guint ochannel;
parent_class = g_type_class_peek_parent (klass);
gobject_class->set_property = (GObjectSetPropertyFunc) bse_sequencer_set_property;
gobject_class->get_property = (GObjectGetPropertyFunc) bse_sequencer_get_property;
gobject_class->finalize = bse_sequencer_finalize;
source_class->prepare = bse_sequencer_prepare;
source_class->context_create = bse_sequencer_context_create;
source_class->reset = bse_sequencer_reset;
bse_object_class_add_param (object_class, "Sequence",
PARAM_LENGTH,
sfi_pspec_int ("length", "Length", NULL,
8, 1, 128, 4,
SFI_PARAM_GUI ":scale"));
bse_object_class_add_param (object_class, "Sequence",
PARAM_NOTES,
bse_param_spec_boxed ("notes", "Notes", NULL,
BSE_TYPE_NOTE_SEQUENCE,
"note-sequence:" SFI_PARAM_STANDARD));
bse_object_class_add_param (object_class, "Sequence",
PARAM_TRANSPOSE,
sfi_pspec_int ("transpose", "Transpose", NULL,
0, -36, +36, 3,
SFI_PARAM_STANDARD ":scale:skip-default"));
bse_object_class_add_param (object_class, "Sequence",
PARAM_COUNTER,
sfi_pspec_real ("counter", "Timing [ms]", NULL,
100, 0, 1000, 5,
SFI_PARAM_STANDARD ":f:scale"));
ochannel = bse_source_class_add_ochannel (source_class, "freq-out", _("Freq Out"), _("Frequency Signal"));
assert (ochannel == BSE_SEQUENCER_OCHANNEL_FREQ);
ochannel = bse_source_class_add_ochannel (source_class, "note-sync", _("Note Sync"), _("Note Sync Signal"));
assert (ochannel == BSE_SEQUENCER_OCHANNEL_NOTE_SYNC);
}
static void
bse_sequencer_init (BseSequencer *seq)
{
seq->sdata = bse_note_sequence_new ();
bse_note_sequence_resize (seq->sdata, 8);
seq->sdata->offset = SFI_NOTE_C (SFI_KAMMER_OCTAVE);
seq->n_freq_values = 0;
seq->freq_values = NULL;
seq->transpose = 0;
}
static void
bse_sequencer_finalize (GObject *object)
{
BseSequencer *seq = BSE_SEQUENCER (object);
bse_note_sequence_free (seq->sdata);
/* chain parent class' handler */
G_OBJECT_CLASS (parent_class)->finalize (object);
}
static void
bse_sequencer_set_property (BseSequencer *seq,
guint param_id,
GValue *value,
GParamSpec *pspec)
{
switch (param_id)
{
BseNoteSequence *sdata;
case PARAM_LENGTH:
if (sfi_value_get_int (value) != (int) bse_note_sequence_length (seq->sdata))
{
bse_note_sequence_resize (seq->sdata, sfi_value_get_int (value));
bse_sequencer_update_modules (seq);
g_object_notify ((GObject*) seq, "notes");
}
break;
case PARAM_NOTES:
bse_note_sequence_free (seq->sdata);
sdata = (BseNoteSequence*) bse_value_get_boxed (value);
if (sdata)
{
guint i, l, mnote = SFI_MAX_NOTE;
seq->sdata = bse_note_sequence_copy_shallow (sdata);
/* fixup offset */
l = bse_note_sequence_length (seq->sdata);
for (i = 0; i < l; i++)
mnote = MIN (mnote, seq->sdata->notes->notes[i]);
if (l && ABS (mnote - seq->sdata->offset) >= 12)
seq->sdata->offset = (mnote < SFI_NOTE_A (SFI_NOTE_OCTAVE (mnote)) ?
SFI_NOTE_C (SFI_NOTE_OCTAVE (mnote)) :
SFI_NOTE_A (SFI_NOTE_OCTAVE (mnote)));
}
else
{
seq->sdata = bse_note_sequence_new ();
bse_note_sequence_resize (seq->sdata, 8);
seq->sdata->offset = SFI_NOTE_C (SFI_KAMMER_OCTAVE);
}
bse_sequencer_update_modules (seq);
g_object_notify ((GObject*) seq, "length");
break;
case PARAM_COUNTER:
seq->counter = sfi_value_get_real (value);
bse_sequencer_update_modules (seq);
break;
case PARAM_TRANSPOSE:
seq->transpose = sfi_value_get_int (value);
bse_sequencer_update_modules (seq);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (seq, param_id, pspec);
break;
}
}
static void
bse_sequencer_get_property (BseSequencer *seq,
guint param_id,
GValue *value,
GParamSpec *pspec)
{
switch (param_id)
{
case PARAM_NOTES:
bse_value_set_boxed (value, seq->sdata);
break;
case PARAM_LENGTH:
sfi_value_set_int (value, bse_note_sequence_length (seq->sdata));
break;
case PARAM_COUNTER:
sfi_value_set_real (value, seq->counter);
break;
case PARAM_TRANSPOSE:
sfi_value_set_int (value, seq->transpose);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (seq, param_id, pspec);
break;
}
}
static gfloat*
freq_values_from_seq (BseMusicalTuningType musical_tuning,
BseNoteSequence *sdata,
gint transpose)
{
gfloat *v = g_new (gfloat, bse_note_sequence_length (sdata));
guint i;
for (i = 0; i < bse_note_sequence_length (sdata); i++)
{
gint note = sdata->notes->notes[i];
if (note == SFI_NOTE_VOID)
v[i] = 0;
else
v[i] = BSE_VALUE_FROM_FREQ (bse_note_to_freq (musical_tuning, CLAMP (note + transpose, SFI_MIN_NOTE, SFI_MAX_NOTE)));
}
return v;
}
typedef struct {
guint n_values;
gfloat *values; /* notes */
guint counter;
guint index; /* nth_note */
guint c; /* timing */
} SeqModule;
typedef struct {
guint n_values;
gfloat *new_values;
guint counter;
gfloat *old_values;
} AccessData;
static void
seq_access (BseModule *module,
gpointer data)
{
SeqModule *smod = (SeqModule*) module->user_data;
AccessData *d = (AccessData*) data;
smod->n_values = d->n_values;
smod->values = d->new_values;
smod->counter = d->counter;
smod->index %= smod->n_values;
smod->c %= smod->counter;
if (smod->c < 1)
smod->c = smod->counter;
}
static void
seq_access_free (gpointer data)
{
AccessData *d = (AccessData*) data;
g_free (d->old_values);
g_free (d);
}
static void
bse_sequencer_update_modules (BseSequencer *seq)
{
if (BSE_SOURCE_PREPARED (seq))
{
AccessData *d = g_new (AccessData, 1);
d->old_values = seq->freq_values;
seq->n_freq_values = bse_note_sequence_length (seq->sdata);
seq->freq_values = freq_values_from_seq (bse_source_prepared_musical_tuning (BSE_SOURCE (seq)), seq->sdata, seq->transpose);
d->n_values = seq->n_freq_values;
d->new_values = seq->freq_values;
d->counter = seq->counter / 1000.0 * bse_engine_sample_freq ();
d->counter = MAX (d->counter, 1);
bse_source_access_modules (BSE_SOURCE (seq),
seq_access, d, seq_access_free,
NULL);
}
}
static void
sequencer_process (BseModule *module,
guint n_values)
{
SeqModule *smod = (SeqModule*) module->user_data;
gfloat *freq_out = BSE_MODULE_OBUFFER (module, BSE_SEQUENCER_OCHANNEL_FREQ);
gfloat *nsync_out = BSE_MODULE_OBUFFER (module, BSE_SEQUENCER_OCHANNEL_NOTE_SYNC);
gfloat *bound = freq_out + n_values;
while (freq_out < bound)
{
gfloat nval = smod->values[smod->index];
if (smod->c == 0)
{
smod->c = smod->counter;
smod->index++;
if (smod->index >= smod->n_values)
smod->index = 0;
*nsync_out = 1.0;
}
else
*nsync_out = 0.0;
*freq_out++ = nval;
nsync_out++;
smod->c--;
}
}
static void
bse_sequencer_prepare (BseSource *source)
{
BseSequencer *seq = BSE_SEQUENCER (source);
seq->n_freq_values = bse_note_sequence_length (seq->sdata);
seq->freq_values = freq_values_from_seq (bse_source_prepared_musical_tuning (source), seq->sdata, seq->transpose);
/* chain parent class' handler */
BSE_SOURCE_CLASS (parent_class)->prepare (source);
}
static void
bse_sequencer_context_create (BseSource *source,
guint context_handle,
BseTrans *trans)
{
static const BseModuleClass sequencer_class = {
0, /* n_istreams */
0, /* n_jstreams */
BSE_SEQUENCER_N_OCHANNELS, /* n_ostreams */
sequencer_process, /* process */
NULL, /* process_defer */
NULL, /* reset */
(BseModuleFreeFunc) g_free, /* free */
BSE_COST_CHEAP, /* flags */
};
BseSequencer *seq = BSE_SEQUENCER (source);
SeqModule *smod = g_new0 (SeqModule, 1);
BseModule *module;
smod->n_values = seq->n_freq_values;
smod->values = seq->freq_values;
smod->counter = seq->counter / 1000.0 * bse_engine_sample_freq ();
smod->counter = MAX (smod->counter, 1);
smod->index = 0;
smod->c = smod->counter;
module = bse_module_new (&sequencer_class, smod);
/* setup module i/o streams with BseSource i/o channels */
bse_source_set_context_module (source, context_handle, module);
/* commit module to engine */
bse_trans_add (trans, bse_job_integrate (module));
/* chain parent class' handler */
BSE_SOURCE_CLASS (parent_class)->context_create (source, context_handle, trans);
}
static void
bse_sequencer_reset (BseSource *source)
{
BseSequencer *seq = BSE_SEQUENCER (source);
g_free (seq->freq_values);
seq->freq_values = NULL;
seq->n_freq_values = 0;
/* chain parent class' handler */
BSE_SOURCE_CLASS (parent_class)->reset (source);
}
PLUGINS: fix signedness compiler warnings
// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#include "bsesequencer.hh"
#include <bse/bseengine.hh>
#include <bse/bsecxxplugin.hh>
enum {
PARAM_0,
PARAM_NOTES,
PARAM_LENGTH,
PARAM_TRANSPOSE,
PARAM_COUNTER
};
/* --- prototypes --- */
static void bse_sequencer_init (BseSequencer *sequencer);
static void bse_sequencer_class_init (BseSequencerClass *klass);
static void bse_sequencer_finalize (GObject *object);
static void bse_sequencer_set_property (BseSequencer *sequencer,
guint param_id,
GValue *value,
GParamSpec *pspec);
static void bse_sequencer_get_property (BseSequencer *sequencer,
guint param_id,
GValue *value,
GParamSpec *pspec);
static void bse_sequencer_prepare (BseSource *source);
static void bse_sequencer_context_create (BseSource *source,
guint context_handle,
BseTrans *trans);
static void bse_sequencer_reset (BseSource *source);
static void bse_sequencer_update_modules (BseSequencer *seq);
// == Type Registration ==
#include "./icons/sequencer.c"
BSE_RESIDENT_SOURCE_DEF (BseSequencer, bse_sequencer, N_("Other Sources/Sequencer"),
"The Sequencer produces a frequency signal according to a sequence of notes",
sequencer_icon);
/* --- variables --- */
static gpointer parent_class = NULL;
/* --- functions --- */
static void
bse_sequencer_class_init (BseSequencerClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
BseObjectClass *object_class = BSE_OBJECT_CLASS (klass);
BseSourceClass *source_class = BSE_SOURCE_CLASS (klass);
guint ochannel;
parent_class = g_type_class_peek_parent (klass);
gobject_class->set_property = (GObjectSetPropertyFunc) bse_sequencer_set_property;
gobject_class->get_property = (GObjectGetPropertyFunc) bse_sequencer_get_property;
gobject_class->finalize = bse_sequencer_finalize;
source_class->prepare = bse_sequencer_prepare;
source_class->context_create = bse_sequencer_context_create;
source_class->reset = bse_sequencer_reset;
bse_object_class_add_param (object_class, "Sequence",
PARAM_LENGTH,
sfi_pspec_int ("length", "Length", NULL,
8, 1, 128, 4,
SFI_PARAM_GUI ":scale"));
bse_object_class_add_param (object_class, "Sequence",
PARAM_NOTES,
bse_param_spec_boxed ("notes", "Notes", NULL,
BSE_TYPE_NOTE_SEQUENCE,
"note-sequence:" SFI_PARAM_STANDARD));
bse_object_class_add_param (object_class, "Sequence",
PARAM_TRANSPOSE,
sfi_pspec_int ("transpose", "Transpose", NULL,
0, -36, +36, 3,
SFI_PARAM_STANDARD ":scale:skip-default"));
bse_object_class_add_param (object_class, "Sequence",
PARAM_COUNTER,
sfi_pspec_real ("counter", "Timing [ms]", NULL,
100, 0, 1000, 5,
SFI_PARAM_STANDARD ":f:scale"));
ochannel = bse_source_class_add_ochannel (source_class, "freq-out", _("Freq Out"), _("Frequency Signal"));
assert (ochannel == BSE_SEQUENCER_OCHANNEL_FREQ);
ochannel = bse_source_class_add_ochannel (source_class, "note-sync", _("Note Sync"), _("Note Sync Signal"));
assert (ochannel == BSE_SEQUENCER_OCHANNEL_NOTE_SYNC);
}
static void
bse_sequencer_init (BseSequencer *seq)
{
seq->sdata = bse_note_sequence_new ();
bse_note_sequence_resize (seq->sdata, 8);
seq->sdata->offset = SFI_NOTE_C (SFI_KAMMER_OCTAVE);
seq->n_freq_values = 0;
seq->freq_values = NULL;
seq->transpose = 0;
}
static void
bse_sequencer_finalize (GObject *object)
{
BseSequencer *seq = BSE_SEQUENCER (object);
bse_note_sequence_free (seq->sdata);
/* chain parent class' handler */
G_OBJECT_CLASS (parent_class)->finalize (object);
}
static void
bse_sequencer_set_property (BseSequencer *seq,
guint param_id,
GValue *value,
GParamSpec *pspec)
{
switch (param_id)
{
BseNoteSequence *sdata;
case PARAM_LENGTH:
if (sfi_value_get_int (value) != (int) bse_note_sequence_length (seq->sdata))
{
bse_note_sequence_resize (seq->sdata, sfi_value_get_int (value));
bse_sequencer_update_modules (seq);
g_object_notify ((GObject*) seq, "notes");
}
break;
case PARAM_NOTES:
bse_note_sequence_free (seq->sdata);
sdata = (BseNoteSequence*) bse_value_get_boxed (value);
if (sdata)
{
int mnote = SFI_MAX_NOTE;
seq->sdata = bse_note_sequence_copy_shallow (sdata);
/* fixup offset */
uint l = bse_note_sequence_length (seq->sdata);
for (uint i = 0; i < l; i++)
mnote = MIN (mnote, seq->sdata->notes->notes[i]);
if (l && ABS (mnote - seq->sdata->offset) >= 12)
seq->sdata->offset = (mnote < SFI_NOTE_A (SFI_NOTE_OCTAVE (mnote)) ?
SFI_NOTE_C (SFI_NOTE_OCTAVE (mnote)) :
SFI_NOTE_A (SFI_NOTE_OCTAVE (mnote)));
}
else
{
seq->sdata = bse_note_sequence_new ();
bse_note_sequence_resize (seq->sdata, 8);
seq->sdata->offset = SFI_NOTE_C (SFI_KAMMER_OCTAVE);
}
bse_sequencer_update_modules (seq);
g_object_notify ((GObject*) seq, "length");
break;
case PARAM_COUNTER:
seq->counter = sfi_value_get_real (value);
bse_sequencer_update_modules (seq);
break;
case PARAM_TRANSPOSE:
seq->transpose = sfi_value_get_int (value);
bse_sequencer_update_modules (seq);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (seq, param_id, pspec);
break;
}
}
static void
bse_sequencer_get_property (BseSequencer *seq,
guint param_id,
GValue *value,
GParamSpec *pspec)
{
switch (param_id)
{
case PARAM_NOTES:
bse_value_set_boxed (value, seq->sdata);
break;
case PARAM_LENGTH:
sfi_value_set_int (value, bse_note_sequence_length (seq->sdata));
break;
case PARAM_COUNTER:
sfi_value_set_real (value, seq->counter);
break;
case PARAM_TRANSPOSE:
sfi_value_set_int (value, seq->transpose);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (seq, param_id, pspec);
break;
}
}
static gfloat*
freq_values_from_seq (BseMusicalTuningType musical_tuning,
BseNoteSequence *sdata,
gint transpose)
{
gfloat *v = g_new (gfloat, bse_note_sequence_length (sdata));
guint i;
for (i = 0; i < bse_note_sequence_length (sdata); i++)
{
gint note = sdata->notes->notes[i];
if (note == SFI_NOTE_VOID)
v[i] = 0;
else
v[i] = BSE_VALUE_FROM_FREQ (bse_note_to_freq (musical_tuning, CLAMP (note + transpose, SFI_MIN_NOTE, SFI_MAX_NOTE)));
}
return v;
}
typedef struct {
guint n_values;
gfloat *values; /* notes */
guint counter;
guint index; /* nth_note */
guint c; /* timing */
} SeqModule;
typedef struct {
guint n_values;
gfloat *new_values;
guint counter;
gfloat *old_values;
} AccessData;
static void
seq_access (BseModule *module,
gpointer data)
{
SeqModule *smod = (SeqModule*) module->user_data;
AccessData *d = (AccessData*) data;
smod->n_values = d->n_values;
smod->values = d->new_values;
smod->counter = d->counter;
smod->index %= smod->n_values;
smod->c %= smod->counter;
if (smod->c < 1)
smod->c = smod->counter;
}
static void
seq_access_free (gpointer data)
{
AccessData *d = (AccessData*) data;
g_free (d->old_values);
g_free (d);
}
static void
bse_sequencer_update_modules (BseSequencer *seq)
{
if (BSE_SOURCE_PREPARED (seq))
{
AccessData *d = g_new (AccessData, 1);
d->old_values = seq->freq_values;
seq->n_freq_values = bse_note_sequence_length (seq->sdata);
seq->freq_values = freq_values_from_seq (bse_source_prepared_musical_tuning (BSE_SOURCE (seq)), seq->sdata, seq->transpose);
d->n_values = seq->n_freq_values;
d->new_values = seq->freq_values;
d->counter = seq->counter / 1000.0 * bse_engine_sample_freq ();
d->counter = MAX (d->counter, 1);
bse_source_access_modules (BSE_SOURCE (seq),
seq_access, d, seq_access_free,
NULL);
}
}
static void
sequencer_process (BseModule *module,
guint n_values)
{
SeqModule *smod = (SeqModule*) module->user_data;
gfloat *freq_out = BSE_MODULE_OBUFFER (module, BSE_SEQUENCER_OCHANNEL_FREQ);
gfloat *nsync_out = BSE_MODULE_OBUFFER (module, BSE_SEQUENCER_OCHANNEL_NOTE_SYNC);
gfloat *bound = freq_out + n_values;
while (freq_out < bound)
{
gfloat nval = smod->values[smod->index];
if (smod->c == 0)
{
smod->c = smod->counter;
smod->index++;
if (smod->index >= smod->n_values)
smod->index = 0;
*nsync_out = 1.0;
}
else
*nsync_out = 0.0;
*freq_out++ = nval;
nsync_out++;
smod->c--;
}
}
static void
bse_sequencer_prepare (BseSource *source)
{
BseSequencer *seq = BSE_SEQUENCER (source);
seq->n_freq_values = bse_note_sequence_length (seq->sdata);
seq->freq_values = freq_values_from_seq (bse_source_prepared_musical_tuning (source), seq->sdata, seq->transpose);
/* chain parent class' handler */
BSE_SOURCE_CLASS (parent_class)->prepare (source);
}
static void
bse_sequencer_context_create (BseSource *source,
guint context_handle,
BseTrans *trans)
{
static const BseModuleClass sequencer_class = {
0, /* n_istreams */
0, /* n_jstreams */
BSE_SEQUENCER_N_OCHANNELS, /* n_ostreams */
sequencer_process, /* process */
NULL, /* process_defer */
NULL, /* reset */
(BseModuleFreeFunc) g_free, /* free */
BSE_COST_CHEAP, /* flags */
};
BseSequencer *seq = BSE_SEQUENCER (source);
SeqModule *smod = g_new0 (SeqModule, 1);
BseModule *module;
smod->n_values = seq->n_freq_values;
smod->values = seq->freq_values;
smod->counter = seq->counter / 1000.0 * bse_engine_sample_freq ();
smod->counter = MAX (smod->counter, 1);
smod->index = 0;
smod->c = smod->counter;
module = bse_module_new (&sequencer_class, smod);
/* setup module i/o streams with BseSource i/o channels */
bse_source_set_context_module (source, context_handle, module);
/* commit module to engine */
bse_trans_add (trans, bse_job_integrate (module));
/* chain parent class' handler */
BSE_SOURCE_CLASS (parent_class)->context_create (source, context_handle, trans);
}
static void
bse_sequencer_reset (BseSource *source)
{
BseSequencer *seq = BSE_SEQUENCER (source);
g_free (seq->freq_values);
seq->freq_values = NULL;
seq->n_freq_values = 0;
/* chain parent class' handler */
BSE_SOURCE_CLASS (parent_class)->reset (source);
}
|
/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkBoundingObjectGroup.h"
#include "vtkTransform.h"
mitk::BoundingObjectGroup::BoundingObjectGroup()
: m_Counter(0), m_CSGMode(Difference) //m_CSGMode(Union) m_CSGMode(Intersection)
{
m_Geometry3D->Initialize();
m_BoundingObjects = mitk::BoundingObjectGroup::BoundingObjectContainer::New();
SetVtkPolyData(NULL);
}
mitk::BoundingObjectGroup::~BoundingObjectGroup()
{
}
void mitk::BoundingObjectGroup::SetRequestedRegionToLargestPossibleRegion()
{
}
bool mitk::BoundingObjectGroup::RequestedRegionIsOutsideOfTheBufferedRegion()
{
return ! VerifyRequestedRegion();
}
bool mitk::BoundingObjectGroup::VerifyRequestedRegion()
{
assert(m_Geometry3D.IsNotNull());
return true;
}
void mitk::BoundingObjectGroup::SetRequestedRegion(itk::DataObject *data)
{
}
void mitk::BoundingObjectGroup::UpdateOutputInformation()
{
ScalarType bounds[6]={0,1,0,1,0,1}; // {xmin,x_max, ymin,y_max,zmin,z_max};
// calculate global bounding box
mitk::BoundingObjectGroup::BoundingObjectContainer::ConstIterator boundingObjectsIterator = m_BoundingObjects->Begin();
const mitk::BoundingObjectGroup::BoundingObjectContainer::ConstIterator boundingObjectsIteratorEnd = m_BoundingObjects->End();
if(boundingObjectsIterator == boundingObjectsIteratorEnd) // if there is no BoundingObject, the bounding box is zero
{
bounds[0] = bounds[1] = bounds[2] = bounds[3] = bounds[4] = bounds[5] = 0.0;
return;
}
mitk::BoundingBox::Pointer boundingBox;
mitk::BoundingBox::PointType minPoint;
mitk::BoundingBox::PointType globalMinPoint;
mitk::BoundingBox::PointType globalMaxPoint;
/* Initialize globalMin/MaxPoints */
boundingObjectsIterator.Value()->UpdateOutputInformation();
boundingBox = const_cast<mitk::BoundingBox*>(boundingObjectsIterator.Value()->GetGeometry()->GetBoundingBox());
minPoint = boundingBox->GetMinimum();
mitk::ScalarType min[3];
min[0] = minPoint[0]; min[1] = minPoint[1]; min[2] = minPoint[2];
boundingObjectsIterator.Value()->GetGeometry()->GetVtkTransform()->TransformPoint(min, min);
globalMinPoint[0] = min[0]; globalMinPoint[1] = min[1]; globalMinPoint[2] = min[2];
globalMaxPoint[0] = min[0]; globalMaxPoint[1] = min[1]; globalMaxPoint[2] = min[2];
//boundingObjectsIterator++;
while (boundingObjectsIterator != boundingObjectsIteratorEnd) // calculate a bounding box that includes all BoundingObjects
{
boundingObjectsIterator.Value()->UpdateOutputInformation();
boundingBox = const_cast<mitk::BoundingBox*>(boundingObjectsIterator.Value()->GetGeometry()->GetBoundingBox());
/* create all 8 points of the bounding box */
mitk::BoundingBox::PointsContainerPointer points = mitk::BoundingBox::PointsContainer::New();
mitk::Point3D p;
p = boundingBox->GetMinimum();
points->InsertElement(0, p);
p[0] = -p[0];
points->InsertElement(1, p);
p = boundingBox->GetMinimum();
p[1] = -p[1];
points->InsertElement(2, p);
p = boundingBox->GetMinimum();
p[2] = -p[2];
points->InsertElement(3, p);
p = boundingBox->GetMaximum();
points->InsertElement(4, p);
p[0] = -p[0];
points->InsertElement(5, p);
p = boundingBox->GetMaximum();
p[1] = -p[1];
points->InsertElement(6, p);
p = boundingBox->GetMaximum();
p[2] = -p[2];
points->InsertElement(7, p);
mitk::BoundingBox::PointsContainerConstIterator pointsIterator = points->Begin();
mitk::BoundingBox::PointsContainerConstIterator pointsIteratorEnd = points->End();
while (pointsIterator != pointsIteratorEnd) // for each vertex of the bounding box
{
minPoint = pointsIterator->Value();
min[0] = minPoint[0]; min[1] = minPoint[1]; min[2] = minPoint[2];
boundingObjectsIterator.Value()->GetGeometry()->GetVtkTransform()->TransformPoint(min, min); // transform vertex point to world coordinates
globalMinPoint[0] = (min[0] < globalMinPoint[0]) ? min[0] : globalMinPoint[0]; // check if world point
globalMinPoint[1] = (min[1] < globalMinPoint[1]) ? min[1] : globalMinPoint[1]; // has a lower or a
globalMinPoint[2] = (min[2] < globalMinPoint[2]) ? min[2] : globalMinPoint[2]; // higher value as
globalMaxPoint[0] = (min[0] > globalMaxPoint[0]) ? min[0] : globalMaxPoint[0]; // the last known highest
globalMaxPoint[1] = (min[1] > globalMaxPoint[1]) ? min[1] : globalMaxPoint[1]; // value
globalMaxPoint[2] = (min[2] > globalMaxPoint[2]) ? min[2] : globalMaxPoint[2]; // in each axis
pointsIterator++;
}
boundingObjectsIterator++;
}
/* BoundingBox is centered around the center of all sub bounding objects */
mitk::BoundingBox::PointType centerPoint;
centerPoint[0] = (globalMinPoint[0] + globalMaxPoint[0])/ 2.0;
centerPoint[1] = (globalMinPoint[1] + globalMaxPoint[1])/ 2.0;
centerPoint[2] = (globalMinPoint[2] + globalMaxPoint[2])/ 2.0;
bounds[0] = globalMinPoint[0] - centerPoint[0]; // x Min
bounds[1] = globalMaxPoint[0] - centerPoint[0]; // x Max
bounds[2] = globalMinPoint[1] - centerPoint[1]; // y Min
bounds[3] = globalMaxPoint[1] - centerPoint[1]; // y Max
bounds[4] = globalMinPoint[2] - centerPoint[2]; // z Min
bounds[5] = globalMaxPoint[2] - centerPoint[2]; // z Max
m_Geometry3D->SetBounds(bounds);
/* the objects position is the center of all sub bounding objects */
m_Geometry3D->GetVtkTransform()->Identity();
m_Geometry3D->GetVtkTransform()->Translate(centerPoint[0], centerPoint[1], centerPoint[2]);
m_Geometry3D->TransferVtkToITKTransform();
}
void mitk::BoundingObjectGroup::AddBoundingObject(mitk::BoundingObject::Pointer boundingObject)
{
m_BoundingObjects->InsertElement( m_Counter++, boundingObject);
UpdateOutputInformation();
}
bool mitk::BoundingObjectGroup::IsInside(mitk::Point3D p)
{
mitk::BoundingObjectGroup::BoundingObjectContainer::ConstIterator boundingObjectsIterator = m_BoundingObjects->Begin();
const mitk::BoundingObjectGroup::BoundingObjectContainer::ConstIterator boundingObjectsIteratorEnd = m_BoundingObjects->End();
bool inside; // initialize with true for intersection, with false for union
switch(m_CSGMode)
{
case Intersection:
{
inside = true;
while (boundingObjectsIterator != boundingObjectsIteratorEnd) // check each BoundingObject
{ // calculate intersection: each point, that is inside each BoundingObject is considered inside the group
inside = boundingObjectsIterator.Value()->IsInside(p) && inside;
if (!inside) // shortcut, it is enough to find one object that does not contain the point
break;
boundingObjectsIterator++;
}
break;
}
case Difference:
{
bool posInside = false;
bool negInside = false;
while (boundingObjectsIterator != boundingObjectsIteratorEnd) // check each BoundingObject
{
// calculate union: each point, that is inside least one BoundingObject is considered inside the group
if (boundingObjectsIterator.Value()->GetPositive())
posInside = boundingObjectsIterator.Value()->IsInside(p) || posInside;
else
negInside = boundingObjectsIterator.Value()->IsInside(p) || negInside;
boundingObjectsIterator++;
}
if (posInside && !negInside)
inside = true;
else
inside = false;
break;
}
case Union:
default:
{
inside = false;
while (boundingObjectsIterator != boundingObjectsIteratorEnd) // check each BoundingObject
{ // calculate union: each point, that is inside least one BoundingObject is considered inside the group
inside = boundingObjectsIterator.Value()->IsInside(p) || inside;
if (inside) // shortcut, it is enough to find one object that contains the point
break;
boundingObjectsIterator++;
}
break;
}
}
return inside;
}
unsigned int mitk::BoundingObjectGroup::GetCount() const
{
return m_Counter;
}
FIX: bounds calculation of bounding object group is no longer overwritten; works now
/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkBoundingObjectGroup.h"
#include "vtkTransform.h"
mitk::BoundingObjectGroup::BoundingObjectGroup()
: m_Counter(0), m_CSGMode(Difference) //m_CSGMode(Union) m_CSGMode(Intersection)
{
m_Geometry3D->Initialize();
m_BoundingObjects = mitk::BoundingObjectGroup::BoundingObjectContainer::New();
SetVtkPolyData(NULL);
}
mitk::BoundingObjectGroup::~BoundingObjectGroup()
{
}
void mitk::BoundingObjectGroup::SetRequestedRegionToLargestPossibleRegion()
{
}
bool mitk::BoundingObjectGroup::RequestedRegionIsOutsideOfTheBufferedRegion()
{
return ! VerifyRequestedRegion();
}
bool mitk::BoundingObjectGroup::VerifyRequestedRegion()
{
assert(m_Geometry3D.IsNotNull());
return true;
}
void mitk::BoundingObjectGroup::SetRequestedRegion(itk::DataObject *data)
{
}
void mitk::BoundingObjectGroup::UpdateOutputInformation()
{
ScalarType bounds[6]={0,1,0,1,0,1}; // {xmin,x_max, ymin,y_max,zmin,z_max};
// calculate global bounding box
mitk::BoundingObjectGroup::BoundingObjectContainer::ConstIterator boundingObjectsIterator = m_BoundingObjects->Begin();
const mitk::BoundingObjectGroup::BoundingObjectContainer::ConstIterator boundingObjectsIteratorEnd = m_BoundingObjects->End();
if(boundingObjectsIterator == boundingObjectsIteratorEnd) // if there is no BoundingObject, the bounding box is zero
{
bounds[0] = bounds[1] = bounds[2] = bounds[3] = bounds[4] = bounds[5] = 0.0;
return;
}
mitk::BoundingBox::Pointer boundingBox;
mitk::BoundingBox::PointType minPoint;
mitk::BoundingBox::PointType globalMinPoint;
mitk::BoundingBox::PointType globalMaxPoint;
/* Initialize globalMin/MaxPoints */
boundingObjectsIterator.Value()->UpdateOutputInformation();
boundingBox = const_cast<mitk::BoundingBox*>(boundingObjectsIterator.Value()->GetGeometry()->GetBoundingBox());
minPoint = boundingBox->GetMinimum();
mitk::ScalarType min[3];
min[0] = minPoint[0]; min[1] = minPoint[1]; min[2] = minPoint[2];
boundingObjectsIterator.Value()->GetGeometry()->GetVtkTransform()->TransformPoint(min, min);
globalMinPoint[0] = min[0]; globalMinPoint[1] = min[1]; globalMinPoint[2] = min[2];
globalMaxPoint[0] = min[0]; globalMaxPoint[1] = min[1]; globalMaxPoint[2] = min[2];
//boundingObjectsIterator++;
while (boundingObjectsIterator != boundingObjectsIteratorEnd) // calculate a bounding box that includes all BoundingObjects
{
boundingObjectsIterator.Value()->UpdateOutputInformation();
boundingBox = const_cast<mitk::BoundingBox*>(boundingObjectsIterator.Value()->GetGeometry()->GetBoundingBox());
/* create all 8 points of the bounding box */
mitk::BoundingBox::PointsContainerPointer points = mitk::BoundingBox::PointsContainer::New();
mitk::Point3D p;
p = boundingBox->GetMinimum();
points->InsertElement(0, p);
p[0] = -p[0];
points->InsertElement(1, p);
p = boundingBox->GetMinimum();
p[1] = -p[1];
points->InsertElement(2, p);
p = boundingBox->GetMinimum();
p[2] = -p[2];
points->InsertElement(3, p);
p = boundingBox->GetMaximum();
points->InsertElement(4, p);
p[0] = -p[0];
points->InsertElement(5, p);
p = boundingBox->GetMaximum();
p[1] = -p[1];
points->InsertElement(6, p);
p = boundingBox->GetMaximum();
p[2] = -p[2];
points->InsertElement(7, p);
mitk::BoundingBox::PointsContainerConstIterator pointsIterator = points->Begin();
mitk::BoundingBox::PointsContainerConstIterator pointsIteratorEnd = points->End();
while (pointsIterator != pointsIteratorEnd) // for each vertex of the bounding box
{
minPoint = pointsIterator->Value();
min[0] = minPoint[0]; min[1] = minPoint[1]; min[2] = minPoint[2];
boundingObjectsIterator.Value()->GetGeometry()->GetVtkTransform()->TransformPoint(min, min); // transform vertex point to world coordinates
globalMinPoint[0] = (min[0] < globalMinPoint[0]) ? min[0] : globalMinPoint[0]; // check if world point
globalMinPoint[1] = (min[1] < globalMinPoint[1]) ? min[1] : globalMinPoint[1]; // has a lower or a
globalMinPoint[2] = (min[2] < globalMinPoint[2]) ? min[2] : globalMinPoint[2]; // higher value as
globalMaxPoint[0] = (min[0] > globalMaxPoint[0]) ? min[0] : globalMaxPoint[0]; // the last known highest
globalMaxPoint[1] = (min[1] > globalMaxPoint[1]) ? min[1] : globalMaxPoint[1]; // value
globalMaxPoint[2] = (min[2] > globalMaxPoint[2]) ? min[2] : globalMaxPoint[2]; // in each axis
pointsIterator++;
}
boundingObjectsIterator++;
}
/* BoundingBox is centered around the center of all sub bounding objects */
mitk::BoundingBox::PointType centerPoint;
centerPoint[0] = (globalMinPoint[0] + globalMaxPoint[0])/ 2.0;
centerPoint[1] = (globalMinPoint[1] + globalMaxPoint[1])/ 2.0;
centerPoint[2] = (globalMinPoint[2] + globalMaxPoint[2])/ 2.0;
bounds[0] = globalMinPoint[0] - centerPoint[0]; // x Min
bounds[1] = globalMaxPoint[0] - centerPoint[0]; // x Max
bounds[2] = globalMinPoint[1] - centerPoint[1]; // y Min
bounds[3] = globalMaxPoint[1] - centerPoint[1]; // y Max
bounds[4] = globalMinPoint[2] - centerPoint[2]; // z Min
bounds[5] = globalMaxPoint[2] - centerPoint[2]; // z Max
mitk::TimeSlicedGeometry::Pointer timeGeometry = const_cast< mitk::TimeSlicedGeometry *>(this->GetTimeSlicedGeometry());
mitk::Geometry3D::Pointer geometry3d = timeGeometry->GetGeometry3D(0);
unsigned int timesteps = timeGeometry->GetTimeSteps();
if(geometry3d.IsNull())
{
assert(timesteps==0);
timeGeometry->SetBounds(bounds);
/* the objects position is the center of all sub bounding objects */
timeGeometry->GetVtkTransform()->Identity();
timeGeometry->GetVtkTransform()->Translate(centerPoint[0], centerPoint[1], centerPoint[2]);
timeGeometry->TransferVtkToITKTransform();
}
else
{
assert(timesteps>0);
geometry3d->SetBounds(bounds);
/* the objects position is the center of all sub bounding objects */
geometry3d->GetVtkTransform()->Identity();
geometry3d->GetVtkTransform()->Translate(centerPoint[0], centerPoint[1], centerPoint[2]);
geometry3d->TransferVtkToITKTransform();
timeGeometry->InitializeEvenlyTimed(geometry3d, timesteps);
}
}
void mitk::BoundingObjectGroup::AddBoundingObject(mitk::BoundingObject::Pointer boundingObject)
{
m_BoundingObjects->InsertElement( m_Counter++, boundingObject);
UpdateOutputInformation();
}
bool mitk::BoundingObjectGroup::IsInside(mitk::Point3D p)
{
mitk::BoundingObjectGroup::BoundingObjectContainer::ConstIterator boundingObjectsIterator = m_BoundingObjects->Begin();
const mitk::BoundingObjectGroup::BoundingObjectContainer::ConstIterator boundingObjectsIteratorEnd = m_BoundingObjects->End();
bool inside; // initialize with true for intersection, with false for union
switch(m_CSGMode)
{
case Intersection:
{
inside = true;
while (boundingObjectsIterator != boundingObjectsIteratorEnd) // check each BoundingObject
{ // calculate intersection: each point, that is inside each BoundingObject is considered inside the group
inside = boundingObjectsIterator.Value()->IsInside(p) && inside;
if (!inside) // shortcut, it is enough to find one object that does not contain the point
break;
boundingObjectsIterator++;
}
break;
}
case Difference:
{
bool posInside = false;
bool negInside = false;
while (boundingObjectsIterator != boundingObjectsIteratorEnd) // check each BoundingObject
{
// calculate union: each point, that is inside least one BoundingObject is considered inside the group
if (boundingObjectsIterator.Value()->GetPositive())
posInside = boundingObjectsIterator.Value()->IsInside(p) || posInside;
else
negInside = boundingObjectsIterator.Value()->IsInside(p) || negInside;
boundingObjectsIterator++;
}
if (posInside && !negInside)
inside = true;
else
inside = false;
break;
}
case Union:
default:
{
inside = false;
while (boundingObjectsIterator != boundingObjectsIteratorEnd) // check each BoundingObject
{ // calculate union: each point, that is inside least one BoundingObject is considered inside the group
inside = boundingObjectsIterator.Value()->IsInside(p) || inside;
if (inside) // shortcut, it is enough to find one object that contains the point
break;
boundingObjectsIterator++;
}
break;
}
}
return inside;
}
unsigned int mitk::BoundingObjectGroup::GetCount() const
{
return m_Counter;
}
|
/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkBoundingObjectGroup.h"
#include <vtkLinearTransform.h>
mitk::BoundingObjectGroup::BoundingObjectGroup()
: m_Counter(0), m_CSGMode(Difference) //m_CSGMode(Union) m_CSGMode(Intersection)
{
m_Geometry3D->Initialize();
m_BoundingObjects = mitk::BoundingObjectGroup::BoundingObjectContainer::New();
SetVtkPolyData(NULL);
}
mitk::BoundingObjectGroup::~BoundingObjectGroup()
{
}
bool mitk::BoundingObjectGroup::VerifyRequestedRegion()
{
assert(m_Geometry3D.IsNotNull());
return true; //Superclass::VerifyRequestedRegion();
}
void mitk::BoundingObjectGroup::UpdateOutputInformation()
{
ScalarType bounds[6]={0,1,0,1,0,1}; // {xmin,x_max, ymin,y_max,zmin,z_max};
// calculate global bounding box
mitk::BoundingObjectGroup::BoundingObjectContainer::ConstIterator boundingObjectsIterator = m_BoundingObjects->Begin();
const mitk::BoundingObjectGroup::BoundingObjectContainer::ConstIterator boundingObjectsIteratorEnd = m_BoundingObjects->End();
if(boundingObjectsIterator == boundingObjectsIteratorEnd) // if there is no BoundingObject, the bounding box is zero
{
bounds[0] = bounds[1] = bounds[2] = bounds[3] = bounds[4] = bounds[5] = 0.0;
return;
}
mitk::BoundingBox::Pointer boundingBox;
mitk::BoundingBox::PointType minPoint;
mitk::BoundingBox::PointType globalMinPoint;
mitk::BoundingBox::PointType globalMaxPoint;
/* Initialize globalMin/MaxPoints */
boundingObjectsIterator.Value()->UpdateOutputInformation();
boundingBox = const_cast<mitk::BoundingBox*>(boundingObjectsIterator.Value()->GetGeometry()->GetBoundingBox());
minPoint = boundingBox->GetMinimum();
mitk::ScalarType min[3];
min[0] = minPoint[0]; min[1] = minPoint[1]; min[2] = minPoint[2];
boundingObjectsIterator.Value()->GetGeometry()->GetVtkTransform()->TransformPoint(min, min);
globalMinPoint[0] = min[0]; globalMinPoint[1] = min[1]; globalMinPoint[2] = min[2];
globalMaxPoint[0] = min[0]; globalMaxPoint[1] = min[1]; globalMaxPoint[2] = min[2];
//boundingObjectsIterator++;
while (boundingObjectsIterator != boundingObjectsIteratorEnd) // calculate a bounding box that includes all BoundingObjects
{
boundingObjectsIterator.Value()->UpdateOutputInformation();
boundingBox = const_cast<mitk::BoundingBox*>(boundingObjectsIterator.Value()->GetGeometry()->GetBoundingBox());
/* create all 8 points of the bounding box */
mitk::BoundingBox::PointsContainerPointer points = mitk::BoundingBox::PointsContainer::New();
mitk::Point3D p;
p = boundingBox->GetMinimum();
points->InsertElement(0, p);
p[0] = -p[0];
points->InsertElement(1, p);
p = boundingBox->GetMinimum();
p[1] = -p[1];
points->InsertElement(2, p);
p = boundingBox->GetMinimum();
p[2] = -p[2];
points->InsertElement(3, p);
p = boundingBox->GetMaximum();
points->InsertElement(4, p);
p[0] = -p[0];
points->InsertElement(5, p);
p = boundingBox->GetMaximum();
p[1] = -p[1];
points->InsertElement(6, p);
p = boundingBox->GetMaximum();
p[2] = -p[2];
points->InsertElement(7, p);
mitk::BoundingBox::PointsContainerConstIterator pointsIterator = points->Begin();
mitk::BoundingBox::PointsContainerConstIterator pointsIteratorEnd = points->End();
while (pointsIterator != pointsIteratorEnd) // for each vertex of the bounding box
{
minPoint = pointsIterator->Value();
min[0] = minPoint[0]; min[1] = minPoint[1]; min[2] = minPoint[2];
boundingObjectsIterator.Value()->GetGeometry()->GetVtkTransform()->TransformPoint(min, min); // transform vertex point to world coordinates
globalMinPoint[0] = (min[0] < globalMinPoint[0]) ? min[0] : globalMinPoint[0]; // check if world point
globalMinPoint[1] = (min[1] < globalMinPoint[1]) ? min[1] : globalMinPoint[1]; // has a lower or a
globalMinPoint[2] = (min[2] < globalMinPoint[2]) ? min[2] : globalMinPoint[2]; // higher value as
globalMaxPoint[0] = (min[0] > globalMaxPoint[0]) ? min[0] : globalMaxPoint[0]; // the last known highest
globalMaxPoint[1] = (min[1] > globalMaxPoint[1]) ? min[1] : globalMaxPoint[1]; // value
globalMaxPoint[2] = (min[2] > globalMaxPoint[2]) ? min[2] : globalMaxPoint[2]; // in each axis
pointsIterator++;
}
boundingObjectsIterator++;
}
/* BoundingBox is centered around the center of all sub bounding objects */
Vector3D centerPoint;
centerPoint[0] = (globalMinPoint[0] + globalMaxPoint[0])/ 2.0;
centerPoint[1] = (globalMinPoint[1] + globalMaxPoint[1])/ 2.0;
centerPoint[2] = (globalMinPoint[2] + globalMaxPoint[2])/ 2.0;
bounds[0] = globalMinPoint[0] - centerPoint[0]; // x Min
bounds[1] = globalMaxPoint[0] - centerPoint[0]; // x Max
bounds[2] = globalMinPoint[1] - centerPoint[1]; // y Min
bounds[3] = globalMaxPoint[1] - centerPoint[1]; // y Max
bounds[4] = globalMinPoint[2] - centerPoint[2]; // z Min
bounds[5] = globalMaxPoint[2] - centerPoint[2]; // z Max
mitk::TimeSlicedGeometry::Pointer timeGeometry = const_cast< mitk::TimeSlicedGeometry *>(this->GetTimeSlicedGeometry());
mitk::Geometry3D::Pointer geometry3d = timeGeometry->GetGeometry3D(0);
unsigned int timesteps = timeGeometry->GetTimeSteps();
if(geometry3d.IsNull())
{
assert(timesteps==0);
geometry3d = mitk::Geometry3D::New();
timesteps = 1;
}
else
{
assert(timesteps>0);
}
/* the objects position is the center of all sub bounding objects */
geometry3d->SetBounds(bounds);
geometry3d->Translate(centerPoint);
geometry3d->TransferItkToVtkTransform();
timeGeometry->InitializeEvenlyTimed(geometry3d, timesteps);
}
void mitk::BoundingObjectGroup::AddBoundingObject(mitk::BoundingObject::Pointer boundingObject)
{
m_BoundingObjects->InsertElement( m_Counter++, boundingObject);
UpdateOutputInformation();
}
bool mitk::BoundingObjectGroup::IsInside(const mitk::Point3D& p) const
{
mitk::BoundingObjectGroup::BoundingObjectContainer::ConstIterator boundingObjectsIterator = m_BoundingObjects->Begin();
const mitk::BoundingObjectGroup::BoundingObjectContainer::ConstIterator boundingObjectsIteratorEnd = m_BoundingObjects->End();
bool inside; // initialize with true for intersection, with false for union
switch(m_CSGMode)
{
case Intersection:
{
inside = true;
while (boundingObjectsIterator != boundingObjectsIteratorEnd) // check each BoundingObject
{ // calculate intersection: each point, that is inside each BoundingObject is considered inside the group
inside = boundingObjectsIterator.Value()->IsInside(p) && inside;
if (!inside) // shortcut, it is enough to find one object that does not contain the point
break;
boundingObjectsIterator++;
}
break;
}
case Difference:
{
bool posInside = false;
bool negInside = false;
while (boundingObjectsIterator != boundingObjectsIteratorEnd) // check each BoundingObject
{
// calculate union: each point, that is inside least one BoundingObject is considered inside the group
if (boundingObjectsIterator.Value()->GetPositive())
posInside = boundingObjectsIterator.Value()->IsInside(p) || posInside;
else
negInside = boundingObjectsIterator.Value()->IsInside(p) || negInside;
boundingObjectsIterator++;
}
if (posInside && !negInside)
inside = true;
else
inside = false;
break;
}
case Union:
default:
{
inside = false;
while (boundingObjectsIterator != boundingObjectsIteratorEnd) // check each BoundingObject
{ // calculate union: each point, that is inside least one BoundingObject is considered inside the group
inside = boundingObjectsIterator.Value()->IsInside(p) || inside;
if (inside) // shortcut, it is enough to find one object that contains the point
break;
boundingObjectsIterator++;
}
break;
}
}
return inside;
}
unsigned int mitk::BoundingObjectGroup::GetCount() const
{
return m_Counter;
}
ENH: calculation of boundingbox of all contained boundingboxes (not yet tested)
ENH: changes according to general availability of TimeSlicedGeometry in BaseData
ENH: removed obsolete VerifyRequestedRegion
/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkBoundingObjectGroup.h"
#include "mitkBaseProcess.h"
#include <vtkLinearTransform.h>
mitk::BoundingObjectGroup::BoundingObjectGroup()
: m_Counter(0), m_CSGMode(Difference) //m_CSGMode(Union) m_CSGMode(Intersection)
{
GetTimeSlicedGeometry()->Initialize(1);
GetGeometry(0)->SetIndexToWorldTransform(GetTimeSlicedGeometry()->GetIndexToWorldTransform());
m_BoundingObjects = mitk::BoundingObjectGroup::BoundingObjectContainer::New();
SetVtkPolyData(NULL);
}
mitk::BoundingObjectGroup::~BoundingObjectGroup()
{
}
void mitk::BoundingObjectGroup::UpdateOutputInformation()
{
if ( this->GetSource() )
{
this->GetSource()->UpdateOutputInformation();
}
// calculate global bounding box
mitk::BoundingObjectGroup::BoundingObjectContainer::ConstIterator boundingObjectsIterator = m_BoundingObjects->Begin();
const mitk::BoundingObjectGroup::BoundingObjectContainer::ConstIterator boundingObjectsIteratorEnd = m_BoundingObjects->End();
if(boundingObjectsIterator == boundingObjectsIteratorEnd) // if there is no BoundingObject, the bounding box is zero
{
mitk::BoundingBox::BoundsArrayType boundsArray;
boundsArray.Fill(0);
GetTimeSlicedGeometry()->Initialize(1);
GetGeometry()->SetBounds(boundsArray);
GetTimeSlicedGeometry()->UpdateInformation();
return;
}
// initialize container
mitk::BoundingBox::PointsContainer::Pointer pointscontainer=mitk::BoundingBox::PointsContainer::New();
mitk::BoundingBox::PointIdentifier pointid=0;
mitk::Point3D point;
mitk::AffineTransform3D* transform = GetTimeSlicedGeometry()->GetIndexToWorldTransform();
// calculate a bounding box that includes all BoundingObjects
// \todo probably we should do this additionally for each time-step
while (boundingObjectsIterator != boundingObjectsIteratorEnd)
{
const Geometry3D* geometry = boundingObjectsIterator.Value()->GetUpdatedTimeSlicedGeometry();
unsigned char i;
for(i=0; i<8; ++i)
{
point = transform->BackTransformPoint(geometry->GetCornerPoint(i));
if(point[0]*point[0]+point[1]*point[1]+point[2]*point[2] < mitk::large)
pointscontainer->InsertElement( pointid++, point);
else
{
itkGenericOutputMacro( << "Unrealistically distant corner point encountered. Ignored. BoundingObject: " << boundingObjectsIterator.Value() );
}
}
++boundingObjectsIterator;
}
mitk::BoundingBox::Pointer boundingBox = mitk::BoundingBox::New();
boundingBox->SetPoints(pointscontainer);
boundingBox->ComputeBoundingBox();
/* BoundingBox is centered around the center of all sub bounding objects */
Point3D center = boundingBox->GetCenter();
Point3D minimum, maximum;
minimum.Fill(0); maximum.Fill(0);
minimum += boundingBox->GetMinimum() - center;
maximum += boundingBox->GetMaximum() - center;
boundingBox->SetMinimum(minimum);
boundingBox->SetMaximum(maximum);
Geometry3D* geometry3d = GetGeometry(0);
geometry3d->SetIndexToWorldTransform(transform);
geometry3d->SetBounds(boundingBox->GetBounds());
/* the objects position is the center of all sub bounding objects */
geometry3d->SetOrigin(center);
GetTimeSlicedGeometry()->InitializeEvenlyTimed(geometry3d, GetTimeSlicedGeometry()->GetTimeSteps());
}
void mitk::BoundingObjectGroup::AddBoundingObject(mitk::BoundingObject::Pointer boundingObject)
{
m_BoundingObjects->InsertElement( m_Counter++, boundingObject);
UpdateOutputInformation();
}
bool mitk::BoundingObjectGroup::IsInside(const mitk::Point3D& p) const
{
mitk::BoundingObjectGroup::BoundingObjectContainer::ConstIterator boundingObjectsIterator = m_BoundingObjects->Begin();
const mitk::BoundingObjectGroup::BoundingObjectContainer::ConstIterator boundingObjectsIteratorEnd = m_BoundingObjects->End();
bool inside; // initialize with true for intersection, with false for union
switch(m_CSGMode)
{
case Intersection:
{
inside = true;
while (boundingObjectsIterator != boundingObjectsIteratorEnd) // check each BoundingObject
{ // calculate intersection: each point, that is inside each BoundingObject is considered inside the group
inside = boundingObjectsIterator.Value()->IsInside(p) && inside;
if (!inside) // shortcut, it is enough to find one object that does not contain the point
break;
boundingObjectsIterator++;
}
break;
}
case Difference:
{
bool posInside = false;
bool negInside = false;
while (boundingObjectsIterator != boundingObjectsIteratorEnd) // check each BoundingObject
{
// calculate union: each point, that is inside least one BoundingObject is considered inside the group
if (boundingObjectsIterator.Value()->GetPositive())
posInside = boundingObjectsIterator.Value()->IsInside(p) || posInside;
else
negInside = boundingObjectsIterator.Value()->IsInside(p) || negInside;
boundingObjectsIterator++;
}
if (posInside && !negInside)
inside = true;
else
inside = false;
break;
}
case Union:
default:
{
inside = false;
while (boundingObjectsIterator != boundingObjectsIteratorEnd) // check each BoundingObject
{ // calculate union: each point, that is inside least one BoundingObject is considered inside the group
inside = boundingObjectsIterator.Value()->IsInside(p) || inside;
if (inside) // shortcut, it is enough to find one object that contains the point
break;
boundingObjectsIterator++;
}
break;
}
}
return inside;
}
unsigned int mitk::BoundingObjectGroup::GetCount() const
{
return m_Counter;
}
|
#include <algorithm>
#include "../Headers/neural_network.h"
using namespace Hippocrates;
using namespace std;
NeuralNetwork::NeuralNetwork(const Genome& genome, bool shouldMutate) :
genome(genome),
inputNeurons(genome.GetInputCount()),
outputNeurons(genome.GetOutputCount())
{
if (shouldMutate) {
MutateGenesAndBuildNetwork();
}
else {
BuildNetworkFromGenes();
}
}
NeuralNetwork::NeuralNetwork(Genome&& genome, bool shouldMutate) :
genome(move(genome)),
inputNeurons(genome.GetInputCount()),
outputNeurons(genome.GetOutputCount())
{
if (shouldMutate) {
MutateGenesAndBuildNetwork();
}
else {
BuildNetworkFromGenes();
}
}
NeuralNetwork::NeuralNetwork(const NeuralNetwork& other) :
genome(other.genome),
inputNeurons(other.inputNeurons.size()),
outputNeurons(other.outputNeurons.size())
{
BuildNetworkFromGenes();
}
auto NeuralNetwork::operator=(const NeuralNetwork& other) -> NeuralNetwork& {
genome = other.genome;
inputNeurons.resize(other.inputNeurons.size());
outputNeurons.resize(other.outputNeurons.size());
neurons.clear();
neurons.reserve(other.neurons.size());
layerMap.clear();
BuildNetworkFromGenes();
return *this;
}
auto NeuralNetwork::BuildNetworkFromGenes() -> void {
neurons.resize(genome.GetNeuronCount());
for (const auto& gene : genome) {
if (gene.isEnabled) {
Neuron::Connection in;
in.weight = gene.weight;
in.isRecursive = gene.isRecursive;
in.neuron = &neurons[gene.from];
neurons[gene.to].AddConnection(move(in));
Neuron::Connection out;
out.weight = gene.weight;
out.isRecursive = gene.isRecursive;
out.neuron = &neurons[gene.to];
out.outGoing = true;
neurons[gene.from].AddConnection(move(out));
}
}
InterpretInputsAndOutputs();
CategorizeNeuronsIntoLayers();
}
auto NeuralNetwork::SetInputs(vector<float> inputs) -> void {
if (inputNeurons.size() != inputs.size()) {
throw out_of_range("Number of inputs provided doesn't match genetic information");
}
for (size_t i = 0U; i < inputNeurons.size(); ++i) {
inputNeurons[i]->SetInput(move(inputs[i]));
};
}
auto NeuralNetwork::GetOutputs() -> vector<float> {
for (size_t i = 1; i < layerMap.size() - 1; ++i) {
for (auto& neuron : layerMap[i]) {
neuron->RequestDataAndGetActionPotential();
}
}
vector<float> outputs;
outputs.reserve(outputNeurons.size());
for (auto& outputNeuron : outputNeurons) {
outputs.push_back(outputNeuron->RequestDataAndGetActionPotential());
}
return outputs;
}
auto NeuralNetwork::GetOutputsUsingInputs(vector<float> inputs) -> vector<float> {
SetInputs(move(inputs));
return GetOutputs();
}
auto NeuralNetwork::InterpretInputsAndOutputs() -> void {
// Bias
for (auto i = 0U; i < GetTrainingParameters().structure.numberOfBiasNeurons; i++) {
neurons[i].SetInput(1.0f);
}
// Inputs
for (auto i = 0U; i < genome.GetInputCount(); i++) {
inputNeurons[i] = &neurons[i + GetTrainingParameters().structure.numberOfBiasNeurons];
}
// Outputs
for (auto i = 0U; i < genome.GetOutputCount(); i++) {
outputNeurons[i] = &neurons[genome[i].to];
}
}
auto NeuralNetwork::ShouldAddNeuron() const -> bool {
return DidChanceOccure(
GetTrainingParameters().
mutation.
chanceForNeuralMutation
);
}
auto NeuralNetwork::ShouldAddConnection() const -> bool {
const bool hasChanceOccured = DidChanceOccure(GetTrainingParameters().mutation.chanceForConnectionalMutation);
if (!hasChanceOccured) {
return false;
}
const size_t inputLayerSize = genome.GetInputCount() + GetTrainingParameters().structure.numberOfBiasNeurons;
const size_t outputLayerSize = genome.GetOutputCount();
const size_t hiddenLayerSize = genome.GetNeuronCount() - inputLayerSize - outputLayerSize;
const auto startingConnections = inputLayerSize * outputLayerSize;
auto hiddenConnections = (hiddenLayerSize * (hiddenLayerSize - 1));
if (!GetTrainingParameters().structure.allowRecursiveConnections) {
hiddenConnections /= 2;
}
const auto connectionsFromInputs = inputLayerSize * hiddenLayerSize;
auto connectionsToOutputs = outputLayerSize * hiddenLayerSize;
if (GetTrainingParameters().structure.allowRecursiveConnections) {
connectionsToOutputs *= 2;
}
const auto possibleConnections =
startingConnections +
hiddenConnections +
connectionsFromInputs +
connectionsToOutputs;
return genome.GetGeneCount() < possibleConnections;
}
auto NeuralNetwork::ShouldMutateWeight() const -> bool {
return DidChanceOccure(
GetTrainingParameters().
mutation.
chanceForWeightMutation
);
}
auto NeuralNetwork::DidChanceOccure(float chance) -> bool {
auto num = rand() % 100;
return num < int(100.0f * chance);
}
auto NeuralNetwork::AddRandomNeuron() -> void {
auto& randGene = GetRandomEnabledGene();
auto indexOfNewNeuron = genome.GetNeuronCount();
Gene g1;
g1.from = randGene.from;
g1.to = indexOfNewNeuron;
g1.weight = 1.0f;
g1.isRecursive = randGene.isRecursive;
Gene g2;
g2.from = indexOfNewNeuron;
g2.to = randGene.to;
g2.weight = randGene.weight;
g2.isRecursive = randGene.isRecursive;
randGene.isEnabled = false;
genome.AppendGene(move(g1));
genome.AppendGene(move(g2));
}
auto NeuralNetwork::AddRandomConnection() -> void {
// Data
auto NeuronPair(GetTwoUnconnectedNeurons());
auto& fromNeuron = *NeuronPair.first;
auto& toNeuron = *NeuronPair.second;
// Gene
Gene newConnectionGene;
while (&neurons[newConnectionGene.from] != &fromNeuron) {
newConnectionGene.from++;
}
while (&neurons[newConnectionGene.to] != &toNeuron) {
newConnectionGene.to++;
}
if (fromNeuron.GetLayer() > toNeuron.GetLayer()) {
newConnectionGene.isRecursive = true;
}
// Connection
Neuron::Connection in;
in.isRecursive = newConnectionGene.isRecursive;
in.neuron = &fromNeuron;
in.weight = newConnectionGene.weight;
toNeuron.AddConnection(move(in));
Neuron::Connection out;
out.isRecursive = newConnectionGene.isRecursive;
out.neuron = &toNeuron;
out.weight = newConnectionGene.weight;
out.outGoing = true;
fromNeuron.AddConnection(move(out));
genome.AppendGene(move(newConnectionGene));
CategorizeNeuronsIntoLayers();
}
auto NeuralNetwork::GetTwoUnconnectedNeurons() -> pair<Neuron*, Neuron*> {
vector<Neuron*> possibleFromNeurons;
possibleFromNeurons.reserve(neurons.size());
for (auto& n : neurons) {
possibleFromNeurons.push_back(&n);
}
auto inputRange = genome.GetInputCount() + GetTrainingParameters().structure.numberOfBiasNeurons;
vector<Neuron*> possibleToNeurons(possibleFromNeurons.begin() + inputRange, possibleFromNeurons.end());
random_shuffle(possibleFromNeurons.begin(), possibleFromNeurons.end());
random_shuffle(possibleToNeurons.begin(), possibleToNeurons.end());
for (auto* from : possibleFromNeurons) {
for (auto* to : possibleToNeurons) {
if (CanNeuronsBeConnected(*from, *to)) {
return{ from, to };
}
}
}
throw runtime_error("Tried to get two unconnected Neurons while every neuron is already connected");
}
auto Hippocrates::NeuralNetwork::CanNeuronsBeConnected(const Neuron & lhs, const Neuron & rhs) const -> bool {
bool AreNeuronsTheSame = &lhs == &rhs;
return (!AreNeuronsTheSame && !AreBothNeuronsOutputs(lhs, rhs) && !AreNeuronsConnected(lhs, rhs));
}
auto NeuralNetwork::AreBothNeuronsOutputs(const Neuron &lhs, const Neuron &rhs) const -> bool {
bool isLhsOutput = false;
bool isRhsOutput = false;
for (const auto& output : outputNeurons) {
if (output == &lhs) {
isLhsOutput = true;
}
else if (output == &rhs) {
isRhsOutput = true;
}
if (isLhsOutput && isRhsOutput) {
return true;
}
}
return false;
}
auto NeuralNetwork::AreNeuronsConnected(const Neuron& lhs, const Neuron & rhs) -> bool {
for (auto& connection : rhs.GetConnections()) {
if (!connection.outGoing && &lhs == connection.neuron) {
return true;
}
}
return false;
}
auto NeuralNetwork::ShuffleWeights() -> void {
for (size_t i = 0; i < genome.GetGeneCount(); i++) {
if (ShouldMutateWeight()) {
MutateWeightOfGeneAt(i);
}
}
}
auto NeuralNetwork::MutateWeightOfGeneAt(size_t index) -> void {
if (DidChanceOccure(GetTrainingParameters().mutation.chanceOfTotalWeightReset)) {
genome[index].SetRandomWeight();
}
else {
PerturbWeightAt(index);
}
}
auto NeuralNetwork::PerturbWeightAt(size_t index) -> void {
constexpr float perturbanceBoundaries = 0.5f;
auto perturbance = static_cast<float>(rand() % 10'000) / 9'999.0f * perturbanceBoundaries;
if (rand() % 2) {
perturbance = -perturbance;
}
genome[index].weight += perturbance;
if (genome[index].weight < -1.0f) {
genome[index].weight = -1.0f;
}
else if (genome[index].weight > 1.0f) {
genome[index].weight = 1.0f;
}
}
auto NeuralNetwork::MutateGenesAndBuildNetwork() -> void {
if (ShouldAddConnection()) {
BuildNetworkFromGenes();
AddRandomConnection();
}
else {
if (ShouldAddNeuron()) {
AddRandomNeuron();
} else {
ShuffleWeights();
}
BuildNetworkFromGenes();
}
}
auto NeuralNetwork::CategorizeNeuronsIntoLayers() -> void {
for (auto i = 0U; i < GetTrainingParameters().structure.numberOfBiasNeurons; i++) {
CategorizeNeuronBranchIntoLayers(neurons[i]);
}
for (auto* in : inputNeurons) {
CategorizeNeuronBranchIntoLayers(*in);
}
size_t highestLayer = 0U;
for (auto* out : outputNeurons) {
highestLayer = max(out->GetLayer(), highestLayer);
}
for (auto* out : outputNeurons) {
out->layer = highestLayer;
}
for (auto& neuron : neurons) {
layerMap[neuron.GetLayer()].push_back(&neuron);
}
}
auto NeuralNetwork::CategorizeNeuronBranchIntoLayers(Neuron& currNode, size_t currentDepth) const -> void {
currNode.layer = currentDepth;
const auto nextLayer = currNode.layer + 1;
auto HasYetToBeLayered = [&nextLayer](const auto& connection) {
return nextLayer > connection.neuron->layer;
};
auto IsInHigherLayer = [](const auto& connection) {
return (connection.outGoing != connection.isRecursive);
};
for (auto &connection : currNode.GetConnections()) {
if (HasYetToBeLayered(connection) && IsInHigherLayer(connection)) {
CategorizeNeuronBranchIntoLayers(*connection.neuron, nextLayer);
}
}
}
auto NeuralNetwork::GetRandomEnabledGene() -> Gene& {
size_t num = rand() % genome.GetGeneCount();
auto randGene = genome.begin();
randGene += num;
while (randGene != genome.end() && !randGene->isEnabled) {
++randGene;
}
if (randGene == genome.end()) {
randGene = genome.begin() + num;
while (randGene != genome.begin() && !randGene->isEnabled) {
--randGene;
}
}
if (!randGene->isEnabled) {
throw runtime_error("Could not insert neuron because every gene is disabled");
}
return *randGene;
}
auto NeuralNetwork::GetJSON() const -> string {
string s("{\"neurons\":[");
for (size_t i = 0; i < neurons.size() - 1; ++i) {
s += neurons[i].GetJSON();
s += ",";
}
s += neurons.back().GetJSON();
s += "],\"genome\":";
s += genome.GetJSON();
s += "}";
return s;
}
Remove unneeded brackets
#include <algorithm>
#include "../Headers/neural_network.h"
using namespace Hippocrates;
using namespace std;
NeuralNetwork::NeuralNetwork(const Genome& genome, bool shouldMutate) :
genome(genome),
inputNeurons(genome.GetInputCount()),
outputNeurons(genome.GetOutputCount())
{
if (shouldMutate) {
MutateGenesAndBuildNetwork();
}
else {
BuildNetworkFromGenes();
}
}
NeuralNetwork::NeuralNetwork(Genome&& genome, bool shouldMutate) :
genome(move(genome)),
inputNeurons(genome.GetInputCount()),
outputNeurons(genome.GetOutputCount())
{
if (shouldMutate) {
MutateGenesAndBuildNetwork();
}
else {
BuildNetworkFromGenes();
}
}
NeuralNetwork::NeuralNetwork(const NeuralNetwork& other) :
genome(other.genome),
inputNeurons(other.inputNeurons.size()),
outputNeurons(other.outputNeurons.size())
{
BuildNetworkFromGenes();
}
auto NeuralNetwork::operator=(const NeuralNetwork& other) -> NeuralNetwork& {
genome = other.genome;
inputNeurons.resize(other.inputNeurons.size());
outputNeurons.resize(other.outputNeurons.size());
neurons.clear();
neurons.reserve(other.neurons.size());
layerMap.clear();
BuildNetworkFromGenes();
return *this;
}
auto NeuralNetwork::BuildNetworkFromGenes() -> void {
neurons.resize(genome.GetNeuronCount());
for (const auto& gene : genome) {
if (gene.isEnabled) {
Neuron::Connection in;
in.weight = gene.weight;
in.isRecursive = gene.isRecursive;
in.neuron = &neurons[gene.from];
neurons[gene.to].AddConnection(move(in));
Neuron::Connection out;
out.weight = gene.weight;
out.isRecursive = gene.isRecursive;
out.neuron = &neurons[gene.to];
out.outGoing = true;
neurons[gene.from].AddConnection(move(out));
}
}
InterpretInputsAndOutputs();
CategorizeNeuronsIntoLayers();
}
auto NeuralNetwork::SetInputs(vector<float> inputs) -> void {
if (inputNeurons.size() != inputs.size()) {
throw out_of_range("Number of inputs provided doesn't match genetic information");
}
for (size_t i = 0U; i < inputNeurons.size(); ++i) {
inputNeurons[i]->SetInput(move(inputs[i]));
};
}
auto NeuralNetwork::GetOutputs() -> vector<float> {
for (size_t i = 1; i < layerMap.size() - 1; ++i) {
for (auto& neuron : layerMap[i]) {
neuron->RequestDataAndGetActionPotential();
}
}
vector<float> outputs;
outputs.reserve(outputNeurons.size());
for (auto& outputNeuron : outputNeurons) {
outputs.push_back(outputNeuron->RequestDataAndGetActionPotential());
}
return outputs;
}
auto NeuralNetwork::GetOutputsUsingInputs(vector<float> inputs) -> vector<float> {
SetInputs(move(inputs));
return GetOutputs();
}
auto NeuralNetwork::InterpretInputsAndOutputs() -> void {
// Bias
for (auto i = 0U; i < GetTrainingParameters().structure.numberOfBiasNeurons; i++) {
neurons[i].SetInput(1.0f);
}
// Inputs
for (auto i = 0U; i < genome.GetInputCount(); i++) {
inputNeurons[i] = &neurons[i + GetTrainingParameters().structure.numberOfBiasNeurons];
}
// Outputs
for (auto i = 0U; i < genome.GetOutputCount(); i++) {
outputNeurons[i] = &neurons[genome[i].to];
}
}
auto NeuralNetwork::ShouldAddNeuron() const -> bool {
return DidChanceOccure(
GetTrainingParameters().
mutation.
chanceForNeuralMutation
);
}
auto NeuralNetwork::ShouldAddConnection() const -> bool {
const bool hasChanceOccured = DidChanceOccure(GetTrainingParameters().mutation.chanceForConnectionalMutation);
if (!hasChanceOccured) {
return false;
}
const auto inputLayerSize = genome.GetInputCount() + GetTrainingParameters().structure.numberOfBiasNeurons;
const auto outputLayerSize = genome.GetOutputCount();
const auto hiddenLayerSize = genome.GetNeuronCount() - inputLayerSize - outputLayerSize;
const auto startingConnections = inputLayerSize * outputLayerSize;
auto hiddenConnections = hiddenLayerSize * (hiddenLayerSize - 1);
if (!GetTrainingParameters().structure.allowRecursiveConnections) {
hiddenConnections /= 2;
}
const auto connectionsFromInputs = inputLayerSize * hiddenLayerSize;
auto connectionsToOutputs = outputLayerSize * hiddenLayerSize;
if (GetTrainingParameters().structure.allowRecursiveConnections) {
connectionsToOutputs *= 2;
}
const auto possibleConnections =
startingConnections +
hiddenConnections +
connectionsFromInputs +
connectionsToOutputs;
return genome.GetGeneCount() < possibleConnections;
}
auto NeuralNetwork::ShouldMutateWeight() const -> bool {
return DidChanceOccure(
GetTrainingParameters().
mutation.
chanceForWeightMutation
);
}
auto NeuralNetwork::DidChanceOccure(float chance) -> bool {
auto num = rand() % 100;
return num < int(100.0f * chance);
}
auto NeuralNetwork::AddRandomNeuron() -> void {
auto& randGene = GetRandomEnabledGene();
auto indexOfNewNeuron = genome.GetNeuronCount();
Gene g1;
g1.from = randGene.from;
g1.to = indexOfNewNeuron;
g1.weight = 1.0f;
g1.isRecursive = randGene.isRecursive;
Gene g2;
g2.from = indexOfNewNeuron;
g2.to = randGene.to;
g2.weight = randGene.weight;
g2.isRecursive = randGene.isRecursive;
randGene.isEnabled = false;
genome.AppendGene(move(g1));
genome.AppendGene(move(g2));
}
auto NeuralNetwork::AddRandomConnection() -> void {
// Data
auto NeuronPair(GetTwoUnconnectedNeurons());
auto& fromNeuron = *NeuronPair.first;
auto& toNeuron = *NeuronPair.second;
// Gene
Gene newConnectionGene;
while (&neurons[newConnectionGene.from] != &fromNeuron) {
newConnectionGene.from++;
}
while (&neurons[newConnectionGene.to] != &toNeuron) {
newConnectionGene.to++;
}
if (fromNeuron.GetLayer() > toNeuron.GetLayer()) {
newConnectionGene.isRecursive = true;
}
// Connection
Neuron::Connection in;
in.isRecursive = newConnectionGene.isRecursive;
in.neuron = &fromNeuron;
in.weight = newConnectionGene.weight;
toNeuron.AddConnection(move(in));
Neuron::Connection out;
out.isRecursive = newConnectionGene.isRecursive;
out.neuron = &toNeuron;
out.weight = newConnectionGene.weight;
out.outGoing = true;
fromNeuron.AddConnection(move(out));
genome.AppendGene(move(newConnectionGene));
CategorizeNeuronsIntoLayers();
}
auto NeuralNetwork::GetTwoUnconnectedNeurons() -> pair<Neuron*, Neuron*> {
vector<Neuron*> possibleFromNeurons;
possibleFromNeurons.reserve(neurons.size());
for (auto& n : neurons) {
possibleFromNeurons.push_back(&n);
}
auto inputRange = genome.GetInputCount() + GetTrainingParameters().structure.numberOfBiasNeurons;
vector<Neuron*> possibleToNeurons(possibleFromNeurons.begin() + inputRange, possibleFromNeurons.end());
random_shuffle(possibleFromNeurons.begin(), possibleFromNeurons.end());
random_shuffle(possibleToNeurons.begin(), possibleToNeurons.end());
for (auto* from : possibleFromNeurons) {
for (auto* to : possibleToNeurons) {
if (CanNeuronsBeConnected(*from, *to)) {
return{ from, to };
}
}
}
throw runtime_error("Tried to get two unconnected Neurons while every neuron is already connected");
}
auto Hippocrates::NeuralNetwork::CanNeuronsBeConnected(const Neuron & lhs, const Neuron & rhs) const -> bool {
bool AreNeuronsTheSame = &lhs == &rhs;
return (!AreNeuronsTheSame && !AreBothNeuronsOutputs(lhs, rhs) && !AreNeuronsConnected(lhs, rhs));
}
auto NeuralNetwork::AreBothNeuronsOutputs(const Neuron &lhs, const Neuron &rhs) const -> bool {
bool isLhsOutput = false;
bool isRhsOutput = false;
for (const auto& output : outputNeurons) {
if (output == &lhs) {
isLhsOutput = true;
}
else if (output == &rhs) {
isRhsOutput = true;
}
if (isLhsOutput && isRhsOutput) {
return true;
}
}
return false;
}
auto NeuralNetwork::AreNeuronsConnected(const Neuron& lhs, const Neuron & rhs) -> bool {
for (auto& connection : rhs.GetConnections()) {
if (!connection.outGoing && &lhs == connection.neuron) {
return true;
}
}
return false;
}
auto NeuralNetwork::ShuffleWeights() -> void {
for (size_t i = 0; i < genome.GetGeneCount(); i++) {
if (ShouldMutateWeight()) {
MutateWeightOfGeneAt(i);
}
}
}
auto NeuralNetwork::MutateWeightOfGeneAt(size_t index) -> void {
if (DidChanceOccure(GetTrainingParameters().mutation.chanceOfTotalWeightReset)) {
genome[index].SetRandomWeight();
}
else {
PerturbWeightAt(index);
}
}
auto NeuralNetwork::PerturbWeightAt(size_t index) -> void {
constexpr float perturbanceBoundaries = 0.5f;
auto perturbance = static_cast<float>(rand() % 10'000) / 9'999.0f * perturbanceBoundaries;
if (rand() % 2) {
perturbance = -perturbance;
}
genome[index].weight += perturbance;
if (genome[index].weight < -1.0f) {
genome[index].weight = -1.0f;
}
else if (genome[index].weight > 1.0f) {
genome[index].weight = 1.0f;
}
}
auto NeuralNetwork::MutateGenesAndBuildNetwork() -> void {
if (ShouldAddConnection()) {
BuildNetworkFromGenes();
AddRandomConnection();
}
else {
if (ShouldAddNeuron()) {
AddRandomNeuron();
} else {
ShuffleWeights();
}
BuildNetworkFromGenes();
}
}
auto NeuralNetwork::CategorizeNeuronsIntoLayers() -> void {
for (auto i = 0U; i < GetTrainingParameters().structure.numberOfBiasNeurons; i++) {
CategorizeNeuronBranchIntoLayers(neurons[i]);
}
for (auto* in : inputNeurons) {
CategorizeNeuronBranchIntoLayers(*in);
}
size_t highestLayer = 0U;
for (auto* out : outputNeurons) {
highestLayer = max(out->GetLayer(), highestLayer);
}
for (auto* out : outputNeurons) {
out->layer = highestLayer;
}
for (auto& neuron : neurons) {
layerMap[neuron.GetLayer()].push_back(&neuron);
}
}
auto NeuralNetwork::CategorizeNeuronBranchIntoLayers(Neuron& currNode, size_t currentDepth) const -> void {
currNode.layer = currentDepth;
const auto nextLayer = currNode.layer + 1;
auto HasYetToBeLayered = [&nextLayer](const auto& connection) {
return nextLayer > connection.neuron->layer;
};
auto IsInHigherLayer = [](const auto& connection) {
return (connection.outGoing != connection.isRecursive);
};
for (auto &connection : currNode.GetConnections()) {
if (HasYetToBeLayered(connection) && IsInHigherLayer(connection)) {
CategorizeNeuronBranchIntoLayers(*connection.neuron, nextLayer);
}
}
}
auto NeuralNetwork::GetRandomEnabledGene() -> Gene& {
size_t num = rand() % genome.GetGeneCount();
auto randGene = genome.begin();
randGene += num;
while (randGene != genome.end() && !randGene->isEnabled) {
++randGene;
}
if (randGene == genome.end()) {
randGene = genome.begin() + num;
while (randGene != genome.begin() && !randGene->isEnabled) {
--randGene;
}
}
if (!randGene->isEnabled) {
throw runtime_error("Could not insert neuron because every gene is disabled");
}
return *randGene;
}
auto NeuralNetwork::GetJSON() const -> string {
string s("{\"neurons\":[");
for (size_t i = 0; i < neurons.size() - 1; ++i) {
s += neurons[i].GetJSON();
s += ",";
}
s += neurons.back().GetJSON();
s += "],\"genome\":";
s += genome.GetJSON();
s += "}";
return s;
}
|
/*
*
* Copyright 2017 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <memory>
#include <mutex>
#include <numeric>
#include <set>
#include <sstream>
#include <thread>
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/time.h>
#include <grpcpp/channel.h>
#include <grpcpp/client_context.h>
#include <grpcpp/create_channel.h>
#include <grpcpp/server.h>
#include <grpcpp/server_builder.h>
#include "src/core/ext/filters/client_channel/backup_poller.h"
#include "src/core/ext/filters/client_channel/parse_address.h"
#include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
#include "src/core/ext/filters/client_channel/server_address.h"
#include "src/core/ext/filters/client_channel/xds/xds_api.h"
#include "src/core/lib/gpr/env.h"
#include "src/core/lib/gpr/tmpfile.h"
#include "src/core/lib/gprpp/map.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/iomgr/sockaddr.h"
#include "src/core/lib/security/credentials/fake/fake_credentials.h"
#include "src/cpp/client/secure_credentials.h"
#include "src/cpp/server/secure_server_credentials.h"
#include "test/core/util/port.h"
#include "test/core/util/test_config.h"
#include "test/cpp/end2end/test_service_impl.h"
#include "src/proto/grpc/testing/echo.grpc.pb.h"
#include "src/proto/grpc/testing/xds/ads_for_test.grpc.pb.h"
#include "src/proto/grpc/testing/xds/cds_for_test.grpc.pb.h"
#include "src/proto/grpc/testing/xds/eds_for_test.grpc.pb.h"
#include "src/proto/grpc/testing/xds/lds_rds_for_test.grpc.pb.h"
#include "src/proto/grpc/testing/xds/lrs_for_test.grpc.pb.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
// TODO(dgq): Other scenarios in need of testing:
// - Send a serverlist with faulty ip:port addresses (port > 2^16, etc).
// - Test reception of invalid serverlist
// - Test against a non-LB server.
// - Random LB server closing the stream unexpectedly.
//
// Findings from end to end testing to be covered here:
// - Handling of LB servers restart, including reconnection after backing-off
// retries.
// - Destruction of load balanced channel (and therefore of xds instance)
// while:
// 1) the internal LB call is still active. This should work by virtue
// of the weak reference the LB call holds. The call should be terminated as
// part of the xds shutdown process.
// 2) the retry timer is active. Again, the weak reference it holds should
// prevent a premature call to \a glb_destroy.
namespace grpc {
namespace testing {
namespace {
using std::chrono::system_clock;
using ::envoy::api::v2::Cluster;
using ::envoy::api::v2::ClusterLoadAssignment;
using ::envoy::api::v2::DiscoveryRequest;
using ::envoy::api::v2::DiscoveryResponse;
using ::envoy::api::v2::FractionalPercent;
using ::envoy::api::v2::HttpConnectionManager;
using ::envoy::api::v2::Listener;
using ::envoy::api::v2::RouteConfiguration;
using ::envoy::api::v2::VirtualHost;
using ::envoy::service::discovery::v2::AggregatedDiscoveryService;
using ::envoy::service::load_stats::v2::ClusterStats;
using ::envoy::service::load_stats::v2::LoadReportingService;
using ::envoy::service::load_stats::v2::LoadStatsRequest;
using ::envoy::service::load_stats::v2::LoadStatsResponse;
using ::envoy::service::load_stats::v2::UpstreamLocalityStats;
constexpr char kLdsTypeUrl[] = "type.googleapis.com/envoy.api.v2.Listener";
constexpr char kRdsTypeUrl[] =
"type.googleapis.com/envoy.api.v2.RouteConfiguration";
constexpr char kCdsTypeUrl[] = "type.googleapis.com/envoy.api.v2.Cluster";
constexpr char kEdsTypeUrl[] =
"type.googleapis.com/envoy.api.v2.ClusterLoadAssignment";
constexpr char kDefaultLocalityRegion[] = "xds_default_locality_region";
constexpr char kDefaultLocalityZone[] = "xds_default_locality_zone";
constexpr char kLbDropType[] = "lb";
constexpr char kThrottleDropType[] = "throttle";
constexpr int kDefaultLocalityWeight = 3;
constexpr int kDefaultLocalityPriority = 0;
constexpr char kBootstrapFile[] =
"{\n"
" \"xds_servers\": [\n"
" {\n"
" \"server_uri\": \"fake:///lb\",\n"
" \"channel_creds\": [\n"
" {\n"
" \"type\": \"fake\"\n"
" }\n"
" ]\n"
" }\n"
" ],\n"
" \"node\": {\n"
" \"id\": \"xds_end2end_test\",\n"
" \"cluster\": \"test\",\n"
" \"metadata\": {\n"
" \"foo\": \"bar\"\n"
" },\n"
" \"locality\": {\n"
" \"region\": \"corp\",\n"
" \"zone\": \"svl\",\n"
" \"subzone\": \"mp3\"\n"
" }\n"
" }\n"
"}\n";
constexpr char kBootstrapFileBad[] =
"{\n"
" \"xds_servers\": [\n"
" {\n"
" \"server_uri\": \"fake:///wrong_lb\",\n"
" \"channel_creds\": [\n"
" {\n"
" \"type\": \"fake\"\n"
" }\n"
" ]\n"
" }\n"
" ],\n"
" \"node\": {\n"
" }\n"
"}\n";
char* g_bootstrap_file;
char* g_bootstrap_file_bad;
void WriteBootstrapFiles() {
char* bootstrap_file;
FILE* out = gpr_tmpfile("xds_bootstrap", &bootstrap_file);
fputs(kBootstrapFile, out);
fclose(out);
g_bootstrap_file = bootstrap_file;
out = gpr_tmpfile("xds_bootstrap_bad", &bootstrap_file);
fputs(kBootstrapFileBad, out);
fclose(out);
g_bootstrap_file_bad = bootstrap_file;
}
// Helper class to minimize the number of unique ports we use for this test.
class PortSaver {
public:
int GetPort() {
if (idx_ >= ports_.size()) {
ports_.push_back(grpc_pick_unused_port_or_die());
}
return ports_[idx_++];
}
void Reset() { idx_ = 0; }
private:
std::vector<int> ports_;
size_t idx_ = 0;
};
PortSaver* g_port_saver = nullptr;
template <typename ServiceType>
class CountedService : public ServiceType {
public:
size_t request_count() {
grpc_core::MutexLock lock(&mu_);
return request_count_;
}
size_t response_count() {
grpc_core::MutexLock lock(&mu_);
return response_count_;
}
void IncreaseResponseCount() {
grpc_core::MutexLock lock(&mu_);
++response_count_;
}
void IncreaseRequestCount() {
grpc_core::MutexLock lock(&mu_);
++request_count_;
}
void ResetCounters() {
grpc_core::MutexLock lock(&mu_);
request_count_ = 0;
response_count_ = 0;
}
protected:
grpc_core::Mutex mu_;
private:
size_t request_count_ = 0;
size_t response_count_ = 0;
};
using BackendService = CountedService<TestServiceImpl>;
using AdsService = CountedService<AggregatedDiscoveryService::Service>;
using LrsService = CountedService<LoadReportingService::Service>;
const char g_kCallCredsMdKey[] = "Balancer should not ...";
const char g_kCallCredsMdValue[] = "... receive me";
class BackendServiceImpl : public BackendService {
public:
BackendServiceImpl() {}
Status Echo(ServerContext* context, const EchoRequest* request,
EchoResponse* response) override {
// Backend should receive the call credentials metadata.
auto call_credentials_entry =
context->client_metadata().find(g_kCallCredsMdKey);
EXPECT_NE(call_credentials_entry, context->client_metadata().end());
if (call_credentials_entry != context->client_metadata().end()) {
EXPECT_EQ(call_credentials_entry->second, g_kCallCredsMdValue);
}
IncreaseRequestCount();
const auto status = TestServiceImpl::Echo(context, request, response);
IncreaseResponseCount();
AddClient(context->peer());
return status;
}
void Start() {}
void Shutdown() {}
std::set<grpc::string> clients() {
grpc_core::MutexLock lock(&clients_mu_);
return clients_;
}
private:
void AddClient(const grpc::string& client) {
grpc_core::MutexLock lock(&clients_mu_);
clients_.insert(client);
}
grpc_core::Mutex mu_;
grpc_core::Mutex clients_mu_;
std::set<grpc::string> clients_;
};
class ClientStats {
public:
struct LocalityStats {
// Converts from proto message class.
LocalityStats(const UpstreamLocalityStats& upstream_locality_stats)
: total_successful_requests(
upstream_locality_stats.total_successful_requests()),
total_requests_in_progress(
upstream_locality_stats.total_requests_in_progress()),
total_error_requests(upstream_locality_stats.total_error_requests()),
total_issued_requests(
upstream_locality_stats.total_issued_requests()) {}
uint64_t total_successful_requests;
uint64_t total_requests_in_progress;
uint64_t total_error_requests;
uint64_t total_issued_requests;
};
// Converts from proto message class.
ClientStats(const ClusterStats& cluster_stats)
: total_dropped_requests_(cluster_stats.total_dropped_requests()) {
for (const auto& input_locality_stats :
cluster_stats.upstream_locality_stats()) {
locality_stats_.emplace(input_locality_stats.locality().sub_zone(),
LocalityStats(input_locality_stats));
}
for (const auto& input_dropped_requests :
cluster_stats.dropped_requests()) {
dropped_requests_.emplace(input_dropped_requests.category(),
input_dropped_requests.dropped_count());
}
}
uint64_t total_successful_requests() const {
uint64_t sum = 0;
for (auto& p : locality_stats_) {
sum += p.second.total_successful_requests;
}
return sum;
}
uint64_t total_requests_in_progress() const {
uint64_t sum = 0;
for (auto& p : locality_stats_) {
sum += p.second.total_requests_in_progress;
}
return sum;
}
uint64_t total_error_requests() const {
uint64_t sum = 0;
for (auto& p : locality_stats_) {
sum += p.second.total_error_requests;
}
return sum;
}
uint64_t total_issued_requests() const {
uint64_t sum = 0;
for (auto& p : locality_stats_) {
sum += p.second.total_issued_requests;
}
return sum;
}
uint64_t total_dropped_requests() const { return total_dropped_requests_; }
uint64_t dropped_requests(const grpc::string& category) const {
auto iter = dropped_requests_.find(category);
GPR_ASSERT(iter != dropped_requests_.end());
return iter->second;
}
private:
std::map<grpc::string, LocalityStats> locality_stats_;
uint64_t total_dropped_requests_;
std::map<grpc::string, uint64_t> dropped_requests_;
};
// TODO(roth): Change this service to a real fake.
class AdsServiceImpl : public AdsService {
public:
enum ResponseState {
NOT_SENT,
SENT,
ACKED,
NACKED,
};
struct ResponseArgs {
struct Locality {
Locality(const grpc::string& sub_zone, std::vector<int> ports,
int lb_weight = kDefaultLocalityWeight,
int priority = kDefaultLocalityPriority,
std::vector<envoy::api::v2::HealthStatus> health_statuses = {})
: sub_zone(std::move(sub_zone)),
ports(std::move(ports)),
lb_weight(lb_weight),
priority(priority),
health_statuses(std::move(health_statuses)) {}
const grpc::string sub_zone;
std::vector<int> ports;
int lb_weight;
int priority;
std::vector<envoy::api::v2::HealthStatus> health_statuses;
};
ResponseArgs() = default;
explicit ResponseArgs(std::vector<Locality> locality_list)
: locality_list(std::move(locality_list)) {}
std::vector<Locality> locality_list;
std::map<grpc::string, uint32_t> drop_categories;
FractionalPercent::DenominatorType drop_denominator =
FractionalPercent::MILLION;
};
using Stream = ServerReaderWriter<DiscoveryResponse, DiscoveryRequest>;
using ResponseDelayPair = std::pair<DiscoveryResponse, int>;
AdsServiceImpl(bool enable_load_reporting) {
// Construct RDS response data.
default_route_config_.set_name("application_target_name");
auto* virtual_host = default_route_config_.add_virtual_hosts();
virtual_host->add_domains("*");
auto* route = virtual_host->add_routes();
route->mutable_match()->set_prefix("");
route->mutable_route()->set_cluster("application_target_name");
rds_response_data_ = {
{"application_target_name", default_route_config_},
};
// Construct LDS response data (with inlined RDS result).
default_listener_ = BuildListener(default_route_config_);
lds_response_data_ = {
{"application_target_name", default_listener_},
};
// Construct CDS response data.
default_cluster_.set_name("application_target_name");
default_cluster_.set_type(envoy::api::v2::Cluster::EDS);
default_cluster_.mutable_eds_cluster_config()
->mutable_eds_config()
->mutable_ads();
default_cluster_.set_lb_policy(envoy::api::v2::Cluster::ROUND_ROBIN);
if (enable_load_reporting) {
default_cluster_.mutable_lrs_server()->mutable_self();
}
cds_response_data_ = {
{"application_target_name", default_cluster_},
};
}
void HandleLdsRequest(DiscoveryRequest* request, Stream* stream) {
gpr_log(GPR_INFO, "ADS[%p]: received LDS request '%s'", this,
request->DebugString().c_str());
const std::string version_str = "version_1";
const std::string nonce_str = "nonce_1";
grpc_core::MutexLock lock(&ads_mu_);
if (lds_ignore_) return;
if (lds_response_state_ == NOT_SENT) {
DiscoveryResponse response;
response.set_type_url(kLdsTypeUrl);
response.set_version_info(version_str);
response.set_nonce(nonce_str);
for (const auto& server_name : request->resource_names()) {
auto iter = lds_response_data_.find(server_name);
if (iter == lds_response_data_.end()) continue;
response.add_resources()->PackFrom(iter->second);
}
stream->Write(response);
lds_response_state_ = SENT;
} else if (lds_response_state_ == SENT) {
GPR_ASSERT(!request->response_nonce().empty());
lds_response_state_ =
request->version_info() == version_str ? ACKED : NACKED;
}
}
void HandleRdsRequest(DiscoveryRequest* request, Stream* stream) {
gpr_log(GPR_INFO, "ADS[%p]: received RDS request '%s'", this,
request->DebugString().c_str());
const std::string version_str = "version_1";
const std::string nonce_str = "nonce_1";
grpc_core::MutexLock lock(&ads_mu_);
if (rds_ignore_) return;
if (rds_response_state_ == NOT_SENT) {
DiscoveryResponse response;
response.set_type_url(kRdsTypeUrl);
response.set_version_info(version_str);
response.set_nonce(nonce_str);
for (const auto& route_config_name : request->resource_names()) {
auto iter = rds_response_data_.find(route_config_name);
if (iter == rds_response_data_.end()) continue;
response.add_resources()->PackFrom(iter->second);
}
stream->Write(response);
rds_response_state_ = SENT;
} else if (rds_response_state_ == SENT) {
GPR_ASSERT(!request->response_nonce().empty());
rds_response_state_ =
request->version_info() == version_str ? ACKED : NACKED;
}
}
void HandleCdsRequest(DiscoveryRequest* request, Stream* stream) {
gpr_log(GPR_INFO, "ADS[%p]: received CDS request '%s'", this,
request->DebugString().c_str());
const std::string version_str = "version_1";
const std::string nonce_str = "nonce_1";
grpc_core::MutexLock lock(&ads_mu_);
if (cds_ignore_) return;
if (cds_response_state_ == NOT_SENT) {
DiscoveryResponse response;
response.set_type_url(kCdsTypeUrl);
response.set_version_info(version_str);
response.set_nonce(nonce_str);
for (const auto& cluster_name : request->resource_names()) {
auto iter = cds_response_data_.find(cluster_name);
if (iter == cds_response_data_.end()) continue;
response.add_resources()->PackFrom(iter->second);
}
stream->Write(response);
cds_response_state_ = SENT;
} else if (cds_response_state_ == SENT) {
GPR_ASSERT(!request->response_nonce().empty());
cds_response_state_ =
request->version_info() == version_str ? ACKED : NACKED;
}
}
void HandleEdsRequest(DiscoveryRequest* request, Stream* stream) {
gpr_log(GPR_INFO, "ADS[%p]: received EDS request '%s'", this,
request->DebugString().c_str());
IncreaseRequestCount();
std::vector<ResponseDelayPair> responses_and_delays;
{
grpc_core::MutexLock lock(&ads_mu_);
if (eds_ignore_) return;
responses_and_delays = eds_responses_and_delays_;
}
// Send response.
for (const auto& p : responses_and_delays) {
const DiscoveryResponse& response = p.first;
const int delay_ms = p.second;
gpr_log(GPR_INFO, "ADS[%p]: sleeping for %d ms...", this, delay_ms);
if (delay_ms > 0) {
gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(delay_ms));
}
gpr_log(GPR_INFO, "ADS[%p]: Woke up! Sending response '%s'", this,
response.DebugString().c_str());
IncreaseResponseCount();
stream->Write(response);
}
}
Status StreamAggregatedResources(ServerContext* context,
Stream* stream) override {
gpr_log(GPR_INFO, "ADS[%p]: StreamAggregatedResources starts", this);
[&]() {
{
grpc_core::MutexLock lock(&ads_mu_);
if (ads_done_) return;
}
// Balancer shouldn't receive the call credentials metadata.
EXPECT_EQ(context->client_metadata().find(g_kCallCredsMdKey),
context->client_metadata().end());
// Keep servicing requests until the EDS response has been sent back.
DiscoveryRequest request;
// TODO(roth): For each supported type, we currently only handle one
// request without replying to any new requests (for ACK/NACK or new
// resource names). It's not causing a big problem now but should be
// fixed.
bool eds_sent = false;
bool seen_first_request = false;
while (!eds_sent || cds_response_state_ == SENT) {
if (!stream->Read(&request)) return;
if (!seen_first_request) {
EXPECT_TRUE(request.has_node());
seen_first_request = true;
}
if (request.type_url() == kLdsTypeUrl) {
HandleLdsRequest(&request, stream);
} else if (request.type_url() == kRdsTypeUrl) {
HandleRdsRequest(&request, stream);
} else if (request.type_url() == kCdsTypeUrl) {
HandleCdsRequest(&request, stream);
} else if (request.type_url() == kEdsTypeUrl) {
HandleEdsRequest(&request, stream);
eds_sent = true;
}
}
// Wait until notified done.
grpc_core::MutexLock lock(&ads_mu_);
ads_cond_.WaitUntil(&ads_mu_, [this] { return ads_done_; });
}();
gpr_log(GPR_INFO, "ADS[%p]: StreamAggregatedResources done", this);
return Status::OK;
}
Listener default_listener() const { return default_listener_; }
RouteConfiguration default_route_config() const {
return default_route_config_;
}
Cluster default_cluster() const { return default_cluster_; }
ResponseState lds_response_state() {
grpc_core::MutexLock lock(&ads_mu_);
return lds_response_state_;
}
ResponseState rds_response_state() {
grpc_core::MutexLock lock(&ads_mu_);
return rds_response_state_;
}
ResponseState cds_response_state() {
grpc_core::MutexLock lock(&ads_mu_);
return cds_response_state_;
}
void SetLdsResponse(
std::map<std::string /*server_name*/, Listener> lds_response_data) {
lds_response_data_ = std::move(lds_response_data);
}
void set_lds_ignore() { lds_ignore_ = true; }
void SetRdsResponse(
std::map<std::string /*route_config_name*/, RouteConfiguration>
rds_response_data) {
rds_response_data_ = std::move(rds_response_data);
}
void set_rds_ignore() { rds_ignore_ = true; }
void SetCdsResponse(
std::map<std::string /*cluster_name*/, Cluster> cds_response_data) {
cds_response_data_ = std::move(cds_response_data);
}
void set_cds_ignore() { cds_ignore_ = true; }
void AddEdsResponse(const DiscoveryResponse& response, int send_after_ms) {
grpc_core::MutexLock lock(&ads_mu_);
eds_responses_and_delays_.push_back(
std::make_pair(response, send_after_ms));
}
void set_eds_ignore() { eds_ignore_ = true; }
void SetLdsToUseDynamicRds() {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
http_connection_manager.mutable_rds()->set_route_config_name(
"application_target_name");
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetLdsResponse({{"application_target_name", std::move(listener)}});
}
static Listener BuildListener(const RouteConfiguration& route_config) {
HttpConnectionManager http_connection_manager;
*(http_connection_manager.mutable_route_config()) = route_config;
Listener listener;
listener.set_name("application_target_name");
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
return listener;
}
void Start() {
grpc_core::MutexLock lock(&ads_mu_);
ads_done_ = false;
eds_responses_and_delays_.clear();
}
void Shutdown() {
{
grpc_core::MutexLock lock(&ads_mu_);
NotifyDoneWithAdsCallLocked();
eds_responses_and_delays_.clear();
}
gpr_log(GPR_INFO, "ADS[%p]: shut down", this);
}
static DiscoveryResponse BuildResponse(const ResponseArgs& args) {
ClusterLoadAssignment assignment;
assignment.set_cluster_name("application_target_name");
for (const auto& locality : args.locality_list) {
auto* endpoints = assignment.add_endpoints();
endpoints->mutable_load_balancing_weight()->set_value(locality.lb_weight);
endpoints->set_priority(locality.priority);
endpoints->mutable_locality()->set_region(kDefaultLocalityRegion);
endpoints->mutable_locality()->set_zone(kDefaultLocalityZone);
endpoints->mutable_locality()->set_sub_zone(locality.sub_zone);
for (size_t i = 0; i < locality.ports.size(); ++i) {
const int& port = locality.ports[i];
auto* lb_endpoints = endpoints->add_lb_endpoints();
if (locality.health_statuses.size() > i &&
locality.health_statuses[i] !=
envoy::api::v2::HealthStatus::UNKNOWN) {
lb_endpoints->set_health_status(locality.health_statuses[i]);
}
auto* endpoint = lb_endpoints->mutable_endpoint();
auto* address = endpoint->mutable_address();
auto* socket_address = address->mutable_socket_address();
socket_address->set_address("127.0.0.1");
socket_address->set_port_value(port);
}
}
if (!args.drop_categories.empty()) {
auto* policy = assignment.mutable_policy();
for (const auto& p : args.drop_categories) {
const grpc::string& name = p.first;
const uint32_t parts_per_million = p.second;
auto* drop_overload = policy->add_drop_overloads();
drop_overload->set_category(name);
auto* drop_percentage = drop_overload->mutable_drop_percentage();
drop_percentage->set_numerator(parts_per_million);
drop_percentage->set_denominator(args.drop_denominator);
}
}
DiscoveryResponse response;
response.set_type_url(kEdsTypeUrl);
response.add_resources()->PackFrom(assignment);
return response;
}
void NotifyDoneWithAdsCall() {
grpc_core::MutexLock lock(&ads_mu_);
NotifyDoneWithAdsCallLocked();
}
void NotifyDoneWithAdsCallLocked() {
if (!ads_done_) {
ads_done_ = true;
ads_cond_.Broadcast();
}
}
private:
grpc_core::CondVar ads_cond_;
// Protect the members below.
grpc_core::Mutex ads_mu_;
bool ads_done_ = false;
// LDS response data.
Listener default_listener_;
std::map<std::string /*server_name*/, Listener> lds_response_data_;
ResponseState lds_response_state_ = NOT_SENT;
bool lds_ignore_ = false;
// RDS response data.
RouteConfiguration default_route_config_;
std::map<std::string /*route_config_name*/, RouteConfiguration>
rds_response_data_;
ResponseState rds_response_state_ = NOT_SENT;
bool rds_ignore_ = false;
// CDS response data.
Cluster default_cluster_;
std::map<std::string /*cluster_name*/, Cluster> cds_response_data_;
ResponseState cds_response_state_ = NOT_SENT;
bool cds_ignore_ = false;
// EDS response data.
std::vector<ResponseDelayPair> eds_responses_and_delays_;
bool eds_ignore_ = false;
};
class LrsServiceImpl : public LrsService {
public:
using Stream = ServerReaderWriter<LoadStatsResponse, LoadStatsRequest>;
explicit LrsServiceImpl(int client_load_reporting_interval_seconds)
: client_load_reporting_interval_seconds_(
client_load_reporting_interval_seconds) {}
Status StreamLoadStats(ServerContext* /*context*/, Stream* stream) override {
gpr_log(GPR_INFO, "LRS[%p]: StreamLoadStats starts", this);
// Read request.
LoadStatsRequest request;
if (stream->Read(&request)) {
if (client_load_reporting_interval_seconds_ > 0) {
IncreaseRequestCount();
// Send response.
LoadStatsResponse response;
auto server_name = request.cluster_stats()[0].cluster_name();
GPR_ASSERT(server_name != "");
response.add_clusters(server_name);
response.mutable_load_reporting_interval()->set_seconds(
client_load_reporting_interval_seconds_);
stream->Write(response);
IncreaseResponseCount();
// Wait for report.
request.Clear();
if (stream->Read(&request)) {
gpr_log(GPR_INFO, "LRS[%p]: received client load report message '%s'",
this, request.DebugString().c_str());
GPR_ASSERT(request.cluster_stats().size() == 1);
const ClusterStats& cluster_stats = request.cluster_stats()[0];
// We need to acquire the lock here in order to prevent the notify_one
// below from firing before its corresponding wait is executed.
grpc_core::MutexLock lock(&load_report_mu_);
GPR_ASSERT(client_stats_ == nullptr);
client_stats_.reset(new ClientStats(cluster_stats));
load_report_ready_ = true;
load_report_cond_.Signal();
}
}
// Wait until notified done.
grpc_core::MutexLock lock(&lrs_mu_);
lrs_cv_.WaitUntil(&lrs_mu_, [this] { return lrs_done; });
}
gpr_log(GPR_INFO, "LRS[%p]: StreamLoadStats done", this);
return Status::OK;
}
void Start() {
lrs_done = false;
load_report_ready_ = false;
client_stats_.reset();
}
void Shutdown() {
{
grpc_core::MutexLock lock(&lrs_mu_);
NotifyDoneWithLrsCallLocked();
}
gpr_log(GPR_INFO, "LRS[%p]: shut down", this);
}
ClientStats* WaitForLoadReport() {
grpc_core::MutexLock lock(&load_report_mu_);
load_report_cond_.WaitUntil(&load_report_mu_,
[this] { return load_report_ready_; });
load_report_ready_ = false;
return client_stats_.get();
}
void NotifyDoneWithLrsCall() {
grpc_core::MutexLock lock(&lrs_mu_);
NotifyDoneWithLrsCallLocked();
}
void NotifyDoneWithLrsCallLocked() {
if (!lrs_done) {
lrs_done = true;
lrs_cv_.Broadcast();
}
}
private:
const int client_load_reporting_interval_seconds_;
grpc_core::CondVar lrs_cv_;
// Protect lrs_done.
grpc_core::Mutex lrs_mu_;
bool lrs_done = false;
grpc_core::CondVar load_report_cond_;
// Protect the members below.
grpc_core::Mutex load_report_mu_;
std::unique_ptr<ClientStats> client_stats_;
bool load_report_ready_ = false;
};
class TestType {
public:
TestType(bool use_xds_resolver, bool enable_load_reporting)
: use_xds_resolver_(use_xds_resolver),
enable_load_reporting_(enable_load_reporting) {}
bool use_xds_resolver() const { return use_xds_resolver_; }
bool enable_load_reporting() const { return enable_load_reporting_; }
grpc::string AsString() const {
grpc::string retval = (use_xds_resolver_ ? "XdsResolver" : "FakeResolver");
if (enable_load_reporting_) retval += "WithLoadReporting";
return retval;
}
private:
const bool use_xds_resolver_;
const bool enable_load_reporting_;
};
class XdsEnd2endTest : public ::testing::TestWithParam<TestType> {
protected:
XdsEnd2endTest(size_t num_backends, size_t num_balancers,
int client_load_reporting_interval_seconds = 100)
: server_host_("localhost"),
num_backends_(num_backends),
num_balancers_(num_balancers),
client_load_reporting_interval_seconds_(
client_load_reporting_interval_seconds) {}
static void SetUpTestCase() {
// Make the backup poller poll very frequently in order to pick up
// updates from all the subchannels's FDs.
GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms, 1);
#if TARGET_OS_IPHONE
// Workaround Apple CFStream bug
gpr_setenv("grpc_cfstream", "0");
#endif
grpc_init();
}
static void TearDownTestCase() { grpc_shutdown(); }
void SetUp() override {
gpr_setenv("GRPC_XDS_BOOTSTRAP", g_bootstrap_file);
g_port_saver->Reset();
response_generator_ =
grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
lb_channel_response_generator_ =
grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
// Start the backends.
for (size_t i = 0; i < num_backends_; ++i) {
backends_.emplace_back(new BackendServerThread);
backends_.back()->Start(server_host_);
}
// Start the load balancers.
for (size_t i = 0; i < num_balancers_; ++i) {
balancers_.emplace_back(
new BalancerServerThread(GetParam().enable_load_reporting()
? client_load_reporting_interval_seconds_
: 0));
balancers_.back()->Start(server_host_);
}
ResetStub();
}
void TearDown() override {
ShutdownAllBackends();
for (auto& balancer : balancers_) balancer->Shutdown();
}
void StartAllBackends() {
for (auto& backend : backends_) backend->Start(server_host_);
}
void StartBackend(size_t index) { backends_[index]->Start(server_host_); }
void ShutdownAllBackends() {
for (auto& backend : backends_) backend->Shutdown();
}
void ShutdownBackend(size_t index) { backends_[index]->Shutdown(); }
void ResetStub(int fallback_timeout = 0, int failover_timeout = 0,
const grpc::string& expected_targets = "",
int xds_resource_does_not_exist_timeout = 0) {
ChannelArguments args;
// TODO(juanlishen): Add setter to ChannelArguments.
if (fallback_timeout > 0) {
args.SetInt(GRPC_ARG_XDS_FALLBACK_TIMEOUT_MS, fallback_timeout);
}
if (failover_timeout > 0) {
args.SetInt(GRPC_ARG_XDS_FAILOVER_TIMEOUT_MS, failover_timeout);
}
if (xds_resource_does_not_exist_timeout > 0) {
args.SetInt(GRPC_ARG_XDS_RESOURCE_DOES_NOT_EXIST_TIMEOUT_MS,
xds_resource_does_not_exist_timeout);
}
// If the parent channel is using the fake resolver, we inject the
// response generator for the parent here, and then SetNextResolution()
// will inject the xds channel's response generator via the parent's
// response generator.
//
// In contrast, if we are using the xds resolver, then the parent
// channel never uses a response generator, and we inject the xds
// channel's response generator here.
args.SetPointer(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
GetParam().use_xds_resolver()
? lb_channel_response_generator_.get()
: response_generator_.get());
if (!expected_targets.empty()) {
args.SetString(GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS, expected_targets);
}
grpc::string scheme =
GetParam().use_xds_resolver() ? "xds-experimental" : "fake";
std::ostringstream uri;
uri << scheme << ":///" << kApplicationTargetName_;
// TODO(dgq): templatize tests to run everything using both secure and
// insecure channel credentials.
grpc_channel_credentials* channel_creds =
grpc_fake_transport_security_credentials_create();
grpc_call_credentials* call_creds = grpc_md_only_test_credentials_create(
g_kCallCredsMdKey, g_kCallCredsMdValue, false);
std::shared_ptr<ChannelCredentials> creds(
new SecureChannelCredentials(grpc_composite_channel_credentials_create(
channel_creds, call_creds, nullptr)));
call_creds->Unref();
channel_creds->Unref();
channel_ = ::grpc::CreateCustomChannel(uri.str(), creds, args);
stub_ = grpc::testing::EchoTestService::NewStub(channel_);
}
void ResetBackendCounters() {
for (auto& backend : backends_) backend->backend_service()->ResetCounters();
}
bool SeenAllBackends(size_t start_index = 0, size_t stop_index = 0) {
if (stop_index == 0) stop_index = backends_.size();
for (size_t i = start_index; i < stop_index; ++i) {
if (backends_[i]->backend_service()->request_count() == 0) return false;
}
return true;
}
void SendRpcAndCount(int* num_total, int* num_ok, int* num_failure,
int* num_drops) {
const Status status = SendRpc();
if (status.ok()) {
++*num_ok;
} else {
if (status.error_message() == "Call dropped by load balancing policy") {
++*num_drops;
} else {
++*num_failure;
}
}
++*num_total;
}
std::tuple<int, int, int> WaitForAllBackends(size_t start_index = 0,
size_t stop_index = 0) {
int num_ok = 0;
int num_failure = 0;
int num_drops = 0;
int num_total = 0;
while (!SeenAllBackends(start_index, stop_index)) {
SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_drops);
}
ResetBackendCounters();
gpr_log(GPR_INFO,
"Performed %d warm up requests against the backends. "
"%d succeeded, %d failed, %d dropped.",
num_total, num_ok, num_failure, num_drops);
return std::make_tuple(num_ok, num_failure, num_drops);
}
void WaitForBackend(size_t backend_idx, bool reset_counters = true) {
gpr_log(GPR_INFO, "========= WAITING FOR BACKEND %lu ==========",
static_cast<unsigned long>(backend_idx));
do {
(void)SendRpc();
} while (backends_[backend_idx]->backend_service()->request_count() == 0);
if (reset_counters) ResetBackendCounters();
gpr_log(GPR_INFO, "========= BACKEND %lu READY ==========",
static_cast<unsigned long>(backend_idx));
}
grpc_core::ServerAddressList CreateAddressListFromPortList(
const std::vector<int>& ports) {
grpc_core::ServerAddressList addresses;
for (int port : ports) {
char* lb_uri_str;
gpr_asprintf(&lb_uri_str, "ipv4:127.0.0.1:%d", port);
grpc_uri* lb_uri = grpc_uri_parse(lb_uri_str, true);
GPR_ASSERT(lb_uri != nullptr);
grpc_resolved_address address;
GPR_ASSERT(grpc_parse_uri(lb_uri, &address));
addresses.emplace_back(address.addr, address.len, nullptr);
grpc_uri_destroy(lb_uri);
gpr_free(lb_uri_str);
}
return addresses;
}
void SetNextResolution(const std::vector<int>& ports,
grpc_core::FakeResolverResponseGenerator*
lb_channel_response_generator = nullptr) {
if (GetParam().use_xds_resolver()) return; // Not used with xds resolver.
grpc_core::ExecCtx exec_ctx;
grpc_core::Resolver::Result result;
result.addresses = CreateAddressListFromPortList(ports);
grpc_error* error = GRPC_ERROR_NONE;
const char* service_config_json =
GetParam().enable_load_reporting()
? kDefaultServiceConfig_
: kDefaultServiceConfigWithoutLoadReporting_;
result.service_config =
grpc_core::ServiceConfig::Create(service_config_json, &error);
GRPC_ERROR_UNREF(error);
grpc_arg arg = grpc_core::FakeResolverResponseGenerator::MakeChannelArg(
lb_channel_response_generator == nullptr
? lb_channel_response_generator_.get()
: lb_channel_response_generator);
result.args = grpc_channel_args_copy_and_add(nullptr, &arg, 1);
response_generator_->SetResponse(std::move(result));
}
void SetNextResolutionForLbChannelAllBalancers(
const char* service_config_json = nullptr,
grpc_core::FakeResolverResponseGenerator* lb_channel_response_generator =
nullptr) {
std::vector<int> ports;
for (size_t i = 0; i < balancers_.size(); ++i) {
ports.emplace_back(balancers_[i]->port());
}
SetNextResolutionForLbChannel(ports, service_config_json,
lb_channel_response_generator);
}
void SetNextResolutionForLbChannel(
const std::vector<int>& ports, const char* service_config_json = nullptr,
grpc_core::FakeResolverResponseGenerator* lb_channel_response_generator =
nullptr) {
grpc_core::ExecCtx exec_ctx;
grpc_core::Resolver::Result result;
result.addresses = CreateAddressListFromPortList(ports);
if (service_config_json != nullptr) {
grpc_error* error = GRPC_ERROR_NONE;
result.service_config =
grpc_core::ServiceConfig::Create(service_config_json, &error);
GRPC_ERROR_UNREF(error);
}
if (lb_channel_response_generator == nullptr) {
lb_channel_response_generator = lb_channel_response_generator_.get();
}
lb_channel_response_generator->SetResponse(std::move(result));
}
void SetNextReresolutionResponse(const std::vector<int>& ports) {
grpc_core::ExecCtx exec_ctx;
grpc_core::Resolver::Result result;
result.addresses = CreateAddressListFromPortList(ports);
response_generator_->SetReresolutionResponse(std::move(result));
}
const std::vector<int> GetBackendPorts(size_t start_index = 0,
size_t stop_index = 0) const {
if (stop_index == 0) stop_index = backends_.size();
std::vector<int> backend_ports;
for (size_t i = start_index; i < stop_index; ++i) {
backend_ports.push_back(backends_[i]->port());
}
return backend_ports;
}
void ScheduleResponseForBalancer(size_t i, const DiscoveryResponse& response,
int delay_ms) {
balancers_[i]->ads_service()->AddEdsResponse(response, delay_ms);
}
Status SendRpc(EchoResponse* response = nullptr, int timeout_ms = 1000,
bool wait_for_ready = false) {
const bool local_response = (response == nullptr);
if (local_response) response = new EchoResponse;
EchoRequest request;
request.set_message(kRequestMessage_);
ClientContext context;
context.set_deadline(grpc_timeout_milliseconds_to_deadline(timeout_ms));
if (wait_for_ready) context.set_wait_for_ready(true);
Status status = stub_->Echo(&context, request, response);
if (local_response) delete response;
return status;
}
void CheckRpcSendOk(const size_t times = 1, const int timeout_ms = 1000,
bool wait_for_ready = false) {
for (size_t i = 0; i < times; ++i) {
EchoResponse response;
const Status status = SendRpc(&response, timeout_ms, wait_for_ready);
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage_);
}
}
void CheckRpcSendFailure() {
const Status status = SendRpc();
EXPECT_FALSE(status.ok());
}
class ServerThread {
public:
ServerThread() : port_(g_port_saver->GetPort()) {}
virtual ~ServerThread(){};
void Start(const grpc::string& server_host) {
gpr_log(GPR_INFO, "starting %s server on port %d", Type(), port_);
GPR_ASSERT(!running_);
running_ = true;
StartAllServices();
grpc_core::Mutex mu;
// We need to acquire the lock here in order to prevent the notify_one
// by ServerThread::Serve from firing before the wait below is hit.
grpc_core::MutexLock lock(&mu);
grpc_core::CondVar cond;
thread_.reset(new std::thread(
std::bind(&ServerThread::Serve, this, server_host, &mu, &cond)));
cond.Wait(&mu);
gpr_log(GPR_INFO, "%s server startup complete", Type());
}
void Serve(const grpc::string& server_host, grpc_core::Mutex* mu,
grpc_core::CondVar* cond) {
// We need to acquire the lock here in order to prevent the notify_one
// below from firing before its corresponding wait is executed.
grpc_core::MutexLock lock(mu);
std::ostringstream server_address;
server_address << server_host << ":" << port_;
ServerBuilder builder;
std::shared_ptr<ServerCredentials> creds(new SecureServerCredentials(
grpc_fake_transport_security_server_credentials_create()));
builder.AddListeningPort(server_address.str(), creds);
RegisterAllServices(&builder);
server_ = builder.BuildAndStart();
cond->Signal();
}
void Shutdown() {
if (!running_) return;
gpr_log(GPR_INFO, "%s about to shutdown", Type());
ShutdownAllServices();
server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
thread_->join();
gpr_log(GPR_INFO, "%s shutdown completed", Type());
running_ = false;
}
int port() const { return port_; }
private:
virtual void RegisterAllServices(ServerBuilder* builder) = 0;
virtual void StartAllServices() = 0;
virtual void ShutdownAllServices() = 0;
virtual const char* Type() = 0;
const int port_;
std::unique_ptr<Server> server_;
std::unique_ptr<std::thread> thread_;
bool running_ = false;
};
class BackendServerThread : public ServerThread {
public:
BackendServiceImpl* backend_service() { return &backend_service_; }
private:
void RegisterAllServices(ServerBuilder* builder) override {
builder->RegisterService(&backend_service_);
}
void StartAllServices() override { backend_service_.Start(); }
void ShutdownAllServices() override { backend_service_.Shutdown(); }
const char* Type() override { return "Backend"; }
BackendServiceImpl backend_service_;
};
class BalancerServerThread : public ServerThread {
public:
explicit BalancerServerThread(int client_load_reporting_interval = 0)
: ads_service_(client_load_reporting_interval > 0),
lrs_service_(client_load_reporting_interval) {}
AdsServiceImpl* ads_service() { return &ads_service_; }
LrsServiceImpl* lrs_service() { return &lrs_service_; }
private:
void RegisterAllServices(ServerBuilder* builder) override {
builder->RegisterService(&ads_service_);
builder->RegisterService(&lrs_service_);
}
void StartAllServices() override {
ads_service_.Start();
lrs_service_.Start();
}
void ShutdownAllServices() override {
ads_service_.Shutdown();
lrs_service_.Shutdown();
}
const char* Type() override { return "Balancer"; }
AdsServiceImpl ads_service_;
LrsServiceImpl lrs_service_;
};
const grpc::string server_host_;
const size_t num_backends_;
const size_t num_balancers_;
const int client_load_reporting_interval_seconds_;
std::shared_ptr<Channel> channel_;
std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
std::vector<std::unique_ptr<BackendServerThread>> backends_;
std::vector<std::unique_ptr<BalancerServerThread>> balancers_;
grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
response_generator_;
grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
lb_channel_response_generator_;
const grpc::string kRequestMessage_ = "Live long and prosper.";
const grpc::string kApplicationTargetName_ = "application_target_name";
const char* kDefaultServiceConfig_ =
"{\n"
" \"loadBalancingConfig\":[\n"
" { \"does_not_exist\":{} },\n"
" { \"xds_experimental\":{\n"
" \"lrsLoadReportingServerName\": \"\"\n"
" } }\n"
" ]\n"
"}";
const char* kDefaultServiceConfigWithoutLoadReporting_ =
"{\n"
" \"loadBalancingConfig\":[\n"
" { \"does_not_exist\":{} },\n"
" { \"xds_experimental\":{\n"
" } }\n"
" ]\n"
"}";
};
class BasicTest : public XdsEnd2endTest {
public:
BasicTest() : XdsEnd2endTest(4, 1) {}
};
// Tests that the balancer sends the correct response to the client, and the
// client sends RPCs to the backends using the default child policy.
TEST_P(BasicTest, Vanilla) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcsPerAddress = 100;
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts()},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// Make sure that trying to connect works without a call.
channel_->GetState(true /* try_to_connect */);
// We need to wait for all backends to come online.
WaitForAllBackends();
// Send kNumRpcsPerAddress RPCs per server.
CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
// Each backend should have gotten 100 requests.
for (size_t i = 0; i < backends_.size(); ++i) {
EXPECT_EQ(kNumRpcsPerAddress,
backends_[i]->backend_service()->request_count());
}
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
// Check LB policy name for the channel.
EXPECT_EQ(
(GetParam().use_xds_resolver() ? "cds_experimental" : "xds_experimental"),
channel_->GetLoadBalancingPolicyName());
}
TEST_P(BasicTest, IgnoresUnhealthyEndpoints) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcsPerAddress = 100;
AdsServiceImpl::ResponseArgs args({
{"locality0",
GetBackendPorts(),
kDefaultLocalityWeight,
kDefaultLocalityPriority,
{envoy::api::v2::HealthStatus::DRAINING}},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// Make sure that trying to connect works without a call.
channel_->GetState(true /* try_to_connect */);
// We need to wait for all backends to come online.
WaitForAllBackends(/*start_index=*/1);
// Send kNumRpcsPerAddress RPCs per server.
CheckRpcSendOk(kNumRpcsPerAddress * (num_backends_ - 1));
// Each backend should have gotten 100 requests.
for (size_t i = 1; i < backends_.size(); ++i) {
EXPECT_EQ(kNumRpcsPerAddress,
backends_[i]->backend_service()->request_count());
}
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// Tests that subchannel sharing works when the same backend is listed multiple
// times.
TEST_P(BasicTest, SameBackendListedMultipleTimes) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Same backend listed twice.
std::vector<int> ports(2, backends_[0]->port());
AdsServiceImpl::ResponseArgs args({
{"locality0", ports},
});
const size_t kNumRpcsPerAddress = 10;
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// We need to wait for the backend to come online.
WaitForBackend(0);
// Send kNumRpcsPerAddress RPCs per server.
CheckRpcSendOk(kNumRpcsPerAddress * ports.size());
// Backend should have gotten 20 requests.
EXPECT_EQ(kNumRpcsPerAddress * ports.size(),
backends_[0]->backend_service()->request_count());
// And they should have come from a single client port, because of
// subchannel sharing.
EXPECT_EQ(1UL, backends_[0]->backend_service()->clients().size());
}
// Tests that RPCs will be blocked until a non-empty serverlist is received.
TEST_P(BasicTest, InitiallyEmptyServerlist) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor();
const int kCallDeadlineMs = kServerlistDelayMs * 2;
// First response is an empty serverlist, sent right away.
AdsServiceImpl::ResponseArgs::Locality empty_locality("locality0", {});
AdsServiceImpl::ResponseArgs args({
empty_locality,
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// Send non-empty serverlist only after kServerlistDelayMs.
args = AdsServiceImpl::ResponseArgs({
{"locality0", GetBackendPorts()},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args),
kServerlistDelayMs);
const auto t0 = system_clock::now();
// Client will block: LB will initially send empty serverlist.
CheckRpcSendOk(1, kCallDeadlineMs, true /* wait_for_ready */);
const auto ellapsed_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(
system_clock::now() - t0);
// but eventually, the LB sends a serverlist update that allows the call to
// proceed. The call delay must be larger than the delay in sending the
// populated serverlist but under the call's deadline (which is enforced by
// the call's deadline).
EXPECT_GT(ellapsed_ms.count(), kServerlistDelayMs);
// The ADS service got a single request.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
// and sent two responses.
EXPECT_EQ(2U, balancers_[0]->ads_service()->response_count());
}
// Tests that RPCs will fail with UNAVAILABLE instead of DEADLINE_EXCEEDED if
// all the servers are unreachable.
TEST_P(BasicTest, AllServersUnreachableFailFast) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumUnreachableServers = 5;
std::vector<int> ports;
for (size_t i = 0; i < kNumUnreachableServers; ++i) {
ports.push_back(g_port_saver->GetPort());
}
AdsServiceImpl::ResponseArgs args({
{"locality0", ports},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
const Status status = SendRpc();
// The error shouldn't be DEADLINE_EXCEEDED.
EXPECT_EQ(StatusCode::UNAVAILABLE, status.error_code());
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// Tests that RPCs fail when the backends are down, and will succeed again after
// the backends are restarted.
TEST_P(BasicTest, BackendsRestart) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts()},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
WaitForAllBackends();
// Stop backends. RPCs should fail.
ShutdownAllBackends();
CheckRpcSendFailure();
// Restart all backends. RPCs should start succeeding again.
StartAllBackends();
CheckRpcSendOk(1 /* times */, 2000 /* timeout_ms */,
true /* wait_for_ready */);
}
using SecureNamingTest = BasicTest;
// Tests that secure naming check passes if target name is expected.
TEST_P(SecureNamingTest, TargetNameIsExpected) {
// TODO(juanlishen): Use separate fake creds for the balancer channel.
ResetStub(0, 0, kApplicationTargetName_ + ";lb");
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()});
const size_t kNumRpcsPerAddress = 100;
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts()},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// Make sure that trying to connect works without a call.
channel_->GetState(true /* try_to_connect */);
// We need to wait for all backends to come online.
WaitForAllBackends();
// Send kNumRpcsPerAddress RPCs per server.
CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
// Each backend should have gotten 100 requests.
for (size_t i = 0; i < backends_.size(); ++i) {
EXPECT_EQ(kNumRpcsPerAddress,
backends_[i]->backend_service()->request_count());
}
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// Tests that secure naming check fails if target name is unexpected.
TEST_P(SecureNamingTest, TargetNameIsUnexpected) {
gpr_setenv("GRPC_XDS_BOOTSTRAP", g_bootstrap_file_bad);
::testing::FLAGS_gtest_death_test_style = "threadsafe";
// Make sure that we blow up (via abort() from the security connector) when
// the name from the balancer doesn't match expectations.
ASSERT_DEATH_IF_SUPPORTED(
{
ResetStub(0, 0, kApplicationTargetName_ + ";lb");
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()});
channel_->WaitForConnected(grpc_timeout_seconds_to_deadline(1));
},
"");
}
using LdsTest = BasicTest;
// Tests that LDS client should send an ACK upon correct LDS response (with
// inlined RDS result).
TEST_P(LdsTest, Vanilla) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state(),
AdsServiceImpl::ACKED);
}
// Tests that LDS client should send a NACK if there is no API listener in the
// Listener in the LDS response.
TEST_P(LdsTest, NoApiListener) {
auto listener = balancers_[0]->ads_service()->default_listener();
listener.clear_api_listener();
balancers_[0]->ads_service()->SetLdsResponse(
{{"application_target_name", listener}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that LDS client should send a NACK if the route_specifier in the
// http_connection_manager is neither inlined route_config nor RDS.
TEST_P(LdsTest, WrongRouteSpecifier) {
auto listener = balancers_[0]->ads_service()->default_listener();
HttpConnectionManager http_connection_manager;
http_connection_manager.mutable_scoped_routes();
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
balancers_[0]->ads_service()->SetLdsResponse(
{{"application_target_name", std::move(listener)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that LDS client should send a NACK if matching domain can't be found in
// the LDS response.
TEST_P(LdsTest, NoMatchedDomain) {
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
route_config.mutable_virtual_hosts(0)->clear_domains();
route_config.mutable_virtual_hosts(0)->add_domains("unmatched_domain");
balancers_[0]->ads_service()->SetLdsResponse(
{{"application_target_name",
AdsServiceImpl::BuildListener(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that LDS client should choose the virtual host with matching domain if
// multiple virtual hosts exist in the LDS response.
TEST_P(LdsTest, ChooseMatchedDomain) {
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
*(route_config.add_virtual_hosts()) = route_config.virtual_hosts(0);
route_config.mutable_virtual_hosts(0)->clear_domains();
route_config.mutable_virtual_hosts(0)->add_domains("unmatched_domain");
route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_cluster_header();
balancers_[0]->ads_service()->SetLdsResponse(
{{"application_target_name",
AdsServiceImpl::BuildListener(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state(),
AdsServiceImpl::ACKED);
}
// Tests that LDS client should choose the last route in the virtual host if
// multiple routes exist in the LDS response.
TEST_P(LdsTest, ChooseLastRoute) {
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
*(route_config.mutable_virtual_hosts(0)->add_routes()) =
route_config.virtual_hosts(0).routes(0);
route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_cluster_header();
balancers_[0]->ads_service()->SetLdsResponse(
{{"application_target_name",
AdsServiceImpl::BuildListener(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state(),
AdsServiceImpl::ACKED);
}
// Tests that LDS client should send a NACK if route match has non-empty prefix
// in the LDS response.
TEST_P(LdsTest, RouteMatchHasNonemptyPrefix) {
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_match()
->set_prefix("nonempty_prefix");
balancers_[0]->ads_service()->SetLdsResponse(
{{"application_target_name",
AdsServiceImpl::BuildListener(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that LDS client should send a NACK if route has an action other than
// RouteAction in the LDS response.
TEST_P(LdsTest, RouteHasNoRouteAction) {
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
route_config.mutable_virtual_hosts(0)->mutable_routes(0)->mutable_redirect();
balancers_[0]->ads_service()->SetLdsResponse(
{{"application_target_name",
AdsServiceImpl::BuildListener(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that LDS client should send a NACK if RouteAction has a
// cluster_specifier other than cluster in the LDS response.
TEST_P(LdsTest, RouteActionHasNoCluster) {
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_cluster_header();
balancers_[0]->ads_service()->SetLdsResponse(
{{"application_target_name",
AdsServiceImpl::BuildListener(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that LDS client times out when no response received.
TEST_P(LdsTest, Timeout) {
ResetStub(0, 0, "", 500);
balancers_[0]->ads_service()->set_lds_ignore();
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
}
using RdsTest = BasicTest;
// Tests that RDS client should send an ACK upon correct RDS response.
TEST_P(RdsTest, Vanilla) {
balancers_[0]->ads_service()->SetLdsToUseDynamicRds();
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
EXPECT_EQ(balancers_[0]->ads_service()->rds_response_state(),
AdsServiceImpl::ACKED);
}
// Tests that RDS client should send a NACK if matching domain can't be found in
// the RDS response.
TEST_P(RdsTest, NoMatchedDomain) {
balancers_[0]->ads_service()->SetLdsToUseDynamicRds();
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
route_config.mutable_virtual_hosts(0)->clear_domains();
route_config.mutable_virtual_hosts(0)->add_domains("unmatched_domain");
balancers_[0]->ads_service()->SetRdsResponse(
{{"application_target_name", std::move(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->rds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that RDS client should choose the virtual host with matching domain if
// multiple virtual hosts exist in the RDS response.
TEST_P(RdsTest, ChooseMatchedDomain) {
balancers_[0]->ads_service()->SetLdsToUseDynamicRds();
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
*(route_config.add_virtual_hosts()) = route_config.virtual_hosts(0);
route_config.mutable_virtual_hosts(0)->clear_domains();
route_config.mutable_virtual_hosts(0)->add_domains("unmatched_domain");
route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_cluster_header();
balancers_[0]->ads_service()->SetRdsResponse(
{{"application_target_name", std::move(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
EXPECT_EQ(balancers_[0]->ads_service()->rds_response_state(),
AdsServiceImpl::ACKED);
}
// Tests that RDS client should choose the last route in the virtual host if
// multiple routes exist in the RDS response.
TEST_P(RdsTest, ChooseLastRoute) {
balancers_[0]->ads_service()->SetLdsToUseDynamicRds();
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
*(route_config.mutable_virtual_hosts(0)->add_routes()) =
route_config.virtual_hosts(0).routes(0);
route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_cluster_header();
balancers_[0]->ads_service()->SetRdsResponse(
{{"application_target_name", std::move(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
EXPECT_EQ(balancers_[0]->ads_service()->rds_response_state(),
AdsServiceImpl::ACKED);
}
// Tests that RDS client should send a NACK if route match has non-empty prefix
// in the RDS response.
TEST_P(RdsTest, RouteMatchHasNonemptyPrefix) {
balancers_[0]->ads_service()->SetLdsToUseDynamicRds();
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_match()
->set_prefix("nonempty_prefix");
balancers_[0]->ads_service()->SetRdsResponse(
{{"application_target_name", std::move(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->rds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that RDS client should send a NACK if route has an action other than
// RouteAction in the RDS response.
TEST_P(RdsTest, RouteHasNoRouteAction) {
balancers_[0]->ads_service()->SetLdsToUseDynamicRds();
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
route_config.mutable_virtual_hosts(0)->mutable_routes(0)->mutable_redirect();
balancers_[0]->ads_service()->SetRdsResponse(
{{"application_target_name", std::move(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->rds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that RDS client should send a NACK if RouteAction has a
// cluster_specifier other than cluster in the RDS response.
TEST_P(RdsTest, RouteActionHasNoCluster) {
balancers_[0]->ads_service()->SetLdsToUseDynamicRds();
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_cluster_header();
balancers_[0]->ads_service()->SetRdsResponse(
{{"application_target_name", std::move(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->rds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that RDS client times out when no response received.
TEST_P(RdsTest, Timeout) {
ResetStub(0, 0, "", 500);
balancers_[0]->ads_service()->SetLdsToUseDynamicRds();
balancers_[0]->ads_service()->set_rds_ignore();
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
}
using CdsTest = BasicTest;
// Tests that CDS client should send an ACK upon correct CDS response.
TEST_P(CdsTest, Vanilla) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state(),
AdsServiceImpl::ACKED);
}
// Tests that CDS client should send a NACK if the cluster type in CDS response
// is other than EDS.
TEST_P(CdsTest, WrongClusterType) {
auto cluster = balancers_[0]->ads_service()->default_cluster();
cluster.set_type(envoy::api::v2::Cluster::STATIC);
balancers_[0]->ads_service()->SetCdsResponse(
{{"application_target_name", std::move(cluster)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that CDS client should send a NACK if the eds_config in CDS response is
// other than ADS.
TEST_P(CdsTest, WrongEdsConfig) {
auto cluster = balancers_[0]->ads_service()->default_cluster();
cluster.mutable_eds_cluster_config()->mutable_eds_config()->mutable_self();
balancers_[0]->ads_service()->SetCdsResponse(
{{"application_target_name", std::move(cluster)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that CDS client should send a NACK if the lb_policy in CDS response is
// other than ROUND_ROBIN.
TEST_P(CdsTest, WrongLbPolicy) {
auto cluster = balancers_[0]->ads_service()->default_cluster();
cluster.set_lb_policy(envoy::api::v2::Cluster::LEAST_REQUEST);
balancers_[0]->ads_service()->SetCdsResponse(
{{"application_target_name", std::move(cluster)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that CDS client should send a NACK if the lrs_server in CDS response is
// other than SELF.
TEST_P(CdsTest, WrongLrsServer) {
auto cluster = balancers_[0]->ads_service()->default_cluster();
cluster.mutable_lrs_server()->mutable_ads();
balancers_[0]->ads_service()->SetCdsResponse(
{{"application_target_name", std::move(cluster)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that CDS client times out when no response received.
TEST_P(CdsTest, Timeout) {
ResetStub(0, 0, "", 500);
balancers_[0]->ads_service()->set_cds_ignore();
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
}
using EdsTest = BasicTest;
// TODO(roth): Add tests showing that RPCs fail when EDS data is invalid.
TEST_P(EdsTest, Timeout) {
ResetStub(0, 0, "", 500);
balancers_[0]->ads_service()->set_eds_ignore();
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
}
using LocalityMapTest = BasicTest;
// Tests that the localities in a locality map are picked according to their
// weights.
TEST_P(LocalityMapTest, WeightedRoundRobin) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 5000;
const int kLocalityWeight0 = 2;
const int kLocalityWeight1 = 8;
const int kTotalLocalityWeight = kLocalityWeight0 + kLocalityWeight1;
const double kLocalityWeightRate0 =
static_cast<double>(kLocalityWeight0) / kTotalLocalityWeight;
const double kLocalityWeightRate1 =
static_cast<double>(kLocalityWeight1) / kTotalLocalityWeight;
// ADS response contains 2 localities, each of which contains 1 backend.
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts(0, 1), kLocalityWeight0},
{"locality1", GetBackendPorts(1, 2), kLocalityWeight1},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// Wait for both backends to be ready.
WaitForAllBackends(0, 2);
// Send kNumRpcs RPCs.
CheckRpcSendOk(kNumRpcs);
// The locality picking rates should be roughly equal to the expectation.
const double locality_picked_rate_0 =
static_cast<double>(backends_[0]->backend_service()->request_count()) /
kNumRpcs;
const double locality_picked_rate_1 =
static_cast<double>(backends_[1]->backend_service()->request_count()) /
kNumRpcs;
const double kErrorTolerance = 0.2;
EXPECT_THAT(locality_picked_rate_0,
::testing::AllOf(
::testing::Ge(kLocalityWeightRate0 * (1 - kErrorTolerance)),
::testing::Le(kLocalityWeightRate0 * (1 + kErrorTolerance))));
EXPECT_THAT(locality_picked_rate_1,
::testing::AllOf(
::testing::Ge(kLocalityWeightRate1 * (1 - kErrorTolerance)),
::testing::Le(kLocalityWeightRate1 * (1 + kErrorTolerance))));
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// Tests that the locality map can work properly even when it contains a large
// number of localities.
TEST_P(LocalityMapTest, StressTest) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumLocalities = 100;
// The first ADS response contains kNumLocalities localities, each of which
// contains backend 0.
AdsServiceImpl::ResponseArgs args;
for (size_t i = 0; i < kNumLocalities; ++i) {
grpc::string name = "locality" + std::to_string(i);
AdsServiceImpl::ResponseArgs::Locality locality(name,
{backends_[0]->port()});
args.locality_list.emplace_back(std::move(locality));
}
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// The second ADS response contains 1 locality, which contains backend 1.
args = AdsServiceImpl::ResponseArgs({
{"locality0", GetBackendPorts(1, 2)},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args),
60 * 1000);
// Wait until backend 0 is ready, before which kNumLocalities localities are
// received and handled by the xds policy.
WaitForBackend(0, /*reset_counters=*/false);
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
// Wait until backend 1 is ready, before which kNumLocalities localities are
// removed by the xds policy.
WaitForBackend(1);
// The ADS service got a single request.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
// and sent two responses.
EXPECT_EQ(2U, balancers_[0]->ads_service()->response_count());
}
// Tests that the localities in a locality map are picked correctly after update
// (addition, modification, deletion).
TEST_P(LocalityMapTest, UpdateMap) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 1000;
// The locality weight for the first 3 localities.
const std::vector<int> kLocalityWeights0 = {2, 3, 4};
const double kTotalLocalityWeight0 =
std::accumulate(kLocalityWeights0.begin(), kLocalityWeights0.end(), 0);
std::vector<double> locality_weight_rate_0;
for (int weight : kLocalityWeights0) {
locality_weight_rate_0.push_back(weight / kTotalLocalityWeight0);
}
// Delete the first locality, keep the second locality, change the third
// locality's weight from 4 to 2, and add a new locality with weight 6.
const std::vector<int> kLocalityWeights1 = {3, 2, 6};
const double kTotalLocalityWeight1 =
std::accumulate(kLocalityWeights1.begin(), kLocalityWeights1.end(), 0);
std::vector<double> locality_weight_rate_1 = {
0 /* placeholder for locality 0 */};
for (int weight : kLocalityWeights1) {
locality_weight_rate_1.push_back(weight / kTotalLocalityWeight1);
}
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts(0, 1), 2},
{"locality1", GetBackendPorts(1, 2), 3},
{"locality2", GetBackendPorts(2, 3), 4},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
args = AdsServiceImpl::ResponseArgs({
{"locality1", GetBackendPorts(1, 2), 3},
{"locality2", GetBackendPorts(2, 3), 2},
{"locality3", GetBackendPorts(3, 4), 6},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 5000);
// Wait for the first 3 backends to be ready.
WaitForAllBackends(0, 3);
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
// Send kNumRpcs RPCs.
CheckRpcSendOk(kNumRpcs);
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// The picking rates of the first 3 backends should be roughly equal to the
// expectation.
std::vector<double> locality_picked_rates;
for (size_t i = 0; i < 3; ++i) {
locality_picked_rates.push_back(
static_cast<double>(backends_[i]->backend_service()->request_count()) /
kNumRpcs);
}
const double kErrorTolerance = 0.2;
for (size_t i = 0; i < 3; ++i) {
EXPECT_THAT(
locality_picked_rates[i],
::testing::AllOf(
::testing::Ge(locality_weight_rate_0[i] * (1 - kErrorTolerance)),
::testing::Le(locality_weight_rate_0[i] * (1 + kErrorTolerance))));
}
// Backend 3 hasn't received any request.
EXPECT_EQ(0U, backends_[3]->backend_service()->request_count());
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
// Wait until the locality update has been processed, as signaled by backend 3
// receiving a request.
WaitForBackend(3);
gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
// Send kNumRpcs RPCs.
CheckRpcSendOk(kNumRpcs);
gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
// Backend 0 no longer receives any request.
EXPECT_EQ(0U, backends_[0]->backend_service()->request_count());
// The picking rates of the last 3 backends should be roughly equal to the
// expectation.
locality_picked_rates = {0 /* placeholder for backend 0 */};
for (size_t i = 1; i < 4; ++i) {
locality_picked_rates.push_back(
static_cast<double>(backends_[i]->backend_service()->request_count()) /
kNumRpcs);
}
for (size_t i = 1; i < 4; ++i) {
EXPECT_THAT(
locality_picked_rates[i],
::testing::AllOf(
::testing::Ge(locality_weight_rate_1[i] * (1 - kErrorTolerance)),
::testing::Le(locality_weight_rate_1[i] * (1 + kErrorTolerance))));
}
// The ADS service got a single request.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
// and sent two responses.
EXPECT_EQ(2U, balancers_[0]->ads_service()->response_count());
}
class FailoverTest : public BasicTest {
public:
FailoverTest() { ResetStub(0, 100, ""); }
};
// Localities with the highest priority are used when multiple priority exist.
TEST_P(FailoverTest, ChooseHighestPriority) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
WaitForBackend(3, false);
for (size_t i = 0; i < 3; ++i) {
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// If the higher priority localities are not reachable, failover to the highest
// priority among the rest.
TEST_P(FailoverTest, Failover) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
});
ShutdownBackend(3);
ShutdownBackend(0);
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
WaitForBackend(1, false);
for (size_t i = 0; i < 4; ++i) {
if (i == 1) continue;
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// If a locality with higher priority than the current one becomes ready,
// switch to it.
TEST_P(FailoverTest, SwitchBackToHigherPriority) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 100;
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
});
ShutdownBackend(3);
ShutdownBackend(0);
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
WaitForBackend(1, false);
for (size_t i = 0; i < 4; ++i) {
if (i == 1) continue;
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
StartBackend(0);
WaitForBackend(0);
CheckRpcSendOk(kNumRpcs);
EXPECT_EQ(kNumRpcs, backends_[0]->backend_service()->request_count());
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// The first update only contains unavailable priorities. The second update
// contains available priorities.
TEST_P(FailoverTest, UpdateInitialUnavailable) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 1},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
args = AdsServiceImpl::ResponseArgs({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 1},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 2},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 3},
});
ShutdownBackend(0);
ShutdownBackend(1);
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 1000);
gpr_timespec deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_millis(500, GPR_TIMESPAN));
// Send 0.5 second worth of RPCs.
do {
CheckRpcSendFailure();
} while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
WaitForBackend(2, false);
for (size_t i = 0; i < 4; ++i) {
if (i == 2) continue;
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(2U, balancers_[0]->ads_service()->response_count());
}
// Tests that after the localities' priorities are updated, we still choose the
// highest READY priority with the updated localities.
TEST_P(FailoverTest, UpdatePriority) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 100;
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
args = AdsServiceImpl::ResponseArgs({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 2},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 0},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 1},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 3},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 1000);
WaitForBackend(3, false);
for (size_t i = 0; i < 3; ++i) {
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
WaitForBackend(1);
CheckRpcSendOk(kNumRpcs);
EXPECT_EQ(kNumRpcs, backends_[1]->backend_service()->request_count());
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(2U, balancers_[0]->ads_service()->response_count());
}
using DropTest = BasicTest;
// Tests that RPCs are dropped according to the drop config.
TEST_P(DropTest, Vanilla) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 5000;
const uint32_t kDropPerMillionForLb = 100000;
const uint32_t kDropPerMillionForThrottle = 200000;
const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
const double KDropRateForLbAndThrottle =
kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
// The ADS response contains two drop categories.
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
{kThrottleDropType, kDropPerMillionForThrottle}};
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
WaitForAllBackends();
// Send kNumRpcs RPCs and count the drops.
size_t num_drops = 0;
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(&response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage_);
}
}
// The drop rate should be roughly equal to the expectation.
const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
const double kErrorTolerance = 0.2;
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(
::testing::Ge(KDropRateForLbAndThrottle * (1 - kErrorTolerance)),
::testing::Le(KDropRateForLbAndThrottle * (1 + kErrorTolerance))));
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// Tests that drop config is converted correctly from per hundred.
TEST_P(DropTest, DropPerHundred) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 5000;
const uint32_t kDropPerHundredForLb = 10;
const double kDropRateForLb = kDropPerHundredForLb / 100.0;
// The ADS response contains one drop category.
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, kDropPerHundredForLb}};
args.drop_denominator = FractionalPercent::HUNDRED;
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
WaitForAllBackends();
// Send kNumRpcs RPCs and count the drops.
size_t num_drops = 0;
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(&response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage_);
}
}
// The drop rate should be roughly equal to the expectation.
const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
const double kErrorTolerance = 0.2;
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(::testing::Ge(kDropRateForLb * (1 - kErrorTolerance)),
::testing::Le(kDropRateForLb * (1 + kErrorTolerance))));
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// Tests that drop config is converted correctly from per ten thousand.
TEST_P(DropTest, DropPerTenThousand) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 5000;
const uint32_t kDropPerTenThousandForLb = 1000;
const double kDropRateForLb = kDropPerTenThousandForLb / 10000.0;
// The ADS response contains one drop category.
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, kDropPerTenThousandForLb}};
args.drop_denominator = FractionalPercent::TEN_THOUSAND;
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
WaitForAllBackends();
// Send kNumRpcs RPCs and count the drops.
size_t num_drops = 0;
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(&response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage_);
}
}
// The drop rate should be roughly equal to the expectation.
const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
const double kErrorTolerance = 0.2;
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(::testing::Ge(kDropRateForLb * (1 - kErrorTolerance)),
::testing::Le(kDropRateForLb * (1 + kErrorTolerance))));
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// Tests that drop is working correctly after update.
TEST_P(DropTest, Update) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 1000;
const uint32_t kDropPerMillionForLb = 100000;
const uint32_t kDropPerMillionForThrottle = 200000;
const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
const double KDropRateForLbAndThrottle =
kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
// The first ADS response contains one drop category.
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, kDropPerMillionForLb}};
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// The second ADS response contains two drop categories.
// TODO(juanlishen): Change the ADS response sending to deterministic style
// (e.g., by using condition variable) so that we can shorten the test
// duration.
args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
{kThrottleDropType, kDropPerMillionForThrottle}};
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 10000);
WaitForAllBackends();
// Send kNumRpcs RPCs and count the drops.
size_t num_drops = 0;
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(&response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage_);
}
}
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// The drop rate should be roughly equal to the expectation.
double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
const double kErrorTolerance = 0.3;
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(::testing::Ge(kDropRateForLb * (1 - kErrorTolerance)),
::testing::Le(kDropRateForLb * (1 + kErrorTolerance))));
// Wait until the drop rate increases to the middle of the two configs, which
// implies that the update has been in effect.
const double kDropRateThreshold =
(kDropRateForLb + KDropRateForLbAndThrottle) / 2;
size_t num_rpcs = kNumRpcs;
while (seen_drop_rate < kDropRateThreshold) {
EchoResponse response;
const Status status = SendRpc(&response);
++num_rpcs;
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage_);
}
seen_drop_rate = static_cast<double>(num_drops) / num_rpcs;
}
// Send kNumRpcs RPCs and count the drops.
num_drops = 0;
gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(&response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage_);
}
}
gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
// The new drop rate should be roughly equal to the expectation.
seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(
::testing::Ge(KDropRateForLbAndThrottle * (1 - kErrorTolerance)),
::testing::Le(KDropRateForLbAndThrottle * (1 + kErrorTolerance))));
// The ADS service got a single request,
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
// and sent two responses
EXPECT_EQ(2U, balancers_[0]->ads_service()->response_count());
}
// Tests that all the RPCs are dropped if any drop category drops 100%.
TEST_P(DropTest, DropAll) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 1000;
const uint32_t kDropPerMillionForLb = 100000;
const uint32_t kDropPerMillionForThrottle = 1000000;
// The ADS response contains two drop categories.
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
{kThrottleDropType, kDropPerMillionForThrottle}};
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// Send kNumRpcs RPCs and all of them are dropped.
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(&response);
EXPECT_TRUE(!status.ok() && status.error_message() ==
"Call dropped by load balancing policy");
}
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
using FallbackTest = BasicTest;
// Tests that RPCs are handled by the fallback backends before the serverlist is
// received, but will be handled by the serverlist after it's received.
TEST_P(FallbackTest, Vanilla) {
const int kFallbackTimeoutMs = 200 * grpc_test_slowdown_factor();
const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor();
const size_t kNumBackendsInResolution = backends_.size() / 2;
ResetStub(kFallbackTimeoutMs);
SetNextResolution(GetBackendPorts(0, kNumBackendsInResolution));
SetNextResolutionForLbChannelAllBalancers();
// Send non-empty serverlist only after kServerlistDelayMs.
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts(kNumBackendsInResolution)},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args),
kServerlistDelayMs);
// Wait until all the fallback backends are reachable.
WaitForAllBackends(0 /* start_index */,
kNumBackendsInResolution /* stop_index */);
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
CheckRpcSendOk(kNumBackendsInResolution);
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// Fallback is used: each backend returned by the resolver should have
// gotten one request.
for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
EXPECT_EQ(1U, backends_[i]->backend_service()->request_count());
}
for (size_t i = kNumBackendsInResolution; i < backends_.size(); ++i) {
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
// Wait until the serverlist reception has been processed and all backends
// in the serverlist are reachable.
WaitForAllBackends(kNumBackendsInResolution /* start_index */);
gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
CheckRpcSendOk(backends_.size() - kNumBackendsInResolution);
gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
// Serverlist is used: each backend returned by the balancer should
// have gotten one request.
for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
for (size_t i = kNumBackendsInResolution; i < backends_.size(); ++i) {
EXPECT_EQ(1U, backends_[i]->backend_service()->request_count());
}
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// Tests that RPCs are handled by the updated fallback backends before
// serverlist is received,
TEST_P(FallbackTest, Update) {
const int kFallbackTimeoutMs = 200 * grpc_test_slowdown_factor();
const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor();
const size_t kNumBackendsInResolution = backends_.size() / 3;
const size_t kNumBackendsInResolutionUpdate = backends_.size() / 3;
ResetStub(kFallbackTimeoutMs);
SetNextResolution(GetBackendPorts(0, kNumBackendsInResolution));
SetNextResolutionForLbChannelAllBalancers();
// Send non-empty serverlist only after kServerlistDelayMs.
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts(kNumBackendsInResolution +
kNumBackendsInResolutionUpdate)},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args),
kServerlistDelayMs);
// Wait until all the fallback backends are reachable.
WaitForAllBackends(0 /* start_index */,
kNumBackendsInResolution /* stop_index */);
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
CheckRpcSendOk(kNumBackendsInResolution);
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// Fallback is used: each backend returned by the resolver should have
// gotten one request.
for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
EXPECT_EQ(1U, backends_[i]->backend_service()->request_count());
}
for (size_t i = kNumBackendsInResolution; i < backends_.size(); ++i) {
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
SetNextResolution(GetBackendPorts(
kNumBackendsInResolution,
kNumBackendsInResolution + kNumBackendsInResolutionUpdate));
// Wait until the resolution update has been processed and all the new
// fallback backends are reachable.
WaitForAllBackends(kNumBackendsInResolution /* start_index */,
kNumBackendsInResolution +
kNumBackendsInResolutionUpdate /* stop_index */);
gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
CheckRpcSendOk(kNumBackendsInResolutionUpdate);
gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
// The resolution update is used: each backend in the resolution update should
// have gotten one request.
for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
for (size_t i = kNumBackendsInResolution;
i < kNumBackendsInResolution + kNumBackendsInResolutionUpdate; ++i) {
EXPECT_EQ(1U, backends_[i]->backend_service()->request_count());
}
for (size_t i = kNumBackendsInResolution + kNumBackendsInResolutionUpdate;
i < backends_.size(); ++i) {
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
// Wait until the serverlist reception has been processed and all backends
// in the serverlist are reachable.
WaitForAllBackends(kNumBackendsInResolution +
kNumBackendsInResolutionUpdate /* start_index */);
gpr_log(GPR_INFO, "========= BEFORE THIRD BATCH ==========");
CheckRpcSendOk(backends_.size() - kNumBackendsInResolution -
kNumBackendsInResolutionUpdate);
gpr_log(GPR_INFO, "========= DONE WITH THIRD BATCH ==========");
// Serverlist is used: each backend returned by the balancer should
// have gotten one request.
for (size_t i = 0;
i < kNumBackendsInResolution + kNumBackendsInResolutionUpdate; ++i) {
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
for (size_t i = kNumBackendsInResolution + kNumBackendsInResolutionUpdate;
i < backends_.size(); ++i) {
EXPECT_EQ(1U, backends_[i]->backend_service()->request_count());
}
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// Tests that fallback will kick in immediately if the balancer channel fails.
TEST_P(FallbackTest, FallbackEarlyWhenBalancerChannelFails) {
const int kFallbackTimeoutMs = 10000 * grpc_test_slowdown_factor();
ResetStub(kFallbackTimeoutMs);
// Return an unreachable balancer and one fallback backend.
SetNextResolution({backends_[0]->port()});
SetNextResolutionForLbChannel({g_port_saver->GetPort()});
// Send RPC with deadline less than the fallback timeout and make sure it
// succeeds.
CheckRpcSendOk(/* times */ 1, /* timeout_ms */ 1000,
/* wait_for_ready */ false);
}
// Tests that fallback will kick in immediately if the balancer call fails.
TEST_P(FallbackTest, FallbackEarlyWhenBalancerCallFails) {
const int kFallbackTimeoutMs = 10000 * grpc_test_slowdown_factor();
ResetStub(kFallbackTimeoutMs);
// Return one balancer and one fallback backend.
SetNextResolution({backends_[0]->port()});
SetNextResolutionForLbChannelAllBalancers();
// Balancer drops call without sending a serverlist.
balancers_[0]->ads_service()->NotifyDoneWithAdsCall();
// Send RPC with deadline less than the fallback timeout and make sure it
// succeeds.
CheckRpcSendOk(/* times */ 1, /* timeout_ms */ 1000,
/* wait_for_ready */ false);
}
// Tests that fallback mode is entered if balancer response is received but the
// backends can't be reached.
TEST_P(FallbackTest, FallbackIfResponseReceivedButChildNotReady) {
const int kFallbackTimeoutMs = 500 * grpc_test_slowdown_factor();
ResetStub(kFallbackTimeoutMs);
SetNextResolution({backends_[0]->port()});
SetNextResolutionForLbChannelAllBalancers();
// Send a serverlist that only contains an unreachable backend before fallback
// timeout.
AdsServiceImpl::ResponseArgs args({
{"locality0", {g_port_saver->GetPort()}},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// Because no child policy is ready before fallback timeout, we enter fallback
// mode.
WaitForBackend(0);
}
// Tests that fallback mode is exited if the balancer tells the client to drop
// all the calls.
TEST_P(FallbackTest, FallbackModeIsExitedWhenBalancerSaysToDropAllCalls) {
// Return an unreachable balancer and one fallback backend.
SetNextResolution({backends_[0]->port()});
SetNextResolutionForLbChannel({g_port_saver->GetPort()});
// Enter fallback mode because the LB channel fails to connect.
WaitForBackend(0);
// Return a new balancer that sends a response to drop all calls.
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, 1000000}};
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
SetNextResolutionForLbChannelAllBalancers();
// Send RPCs until failure.
gpr_timespec deadline = gpr_time_add(
gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(5000, GPR_TIMESPAN));
do {
auto status = SendRpc();
if (!status.ok()) break;
} while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
CheckRpcSendFailure();
}
// Tests that fallback mode is exited if the child policy becomes ready.
TEST_P(FallbackTest, FallbackModeIsExitedAfterChildRready) {
// Return an unreachable balancer and one fallback backend.
SetNextResolution({backends_[0]->port()});
SetNextResolutionForLbChannel({g_port_saver->GetPort()});
// Enter fallback mode because the LB channel fails to connect.
WaitForBackend(0);
// Return a new balancer that sends a dead backend.
ShutdownBackend(1);
AdsServiceImpl::ResponseArgs args({
{"locality0", {backends_[1]->port()}},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
SetNextResolutionForLbChannelAllBalancers();
// The state (TRANSIENT_FAILURE) update from the child policy will be ignored
// because we are still in fallback mode.
gpr_timespec deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_millis(500, GPR_TIMESPAN));
// Send 0.5 second worth of RPCs.
do {
CheckRpcSendOk();
} while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
// After the backend is restarted, the child policy will eventually be READY,
// and we will exit fallback mode.
StartBackend(1);
WaitForBackend(1);
// We have exited fallback mode, so calls will go to the child policy
// exclusively.
CheckRpcSendOk(100);
EXPECT_EQ(0U, backends_[0]->backend_service()->request_count());
EXPECT_EQ(100U, backends_[1]->backend_service()->request_count());
}
class BalancerUpdateTest : public XdsEnd2endTest {
public:
BalancerUpdateTest() : XdsEnd2endTest(4, 3) {}
};
// Tests that the old LB call is still used after the balancer address update as
// long as that call is still alive.
TEST_P(BalancerUpdateTest, UpdateBalancersButKeepUsingOriginalBalancer) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::ResponseArgs args({
{"locality0", {backends_[0]->port()}},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
args = AdsServiceImpl::ResponseArgs({
{"locality0", {backends_[1]->port()}},
});
ScheduleResponseForBalancer(1, AdsServiceImpl::BuildResponse(args), 0);
// Wait until the first backend is ready.
WaitForBackend(0);
// Send 10 requests.
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
CheckRpcSendOk(10);
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// All 10 requests should have gone to the first backend.
EXPECT_EQ(10U, backends_[0]->backend_service()->request_count());
// The ADS service of balancer 0 got a single request, and sent a single
// response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
EXPECT_EQ(0U, balancers_[1]->ads_service()->request_count());
EXPECT_EQ(0U, balancers_[1]->ads_service()->response_count());
EXPECT_EQ(0U, balancers_[2]->ads_service()->request_count());
EXPECT_EQ(0U, balancers_[2]->ads_service()->response_count());
gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
SetNextResolutionForLbChannel({balancers_[1]->port()});
gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
gpr_timespec deadline = gpr_time_add(
gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(10000, GPR_TIMESPAN));
// Send 10 seconds worth of RPCs
do {
CheckRpcSendOk();
} while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
// The current LB call is still working, so xds continued using it to the
// first balancer, which doesn't assign the second backend.
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
EXPECT_EQ(0U, balancers_[1]->ads_service()->request_count());
EXPECT_EQ(0U, balancers_[1]->ads_service()->response_count());
EXPECT_EQ(0U, balancers_[2]->ads_service()->request_count());
EXPECT_EQ(0U, balancers_[2]->ads_service()->response_count());
}
// Tests that the old LB call is still used after multiple balancer address
// updates as long as that call is still alive. Send an update with the same set
// of LBs as the one in SetUp() in order to verify that the LB channel inside
// xds keeps the initial connection (which by definition is also present in the
// update).
TEST_P(BalancerUpdateTest, Repeated) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::ResponseArgs args({
{"locality0", {backends_[0]->port()}},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
args = AdsServiceImpl::ResponseArgs({
{"locality0", {backends_[1]->port()}},
});
ScheduleResponseForBalancer(1, AdsServiceImpl::BuildResponse(args), 0);
// Wait until the first backend is ready.
WaitForBackend(0);
// Send 10 requests.
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
CheckRpcSendOk(10);
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// All 10 requests should have gone to the first backend.
EXPECT_EQ(10U, backends_[0]->backend_service()->request_count());
// The ADS service of balancer 0 got a single request, and sent a single
// response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
EXPECT_EQ(0U, balancers_[1]->ads_service()->request_count());
EXPECT_EQ(0U, balancers_[1]->ads_service()->response_count());
EXPECT_EQ(0U, balancers_[2]->ads_service()->request_count());
EXPECT_EQ(0U, balancers_[2]->ads_service()->response_count());
std::vector<int> ports;
ports.emplace_back(balancers_[0]->port());
ports.emplace_back(balancers_[1]->port());
ports.emplace_back(balancers_[2]->port());
gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
SetNextResolutionForLbChannel(ports);
gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
gpr_timespec deadline = gpr_time_add(
gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(10000, GPR_TIMESPAN));
// Send 10 seconds worth of RPCs
do {
CheckRpcSendOk();
} while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
// xds continued using the original LB call to the first balancer, which
// doesn't assign the second backend.
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
ports.clear();
ports.emplace_back(balancers_[0]->port());
ports.emplace_back(balancers_[1]->port());
gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 2 ==========");
SetNextResolutionForLbChannel(ports);
gpr_log(GPR_INFO, "========= UPDATE 2 DONE ==========");
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_millis(10000, GPR_TIMESPAN));
// Send 10 seconds worth of RPCs
do {
CheckRpcSendOk();
} while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
// xds continued using the original LB call to the first balancer, which
// doesn't assign the second backend.
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
}
// Tests that if the balancer is down, the RPCs will still be sent to the
// backends according to the last balancer response, until a new balancer is
// reachable.
TEST_P(BalancerUpdateTest, DeadUpdate) {
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()});
AdsServiceImpl::ResponseArgs args({
{"locality0", {backends_[0]->port()}},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
args = AdsServiceImpl::ResponseArgs({
{"locality0", {backends_[1]->port()}},
});
ScheduleResponseForBalancer(1, AdsServiceImpl::BuildResponse(args), 0);
// Start servers and send 10 RPCs per server.
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
CheckRpcSendOk(10);
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// All 10 requests should have gone to the first backend.
EXPECT_EQ(10U, backends_[0]->backend_service()->request_count());
// Kill balancer 0
gpr_log(GPR_INFO, "********** ABOUT TO KILL BALANCER 0 *************");
balancers_[0]->Shutdown();
gpr_log(GPR_INFO, "********** KILLED BALANCER 0 *************");
// This is serviced by the existing child policy.
gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
CheckRpcSendOk(10);
gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
// All 10 requests should again have gone to the first backend.
EXPECT_EQ(20U, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
// The ADS service of balancer 0 got a single request, and sent a single
// response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
EXPECT_EQ(0U, balancers_[1]->ads_service()->request_count());
EXPECT_EQ(0U, balancers_[1]->ads_service()->response_count());
EXPECT_EQ(0U, balancers_[2]->ads_service()->request_count());
EXPECT_EQ(0U, balancers_[2]->ads_service()->response_count());
gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
SetNextResolutionForLbChannel({balancers_[1]->port()});
gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
// Wait until update has been processed, as signaled by the second backend
// receiving a request. In the meantime, the client continues to be serviced
// (by the first backend) without interruption.
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
WaitForBackend(1);
// This is serviced by the updated RR policy
backends_[1]->backend_service()->ResetCounters();
gpr_log(GPR_INFO, "========= BEFORE THIRD BATCH ==========");
CheckRpcSendOk(10);
gpr_log(GPR_INFO, "========= DONE WITH THIRD BATCH ==========");
// All 10 requests should have gone to the second backend.
EXPECT_EQ(10U, backends_[1]->backend_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
// The second balancer, published as part of the first update, may end up
// getting two requests (that is, 1 <= #req <= 2) if the LB call retry timer
// firing races with the arrival of the update containing the second
// balancer.
EXPECT_GE(balancers_[1]->ads_service()->request_count(), 1U);
EXPECT_GE(balancers_[1]->ads_service()->response_count(), 1U);
EXPECT_LE(balancers_[1]->ads_service()->request_count(), 2U);
EXPECT_LE(balancers_[1]->ads_service()->response_count(), 2U);
EXPECT_EQ(0U, balancers_[2]->ads_service()->request_count());
EXPECT_EQ(0U, balancers_[2]->ads_service()->response_count());
}
// The re-resolution tests are deferred because they rely on the fallback mode,
// which hasn't been supported.
// TODO(juanlishen): Add TEST_P(BalancerUpdateTest, ReresolveDeadBackend).
// TODO(juanlishen): Add TEST_P(UpdatesWithClientLoadReportingTest,
// ReresolveDeadBalancer)
class ClientLoadReportingTest : public XdsEnd2endTest {
public:
ClientLoadReportingTest() : XdsEnd2endTest(4, 1, 3) {}
};
// Tests that the load report received at the balancer is correct.
TEST_P(ClientLoadReportingTest, Vanilla) {
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()});
const size_t kNumRpcsPerAddress = 100;
// TODO(juanlishen): Partition the backends after multiple localities is
// tested.
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts()},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// Wait until all backends are ready.
int num_ok = 0;
int num_failure = 0;
int num_drops = 0;
std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
// Send kNumRpcsPerAddress RPCs per server.
CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
// Each backend should have gotten 100 requests.
for (size_t i = 0; i < backends_.size(); ++i) {
EXPECT_EQ(kNumRpcsPerAddress,
backends_[i]->backend_service()->request_count());
}
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
// The LRS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->lrs_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->lrs_service()->response_count());
// The load report received at the balancer should be correct.
ClientStats* client_stats = balancers_[0]->lrs_service()->WaitForLoadReport();
EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_ok,
client_stats->total_successful_requests());
EXPECT_EQ(0U, client_stats->total_requests_in_progress());
EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_ok,
client_stats->total_issued_requests());
EXPECT_EQ(0U, client_stats->total_error_requests());
EXPECT_EQ(0U, client_stats->total_dropped_requests());
}
// Tests that if the balancer restarts, the client load report contains the
// stats before and after the restart correctly.
TEST_P(ClientLoadReportingTest, BalancerRestart) {
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()});
const size_t kNumBackendsFirstPass = backends_.size() / 2;
const size_t kNumBackendsSecondPass =
backends_.size() - kNumBackendsFirstPass;
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts(0, kNumBackendsFirstPass)},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// Wait until all backends returned by the balancer are ready.
int num_ok = 0;
int num_failure = 0;
int num_drops = 0;
std::tie(num_ok, num_failure, num_drops) =
WaitForAllBackends(/* start_index */ 0,
/* stop_index */ kNumBackendsFirstPass);
ClientStats* client_stats = balancers_[0]->lrs_service()->WaitForLoadReport();
EXPECT_EQ(static_cast<size_t>(num_ok),
client_stats->total_successful_requests());
EXPECT_EQ(0U, client_stats->total_requests_in_progress());
EXPECT_EQ(0U, client_stats->total_error_requests());
EXPECT_EQ(0U, client_stats->total_dropped_requests());
// Shut down the balancer.
balancers_[0]->Shutdown();
// We should continue using the last EDS response we received from the
// balancer before it was shut down.
// Note: We need to use WaitForAllBackends() here instead of just
// CheckRpcSendOk(kNumBackendsFirstPass), because when the balancer
// shuts down, the XdsClient will generate an error to the
// ServiceConfigWatcher, which will cause the xds resolver to send a
// no-op update to the LB policy. When this update gets down to the
// round_robin child policy for the locality, it will generate a new
// subchannel list, which resets the start index randomly. So we need
// to be a little more permissive here to avoid spurious failures.
ResetBackendCounters();
int num_started = std::get<0>(WaitForAllBackends(
/* start_index */ 0, /* stop_index */ kNumBackendsFirstPass));
// Now restart the balancer, this time pointing to the new backends.
balancers_[0]->Start(server_host_);
args = AdsServiceImpl::ResponseArgs({
{"locality0", GetBackendPorts(kNumBackendsFirstPass)},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// Wait for queries to start going to one of the new backends.
// This tells us that we're now using the new serverlist.
std::tie(num_ok, num_failure, num_drops) =
WaitForAllBackends(/* start_index */ kNumBackendsFirstPass);
num_started += num_ok + num_failure + num_drops;
// Send one RPC per backend.
CheckRpcSendOk(kNumBackendsSecondPass);
num_started += kNumBackendsSecondPass;
// Check client stats.
client_stats = balancers_[0]->lrs_service()->WaitForLoadReport();
EXPECT_EQ(num_started, client_stats->total_successful_requests());
EXPECT_EQ(0U, client_stats->total_requests_in_progress());
EXPECT_EQ(0U, client_stats->total_error_requests());
EXPECT_EQ(0U, client_stats->total_dropped_requests());
}
class ClientLoadReportingWithDropTest : public XdsEnd2endTest {
public:
ClientLoadReportingWithDropTest() : XdsEnd2endTest(4, 1, 20) {}
};
// Tests that the drop stats are correctly reported by client load reporting.
TEST_P(ClientLoadReportingWithDropTest, Vanilla) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 3000;
const uint32_t kDropPerMillionForLb = 100000;
const uint32_t kDropPerMillionForThrottle = 200000;
const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
const double KDropRateForLbAndThrottle =
kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
// The ADS response contains two drop categories.
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
{kThrottleDropType, kDropPerMillionForThrottle}};
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
int num_ok = 0;
int num_failure = 0;
int num_drops = 0;
std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
const size_t num_warmup = num_ok + num_failure + num_drops;
// Send kNumRpcs RPCs and count the drops.
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(&response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage_);
}
}
// The drop rate should be roughly equal to the expectation.
const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
const double kErrorTolerance = 0.2;
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(
::testing::Ge(KDropRateForLbAndThrottle * (1 - kErrorTolerance)),
::testing::Le(KDropRateForLbAndThrottle * (1 + kErrorTolerance))));
// Check client stats.
ClientStats* client_stats = balancers_[0]->lrs_service()->WaitForLoadReport();
EXPECT_EQ(num_drops, client_stats->total_dropped_requests());
const size_t total_rpc = num_warmup + kNumRpcs;
EXPECT_THAT(
client_stats->dropped_requests(kLbDropType),
::testing::AllOf(
::testing::Ge(total_rpc * kDropRateForLb * (1 - kErrorTolerance)),
::testing::Le(total_rpc * kDropRateForLb * (1 + kErrorTolerance))));
EXPECT_THAT(client_stats->dropped_requests(kThrottleDropType),
::testing::AllOf(
::testing::Ge(total_rpc * (1 - kDropRateForLb) *
kDropRateForThrottle * (1 - kErrorTolerance)),
::testing::Le(total_rpc * (1 - kDropRateForLb) *
kDropRateForThrottle * (1 + kErrorTolerance))));
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
grpc::string TestTypeName(const ::testing::TestParamInfo<TestType>& info) {
return info.param.AsString();
}
INSTANTIATE_TEST_SUITE_P(XdsTest, BasicTest,
::testing::Values(TestType(false, true),
TestType(false, false),
TestType(true, false),
TestType(true, true)),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(XdsTest, SecureNamingTest,
::testing::Values(TestType(false, true),
TestType(false, false),
TestType(true, false),
TestType(true, true)),
&TestTypeName);
// LDS depends on XdsResolver.
INSTANTIATE_TEST_SUITE_P(XdsTest, LdsTest,
::testing::Values(TestType(true, false),
TestType(true, true)),
&TestTypeName);
// RDS depends on XdsResolver.
INSTANTIATE_TEST_SUITE_P(XdsTest, RdsTest,
::testing::Values(TestType(true, false),
TestType(true, true)),
&TestTypeName);
// CDS depends on XdsResolver.
INSTANTIATE_TEST_SUITE_P(XdsTest, CdsTest,
::testing::Values(TestType(true, false),
TestType(true, true)),
&TestTypeName);
// EDS could be tested with or without XdsResolver, but the tests would
// be the same either way, so we test it only with XdsResolver.
INSTANTIATE_TEST_SUITE_P(XdsTest, EdsTest,
::testing::Values(TestType(true, false),
TestType(true, true)),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(XdsTest, LocalityMapTest,
::testing::Values(TestType(false, true),
TestType(false, false),
TestType(true, false),
TestType(true, true)),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(XdsTest, FailoverTest,
::testing::Values(TestType(false, true),
TestType(false, false),
TestType(true, false),
TestType(true, true)),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(XdsTest, DropTest,
::testing::Values(TestType(false, true),
TestType(false, false),
TestType(true, false),
TestType(true, true)),
&TestTypeName);
// Fallback does not work with xds resolver.
INSTANTIATE_TEST_SUITE_P(XdsTest, FallbackTest,
::testing::Values(TestType(false, true),
TestType(false, false)),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(XdsTest, BalancerUpdateTest,
::testing::Values(TestType(false, true),
TestType(false, false),
TestType(true, true)),
&TestTypeName);
// Load reporting tests are not run with load reporting disabled.
INSTANTIATE_TEST_SUITE_P(XdsTest, ClientLoadReportingTest,
::testing::Values(TestType(false, true),
TestType(true, true)),
&TestTypeName);
// Load reporting tests are not run with load reporting disabled.
INSTANTIATE_TEST_SUITE_P(XdsTest, ClientLoadReportingWithDropTest,
::testing::Values(TestType(false, true),
TestType(true, true)),
&TestTypeName);
} // namespace
} // namespace testing
} // namespace grpc
int main(int argc, char** argv) {
grpc::testing::TestEnvironment env(argc, argv);
::testing::InitGoogleTest(&argc, argv);
grpc::testing::WriteBootstrapFiles();
grpc::testing::g_port_saver = new grpc::testing::PortSaver();
const auto result = RUN_ALL_TESTS();
return result;
}
remove unused "using" declaration
/*
*
* Copyright 2017 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <memory>
#include <mutex>
#include <numeric>
#include <set>
#include <sstream>
#include <thread>
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/time.h>
#include <grpcpp/channel.h>
#include <grpcpp/client_context.h>
#include <grpcpp/create_channel.h>
#include <grpcpp/server.h>
#include <grpcpp/server_builder.h>
#include "src/core/ext/filters/client_channel/backup_poller.h"
#include "src/core/ext/filters/client_channel/parse_address.h"
#include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
#include "src/core/ext/filters/client_channel/server_address.h"
#include "src/core/ext/filters/client_channel/xds/xds_api.h"
#include "src/core/lib/gpr/env.h"
#include "src/core/lib/gpr/tmpfile.h"
#include "src/core/lib/gprpp/map.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/iomgr/sockaddr.h"
#include "src/core/lib/security/credentials/fake/fake_credentials.h"
#include "src/cpp/client/secure_credentials.h"
#include "src/cpp/server/secure_server_credentials.h"
#include "test/core/util/port.h"
#include "test/core/util/test_config.h"
#include "test/cpp/end2end/test_service_impl.h"
#include "src/proto/grpc/testing/echo.grpc.pb.h"
#include "src/proto/grpc/testing/xds/ads_for_test.grpc.pb.h"
#include "src/proto/grpc/testing/xds/cds_for_test.grpc.pb.h"
#include "src/proto/grpc/testing/xds/eds_for_test.grpc.pb.h"
#include "src/proto/grpc/testing/xds/lds_rds_for_test.grpc.pb.h"
#include "src/proto/grpc/testing/xds/lrs_for_test.grpc.pb.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
// TODO(dgq): Other scenarios in need of testing:
// - Send a serverlist with faulty ip:port addresses (port > 2^16, etc).
// - Test reception of invalid serverlist
// - Test against a non-LB server.
// - Random LB server closing the stream unexpectedly.
//
// Findings from end to end testing to be covered here:
// - Handling of LB servers restart, including reconnection after backing-off
// retries.
// - Destruction of load balanced channel (and therefore of xds instance)
// while:
// 1) the internal LB call is still active. This should work by virtue
// of the weak reference the LB call holds. The call should be terminated as
// part of the xds shutdown process.
// 2) the retry timer is active. Again, the weak reference it holds should
// prevent a premature call to \a glb_destroy.
namespace grpc {
namespace testing {
namespace {
using std::chrono::system_clock;
using ::envoy::api::v2::Cluster;
using ::envoy::api::v2::ClusterLoadAssignment;
using ::envoy::api::v2::DiscoveryRequest;
using ::envoy::api::v2::DiscoveryResponse;
using ::envoy::api::v2::FractionalPercent;
using ::envoy::api::v2::HttpConnectionManager;
using ::envoy::api::v2::Listener;
using ::envoy::api::v2::RouteConfiguration;
using ::envoy::service::discovery::v2::AggregatedDiscoveryService;
using ::envoy::service::load_stats::v2::ClusterStats;
using ::envoy::service::load_stats::v2::LoadReportingService;
using ::envoy::service::load_stats::v2::LoadStatsRequest;
using ::envoy::service::load_stats::v2::LoadStatsResponse;
using ::envoy::service::load_stats::v2::UpstreamLocalityStats;
constexpr char kLdsTypeUrl[] = "type.googleapis.com/envoy.api.v2.Listener";
constexpr char kRdsTypeUrl[] =
"type.googleapis.com/envoy.api.v2.RouteConfiguration";
constexpr char kCdsTypeUrl[] = "type.googleapis.com/envoy.api.v2.Cluster";
constexpr char kEdsTypeUrl[] =
"type.googleapis.com/envoy.api.v2.ClusterLoadAssignment";
constexpr char kDefaultLocalityRegion[] = "xds_default_locality_region";
constexpr char kDefaultLocalityZone[] = "xds_default_locality_zone";
constexpr char kLbDropType[] = "lb";
constexpr char kThrottleDropType[] = "throttle";
constexpr int kDefaultLocalityWeight = 3;
constexpr int kDefaultLocalityPriority = 0;
constexpr char kBootstrapFile[] =
"{\n"
" \"xds_servers\": [\n"
" {\n"
" \"server_uri\": \"fake:///lb\",\n"
" \"channel_creds\": [\n"
" {\n"
" \"type\": \"fake\"\n"
" }\n"
" ]\n"
" }\n"
" ],\n"
" \"node\": {\n"
" \"id\": \"xds_end2end_test\",\n"
" \"cluster\": \"test\",\n"
" \"metadata\": {\n"
" \"foo\": \"bar\"\n"
" },\n"
" \"locality\": {\n"
" \"region\": \"corp\",\n"
" \"zone\": \"svl\",\n"
" \"subzone\": \"mp3\"\n"
" }\n"
" }\n"
"}\n";
constexpr char kBootstrapFileBad[] =
"{\n"
" \"xds_servers\": [\n"
" {\n"
" \"server_uri\": \"fake:///wrong_lb\",\n"
" \"channel_creds\": [\n"
" {\n"
" \"type\": \"fake\"\n"
" }\n"
" ]\n"
" }\n"
" ],\n"
" \"node\": {\n"
" }\n"
"}\n";
char* g_bootstrap_file;
char* g_bootstrap_file_bad;
void WriteBootstrapFiles() {
char* bootstrap_file;
FILE* out = gpr_tmpfile("xds_bootstrap", &bootstrap_file);
fputs(kBootstrapFile, out);
fclose(out);
g_bootstrap_file = bootstrap_file;
out = gpr_tmpfile("xds_bootstrap_bad", &bootstrap_file);
fputs(kBootstrapFileBad, out);
fclose(out);
g_bootstrap_file_bad = bootstrap_file;
}
// Helper class to minimize the number of unique ports we use for this test.
class PortSaver {
public:
int GetPort() {
if (idx_ >= ports_.size()) {
ports_.push_back(grpc_pick_unused_port_or_die());
}
return ports_[idx_++];
}
void Reset() { idx_ = 0; }
private:
std::vector<int> ports_;
size_t idx_ = 0;
};
PortSaver* g_port_saver = nullptr;
template <typename ServiceType>
class CountedService : public ServiceType {
public:
size_t request_count() {
grpc_core::MutexLock lock(&mu_);
return request_count_;
}
size_t response_count() {
grpc_core::MutexLock lock(&mu_);
return response_count_;
}
void IncreaseResponseCount() {
grpc_core::MutexLock lock(&mu_);
++response_count_;
}
void IncreaseRequestCount() {
grpc_core::MutexLock lock(&mu_);
++request_count_;
}
void ResetCounters() {
grpc_core::MutexLock lock(&mu_);
request_count_ = 0;
response_count_ = 0;
}
protected:
grpc_core::Mutex mu_;
private:
size_t request_count_ = 0;
size_t response_count_ = 0;
};
using BackendService = CountedService<TestServiceImpl>;
using AdsService = CountedService<AggregatedDiscoveryService::Service>;
using LrsService = CountedService<LoadReportingService::Service>;
const char g_kCallCredsMdKey[] = "Balancer should not ...";
const char g_kCallCredsMdValue[] = "... receive me";
class BackendServiceImpl : public BackendService {
public:
BackendServiceImpl() {}
Status Echo(ServerContext* context, const EchoRequest* request,
EchoResponse* response) override {
// Backend should receive the call credentials metadata.
auto call_credentials_entry =
context->client_metadata().find(g_kCallCredsMdKey);
EXPECT_NE(call_credentials_entry, context->client_metadata().end());
if (call_credentials_entry != context->client_metadata().end()) {
EXPECT_EQ(call_credentials_entry->second, g_kCallCredsMdValue);
}
IncreaseRequestCount();
const auto status = TestServiceImpl::Echo(context, request, response);
IncreaseResponseCount();
AddClient(context->peer());
return status;
}
void Start() {}
void Shutdown() {}
std::set<grpc::string> clients() {
grpc_core::MutexLock lock(&clients_mu_);
return clients_;
}
private:
void AddClient(const grpc::string& client) {
grpc_core::MutexLock lock(&clients_mu_);
clients_.insert(client);
}
grpc_core::Mutex mu_;
grpc_core::Mutex clients_mu_;
std::set<grpc::string> clients_;
};
class ClientStats {
public:
struct LocalityStats {
// Converts from proto message class.
LocalityStats(const UpstreamLocalityStats& upstream_locality_stats)
: total_successful_requests(
upstream_locality_stats.total_successful_requests()),
total_requests_in_progress(
upstream_locality_stats.total_requests_in_progress()),
total_error_requests(upstream_locality_stats.total_error_requests()),
total_issued_requests(
upstream_locality_stats.total_issued_requests()) {}
uint64_t total_successful_requests;
uint64_t total_requests_in_progress;
uint64_t total_error_requests;
uint64_t total_issued_requests;
};
// Converts from proto message class.
ClientStats(const ClusterStats& cluster_stats)
: total_dropped_requests_(cluster_stats.total_dropped_requests()) {
for (const auto& input_locality_stats :
cluster_stats.upstream_locality_stats()) {
locality_stats_.emplace(input_locality_stats.locality().sub_zone(),
LocalityStats(input_locality_stats));
}
for (const auto& input_dropped_requests :
cluster_stats.dropped_requests()) {
dropped_requests_.emplace(input_dropped_requests.category(),
input_dropped_requests.dropped_count());
}
}
uint64_t total_successful_requests() const {
uint64_t sum = 0;
for (auto& p : locality_stats_) {
sum += p.second.total_successful_requests;
}
return sum;
}
uint64_t total_requests_in_progress() const {
uint64_t sum = 0;
for (auto& p : locality_stats_) {
sum += p.second.total_requests_in_progress;
}
return sum;
}
uint64_t total_error_requests() const {
uint64_t sum = 0;
for (auto& p : locality_stats_) {
sum += p.second.total_error_requests;
}
return sum;
}
uint64_t total_issued_requests() const {
uint64_t sum = 0;
for (auto& p : locality_stats_) {
sum += p.second.total_issued_requests;
}
return sum;
}
uint64_t total_dropped_requests() const { return total_dropped_requests_; }
uint64_t dropped_requests(const grpc::string& category) const {
auto iter = dropped_requests_.find(category);
GPR_ASSERT(iter != dropped_requests_.end());
return iter->second;
}
private:
std::map<grpc::string, LocalityStats> locality_stats_;
uint64_t total_dropped_requests_;
std::map<grpc::string, uint64_t> dropped_requests_;
};
// TODO(roth): Change this service to a real fake.
class AdsServiceImpl : public AdsService {
public:
enum ResponseState {
NOT_SENT,
SENT,
ACKED,
NACKED,
};
struct ResponseArgs {
struct Locality {
Locality(const grpc::string& sub_zone, std::vector<int> ports,
int lb_weight = kDefaultLocalityWeight,
int priority = kDefaultLocalityPriority,
std::vector<envoy::api::v2::HealthStatus> health_statuses = {})
: sub_zone(std::move(sub_zone)),
ports(std::move(ports)),
lb_weight(lb_weight),
priority(priority),
health_statuses(std::move(health_statuses)) {}
const grpc::string sub_zone;
std::vector<int> ports;
int lb_weight;
int priority;
std::vector<envoy::api::v2::HealthStatus> health_statuses;
};
ResponseArgs() = default;
explicit ResponseArgs(std::vector<Locality> locality_list)
: locality_list(std::move(locality_list)) {}
std::vector<Locality> locality_list;
std::map<grpc::string, uint32_t> drop_categories;
FractionalPercent::DenominatorType drop_denominator =
FractionalPercent::MILLION;
};
using Stream = ServerReaderWriter<DiscoveryResponse, DiscoveryRequest>;
using ResponseDelayPair = std::pair<DiscoveryResponse, int>;
AdsServiceImpl(bool enable_load_reporting) {
// Construct RDS response data.
default_route_config_.set_name("application_target_name");
auto* virtual_host = default_route_config_.add_virtual_hosts();
virtual_host->add_domains("*");
auto* route = virtual_host->add_routes();
route->mutable_match()->set_prefix("");
route->mutable_route()->set_cluster("application_target_name");
rds_response_data_ = {
{"application_target_name", default_route_config_},
};
// Construct LDS response data (with inlined RDS result).
default_listener_ = BuildListener(default_route_config_);
lds_response_data_ = {
{"application_target_name", default_listener_},
};
// Construct CDS response data.
default_cluster_.set_name("application_target_name");
default_cluster_.set_type(envoy::api::v2::Cluster::EDS);
default_cluster_.mutable_eds_cluster_config()
->mutable_eds_config()
->mutable_ads();
default_cluster_.set_lb_policy(envoy::api::v2::Cluster::ROUND_ROBIN);
if (enable_load_reporting) {
default_cluster_.mutable_lrs_server()->mutable_self();
}
cds_response_data_ = {
{"application_target_name", default_cluster_},
};
}
void HandleLdsRequest(DiscoveryRequest* request, Stream* stream) {
gpr_log(GPR_INFO, "ADS[%p]: received LDS request '%s'", this,
request->DebugString().c_str());
const std::string version_str = "version_1";
const std::string nonce_str = "nonce_1";
grpc_core::MutexLock lock(&ads_mu_);
if (lds_ignore_) return;
if (lds_response_state_ == NOT_SENT) {
DiscoveryResponse response;
response.set_type_url(kLdsTypeUrl);
response.set_version_info(version_str);
response.set_nonce(nonce_str);
for (const auto& server_name : request->resource_names()) {
auto iter = lds_response_data_.find(server_name);
if (iter == lds_response_data_.end()) continue;
response.add_resources()->PackFrom(iter->second);
}
stream->Write(response);
lds_response_state_ = SENT;
} else if (lds_response_state_ == SENT) {
GPR_ASSERT(!request->response_nonce().empty());
lds_response_state_ =
request->version_info() == version_str ? ACKED : NACKED;
}
}
void HandleRdsRequest(DiscoveryRequest* request, Stream* stream) {
gpr_log(GPR_INFO, "ADS[%p]: received RDS request '%s'", this,
request->DebugString().c_str());
const std::string version_str = "version_1";
const std::string nonce_str = "nonce_1";
grpc_core::MutexLock lock(&ads_mu_);
if (rds_ignore_) return;
if (rds_response_state_ == NOT_SENT) {
DiscoveryResponse response;
response.set_type_url(kRdsTypeUrl);
response.set_version_info(version_str);
response.set_nonce(nonce_str);
for (const auto& route_config_name : request->resource_names()) {
auto iter = rds_response_data_.find(route_config_name);
if (iter == rds_response_data_.end()) continue;
response.add_resources()->PackFrom(iter->second);
}
stream->Write(response);
rds_response_state_ = SENT;
} else if (rds_response_state_ == SENT) {
GPR_ASSERT(!request->response_nonce().empty());
rds_response_state_ =
request->version_info() == version_str ? ACKED : NACKED;
}
}
void HandleCdsRequest(DiscoveryRequest* request, Stream* stream) {
gpr_log(GPR_INFO, "ADS[%p]: received CDS request '%s'", this,
request->DebugString().c_str());
const std::string version_str = "version_1";
const std::string nonce_str = "nonce_1";
grpc_core::MutexLock lock(&ads_mu_);
if (cds_ignore_) return;
if (cds_response_state_ == NOT_SENT) {
DiscoveryResponse response;
response.set_type_url(kCdsTypeUrl);
response.set_version_info(version_str);
response.set_nonce(nonce_str);
for (const auto& cluster_name : request->resource_names()) {
auto iter = cds_response_data_.find(cluster_name);
if (iter == cds_response_data_.end()) continue;
response.add_resources()->PackFrom(iter->second);
}
stream->Write(response);
cds_response_state_ = SENT;
} else if (cds_response_state_ == SENT) {
GPR_ASSERT(!request->response_nonce().empty());
cds_response_state_ =
request->version_info() == version_str ? ACKED : NACKED;
}
}
void HandleEdsRequest(DiscoveryRequest* request, Stream* stream) {
gpr_log(GPR_INFO, "ADS[%p]: received EDS request '%s'", this,
request->DebugString().c_str());
IncreaseRequestCount();
std::vector<ResponseDelayPair> responses_and_delays;
{
grpc_core::MutexLock lock(&ads_mu_);
if (eds_ignore_) return;
responses_and_delays = eds_responses_and_delays_;
}
// Send response.
for (const auto& p : responses_and_delays) {
const DiscoveryResponse& response = p.first;
const int delay_ms = p.second;
gpr_log(GPR_INFO, "ADS[%p]: sleeping for %d ms...", this, delay_ms);
if (delay_ms > 0) {
gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(delay_ms));
}
gpr_log(GPR_INFO, "ADS[%p]: Woke up! Sending response '%s'", this,
response.DebugString().c_str());
IncreaseResponseCount();
stream->Write(response);
}
}
Status StreamAggregatedResources(ServerContext* context,
Stream* stream) override {
gpr_log(GPR_INFO, "ADS[%p]: StreamAggregatedResources starts", this);
[&]() {
{
grpc_core::MutexLock lock(&ads_mu_);
if (ads_done_) return;
}
// Balancer shouldn't receive the call credentials metadata.
EXPECT_EQ(context->client_metadata().find(g_kCallCredsMdKey),
context->client_metadata().end());
// Keep servicing requests until the EDS response has been sent back.
DiscoveryRequest request;
// TODO(roth): For each supported type, we currently only handle one
// request without replying to any new requests (for ACK/NACK or new
// resource names). It's not causing a big problem now but should be
// fixed.
bool eds_sent = false;
bool seen_first_request = false;
while (!eds_sent || cds_response_state_ == SENT) {
if (!stream->Read(&request)) return;
if (!seen_first_request) {
EXPECT_TRUE(request.has_node());
seen_first_request = true;
}
if (request.type_url() == kLdsTypeUrl) {
HandleLdsRequest(&request, stream);
} else if (request.type_url() == kRdsTypeUrl) {
HandleRdsRequest(&request, stream);
} else if (request.type_url() == kCdsTypeUrl) {
HandleCdsRequest(&request, stream);
} else if (request.type_url() == kEdsTypeUrl) {
HandleEdsRequest(&request, stream);
eds_sent = true;
}
}
// Wait until notified done.
grpc_core::MutexLock lock(&ads_mu_);
ads_cond_.WaitUntil(&ads_mu_, [this] { return ads_done_; });
}();
gpr_log(GPR_INFO, "ADS[%p]: StreamAggregatedResources done", this);
return Status::OK;
}
Listener default_listener() const { return default_listener_; }
RouteConfiguration default_route_config() const {
return default_route_config_;
}
Cluster default_cluster() const { return default_cluster_; }
ResponseState lds_response_state() {
grpc_core::MutexLock lock(&ads_mu_);
return lds_response_state_;
}
ResponseState rds_response_state() {
grpc_core::MutexLock lock(&ads_mu_);
return rds_response_state_;
}
ResponseState cds_response_state() {
grpc_core::MutexLock lock(&ads_mu_);
return cds_response_state_;
}
void SetLdsResponse(
std::map<std::string /*server_name*/, Listener> lds_response_data) {
lds_response_data_ = std::move(lds_response_data);
}
void set_lds_ignore() { lds_ignore_ = true; }
void SetRdsResponse(
std::map<std::string /*route_config_name*/, RouteConfiguration>
rds_response_data) {
rds_response_data_ = std::move(rds_response_data);
}
void set_rds_ignore() { rds_ignore_ = true; }
void SetCdsResponse(
std::map<std::string /*cluster_name*/, Cluster> cds_response_data) {
cds_response_data_ = std::move(cds_response_data);
}
void set_cds_ignore() { cds_ignore_ = true; }
void AddEdsResponse(const DiscoveryResponse& response, int send_after_ms) {
grpc_core::MutexLock lock(&ads_mu_);
eds_responses_and_delays_.push_back(
std::make_pair(response, send_after_ms));
}
void set_eds_ignore() { eds_ignore_ = true; }
void SetLdsToUseDynamicRds() {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
http_connection_manager.mutable_rds()->set_route_config_name(
"application_target_name");
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetLdsResponse({{"application_target_name", std::move(listener)}});
}
static Listener BuildListener(const RouteConfiguration& route_config) {
HttpConnectionManager http_connection_manager;
*(http_connection_manager.mutable_route_config()) = route_config;
Listener listener;
listener.set_name("application_target_name");
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
return listener;
}
void Start() {
grpc_core::MutexLock lock(&ads_mu_);
ads_done_ = false;
eds_responses_and_delays_.clear();
}
void Shutdown() {
{
grpc_core::MutexLock lock(&ads_mu_);
NotifyDoneWithAdsCallLocked();
eds_responses_and_delays_.clear();
}
gpr_log(GPR_INFO, "ADS[%p]: shut down", this);
}
static DiscoveryResponse BuildResponse(const ResponseArgs& args) {
ClusterLoadAssignment assignment;
assignment.set_cluster_name("application_target_name");
for (const auto& locality : args.locality_list) {
auto* endpoints = assignment.add_endpoints();
endpoints->mutable_load_balancing_weight()->set_value(locality.lb_weight);
endpoints->set_priority(locality.priority);
endpoints->mutable_locality()->set_region(kDefaultLocalityRegion);
endpoints->mutable_locality()->set_zone(kDefaultLocalityZone);
endpoints->mutable_locality()->set_sub_zone(locality.sub_zone);
for (size_t i = 0; i < locality.ports.size(); ++i) {
const int& port = locality.ports[i];
auto* lb_endpoints = endpoints->add_lb_endpoints();
if (locality.health_statuses.size() > i &&
locality.health_statuses[i] !=
envoy::api::v2::HealthStatus::UNKNOWN) {
lb_endpoints->set_health_status(locality.health_statuses[i]);
}
auto* endpoint = lb_endpoints->mutable_endpoint();
auto* address = endpoint->mutable_address();
auto* socket_address = address->mutable_socket_address();
socket_address->set_address("127.0.0.1");
socket_address->set_port_value(port);
}
}
if (!args.drop_categories.empty()) {
auto* policy = assignment.mutable_policy();
for (const auto& p : args.drop_categories) {
const grpc::string& name = p.first;
const uint32_t parts_per_million = p.second;
auto* drop_overload = policy->add_drop_overloads();
drop_overload->set_category(name);
auto* drop_percentage = drop_overload->mutable_drop_percentage();
drop_percentage->set_numerator(parts_per_million);
drop_percentage->set_denominator(args.drop_denominator);
}
}
DiscoveryResponse response;
response.set_type_url(kEdsTypeUrl);
response.add_resources()->PackFrom(assignment);
return response;
}
void NotifyDoneWithAdsCall() {
grpc_core::MutexLock lock(&ads_mu_);
NotifyDoneWithAdsCallLocked();
}
void NotifyDoneWithAdsCallLocked() {
if (!ads_done_) {
ads_done_ = true;
ads_cond_.Broadcast();
}
}
private:
grpc_core::CondVar ads_cond_;
// Protect the members below.
grpc_core::Mutex ads_mu_;
bool ads_done_ = false;
// LDS response data.
Listener default_listener_;
std::map<std::string /*server_name*/, Listener> lds_response_data_;
ResponseState lds_response_state_ = NOT_SENT;
bool lds_ignore_ = false;
// RDS response data.
RouteConfiguration default_route_config_;
std::map<std::string /*route_config_name*/, RouteConfiguration>
rds_response_data_;
ResponseState rds_response_state_ = NOT_SENT;
bool rds_ignore_ = false;
// CDS response data.
Cluster default_cluster_;
std::map<std::string /*cluster_name*/, Cluster> cds_response_data_;
ResponseState cds_response_state_ = NOT_SENT;
bool cds_ignore_ = false;
// EDS response data.
std::vector<ResponseDelayPair> eds_responses_and_delays_;
bool eds_ignore_ = false;
};
class LrsServiceImpl : public LrsService {
public:
using Stream = ServerReaderWriter<LoadStatsResponse, LoadStatsRequest>;
explicit LrsServiceImpl(int client_load_reporting_interval_seconds)
: client_load_reporting_interval_seconds_(
client_load_reporting_interval_seconds) {}
Status StreamLoadStats(ServerContext* /*context*/, Stream* stream) override {
gpr_log(GPR_INFO, "LRS[%p]: StreamLoadStats starts", this);
// Read request.
LoadStatsRequest request;
if (stream->Read(&request)) {
if (client_load_reporting_interval_seconds_ > 0) {
IncreaseRequestCount();
// Send response.
LoadStatsResponse response;
auto server_name = request.cluster_stats()[0].cluster_name();
GPR_ASSERT(server_name != "");
response.add_clusters(server_name);
response.mutable_load_reporting_interval()->set_seconds(
client_load_reporting_interval_seconds_);
stream->Write(response);
IncreaseResponseCount();
// Wait for report.
request.Clear();
if (stream->Read(&request)) {
gpr_log(GPR_INFO, "LRS[%p]: received client load report message '%s'",
this, request.DebugString().c_str());
GPR_ASSERT(request.cluster_stats().size() == 1);
const ClusterStats& cluster_stats = request.cluster_stats()[0];
// We need to acquire the lock here in order to prevent the notify_one
// below from firing before its corresponding wait is executed.
grpc_core::MutexLock lock(&load_report_mu_);
GPR_ASSERT(client_stats_ == nullptr);
client_stats_.reset(new ClientStats(cluster_stats));
load_report_ready_ = true;
load_report_cond_.Signal();
}
}
// Wait until notified done.
grpc_core::MutexLock lock(&lrs_mu_);
lrs_cv_.WaitUntil(&lrs_mu_, [this] { return lrs_done; });
}
gpr_log(GPR_INFO, "LRS[%p]: StreamLoadStats done", this);
return Status::OK;
}
void Start() {
lrs_done = false;
load_report_ready_ = false;
client_stats_.reset();
}
void Shutdown() {
{
grpc_core::MutexLock lock(&lrs_mu_);
NotifyDoneWithLrsCallLocked();
}
gpr_log(GPR_INFO, "LRS[%p]: shut down", this);
}
ClientStats* WaitForLoadReport() {
grpc_core::MutexLock lock(&load_report_mu_);
load_report_cond_.WaitUntil(&load_report_mu_,
[this] { return load_report_ready_; });
load_report_ready_ = false;
return client_stats_.get();
}
void NotifyDoneWithLrsCall() {
grpc_core::MutexLock lock(&lrs_mu_);
NotifyDoneWithLrsCallLocked();
}
void NotifyDoneWithLrsCallLocked() {
if (!lrs_done) {
lrs_done = true;
lrs_cv_.Broadcast();
}
}
private:
const int client_load_reporting_interval_seconds_;
grpc_core::CondVar lrs_cv_;
// Protect lrs_done.
grpc_core::Mutex lrs_mu_;
bool lrs_done = false;
grpc_core::CondVar load_report_cond_;
// Protect the members below.
grpc_core::Mutex load_report_mu_;
std::unique_ptr<ClientStats> client_stats_;
bool load_report_ready_ = false;
};
class TestType {
public:
TestType(bool use_xds_resolver, bool enable_load_reporting)
: use_xds_resolver_(use_xds_resolver),
enable_load_reporting_(enable_load_reporting) {}
bool use_xds_resolver() const { return use_xds_resolver_; }
bool enable_load_reporting() const { return enable_load_reporting_; }
grpc::string AsString() const {
grpc::string retval = (use_xds_resolver_ ? "XdsResolver" : "FakeResolver");
if (enable_load_reporting_) retval += "WithLoadReporting";
return retval;
}
private:
const bool use_xds_resolver_;
const bool enable_load_reporting_;
};
class XdsEnd2endTest : public ::testing::TestWithParam<TestType> {
protected:
XdsEnd2endTest(size_t num_backends, size_t num_balancers,
int client_load_reporting_interval_seconds = 100)
: server_host_("localhost"),
num_backends_(num_backends),
num_balancers_(num_balancers),
client_load_reporting_interval_seconds_(
client_load_reporting_interval_seconds) {}
static void SetUpTestCase() {
// Make the backup poller poll very frequently in order to pick up
// updates from all the subchannels's FDs.
GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms, 1);
#if TARGET_OS_IPHONE
// Workaround Apple CFStream bug
gpr_setenv("grpc_cfstream", "0");
#endif
grpc_init();
}
static void TearDownTestCase() { grpc_shutdown(); }
void SetUp() override {
gpr_setenv("GRPC_XDS_BOOTSTRAP", g_bootstrap_file);
g_port_saver->Reset();
response_generator_ =
grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
lb_channel_response_generator_ =
grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
// Start the backends.
for (size_t i = 0; i < num_backends_; ++i) {
backends_.emplace_back(new BackendServerThread);
backends_.back()->Start(server_host_);
}
// Start the load balancers.
for (size_t i = 0; i < num_balancers_; ++i) {
balancers_.emplace_back(
new BalancerServerThread(GetParam().enable_load_reporting()
? client_load_reporting_interval_seconds_
: 0));
balancers_.back()->Start(server_host_);
}
ResetStub();
}
void TearDown() override {
ShutdownAllBackends();
for (auto& balancer : balancers_) balancer->Shutdown();
}
void StartAllBackends() {
for (auto& backend : backends_) backend->Start(server_host_);
}
void StartBackend(size_t index) { backends_[index]->Start(server_host_); }
void ShutdownAllBackends() {
for (auto& backend : backends_) backend->Shutdown();
}
void ShutdownBackend(size_t index) { backends_[index]->Shutdown(); }
void ResetStub(int fallback_timeout = 0, int failover_timeout = 0,
const grpc::string& expected_targets = "",
int xds_resource_does_not_exist_timeout = 0) {
ChannelArguments args;
// TODO(juanlishen): Add setter to ChannelArguments.
if (fallback_timeout > 0) {
args.SetInt(GRPC_ARG_XDS_FALLBACK_TIMEOUT_MS, fallback_timeout);
}
if (failover_timeout > 0) {
args.SetInt(GRPC_ARG_XDS_FAILOVER_TIMEOUT_MS, failover_timeout);
}
if (xds_resource_does_not_exist_timeout > 0) {
args.SetInt(GRPC_ARG_XDS_RESOURCE_DOES_NOT_EXIST_TIMEOUT_MS,
xds_resource_does_not_exist_timeout);
}
// If the parent channel is using the fake resolver, we inject the
// response generator for the parent here, and then SetNextResolution()
// will inject the xds channel's response generator via the parent's
// response generator.
//
// In contrast, if we are using the xds resolver, then the parent
// channel never uses a response generator, and we inject the xds
// channel's response generator here.
args.SetPointer(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
GetParam().use_xds_resolver()
? lb_channel_response_generator_.get()
: response_generator_.get());
if (!expected_targets.empty()) {
args.SetString(GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS, expected_targets);
}
grpc::string scheme =
GetParam().use_xds_resolver() ? "xds-experimental" : "fake";
std::ostringstream uri;
uri << scheme << ":///" << kApplicationTargetName_;
// TODO(dgq): templatize tests to run everything using both secure and
// insecure channel credentials.
grpc_channel_credentials* channel_creds =
grpc_fake_transport_security_credentials_create();
grpc_call_credentials* call_creds = grpc_md_only_test_credentials_create(
g_kCallCredsMdKey, g_kCallCredsMdValue, false);
std::shared_ptr<ChannelCredentials> creds(
new SecureChannelCredentials(grpc_composite_channel_credentials_create(
channel_creds, call_creds, nullptr)));
call_creds->Unref();
channel_creds->Unref();
channel_ = ::grpc::CreateCustomChannel(uri.str(), creds, args);
stub_ = grpc::testing::EchoTestService::NewStub(channel_);
}
void ResetBackendCounters() {
for (auto& backend : backends_) backend->backend_service()->ResetCounters();
}
bool SeenAllBackends(size_t start_index = 0, size_t stop_index = 0) {
if (stop_index == 0) stop_index = backends_.size();
for (size_t i = start_index; i < stop_index; ++i) {
if (backends_[i]->backend_service()->request_count() == 0) return false;
}
return true;
}
void SendRpcAndCount(int* num_total, int* num_ok, int* num_failure,
int* num_drops) {
const Status status = SendRpc();
if (status.ok()) {
++*num_ok;
} else {
if (status.error_message() == "Call dropped by load balancing policy") {
++*num_drops;
} else {
++*num_failure;
}
}
++*num_total;
}
std::tuple<int, int, int> WaitForAllBackends(size_t start_index = 0,
size_t stop_index = 0) {
int num_ok = 0;
int num_failure = 0;
int num_drops = 0;
int num_total = 0;
while (!SeenAllBackends(start_index, stop_index)) {
SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_drops);
}
ResetBackendCounters();
gpr_log(GPR_INFO,
"Performed %d warm up requests against the backends. "
"%d succeeded, %d failed, %d dropped.",
num_total, num_ok, num_failure, num_drops);
return std::make_tuple(num_ok, num_failure, num_drops);
}
void WaitForBackend(size_t backend_idx, bool reset_counters = true) {
gpr_log(GPR_INFO, "========= WAITING FOR BACKEND %lu ==========",
static_cast<unsigned long>(backend_idx));
do {
(void)SendRpc();
} while (backends_[backend_idx]->backend_service()->request_count() == 0);
if (reset_counters) ResetBackendCounters();
gpr_log(GPR_INFO, "========= BACKEND %lu READY ==========",
static_cast<unsigned long>(backend_idx));
}
grpc_core::ServerAddressList CreateAddressListFromPortList(
const std::vector<int>& ports) {
grpc_core::ServerAddressList addresses;
for (int port : ports) {
char* lb_uri_str;
gpr_asprintf(&lb_uri_str, "ipv4:127.0.0.1:%d", port);
grpc_uri* lb_uri = grpc_uri_parse(lb_uri_str, true);
GPR_ASSERT(lb_uri != nullptr);
grpc_resolved_address address;
GPR_ASSERT(grpc_parse_uri(lb_uri, &address));
addresses.emplace_back(address.addr, address.len, nullptr);
grpc_uri_destroy(lb_uri);
gpr_free(lb_uri_str);
}
return addresses;
}
void SetNextResolution(const std::vector<int>& ports,
grpc_core::FakeResolverResponseGenerator*
lb_channel_response_generator = nullptr) {
if (GetParam().use_xds_resolver()) return; // Not used with xds resolver.
grpc_core::ExecCtx exec_ctx;
grpc_core::Resolver::Result result;
result.addresses = CreateAddressListFromPortList(ports);
grpc_error* error = GRPC_ERROR_NONE;
const char* service_config_json =
GetParam().enable_load_reporting()
? kDefaultServiceConfig_
: kDefaultServiceConfigWithoutLoadReporting_;
result.service_config =
grpc_core::ServiceConfig::Create(service_config_json, &error);
GRPC_ERROR_UNREF(error);
grpc_arg arg = grpc_core::FakeResolverResponseGenerator::MakeChannelArg(
lb_channel_response_generator == nullptr
? lb_channel_response_generator_.get()
: lb_channel_response_generator);
result.args = grpc_channel_args_copy_and_add(nullptr, &arg, 1);
response_generator_->SetResponse(std::move(result));
}
void SetNextResolutionForLbChannelAllBalancers(
const char* service_config_json = nullptr,
grpc_core::FakeResolverResponseGenerator* lb_channel_response_generator =
nullptr) {
std::vector<int> ports;
for (size_t i = 0; i < balancers_.size(); ++i) {
ports.emplace_back(balancers_[i]->port());
}
SetNextResolutionForLbChannel(ports, service_config_json,
lb_channel_response_generator);
}
void SetNextResolutionForLbChannel(
const std::vector<int>& ports, const char* service_config_json = nullptr,
grpc_core::FakeResolverResponseGenerator* lb_channel_response_generator =
nullptr) {
grpc_core::ExecCtx exec_ctx;
grpc_core::Resolver::Result result;
result.addresses = CreateAddressListFromPortList(ports);
if (service_config_json != nullptr) {
grpc_error* error = GRPC_ERROR_NONE;
result.service_config =
grpc_core::ServiceConfig::Create(service_config_json, &error);
GRPC_ERROR_UNREF(error);
}
if (lb_channel_response_generator == nullptr) {
lb_channel_response_generator = lb_channel_response_generator_.get();
}
lb_channel_response_generator->SetResponse(std::move(result));
}
void SetNextReresolutionResponse(const std::vector<int>& ports) {
grpc_core::ExecCtx exec_ctx;
grpc_core::Resolver::Result result;
result.addresses = CreateAddressListFromPortList(ports);
response_generator_->SetReresolutionResponse(std::move(result));
}
const std::vector<int> GetBackendPorts(size_t start_index = 0,
size_t stop_index = 0) const {
if (stop_index == 0) stop_index = backends_.size();
std::vector<int> backend_ports;
for (size_t i = start_index; i < stop_index; ++i) {
backend_ports.push_back(backends_[i]->port());
}
return backend_ports;
}
void ScheduleResponseForBalancer(size_t i, const DiscoveryResponse& response,
int delay_ms) {
balancers_[i]->ads_service()->AddEdsResponse(response, delay_ms);
}
Status SendRpc(EchoResponse* response = nullptr, int timeout_ms = 1000,
bool wait_for_ready = false) {
const bool local_response = (response == nullptr);
if (local_response) response = new EchoResponse;
EchoRequest request;
request.set_message(kRequestMessage_);
ClientContext context;
context.set_deadline(grpc_timeout_milliseconds_to_deadline(timeout_ms));
if (wait_for_ready) context.set_wait_for_ready(true);
Status status = stub_->Echo(&context, request, response);
if (local_response) delete response;
return status;
}
void CheckRpcSendOk(const size_t times = 1, const int timeout_ms = 1000,
bool wait_for_ready = false) {
for (size_t i = 0; i < times; ++i) {
EchoResponse response;
const Status status = SendRpc(&response, timeout_ms, wait_for_ready);
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage_);
}
}
void CheckRpcSendFailure() {
const Status status = SendRpc();
EXPECT_FALSE(status.ok());
}
class ServerThread {
public:
ServerThread() : port_(g_port_saver->GetPort()) {}
virtual ~ServerThread(){};
void Start(const grpc::string& server_host) {
gpr_log(GPR_INFO, "starting %s server on port %d", Type(), port_);
GPR_ASSERT(!running_);
running_ = true;
StartAllServices();
grpc_core::Mutex mu;
// We need to acquire the lock here in order to prevent the notify_one
// by ServerThread::Serve from firing before the wait below is hit.
grpc_core::MutexLock lock(&mu);
grpc_core::CondVar cond;
thread_.reset(new std::thread(
std::bind(&ServerThread::Serve, this, server_host, &mu, &cond)));
cond.Wait(&mu);
gpr_log(GPR_INFO, "%s server startup complete", Type());
}
void Serve(const grpc::string& server_host, grpc_core::Mutex* mu,
grpc_core::CondVar* cond) {
// We need to acquire the lock here in order to prevent the notify_one
// below from firing before its corresponding wait is executed.
grpc_core::MutexLock lock(mu);
std::ostringstream server_address;
server_address << server_host << ":" << port_;
ServerBuilder builder;
std::shared_ptr<ServerCredentials> creds(new SecureServerCredentials(
grpc_fake_transport_security_server_credentials_create()));
builder.AddListeningPort(server_address.str(), creds);
RegisterAllServices(&builder);
server_ = builder.BuildAndStart();
cond->Signal();
}
void Shutdown() {
if (!running_) return;
gpr_log(GPR_INFO, "%s about to shutdown", Type());
ShutdownAllServices();
server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
thread_->join();
gpr_log(GPR_INFO, "%s shutdown completed", Type());
running_ = false;
}
int port() const { return port_; }
private:
virtual void RegisterAllServices(ServerBuilder* builder) = 0;
virtual void StartAllServices() = 0;
virtual void ShutdownAllServices() = 0;
virtual const char* Type() = 0;
const int port_;
std::unique_ptr<Server> server_;
std::unique_ptr<std::thread> thread_;
bool running_ = false;
};
class BackendServerThread : public ServerThread {
public:
BackendServiceImpl* backend_service() { return &backend_service_; }
private:
void RegisterAllServices(ServerBuilder* builder) override {
builder->RegisterService(&backend_service_);
}
void StartAllServices() override { backend_service_.Start(); }
void ShutdownAllServices() override { backend_service_.Shutdown(); }
const char* Type() override { return "Backend"; }
BackendServiceImpl backend_service_;
};
class BalancerServerThread : public ServerThread {
public:
explicit BalancerServerThread(int client_load_reporting_interval = 0)
: ads_service_(client_load_reporting_interval > 0),
lrs_service_(client_load_reporting_interval) {}
AdsServiceImpl* ads_service() { return &ads_service_; }
LrsServiceImpl* lrs_service() { return &lrs_service_; }
private:
void RegisterAllServices(ServerBuilder* builder) override {
builder->RegisterService(&ads_service_);
builder->RegisterService(&lrs_service_);
}
void StartAllServices() override {
ads_service_.Start();
lrs_service_.Start();
}
void ShutdownAllServices() override {
ads_service_.Shutdown();
lrs_service_.Shutdown();
}
const char* Type() override { return "Balancer"; }
AdsServiceImpl ads_service_;
LrsServiceImpl lrs_service_;
};
const grpc::string server_host_;
const size_t num_backends_;
const size_t num_balancers_;
const int client_load_reporting_interval_seconds_;
std::shared_ptr<Channel> channel_;
std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
std::vector<std::unique_ptr<BackendServerThread>> backends_;
std::vector<std::unique_ptr<BalancerServerThread>> balancers_;
grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
response_generator_;
grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
lb_channel_response_generator_;
const grpc::string kRequestMessage_ = "Live long and prosper.";
const grpc::string kApplicationTargetName_ = "application_target_name";
const char* kDefaultServiceConfig_ =
"{\n"
" \"loadBalancingConfig\":[\n"
" { \"does_not_exist\":{} },\n"
" { \"xds_experimental\":{\n"
" \"lrsLoadReportingServerName\": \"\"\n"
" } }\n"
" ]\n"
"}";
const char* kDefaultServiceConfigWithoutLoadReporting_ =
"{\n"
" \"loadBalancingConfig\":[\n"
" { \"does_not_exist\":{} },\n"
" { \"xds_experimental\":{\n"
" } }\n"
" ]\n"
"}";
};
class BasicTest : public XdsEnd2endTest {
public:
BasicTest() : XdsEnd2endTest(4, 1) {}
};
// Tests that the balancer sends the correct response to the client, and the
// client sends RPCs to the backends using the default child policy.
TEST_P(BasicTest, Vanilla) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcsPerAddress = 100;
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts()},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// Make sure that trying to connect works without a call.
channel_->GetState(true /* try_to_connect */);
// We need to wait for all backends to come online.
WaitForAllBackends();
// Send kNumRpcsPerAddress RPCs per server.
CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
// Each backend should have gotten 100 requests.
for (size_t i = 0; i < backends_.size(); ++i) {
EXPECT_EQ(kNumRpcsPerAddress,
backends_[i]->backend_service()->request_count());
}
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
// Check LB policy name for the channel.
EXPECT_EQ(
(GetParam().use_xds_resolver() ? "cds_experimental" : "xds_experimental"),
channel_->GetLoadBalancingPolicyName());
}
TEST_P(BasicTest, IgnoresUnhealthyEndpoints) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcsPerAddress = 100;
AdsServiceImpl::ResponseArgs args({
{"locality0",
GetBackendPorts(),
kDefaultLocalityWeight,
kDefaultLocalityPriority,
{envoy::api::v2::HealthStatus::DRAINING}},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// Make sure that trying to connect works without a call.
channel_->GetState(true /* try_to_connect */);
// We need to wait for all backends to come online.
WaitForAllBackends(/*start_index=*/1);
// Send kNumRpcsPerAddress RPCs per server.
CheckRpcSendOk(kNumRpcsPerAddress * (num_backends_ - 1));
// Each backend should have gotten 100 requests.
for (size_t i = 1; i < backends_.size(); ++i) {
EXPECT_EQ(kNumRpcsPerAddress,
backends_[i]->backend_service()->request_count());
}
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// Tests that subchannel sharing works when the same backend is listed multiple
// times.
TEST_P(BasicTest, SameBackendListedMultipleTimes) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Same backend listed twice.
std::vector<int> ports(2, backends_[0]->port());
AdsServiceImpl::ResponseArgs args({
{"locality0", ports},
});
const size_t kNumRpcsPerAddress = 10;
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// We need to wait for the backend to come online.
WaitForBackend(0);
// Send kNumRpcsPerAddress RPCs per server.
CheckRpcSendOk(kNumRpcsPerAddress * ports.size());
// Backend should have gotten 20 requests.
EXPECT_EQ(kNumRpcsPerAddress * ports.size(),
backends_[0]->backend_service()->request_count());
// And they should have come from a single client port, because of
// subchannel sharing.
EXPECT_EQ(1UL, backends_[0]->backend_service()->clients().size());
}
// Tests that RPCs will be blocked until a non-empty serverlist is received.
TEST_P(BasicTest, InitiallyEmptyServerlist) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor();
const int kCallDeadlineMs = kServerlistDelayMs * 2;
// First response is an empty serverlist, sent right away.
AdsServiceImpl::ResponseArgs::Locality empty_locality("locality0", {});
AdsServiceImpl::ResponseArgs args({
empty_locality,
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// Send non-empty serverlist only after kServerlistDelayMs.
args = AdsServiceImpl::ResponseArgs({
{"locality0", GetBackendPorts()},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args),
kServerlistDelayMs);
const auto t0 = system_clock::now();
// Client will block: LB will initially send empty serverlist.
CheckRpcSendOk(1, kCallDeadlineMs, true /* wait_for_ready */);
const auto ellapsed_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(
system_clock::now() - t0);
// but eventually, the LB sends a serverlist update that allows the call to
// proceed. The call delay must be larger than the delay in sending the
// populated serverlist but under the call's deadline (which is enforced by
// the call's deadline).
EXPECT_GT(ellapsed_ms.count(), kServerlistDelayMs);
// The ADS service got a single request.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
// and sent two responses.
EXPECT_EQ(2U, balancers_[0]->ads_service()->response_count());
}
// Tests that RPCs will fail with UNAVAILABLE instead of DEADLINE_EXCEEDED if
// all the servers are unreachable.
TEST_P(BasicTest, AllServersUnreachableFailFast) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumUnreachableServers = 5;
std::vector<int> ports;
for (size_t i = 0; i < kNumUnreachableServers; ++i) {
ports.push_back(g_port_saver->GetPort());
}
AdsServiceImpl::ResponseArgs args({
{"locality0", ports},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
const Status status = SendRpc();
// The error shouldn't be DEADLINE_EXCEEDED.
EXPECT_EQ(StatusCode::UNAVAILABLE, status.error_code());
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// Tests that RPCs fail when the backends are down, and will succeed again after
// the backends are restarted.
TEST_P(BasicTest, BackendsRestart) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts()},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
WaitForAllBackends();
// Stop backends. RPCs should fail.
ShutdownAllBackends();
CheckRpcSendFailure();
// Restart all backends. RPCs should start succeeding again.
StartAllBackends();
CheckRpcSendOk(1 /* times */, 2000 /* timeout_ms */,
true /* wait_for_ready */);
}
using SecureNamingTest = BasicTest;
// Tests that secure naming check passes if target name is expected.
TEST_P(SecureNamingTest, TargetNameIsExpected) {
// TODO(juanlishen): Use separate fake creds for the balancer channel.
ResetStub(0, 0, kApplicationTargetName_ + ";lb");
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()});
const size_t kNumRpcsPerAddress = 100;
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts()},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// Make sure that trying to connect works without a call.
channel_->GetState(true /* try_to_connect */);
// We need to wait for all backends to come online.
WaitForAllBackends();
// Send kNumRpcsPerAddress RPCs per server.
CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
// Each backend should have gotten 100 requests.
for (size_t i = 0; i < backends_.size(); ++i) {
EXPECT_EQ(kNumRpcsPerAddress,
backends_[i]->backend_service()->request_count());
}
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// Tests that secure naming check fails if target name is unexpected.
TEST_P(SecureNamingTest, TargetNameIsUnexpected) {
gpr_setenv("GRPC_XDS_BOOTSTRAP", g_bootstrap_file_bad);
::testing::FLAGS_gtest_death_test_style = "threadsafe";
// Make sure that we blow up (via abort() from the security connector) when
// the name from the balancer doesn't match expectations.
ASSERT_DEATH_IF_SUPPORTED(
{
ResetStub(0, 0, kApplicationTargetName_ + ";lb");
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()});
channel_->WaitForConnected(grpc_timeout_seconds_to_deadline(1));
},
"");
}
using LdsTest = BasicTest;
// Tests that LDS client should send an ACK upon correct LDS response (with
// inlined RDS result).
TEST_P(LdsTest, Vanilla) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state(),
AdsServiceImpl::ACKED);
}
// Tests that LDS client should send a NACK if there is no API listener in the
// Listener in the LDS response.
TEST_P(LdsTest, NoApiListener) {
auto listener = balancers_[0]->ads_service()->default_listener();
listener.clear_api_listener();
balancers_[0]->ads_service()->SetLdsResponse(
{{"application_target_name", listener}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that LDS client should send a NACK if the route_specifier in the
// http_connection_manager is neither inlined route_config nor RDS.
TEST_P(LdsTest, WrongRouteSpecifier) {
auto listener = balancers_[0]->ads_service()->default_listener();
HttpConnectionManager http_connection_manager;
http_connection_manager.mutable_scoped_routes();
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
balancers_[0]->ads_service()->SetLdsResponse(
{{"application_target_name", std::move(listener)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that LDS client should send a NACK if matching domain can't be found in
// the LDS response.
TEST_P(LdsTest, NoMatchedDomain) {
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
route_config.mutable_virtual_hosts(0)->clear_domains();
route_config.mutable_virtual_hosts(0)->add_domains("unmatched_domain");
balancers_[0]->ads_service()->SetLdsResponse(
{{"application_target_name",
AdsServiceImpl::BuildListener(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that LDS client should choose the virtual host with matching domain if
// multiple virtual hosts exist in the LDS response.
TEST_P(LdsTest, ChooseMatchedDomain) {
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
*(route_config.add_virtual_hosts()) = route_config.virtual_hosts(0);
route_config.mutable_virtual_hosts(0)->clear_domains();
route_config.mutable_virtual_hosts(0)->add_domains("unmatched_domain");
route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_cluster_header();
balancers_[0]->ads_service()->SetLdsResponse(
{{"application_target_name",
AdsServiceImpl::BuildListener(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state(),
AdsServiceImpl::ACKED);
}
// Tests that LDS client should choose the last route in the virtual host if
// multiple routes exist in the LDS response.
TEST_P(LdsTest, ChooseLastRoute) {
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
*(route_config.mutable_virtual_hosts(0)->add_routes()) =
route_config.virtual_hosts(0).routes(0);
route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_cluster_header();
balancers_[0]->ads_service()->SetLdsResponse(
{{"application_target_name",
AdsServiceImpl::BuildListener(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state(),
AdsServiceImpl::ACKED);
}
// Tests that LDS client should send a NACK if route match has non-empty prefix
// in the LDS response.
TEST_P(LdsTest, RouteMatchHasNonemptyPrefix) {
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_match()
->set_prefix("nonempty_prefix");
balancers_[0]->ads_service()->SetLdsResponse(
{{"application_target_name",
AdsServiceImpl::BuildListener(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that LDS client should send a NACK if route has an action other than
// RouteAction in the LDS response.
TEST_P(LdsTest, RouteHasNoRouteAction) {
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
route_config.mutable_virtual_hosts(0)->mutable_routes(0)->mutable_redirect();
balancers_[0]->ads_service()->SetLdsResponse(
{{"application_target_name",
AdsServiceImpl::BuildListener(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that LDS client should send a NACK if RouteAction has a
// cluster_specifier other than cluster in the LDS response.
TEST_P(LdsTest, RouteActionHasNoCluster) {
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_cluster_header();
balancers_[0]->ads_service()->SetLdsResponse(
{{"application_target_name",
AdsServiceImpl::BuildListener(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that LDS client times out when no response received.
TEST_P(LdsTest, Timeout) {
ResetStub(0, 0, "", 500);
balancers_[0]->ads_service()->set_lds_ignore();
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
}
using RdsTest = BasicTest;
// Tests that RDS client should send an ACK upon correct RDS response.
TEST_P(RdsTest, Vanilla) {
balancers_[0]->ads_service()->SetLdsToUseDynamicRds();
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
EXPECT_EQ(balancers_[0]->ads_service()->rds_response_state(),
AdsServiceImpl::ACKED);
}
// Tests that RDS client should send a NACK if matching domain can't be found in
// the RDS response.
TEST_P(RdsTest, NoMatchedDomain) {
balancers_[0]->ads_service()->SetLdsToUseDynamicRds();
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
route_config.mutable_virtual_hosts(0)->clear_domains();
route_config.mutable_virtual_hosts(0)->add_domains("unmatched_domain");
balancers_[0]->ads_service()->SetRdsResponse(
{{"application_target_name", std::move(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->rds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that RDS client should choose the virtual host with matching domain if
// multiple virtual hosts exist in the RDS response.
TEST_P(RdsTest, ChooseMatchedDomain) {
balancers_[0]->ads_service()->SetLdsToUseDynamicRds();
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
*(route_config.add_virtual_hosts()) = route_config.virtual_hosts(0);
route_config.mutable_virtual_hosts(0)->clear_domains();
route_config.mutable_virtual_hosts(0)->add_domains("unmatched_domain");
route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_cluster_header();
balancers_[0]->ads_service()->SetRdsResponse(
{{"application_target_name", std::move(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
EXPECT_EQ(balancers_[0]->ads_service()->rds_response_state(),
AdsServiceImpl::ACKED);
}
// Tests that RDS client should choose the last route in the virtual host if
// multiple routes exist in the RDS response.
TEST_P(RdsTest, ChooseLastRoute) {
balancers_[0]->ads_service()->SetLdsToUseDynamicRds();
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
*(route_config.mutable_virtual_hosts(0)->add_routes()) =
route_config.virtual_hosts(0).routes(0);
route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_cluster_header();
balancers_[0]->ads_service()->SetRdsResponse(
{{"application_target_name", std::move(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
EXPECT_EQ(balancers_[0]->ads_service()->rds_response_state(),
AdsServiceImpl::ACKED);
}
// Tests that RDS client should send a NACK if route match has non-empty prefix
// in the RDS response.
TEST_P(RdsTest, RouteMatchHasNonemptyPrefix) {
balancers_[0]->ads_service()->SetLdsToUseDynamicRds();
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_match()
->set_prefix("nonempty_prefix");
balancers_[0]->ads_service()->SetRdsResponse(
{{"application_target_name", std::move(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->rds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that RDS client should send a NACK if route has an action other than
// RouteAction in the RDS response.
TEST_P(RdsTest, RouteHasNoRouteAction) {
balancers_[0]->ads_service()->SetLdsToUseDynamicRds();
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
route_config.mutable_virtual_hosts(0)->mutable_routes(0)->mutable_redirect();
balancers_[0]->ads_service()->SetRdsResponse(
{{"application_target_name", std::move(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->rds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that RDS client should send a NACK if RouteAction has a
// cluster_specifier other than cluster in the RDS response.
TEST_P(RdsTest, RouteActionHasNoCluster) {
balancers_[0]->ads_service()->SetLdsToUseDynamicRds();
RouteConfiguration route_config =
balancers_[0]->ads_service()->default_route_config();
route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_cluster_header();
balancers_[0]->ads_service()->SetRdsResponse(
{{"application_target_name", std::move(route_config)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->rds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that RDS client times out when no response received.
TEST_P(RdsTest, Timeout) {
ResetStub(0, 0, "", 500);
balancers_[0]->ads_service()->SetLdsToUseDynamicRds();
balancers_[0]->ads_service()->set_rds_ignore();
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
}
using CdsTest = BasicTest;
// Tests that CDS client should send an ACK upon correct CDS response.
TEST_P(CdsTest, Vanilla) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state(),
AdsServiceImpl::ACKED);
}
// Tests that CDS client should send a NACK if the cluster type in CDS response
// is other than EDS.
TEST_P(CdsTest, WrongClusterType) {
auto cluster = balancers_[0]->ads_service()->default_cluster();
cluster.set_type(envoy::api::v2::Cluster::STATIC);
balancers_[0]->ads_service()->SetCdsResponse(
{{"application_target_name", std::move(cluster)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that CDS client should send a NACK if the eds_config in CDS response is
// other than ADS.
TEST_P(CdsTest, WrongEdsConfig) {
auto cluster = balancers_[0]->ads_service()->default_cluster();
cluster.mutable_eds_cluster_config()->mutable_eds_config()->mutable_self();
balancers_[0]->ads_service()->SetCdsResponse(
{{"application_target_name", std::move(cluster)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that CDS client should send a NACK if the lb_policy in CDS response is
// other than ROUND_ROBIN.
TEST_P(CdsTest, WrongLbPolicy) {
auto cluster = balancers_[0]->ads_service()->default_cluster();
cluster.set_lb_policy(envoy::api::v2::Cluster::LEAST_REQUEST);
balancers_[0]->ads_service()->SetCdsResponse(
{{"application_target_name", std::move(cluster)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that CDS client should send a NACK if the lrs_server in CDS response is
// other than SELF.
TEST_P(CdsTest, WrongLrsServer) {
auto cluster = balancers_[0]->ads_service()->default_cluster();
cluster.mutable_lrs_server()->mutable_ads();
balancers_[0]->ads_service()->SetCdsResponse(
{{"application_target_name", std::move(cluster)}});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state(),
AdsServiceImpl::NACKED);
}
// Tests that CDS client times out when no response received.
TEST_P(CdsTest, Timeout) {
ResetStub(0, 0, "", 500);
balancers_[0]->ads_service()->set_cds_ignore();
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
}
using EdsTest = BasicTest;
// TODO(roth): Add tests showing that RPCs fail when EDS data is invalid.
TEST_P(EdsTest, Timeout) {
ResetStub(0, 0, "", 500);
balancers_[0]->ads_service()->set_eds_ignore();
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
}
using LocalityMapTest = BasicTest;
// Tests that the localities in a locality map are picked according to their
// weights.
TEST_P(LocalityMapTest, WeightedRoundRobin) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 5000;
const int kLocalityWeight0 = 2;
const int kLocalityWeight1 = 8;
const int kTotalLocalityWeight = kLocalityWeight0 + kLocalityWeight1;
const double kLocalityWeightRate0 =
static_cast<double>(kLocalityWeight0) / kTotalLocalityWeight;
const double kLocalityWeightRate1 =
static_cast<double>(kLocalityWeight1) / kTotalLocalityWeight;
// ADS response contains 2 localities, each of which contains 1 backend.
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts(0, 1), kLocalityWeight0},
{"locality1", GetBackendPorts(1, 2), kLocalityWeight1},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// Wait for both backends to be ready.
WaitForAllBackends(0, 2);
// Send kNumRpcs RPCs.
CheckRpcSendOk(kNumRpcs);
// The locality picking rates should be roughly equal to the expectation.
const double locality_picked_rate_0 =
static_cast<double>(backends_[0]->backend_service()->request_count()) /
kNumRpcs;
const double locality_picked_rate_1 =
static_cast<double>(backends_[1]->backend_service()->request_count()) /
kNumRpcs;
const double kErrorTolerance = 0.2;
EXPECT_THAT(locality_picked_rate_0,
::testing::AllOf(
::testing::Ge(kLocalityWeightRate0 * (1 - kErrorTolerance)),
::testing::Le(kLocalityWeightRate0 * (1 + kErrorTolerance))));
EXPECT_THAT(locality_picked_rate_1,
::testing::AllOf(
::testing::Ge(kLocalityWeightRate1 * (1 - kErrorTolerance)),
::testing::Le(kLocalityWeightRate1 * (1 + kErrorTolerance))));
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// Tests that the locality map can work properly even when it contains a large
// number of localities.
TEST_P(LocalityMapTest, StressTest) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumLocalities = 100;
// The first ADS response contains kNumLocalities localities, each of which
// contains backend 0.
AdsServiceImpl::ResponseArgs args;
for (size_t i = 0; i < kNumLocalities; ++i) {
grpc::string name = "locality" + std::to_string(i);
AdsServiceImpl::ResponseArgs::Locality locality(name,
{backends_[0]->port()});
args.locality_list.emplace_back(std::move(locality));
}
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// The second ADS response contains 1 locality, which contains backend 1.
args = AdsServiceImpl::ResponseArgs({
{"locality0", GetBackendPorts(1, 2)},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args),
60 * 1000);
// Wait until backend 0 is ready, before which kNumLocalities localities are
// received and handled by the xds policy.
WaitForBackend(0, /*reset_counters=*/false);
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
// Wait until backend 1 is ready, before which kNumLocalities localities are
// removed by the xds policy.
WaitForBackend(1);
// The ADS service got a single request.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
// and sent two responses.
EXPECT_EQ(2U, balancers_[0]->ads_service()->response_count());
}
// Tests that the localities in a locality map are picked correctly after update
// (addition, modification, deletion).
TEST_P(LocalityMapTest, UpdateMap) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 1000;
// The locality weight for the first 3 localities.
const std::vector<int> kLocalityWeights0 = {2, 3, 4};
const double kTotalLocalityWeight0 =
std::accumulate(kLocalityWeights0.begin(), kLocalityWeights0.end(), 0);
std::vector<double> locality_weight_rate_0;
for (int weight : kLocalityWeights0) {
locality_weight_rate_0.push_back(weight / kTotalLocalityWeight0);
}
// Delete the first locality, keep the second locality, change the third
// locality's weight from 4 to 2, and add a new locality with weight 6.
const std::vector<int> kLocalityWeights1 = {3, 2, 6};
const double kTotalLocalityWeight1 =
std::accumulate(kLocalityWeights1.begin(), kLocalityWeights1.end(), 0);
std::vector<double> locality_weight_rate_1 = {
0 /* placeholder for locality 0 */};
for (int weight : kLocalityWeights1) {
locality_weight_rate_1.push_back(weight / kTotalLocalityWeight1);
}
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts(0, 1), 2},
{"locality1", GetBackendPorts(1, 2), 3},
{"locality2", GetBackendPorts(2, 3), 4},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
args = AdsServiceImpl::ResponseArgs({
{"locality1", GetBackendPorts(1, 2), 3},
{"locality2", GetBackendPorts(2, 3), 2},
{"locality3", GetBackendPorts(3, 4), 6},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 5000);
// Wait for the first 3 backends to be ready.
WaitForAllBackends(0, 3);
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
// Send kNumRpcs RPCs.
CheckRpcSendOk(kNumRpcs);
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// The picking rates of the first 3 backends should be roughly equal to the
// expectation.
std::vector<double> locality_picked_rates;
for (size_t i = 0; i < 3; ++i) {
locality_picked_rates.push_back(
static_cast<double>(backends_[i]->backend_service()->request_count()) /
kNumRpcs);
}
const double kErrorTolerance = 0.2;
for (size_t i = 0; i < 3; ++i) {
EXPECT_THAT(
locality_picked_rates[i],
::testing::AllOf(
::testing::Ge(locality_weight_rate_0[i] * (1 - kErrorTolerance)),
::testing::Le(locality_weight_rate_0[i] * (1 + kErrorTolerance))));
}
// Backend 3 hasn't received any request.
EXPECT_EQ(0U, backends_[3]->backend_service()->request_count());
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
// Wait until the locality update has been processed, as signaled by backend 3
// receiving a request.
WaitForBackend(3);
gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
// Send kNumRpcs RPCs.
CheckRpcSendOk(kNumRpcs);
gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
// Backend 0 no longer receives any request.
EXPECT_EQ(0U, backends_[0]->backend_service()->request_count());
// The picking rates of the last 3 backends should be roughly equal to the
// expectation.
locality_picked_rates = {0 /* placeholder for backend 0 */};
for (size_t i = 1; i < 4; ++i) {
locality_picked_rates.push_back(
static_cast<double>(backends_[i]->backend_service()->request_count()) /
kNumRpcs);
}
for (size_t i = 1; i < 4; ++i) {
EXPECT_THAT(
locality_picked_rates[i],
::testing::AllOf(
::testing::Ge(locality_weight_rate_1[i] * (1 - kErrorTolerance)),
::testing::Le(locality_weight_rate_1[i] * (1 + kErrorTolerance))));
}
// The ADS service got a single request.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
// and sent two responses.
EXPECT_EQ(2U, balancers_[0]->ads_service()->response_count());
}
class FailoverTest : public BasicTest {
public:
FailoverTest() { ResetStub(0, 100, ""); }
};
// Localities with the highest priority are used when multiple priority exist.
TEST_P(FailoverTest, ChooseHighestPriority) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
WaitForBackend(3, false);
for (size_t i = 0; i < 3; ++i) {
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// If the higher priority localities are not reachable, failover to the highest
// priority among the rest.
TEST_P(FailoverTest, Failover) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
});
ShutdownBackend(3);
ShutdownBackend(0);
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
WaitForBackend(1, false);
for (size_t i = 0; i < 4; ++i) {
if (i == 1) continue;
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// If a locality with higher priority than the current one becomes ready,
// switch to it.
TEST_P(FailoverTest, SwitchBackToHigherPriority) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 100;
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
});
ShutdownBackend(3);
ShutdownBackend(0);
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
WaitForBackend(1, false);
for (size_t i = 0; i < 4; ++i) {
if (i == 1) continue;
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
StartBackend(0);
WaitForBackend(0);
CheckRpcSendOk(kNumRpcs);
EXPECT_EQ(kNumRpcs, backends_[0]->backend_service()->request_count());
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// The first update only contains unavailable priorities. The second update
// contains available priorities.
TEST_P(FailoverTest, UpdateInitialUnavailable) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 1},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
args = AdsServiceImpl::ResponseArgs({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 1},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 2},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 3},
});
ShutdownBackend(0);
ShutdownBackend(1);
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 1000);
gpr_timespec deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_millis(500, GPR_TIMESPAN));
// Send 0.5 second worth of RPCs.
do {
CheckRpcSendFailure();
} while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
WaitForBackend(2, false);
for (size_t i = 0; i < 4; ++i) {
if (i == 2) continue;
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(2U, balancers_[0]->ads_service()->response_count());
}
// Tests that after the localities' priorities are updated, we still choose the
// highest READY priority with the updated localities.
TEST_P(FailoverTest, UpdatePriority) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 100;
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
args = AdsServiceImpl::ResponseArgs({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 2},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 0},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 1},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 3},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 1000);
WaitForBackend(3, false);
for (size_t i = 0; i < 3; ++i) {
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
WaitForBackend(1);
CheckRpcSendOk(kNumRpcs);
EXPECT_EQ(kNumRpcs, backends_[1]->backend_service()->request_count());
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(2U, balancers_[0]->ads_service()->response_count());
}
using DropTest = BasicTest;
// Tests that RPCs are dropped according to the drop config.
TEST_P(DropTest, Vanilla) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 5000;
const uint32_t kDropPerMillionForLb = 100000;
const uint32_t kDropPerMillionForThrottle = 200000;
const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
const double KDropRateForLbAndThrottle =
kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
// The ADS response contains two drop categories.
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
{kThrottleDropType, kDropPerMillionForThrottle}};
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
WaitForAllBackends();
// Send kNumRpcs RPCs and count the drops.
size_t num_drops = 0;
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(&response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage_);
}
}
// The drop rate should be roughly equal to the expectation.
const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
const double kErrorTolerance = 0.2;
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(
::testing::Ge(KDropRateForLbAndThrottle * (1 - kErrorTolerance)),
::testing::Le(KDropRateForLbAndThrottle * (1 + kErrorTolerance))));
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// Tests that drop config is converted correctly from per hundred.
TEST_P(DropTest, DropPerHundred) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 5000;
const uint32_t kDropPerHundredForLb = 10;
const double kDropRateForLb = kDropPerHundredForLb / 100.0;
// The ADS response contains one drop category.
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, kDropPerHundredForLb}};
args.drop_denominator = FractionalPercent::HUNDRED;
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
WaitForAllBackends();
// Send kNumRpcs RPCs and count the drops.
size_t num_drops = 0;
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(&response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage_);
}
}
// The drop rate should be roughly equal to the expectation.
const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
const double kErrorTolerance = 0.2;
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(::testing::Ge(kDropRateForLb * (1 - kErrorTolerance)),
::testing::Le(kDropRateForLb * (1 + kErrorTolerance))));
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// Tests that drop config is converted correctly from per ten thousand.
TEST_P(DropTest, DropPerTenThousand) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 5000;
const uint32_t kDropPerTenThousandForLb = 1000;
const double kDropRateForLb = kDropPerTenThousandForLb / 10000.0;
// The ADS response contains one drop category.
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, kDropPerTenThousandForLb}};
args.drop_denominator = FractionalPercent::TEN_THOUSAND;
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
WaitForAllBackends();
// Send kNumRpcs RPCs and count the drops.
size_t num_drops = 0;
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(&response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage_);
}
}
// The drop rate should be roughly equal to the expectation.
const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
const double kErrorTolerance = 0.2;
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(::testing::Ge(kDropRateForLb * (1 - kErrorTolerance)),
::testing::Le(kDropRateForLb * (1 + kErrorTolerance))));
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// Tests that drop is working correctly after update.
TEST_P(DropTest, Update) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 1000;
const uint32_t kDropPerMillionForLb = 100000;
const uint32_t kDropPerMillionForThrottle = 200000;
const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
const double KDropRateForLbAndThrottle =
kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
// The first ADS response contains one drop category.
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, kDropPerMillionForLb}};
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// The second ADS response contains two drop categories.
// TODO(juanlishen): Change the ADS response sending to deterministic style
// (e.g., by using condition variable) so that we can shorten the test
// duration.
args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
{kThrottleDropType, kDropPerMillionForThrottle}};
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 10000);
WaitForAllBackends();
// Send kNumRpcs RPCs and count the drops.
size_t num_drops = 0;
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(&response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage_);
}
}
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// The drop rate should be roughly equal to the expectation.
double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
const double kErrorTolerance = 0.3;
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(::testing::Ge(kDropRateForLb * (1 - kErrorTolerance)),
::testing::Le(kDropRateForLb * (1 + kErrorTolerance))));
// Wait until the drop rate increases to the middle of the two configs, which
// implies that the update has been in effect.
const double kDropRateThreshold =
(kDropRateForLb + KDropRateForLbAndThrottle) / 2;
size_t num_rpcs = kNumRpcs;
while (seen_drop_rate < kDropRateThreshold) {
EchoResponse response;
const Status status = SendRpc(&response);
++num_rpcs;
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage_);
}
seen_drop_rate = static_cast<double>(num_drops) / num_rpcs;
}
// Send kNumRpcs RPCs and count the drops.
num_drops = 0;
gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(&response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage_);
}
}
gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
// The new drop rate should be roughly equal to the expectation.
seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(
::testing::Ge(KDropRateForLbAndThrottle * (1 - kErrorTolerance)),
::testing::Le(KDropRateForLbAndThrottle * (1 + kErrorTolerance))));
// The ADS service got a single request,
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
// and sent two responses
EXPECT_EQ(2U, balancers_[0]->ads_service()->response_count());
}
// Tests that all the RPCs are dropped if any drop category drops 100%.
TEST_P(DropTest, DropAll) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 1000;
const uint32_t kDropPerMillionForLb = 100000;
const uint32_t kDropPerMillionForThrottle = 1000000;
// The ADS response contains two drop categories.
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
{kThrottleDropType, kDropPerMillionForThrottle}};
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// Send kNumRpcs RPCs and all of them are dropped.
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(&response);
EXPECT_TRUE(!status.ok() && status.error_message() ==
"Call dropped by load balancing policy");
}
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
using FallbackTest = BasicTest;
// Tests that RPCs are handled by the fallback backends before the serverlist is
// received, but will be handled by the serverlist after it's received.
TEST_P(FallbackTest, Vanilla) {
const int kFallbackTimeoutMs = 200 * grpc_test_slowdown_factor();
const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor();
const size_t kNumBackendsInResolution = backends_.size() / 2;
ResetStub(kFallbackTimeoutMs);
SetNextResolution(GetBackendPorts(0, kNumBackendsInResolution));
SetNextResolutionForLbChannelAllBalancers();
// Send non-empty serverlist only after kServerlistDelayMs.
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts(kNumBackendsInResolution)},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args),
kServerlistDelayMs);
// Wait until all the fallback backends are reachable.
WaitForAllBackends(0 /* start_index */,
kNumBackendsInResolution /* stop_index */);
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
CheckRpcSendOk(kNumBackendsInResolution);
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// Fallback is used: each backend returned by the resolver should have
// gotten one request.
for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
EXPECT_EQ(1U, backends_[i]->backend_service()->request_count());
}
for (size_t i = kNumBackendsInResolution; i < backends_.size(); ++i) {
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
// Wait until the serverlist reception has been processed and all backends
// in the serverlist are reachable.
WaitForAllBackends(kNumBackendsInResolution /* start_index */);
gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
CheckRpcSendOk(backends_.size() - kNumBackendsInResolution);
gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
// Serverlist is used: each backend returned by the balancer should
// have gotten one request.
for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
for (size_t i = kNumBackendsInResolution; i < backends_.size(); ++i) {
EXPECT_EQ(1U, backends_[i]->backend_service()->request_count());
}
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// Tests that RPCs are handled by the updated fallback backends before
// serverlist is received,
TEST_P(FallbackTest, Update) {
const int kFallbackTimeoutMs = 200 * grpc_test_slowdown_factor();
const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor();
const size_t kNumBackendsInResolution = backends_.size() / 3;
const size_t kNumBackendsInResolutionUpdate = backends_.size() / 3;
ResetStub(kFallbackTimeoutMs);
SetNextResolution(GetBackendPorts(0, kNumBackendsInResolution));
SetNextResolutionForLbChannelAllBalancers();
// Send non-empty serverlist only after kServerlistDelayMs.
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts(kNumBackendsInResolution +
kNumBackendsInResolutionUpdate)},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args),
kServerlistDelayMs);
// Wait until all the fallback backends are reachable.
WaitForAllBackends(0 /* start_index */,
kNumBackendsInResolution /* stop_index */);
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
CheckRpcSendOk(kNumBackendsInResolution);
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// Fallback is used: each backend returned by the resolver should have
// gotten one request.
for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
EXPECT_EQ(1U, backends_[i]->backend_service()->request_count());
}
for (size_t i = kNumBackendsInResolution; i < backends_.size(); ++i) {
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
SetNextResolution(GetBackendPorts(
kNumBackendsInResolution,
kNumBackendsInResolution + kNumBackendsInResolutionUpdate));
// Wait until the resolution update has been processed and all the new
// fallback backends are reachable.
WaitForAllBackends(kNumBackendsInResolution /* start_index */,
kNumBackendsInResolution +
kNumBackendsInResolutionUpdate /* stop_index */);
gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
CheckRpcSendOk(kNumBackendsInResolutionUpdate);
gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
// The resolution update is used: each backend in the resolution update should
// have gotten one request.
for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
for (size_t i = kNumBackendsInResolution;
i < kNumBackendsInResolution + kNumBackendsInResolutionUpdate; ++i) {
EXPECT_EQ(1U, backends_[i]->backend_service()->request_count());
}
for (size_t i = kNumBackendsInResolution + kNumBackendsInResolutionUpdate;
i < backends_.size(); ++i) {
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
// Wait until the serverlist reception has been processed and all backends
// in the serverlist are reachable.
WaitForAllBackends(kNumBackendsInResolution +
kNumBackendsInResolutionUpdate /* start_index */);
gpr_log(GPR_INFO, "========= BEFORE THIRD BATCH ==========");
CheckRpcSendOk(backends_.size() - kNumBackendsInResolution -
kNumBackendsInResolutionUpdate);
gpr_log(GPR_INFO, "========= DONE WITH THIRD BATCH ==========");
// Serverlist is used: each backend returned by the balancer should
// have gotten one request.
for (size_t i = 0;
i < kNumBackendsInResolution + kNumBackendsInResolutionUpdate; ++i) {
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
for (size_t i = kNumBackendsInResolution + kNumBackendsInResolutionUpdate;
i < backends_.size(); ++i) {
EXPECT_EQ(1U, backends_[i]->backend_service()->request_count());
}
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
// Tests that fallback will kick in immediately if the balancer channel fails.
TEST_P(FallbackTest, FallbackEarlyWhenBalancerChannelFails) {
const int kFallbackTimeoutMs = 10000 * grpc_test_slowdown_factor();
ResetStub(kFallbackTimeoutMs);
// Return an unreachable balancer and one fallback backend.
SetNextResolution({backends_[0]->port()});
SetNextResolutionForLbChannel({g_port_saver->GetPort()});
// Send RPC with deadline less than the fallback timeout and make sure it
// succeeds.
CheckRpcSendOk(/* times */ 1, /* timeout_ms */ 1000,
/* wait_for_ready */ false);
}
// Tests that fallback will kick in immediately if the balancer call fails.
TEST_P(FallbackTest, FallbackEarlyWhenBalancerCallFails) {
const int kFallbackTimeoutMs = 10000 * grpc_test_slowdown_factor();
ResetStub(kFallbackTimeoutMs);
// Return one balancer and one fallback backend.
SetNextResolution({backends_[0]->port()});
SetNextResolutionForLbChannelAllBalancers();
// Balancer drops call without sending a serverlist.
balancers_[0]->ads_service()->NotifyDoneWithAdsCall();
// Send RPC with deadline less than the fallback timeout and make sure it
// succeeds.
CheckRpcSendOk(/* times */ 1, /* timeout_ms */ 1000,
/* wait_for_ready */ false);
}
// Tests that fallback mode is entered if balancer response is received but the
// backends can't be reached.
TEST_P(FallbackTest, FallbackIfResponseReceivedButChildNotReady) {
const int kFallbackTimeoutMs = 500 * grpc_test_slowdown_factor();
ResetStub(kFallbackTimeoutMs);
SetNextResolution({backends_[0]->port()});
SetNextResolutionForLbChannelAllBalancers();
// Send a serverlist that only contains an unreachable backend before fallback
// timeout.
AdsServiceImpl::ResponseArgs args({
{"locality0", {g_port_saver->GetPort()}},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// Because no child policy is ready before fallback timeout, we enter fallback
// mode.
WaitForBackend(0);
}
// Tests that fallback mode is exited if the balancer tells the client to drop
// all the calls.
TEST_P(FallbackTest, FallbackModeIsExitedWhenBalancerSaysToDropAllCalls) {
// Return an unreachable balancer and one fallback backend.
SetNextResolution({backends_[0]->port()});
SetNextResolutionForLbChannel({g_port_saver->GetPort()});
// Enter fallback mode because the LB channel fails to connect.
WaitForBackend(0);
// Return a new balancer that sends a response to drop all calls.
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, 1000000}};
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
SetNextResolutionForLbChannelAllBalancers();
// Send RPCs until failure.
gpr_timespec deadline = gpr_time_add(
gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(5000, GPR_TIMESPAN));
do {
auto status = SendRpc();
if (!status.ok()) break;
} while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
CheckRpcSendFailure();
}
// Tests that fallback mode is exited if the child policy becomes ready.
TEST_P(FallbackTest, FallbackModeIsExitedAfterChildRready) {
// Return an unreachable balancer and one fallback backend.
SetNextResolution({backends_[0]->port()});
SetNextResolutionForLbChannel({g_port_saver->GetPort()});
// Enter fallback mode because the LB channel fails to connect.
WaitForBackend(0);
// Return a new balancer that sends a dead backend.
ShutdownBackend(1);
AdsServiceImpl::ResponseArgs args({
{"locality0", {backends_[1]->port()}},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
SetNextResolutionForLbChannelAllBalancers();
// The state (TRANSIENT_FAILURE) update from the child policy will be ignored
// because we are still in fallback mode.
gpr_timespec deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_millis(500, GPR_TIMESPAN));
// Send 0.5 second worth of RPCs.
do {
CheckRpcSendOk();
} while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
// After the backend is restarted, the child policy will eventually be READY,
// and we will exit fallback mode.
StartBackend(1);
WaitForBackend(1);
// We have exited fallback mode, so calls will go to the child policy
// exclusively.
CheckRpcSendOk(100);
EXPECT_EQ(0U, backends_[0]->backend_service()->request_count());
EXPECT_EQ(100U, backends_[1]->backend_service()->request_count());
}
class BalancerUpdateTest : public XdsEnd2endTest {
public:
BalancerUpdateTest() : XdsEnd2endTest(4, 3) {}
};
// Tests that the old LB call is still used after the balancer address update as
// long as that call is still alive.
TEST_P(BalancerUpdateTest, UpdateBalancersButKeepUsingOriginalBalancer) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::ResponseArgs args({
{"locality0", {backends_[0]->port()}},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
args = AdsServiceImpl::ResponseArgs({
{"locality0", {backends_[1]->port()}},
});
ScheduleResponseForBalancer(1, AdsServiceImpl::BuildResponse(args), 0);
// Wait until the first backend is ready.
WaitForBackend(0);
// Send 10 requests.
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
CheckRpcSendOk(10);
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// All 10 requests should have gone to the first backend.
EXPECT_EQ(10U, backends_[0]->backend_service()->request_count());
// The ADS service of balancer 0 got a single request, and sent a single
// response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
EXPECT_EQ(0U, balancers_[1]->ads_service()->request_count());
EXPECT_EQ(0U, balancers_[1]->ads_service()->response_count());
EXPECT_EQ(0U, balancers_[2]->ads_service()->request_count());
EXPECT_EQ(0U, balancers_[2]->ads_service()->response_count());
gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
SetNextResolutionForLbChannel({balancers_[1]->port()});
gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
gpr_timespec deadline = gpr_time_add(
gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(10000, GPR_TIMESPAN));
// Send 10 seconds worth of RPCs
do {
CheckRpcSendOk();
} while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
// The current LB call is still working, so xds continued using it to the
// first balancer, which doesn't assign the second backend.
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
EXPECT_EQ(0U, balancers_[1]->ads_service()->request_count());
EXPECT_EQ(0U, balancers_[1]->ads_service()->response_count());
EXPECT_EQ(0U, balancers_[2]->ads_service()->request_count());
EXPECT_EQ(0U, balancers_[2]->ads_service()->response_count());
}
// Tests that the old LB call is still used after multiple balancer address
// updates as long as that call is still alive. Send an update with the same set
// of LBs as the one in SetUp() in order to verify that the LB channel inside
// xds keeps the initial connection (which by definition is also present in the
// update).
TEST_P(BalancerUpdateTest, Repeated) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::ResponseArgs args({
{"locality0", {backends_[0]->port()}},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
args = AdsServiceImpl::ResponseArgs({
{"locality0", {backends_[1]->port()}},
});
ScheduleResponseForBalancer(1, AdsServiceImpl::BuildResponse(args), 0);
// Wait until the first backend is ready.
WaitForBackend(0);
// Send 10 requests.
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
CheckRpcSendOk(10);
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// All 10 requests should have gone to the first backend.
EXPECT_EQ(10U, backends_[0]->backend_service()->request_count());
// The ADS service of balancer 0 got a single request, and sent a single
// response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
EXPECT_EQ(0U, balancers_[1]->ads_service()->request_count());
EXPECT_EQ(0U, balancers_[1]->ads_service()->response_count());
EXPECT_EQ(0U, balancers_[2]->ads_service()->request_count());
EXPECT_EQ(0U, balancers_[2]->ads_service()->response_count());
std::vector<int> ports;
ports.emplace_back(balancers_[0]->port());
ports.emplace_back(balancers_[1]->port());
ports.emplace_back(balancers_[2]->port());
gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
SetNextResolutionForLbChannel(ports);
gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
gpr_timespec deadline = gpr_time_add(
gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(10000, GPR_TIMESPAN));
// Send 10 seconds worth of RPCs
do {
CheckRpcSendOk();
} while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
// xds continued using the original LB call to the first balancer, which
// doesn't assign the second backend.
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
ports.clear();
ports.emplace_back(balancers_[0]->port());
ports.emplace_back(balancers_[1]->port());
gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 2 ==========");
SetNextResolutionForLbChannel(ports);
gpr_log(GPR_INFO, "========= UPDATE 2 DONE ==========");
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_millis(10000, GPR_TIMESPAN));
// Send 10 seconds worth of RPCs
do {
CheckRpcSendOk();
} while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
// xds continued using the original LB call to the first balancer, which
// doesn't assign the second backend.
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
}
// Tests that if the balancer is down, the RPCs will still be sent to the
// backends according to the last balancer response, until a new balancer is
// reachable.
TEST_P(BalancerUpdateTest, DeadUpdate) {
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()});
AdsServiceImpl::ResponseArgs args({
{"locality0", {backends_[0]->port()}},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
args = AdsServiceImpl::ResponseArgs({
{"locality0", {backends_[1]->port()}},
});
ScheduleResponseForBalancer(1, AdsServiceImpl::BuildResponse(args), 0);
// Start servers and send 10 RPCs per server.
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
CheckRpcSendOk(10);
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// All 10 requests should have gone to the first backend.
EXPECT_EQ(10U, backends_[0]->backend_service()->request_count());
// Kill balancer 0
gpr_log(GPR_INFO, "********** ABOUT TO KILL BALANCER 0 *************");
balancers_[0]->Shutdown();
gpr_log(GPR_INFO, "********** KILLED BALANCER 0 *************");
// This is serviced by the existing child policy.
gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
CheckRpcSendOk(10);
gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
// All 10 requests should again have gone to the first backend.
EXPECT_EQ(20U, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
// The ADS service of balancer 0 got a single request, and sent a single
// response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
EXPECT_EQ(0U, balancers_[1]->ads_service()->request_count());
EXPECT_EQ(0U, balancers_[1]->ads_service()->response_count());
EXPECT_EQ(0U, balancers_[2]->ads_service()->request_count());
EXPECT_EQ(0U, balancers_[2]->ads_service()->response_count());
gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
SetNextResolutionForLbChannel({balancers_[1]->port()});
gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
// Wait until update has been processed, as signaled by the second backend
// receiving a request. In the meantime, the client continues to be serviced
// (by the first backend) without interruption.
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
WaitForBackend(1);
// This is serviced by the updated RR policy
backends_[1]->backend_service()->ResetCounters();
gpr_log(GPR_INFO, "========= BEFORE THIRD BATCH ==========");
CheckRpcSendOk(10);
gpr_log(GPR_INFO, "========= DONE WITH THIRD BATCH ==========");
// All 10 requests should have gone to the second backend.
EXPECT_EQ(10U, backends_[1]->backend_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
// The second balancer, published as part of the first update, may end up
// getting two requests (that is, 1 <= #req <= 2) if the LB call retry timer
// firing races with the arrival of the update containing the second
// balancer.
EXPECT_GE(balancers_[1]->ads_service()->request_count(), 1U);
EXPECT_GE(balancers_[1]->ads_service()->response_count(), 1U);
EXPECT_LE(balancers_[1]->ads_service()->request_count(), 2U);
EXPECT_LE(balancers_[1]->ads_service()->response_count(), 2U);
EXPECT_EQ(0U, balancers_[2]->ads_service()->request_count());
EXPECT_EQ(0U, balancers_[2]->ads_service()->response_count());
}
// The re-resolution tests are deferred because they rely on the fallback mode,
// which hasn't been supported.
// TODO(juanlishen): Add TEST_P(BalancerUpdateTest, ReresolveDeadBackend).
// TODO(juanlishen): Add TEST_P(UpdatesWithClientLoadReportingTest,
// ReresolveDeadBalancer)
class ClientLoadReportingTest : public XdsEnd2endTest {
public:
ClientLoadReportingTest() : XdsEnd2endTest(4, 1, 3) {}
};
// Tests that the load report received at the balancer is correct.
TEST_P(ClientLoadReportingTest, Vanilla) {
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()});
const size_t kNumRpcsPerAddress = 100;
// TODO(juanlishen): Partition the backends after multiple localities is
// tested.
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts()},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// Wait until all backends are ready.
int num_ok = 0;
int num_failure = 0;
int num_drops = 0;
std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
// Send kNumRpcsPerAddress RPCs per server.
CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
// Each backend should have gotten 100 requests.
for (size_t i = 0; i < backends_.size(); ++i) {
EXPECT_EQ(kNumRpcsPerAddress,
backends_[i]->backend_service()->request_count());
}
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
// The LRS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->lrs_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->lrs_service()->response_count());
// The load report received at the balancer should be correct.
ClientStats* client_stats = balancers_[0]->lrs_service()->WaitForLoadReport();
EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_ok,
client_stats->total_successful_requests());
EXPECT_EQ(0U, client_stats->total_requests_in_progress());
EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_ok,
client_stats->total_issued_requests());
EXPECT_EQ(0U, client_stats->total_error_requests());
EXPECT_EQ(0U, client_stats->total_dropped_requests());
}
// Tests that if the balancer restarts, the client load report contains the
// stats before and after the restart correctly.
TEST_P(ClientLoadReportingTest, BalancerRestart) {
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()});
const size_t kNumBackendsFirstPass = backends_.size() / 2;
const size_t kNumBackendsSecondPass =
backends_.size() - kNumBackendsFirstPass;
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts(0, kNumBackendsFirstPass)},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// Wait until all backends returned by the balancer are ready.
int num_ok = 0;
int num_failure = 0;
int num_drops = 0;
std::tie(num_ok, num_failure, num_drops) =
WaitForAllBackends(/* start_index */ 0,
/* stop_index */ kNumBackendsFirstPass);
ClientStats* client_stats = balancers_[0]->lrs_service()->WaitForLoadReport();
EXPECT_EQ(static_cast<size_t>(num_ok),
client_stats->total_successful_requests());
EXPECT_EQ(0U, client_stats->total_requests_in_progress());
EXPECT_EQ(0U, client_stats->total_error_requests());
EXPECT_EQ(0U, client_stats->total_dropped_requests());
// Shut down the balancer.
balancers_[0]->Shutdown();
// We should continue using the last EDS response we received from the
// balancer before it was shut down.
// Note: We need to use WaitForAllBackends() here instead of just
// CheckRpcSendOk(kNumBackendsFirstPass), because when the balancer
// shuts down, the XdsClient will generate an error to the
// ServiceConfigWatcher, which will cause the xds resolver to send a
// no-op update to the LB policy. When this update gets down to the
// round_robin child policy for the locality, it will generate a new
// subchannel list, which resets the start index randomly. So we need
// to be a little more permissive here to avoid spurious failures.
ResetBackendCounters();
int num_started = std::get<0>(WaitForAllBackends(
/* start_index */ 0, /* stop_index */ kNumBackendsFirstPass));
// Now restart the balancer, this time pointing to the new backends.
balancers_[0]->Start(server_host_);
args = AdsServiceImpl::ResponseArgs({
{"locality0", GetBackendPorts(kNumBackendsFirstPass)},
});
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
// Wait for queries to start going to one of the new backends.
// This tells us that we're now using the new serverlist.
std::tie(num_ok, num_failure, num_drops) =
WaitForAllBackends(/* start_index */ kNumBackendsFirstPass);
num_started += num_ok + num_failure + num_drops;
// Send one RPC per backend.
CheckRpcSendOk(kNumBackendsSecondPass);
num_started += kNumBackendsSecondPass;
// Check client stats.
client_stats = balancers_[0]->lrs_service()->WaitForLoadReport();
EXPECT_EQ(num_started, client_stats->total_successful_requests());
EXPECT_EQ(0U, client_stats->total_requests_in_progress());
EXPECT_EQ(0U, client_stats->total_error_requests());
EXPECT_EQ(0U, client_stats->total_dropped_requests());
}
class ClientLoadReportingWithDropTest : public XdsEnd2endTest {
public:
ClientLoadReportingWithDropTest() : XdsEnd2endTest(4, 1, 20) {}
};
// Tests that the drop stats are correctly reported by client load reporting.
TEST_P(ClientLoadReportingWithDropTest, Vanilla) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 3000;
const uint32_t kDropPerMillionForLb = 100000;
const uint32_t kDropPerMillionForThrottle = 200000;
const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
const double KDropRateForLbAndThrottle =
kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
// The ADS response contains two drop categories.
AdsServiceImpl::ResponseArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
{kThrottleDropType, kDropPerMillionForThrottle}};
ScheduleResponseForBalancer(0, AdsServiceImpl::BuildResponse(args), 0);
int num_ok = 0;
int num_failure = 0;
int num_drops = 0;
std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
const size_t num_warmup = num_ok + num_failure + num_drops;
// Send kNumRpcs RPCs and count the drops.
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(&response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage_);
}
}
// The drop rate should be roughly equal to the expectation.
const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
const double kErrorTolerance = 0.2;
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(
::testing::Ge(KDropRateForLbAndThrottle * (1 - kErrorTolerance)),
::testing::Le(KDropRateForLbAndThrottle * (1 + kErrorTolerance))));
// Check client stats.
ClientStats* client_stats = balancers_[0]->lrs_service()->WaitForLoadReport();
EXPECT_EQ(num_drops, client_stats->total_dropped_requests());
const size_t total_rpc = num_warmup + kNumRpcs;
EXPECT_THAT(
client_stats->dropped_requests(kLbDropType),
::testing::AllOf(
::testing::Ge(total_rpc * kDropRateForLb * (1 - kErrorTolerance)),
::testing::Le(total_rpc * kDropRateForLb * (1 + kErrorTolerance))));
EXPECT_THAT(client_stats->dropped_requests(kThrottleDropType),
::testing::AllOf(
::testing::Ge(total_rpc * (1 - kDropRateForLb) *
kDropRateForThrottle * (1 - kErrorTolerance)),
::testing::Le(total_rpc * (1 - kDropRateForLb) *
kDropRateForThrottle * (1 + kErrorTolerance))));
// The ADS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->ads_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->ads_service()->response_count());
}
grpc::string TestTypeName(const ::testing::TestParamInfo<TestType>& info) {
return info.param.AsString();
}
INSTANTIATE_TEST_SUITE_P(XdsTest, BasicTest,
::testing::Values(TestType(false, true),
TestType(false, false),
TestType(true, false),
TestType(true, true)),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(XdsTest, SecureNamingTest,
::testing::Values(TestType(false, true),
TestType(false, false),
TestType(true, false),
TestType(true, true)),
&TestTypeName);
// LDS depends on XdsResolver.
INSTANTIATE_TEST_SUITE_P(XdsTest, LdsTest,
::testing::Values(TestType(true, false),
TestType(true, true)),
&TestTypeName);
// RDS depends on XdsResolver.
INSTANTIATE_TEST_SUITE_P(XdsTest, RdsTest,
::testing::Values(TestType(true, false),
TestType(true, true)),
&TestTypeName);
// CDS depends on XdsResolver.
INSTANTIATE_TEST_SUITE_P(XdsTest, CdsTest,
::testing::Values(TestType(true, false),
TestType(true, true)),
&TestTypeName);
// EDS could be tested with or without XdsResolver, but the tests would
// be the same either way, so we test it only with XdsResolver.
INSTANTIATE_TEST_SUITE_P(XdsTest, EdsTest,
::testing::Values(TestType(true, false),
TestType(true, true)),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(XdsTest, LocalityMapTest,
::testing::Values(TestType(false, true),
TestType(false, false),
TestType(true, false),
TestType(true, true)),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(XdsTest, FailoverTest,
::testing::Values(TestType(false, true),
TestType(false, false),
TestType(true, false),
TestType(true, true)),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(XdsTest, DropTest,
::testing::Values(TestType(false, true),
TestType(false, false),
TestType(true, false),
TestType(true, true)),
&TestTypeName);
// Fallback does not work with xds resolver.
INSTANTIATE_TEST_SUITE_P(XdsTest, FallbackTest,
::testing::Values(TestType(false, true),
TestType(false, false)),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(XdsTest, BalancerUpdateTest,
::testing::Values(TestType(false, true),
TestType(false, false),
TestType(true, true)),
&TestTypeName);
// Load reporting tests are not run with load reporting disabled.
INSTANTIATE_TEST_SUITE_P(XdsTest, ClientLoadReportingTest,
::testing::Values(TestType(false, true),
TestType(true, true)),
&TestTypeName);
// Load reporting tests are not run with load reporting disabled.
INSTANTIATE_TEST_SUITE_P(XdsTest, ClientLoadReportingWithDropTest,
::testing::Values(TestType(false, true),
TestType(true, true)),
&TestTypeName);
} // namespace
} // namespace testing
} // namespace grpc
int main(int argc, char** argv) {
grpc::testing::TestEnvironment env(argc, argv);
::testing::InitGoogleTest(&argc, argv);
grpc::testing::WriteBootstrapFiles();
grpc::testing::g_port_saver = new grpc::testing::PortSaver();
const auto result = RUN_ALL_TESTS();
return result;
}
|
/*
*
* Copyright 2017 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <deque>
#include <memory>
#include <mutex>
#include <numeric>
#include <set>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/functional/bind_front.h"
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/types/optional.h"
#include <grpc/grpc.h>
#include <grpc/grpc_security.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/time.h>
#include <grpcpp/channel.h>
#include <grpcpp/client_context.h>
#include <grpcpp/create_channel.h>
#include <grpcpp/security/tls_certificate_provider.h>
#include <grpcpp/server.h>
#include <grpcpp/server_builder.h>
#include <grpcpp/xds_server_builder.h>
#include "src/core/ext/filters/client_channel/backup_poller.h"
#include "src/core/ext/filters/client_channel/lb_policy/xds/xds_channel_args.h"
#include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
#include "src/core/ext/filters/client_channel/server_address.h"
#include "src/core/ext/xds/certificate_provider_registry.h"
#include "src/core/ext/xds/xds_api.h"
#include "src/core/ext/xds/xds_channel_args.h"
#include "src/core/ext/xds/xds_client.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/gpr/env.h"
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gpr/time_precise.h"
#include "src/core/lib/gpr/tmpfile.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/gprpp/time_util.h"
#include "src/core/lib/iomgr/load_file.h"
#include "src/core/lib/iomgr/parse_address.h"
#include "src/core/lib/iomgr/sockaddr.h"
#include "src/core/lib/security/credentials/fake/fake_credentials.h"
#include "src/cpp/client/secure_credentials.h"
#include "src/cpp/server/secure_server_credentials.h"
#include "src/proto/grpc/testing/echo.grpc.pb.h"
#include "src/proto/grpc/testing/xds/ads_for_test.grpc.pb.h"
#include "src/proto/grpc/testing/xds/cds_for_test.grpc.pb.h"
#include "src/proto/grpc/testing/xds/eds_for_test.grpc.pb.h"
#include "src/proto/grpc/testing/xds/lds_rds_for_test.grpc.pb.h"
#include "src/proto/grpc/testing/xds/lrs_for_test.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/ads.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/aggregate_cluster.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/cluster.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/discovery.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/endpoint.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/fault.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/http_connection_manager.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/listener.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/lrs.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/route.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/router.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/tls.grpc.pb.h"
#include "test/core/util/port.h"
#include "test/core/util/resolve_localhost_ip46.h"
#include "test/core/util/test_config.h"
#include "test/cpp/end2end/test_service_impl.h"
#ifndef DISABLED_XDS_PROTO_IN_CC
#include "src/cpp/server/csds/csds.h"
#include "src/proto/grpc/testing/xds/v3/csds.grpc.pb.h"
#endif // DISABLED_XDS_PROTO_IN_CC
namespace grpc {
namespace testing {
namespace {
using std::chrono::system_clock;
#ifndef DISABLED_XDS_PROTO_IN_CC
using ::envoy::admin::v3::ClientResourceStatus;
#endif // DISABLED_XDS_PROTO_IN_CC
using ::envoy::config::cluster::v3::CircuitBreakers;
using ::envoy::config::cluster::v3::Cluster;
using ::envoy::config::cluster::v3::CustomClusterType;
using ::envoy::config::cluster::v3::RoutingPriority;
using ::envoy::config::endpoint::v3::ClusterLoadAssignment;
using ::envoy::config::endpoint::v3::HealthStatus;
using ::envoy::config::listener::v3::FilterChainMatch;
using ::envoy::config::listener::v3::Listener;
using ::envoy::config::route::v3::RouteConfiguration;
using ::envoy::extensions::clusters::aggregate::v3::ClusterConfig;
using ::envoy::extensions::filters::http::fault::v3::HTTPFault;
using ::envoy::extensions::filters::network::http_connection_manager::v3::
HttpConnectionManager;
using ::envoy::extensions::filters::network::http_connection_manager::v3::
HttpFilter;
using ::envoy::extensions::transport_sockets::tls::v3::DownstreamTlsContext;
using ::envoy::extensions::transport_sockets::tls::v3::UpstreamTlsContext;
using ::envoy::type::matcher::v3::StringMatcher;
using ::envoy::type::v3::FractionalPercent;
constexpr char kLdsTypeUrl[] =
"type.googleapis.com/envoy.config.listener.v3.Listener";
constexpr char kRdsTypeUrl[] =
"type.googleapis.com/envoy.config.route.v3.RouteConfiguration";
constexpr char kCdsTypeUrl[] =
"type.googleapis.com/envoy.config.cluster.v3.Cluster";
constexpr char kEdsTypeUrl[] =
"type.googleapis.com/envoy.config.endpoint.v3.ClusterLoadAssignment";
constexpr char kLdsV2TypeUrl[] = "type.googleapis.com/envoy.api.v2.Listener";
constexpr char kRdsV2TypeUrl[] =
"type.googleapis.com/envoy.api.v2.RouteConfiguration";
constexpr char kCdsV2TypeUrl[] = "type.googleapis.com/envoy.api.v2.Cluster";
constexpr char kEdsV2TypeUrl[] =
"type.googleapis.com/envoy.api.v2.ClusterLoadAssignment";
constexpr char kDefaultLocalityRegion[] = "xds_default_locality_region";
constexpr char kDefaultLocalityZone[] = "xds_default_locality_zone";
constexpr char kLbDropType[] = "lb";
constexpr char kThrottleDropType[] = "throttle";
constexpr char kServerName[] = "server.example.com";
constexpr char kDefaultRouteConfigurationName[] = "route_config_name";
constexpr char kDefaultClusterName[] = "cluster_name";
constexpr char kDefaultEdsServiceName[] = "eds_service_name";
constexpr int kDefaultLocalityWeight = 3;
constexpr int kDefaultLocalityPriority = 0;
constexpr char kRequestMessage[] = "Live long and prosper.";
constexpr char kDefaultServiceConfig[] =
"{\n"
" \"loadBalancingConfig\":[\n"
" { \"does_not_exist\":{} },\n"
" { \"xds_cluster_resolver_experimental\":{\n"
" \"discoveryMechanisms\": [\n"
" { \"clusterName\": \"server.example.com\",\n"
" \"type\": \"EDS\",\n"
" \"lrsLoadReportingServerName\": \"\"\n"
" } ]\n"
" } }\n"
" ]\n"
"}";
constexpr char kDefaultServiceConfigWithoutLoadReporting[] =
"{\n"
" \"loadBalancingConfig\":[\n"
" { \"does_not_exist\":{} },\n"
" { \"xds_cluster_resolver_experimental\":{\n"
" \"discoveryMechanisms\": [\n"
" { \"clusterName\": \"server.example.com\",\n"
" \"type\": \"EDS\"\n"
" } ]\n"
" } }\n"
" ]\n"
"}";
constexpr char kBootstrapFileV3[] =
"{\n"
" \"xds_servers\": [\n"
" {\n"
" \"server_uri\": \"fake:///xds_server\",\n"
" \"channel_creds\": [\n"
" {\n"
" \"type\": \"fake\"\n"
" }\n"
" ],\n"
" \"server_features\": [\"xds_v3\"]\n"
" }\n"
" ],\n"
" \"node\": {\n"
" \"id\": \"xds_end2end_test\",\n"
" \"cluster\": \"test\",\n"
" \"metadata\": {\n"
" \"foo\": \"bar\"\n"
" },\n"
" \"locality\": {\n"
" \"region\": \"corp\",\n"
" \"zone\": \"svl\",\n"
" \"sub_zone\": \"mp3\"\n"
" }\n"
" },\n"
" \"server_listener_resource_name_template\": "
"\"grpc/server?xds.resource.listening_address=%s\",\n"
" \"certificate_providers\": {\n"
" \"fake_plugin1\": {\n"
" \"plugin_name\": \"fake1\"\n"
" },\n"
" \"fake_plugin2\": {\n"
" \"plugin_name\": \"fake2\"\n"
" },\n"
" \"file_plugin\": {\n"
" \"plugin_name\": \"file_watcher\",\n"
" \"config\": {\n"
" \"certificate_file\": \"src/core/tsi/test_creds/client.pem\",\n"
" \"private_key_file\": \"src/core/tsi/test_creds/client.key\",\n"
" \"ca_certificate_file\": \"src/core/tsi/test_creds/ca.pem\"\n"
" }"
" }\n"
" }\n"
"}\n";
constexpr char kBootstrapFileV2[] =
"{\n"
" \"xds_servers\": [\n"
" {\n"
" \"server_uri\": \"fake:///xds_server\",\n"
" \"channel_creds\": [\n"
" {\n"
" \"type\": \"fake\"\n"
" }\n"
" ]\n"
" }\n"
" ],\n"
" \"node\": {\n"
" \"id\": \"xds_end2end_test\",\n"
" \"cluster\": \"test\",\n"
" \"metadata\": {\n"
" \"foo\": \"bar\"\n"
" },\n"
" \"locality\": {\n"
" \"region\": \"corp\",\n"
" \"zone\": \"svl\",\n"
" \"sub_zone\": \"mp3\"\n"
" }\n"
" }\n"
"}\n";
constexpr char kCaCertPath[] = "src/core/tsi/test_creds/ca.pem";
constexpr char kServerCertPath[] = "src/core/tsi/test_creds/server1.pem";
constexpr char kServerKeyPath[] = "src/core/tsi/test_creds/server1.key";
constexpr char kClientCertPath[] = "src/core/tsi/test_creds/client.pem";
constexpr char kClientKeyPath[] = "src/core/tsi/test_creds/client.key";
constexpr char kBadClientCertPath[] = "src/core/tsi/test_creds/badclient.pem";
constexpr char kBadClientKeyPath[] = "src/core/tsi/test_creds/badclient.key";
char* g_bootstrap_file_v3;
char* g_bootstrap_file_v2;
void WriteBootstrapFiles() {
char* bootstrap_file;
FILE* out = gpr_tmpfile("xds_bootstrap_v3", &bootstrap_file);
fputs(kBootstrapFileV3, out);
fclose(out);
g_bootstrap_file_v3 = bootstrap_file;
out = gpr_tmpfile("xds_bootstrap_v2", &bootstrap_file);
fputs(kBootstrapFileV2, out);
fclose(out);
g_bootstrap_file_v2 = bootstrap_file;
}
template <typename ServiceType>
class CountedService : public ServiceType {
public:
size_t request_count() {
grpc_core::MutexLock lock(&mu_);
return request_count_;
}
size_t response_count() {
grpc_core::MutexLock lock(&mu_);
return response_count_;
}
void IncreaseResponseCount() {
grpc_core::MutexLock lock(&mu_);
++response_count_;
}
void IncreaseRequestCount() {
grpc_core::MutexLock lock(&mu_);
++request_count_;
}
void ResetCounters() {
grpc_core::MutexLock lock(&mu_);
request_count_ = 0;
response_count_ = 0;
}
private:
grpc_core::Mutex mu_;
size_t request_count_ = 0;
size_t response_count_ = 0;
};
template <typename RpcService>
class BackendServiceImpl
: public CountedService<TestMultipleServiceImpl<RpcService>> {
public:
BackendServiceImpl() {}
Status Echo(ServerContext* context, const EchoRequest* request,
EchoResponse* response) override {
auto peer_identity = context->auth_context()->GetPeerIdentity();
CountedService<TestMultipleServiceImpl<RpcService>>::IncreaseRequestCount();
const auto status =
TestMultipleServiceImpl<RpcService>::Echo(context, request, response);
CountedService<
TestMultipleServiceImpl<RpcService>>::IncreaseResponseCount();
{
grpc_core::MutexLock lock(&mu_);
clients_.insert(context->peer());
last_peer_identity_.clear();
for (const auto& entry : peer_identity) {
last_peer_identity_.emplace_back(entry.data(), entry.size());
}
}
return status;
}
Status Echo1(ServerContext* context, const EchoRequest* request,
EchoResponse* response) override {
return Echo(context, request, response);
}
Status Echo2(ServerContext* context, const EchoRequest* request,
EchoResponse* response) override {
return Echo(context, request, response);
}
void Start() {}
void Shutdown() {}
std::set<std::string> clients() {
grpc_core::MutexLock lock(&mu_);
return clients_;
}
const std::vector<std::string>& last_peer_identity() {
grpc_core::MutexLock lock(&mu_);
return last_peer_identity_;
}
private:
grpc_core::Mutex mu_;
std::set<std::string> clients_;
std::vector<std::string> last_peer_identity_;
};
class ClientStats {
public:
struct LocalityStats {
LocalityStats() {}
// Converts from proto message class.
template <class UpstreamLocalityStats>
explicit LocalityStats(const UpstreamLocalityStats& upstream_locality_stats)
: total_successful_requests(
upstream_locality_stats.total_successful_requests()),
total_requests_in_progress(
upstream_locality_stats.total_requests_in_progress()),
total_error_requests(upstream_locality_stats.total_error_requests()),
total_issued_requests(
upstream_locality_stats.total_issued_requests()) {}
LocalityStats& operator+=(const LocalityStats& other) {
total_successful_requests += other.total_successful_requests;
total_requests_in_progress += other.total_requests_in_progress;
total_error_requests += other.total_error_requests;
total_issued_requests += other.total_issued_requests;
return *this;
}
uint64_t total_successful_requests = 0;
uint64_t total_requests_in_progress = 0;
uint64_t total_error_requests = 0;
uint64_t total_issued_requests = 0;
};
ClientStats() {}
// Converts from proto message class.
template <class ClusterStats>
explicit ClientStats(const ClusterStats& cluster_stats)
: cluster_name_(cluster_stats.cluster_name()),
total_dropped_requests_(cluster_stats.total_dropped_requests()) {
for (const auto& input_locality_stats :
cluster_stats.upstream_locality_stats()) {
locality_stats_.emplace(input_locality_stats.locality().sub_zone(),
LocalityStats(input_locality_stats));
}
for (const auto& input_dropped_requests :
cluster_stats.dropped_requests()) {
dropped_requests_.emplace(input_dropped_requests.category(),
input_dropped_requests.dropped_count());
}
}
const std::string& cluster_name() const { return cluster_name_; }
const std::map<std::string, LocalityStats>& locality_stats() const {
return locality_stats_;
}
uint64_t total_successful_requests() const {
uint64_t sum = 0;
for (auto& p : locality_stats_) {
sum += p.second.total_successful_requests;
}
return sum;
}
uint64_t total_requests_in_progress() const {
uint64_t sum = 0;
for (auto& p : locality_stats_) {
sum += p.second.total_requests_in_progress;
}
return sum;
}
uint64_t total_error_requests() const {
uint64_t sum = 0;
for (auto& p : locality_stats_) {
sum += p.second.total_error_requests;
}
return sum;
}
uint64_t total_issued_requests() const {
uint64_t sum = 0;
for (auto& p : locality_stats_) {
sum += p.second.total_issued_requests;
}
return sum;
}
uint64_t total_dropped_requests() const { return total_dropped_requests_; }
uint64_t dropped_requests(const std::string& category) const {
auto iter = dropped_requests_.find(category);
GPR_ASSERT(iter != dropped_requests_.end());
return iter->second;
}
ClientStats& operator+=(const ClientStats& other) {
for (const auto& p : other.locality_stats_) {
locality_stats_[p.first] += p.second;
}
total_dropped_requests_ += other.total_dropped_requests_;
for (const auto& p : other.dropped_requests_) {
dropped_requests_[p.first] += p.second;
}
return *this;
}
private:
std::string cluster_name_;
std::map<std::string, LocalityStats> locality_stats_;
uint64_t total_dropped_requests_ = 0;
std::map<std::string, uint64_t> dropped_requests_;
};
class AdsServiceImpl : public std::enable_shared_from_this<AdsServiceImpl> {
public:
struct ResponseState {
enum State { NOT_SENT, SENT, ACKED, NACKED };
State state = NOT_SENT;
std::string error_message;
};
struct EdsResourceArgs {
struct Locality {
Locality(std::string sub_zone, std::vector<int> ports,
int lb_weight = kDefaultLocalityWeight,
int priority = kDefaultLocalityPriority,
std::vector<HealthStatus> health_statuses = {})
: sub_zone(std::move(sub_zone)),
ports(std::move(ports)),
lb_weight(lb_weight),
priority(priority),
health_statuses(std::move(health_statuses)) {}
const std::string sub_zone;
std::vector<int> ports;
int lb_weight;
int priority;
std::vector<HealthStatus> health_statuses;
};
EdsResourceArgs() = default;
explicit EdsResourceArgs(std::vector<Locality> locality_list)
: locality_list(std::move(locality_list)) {}
std::vector<Locality> locality_list;
std::map<std::string, uint32_t> drop_categories;
FractionalPercent::DenominatorType drop_denominator =
FractionalPercent::MILLION;
};
AdsServiceImpl()
: v2_rpc_service_(this, /*is_v2=*/true),
v3_rpc_service_(this, /*is_v2=*/false) {}
bool seen_v2_client() const { return seen_v2_client_; }
bool seen_v3_client() const { return seen_v3_client_; }
::envoy::service::discovery::v2::AggregatedDiscoveryService::Service*
v2_rpc_service() {
return &v2_rpc_service_;
}
::envoy::service::discovery::v3::AggregatedDiscoveryService::Service*
v3_rpc_service() {
return &v3_rpc_service_;
}
ResponseState lds_response_state() {
grpc_core::MutexLock lock(&ads_mu_);
return resource_type_response_state_[kLdsTypeUrl];
}
ResponseState rds_response_state() {
grpc_core::MutexLock lock(&ads_mu_);
return resource_type_response_state_[kRdsTypeUrl];
}
ResponseState cds_response_state() {
grpc_core::MutexLock lock(&ads_mu_);
return resource_type_response_state_[kCdsTypeUrl];
}
ResponseState eds_response_state() {
grpc_core::MutexLock lock(&ads_mu_);
return resource_type_response_state_[kEdsTypeUrl];
}
void SetResourceIgnore(const std::string& type_url) {
grpc_core::MutexLock lock(&ads_mu_);
resource_types_to_ignore_.emplace(type_url);
}
void SetResourceMinVersion(const std::string& type_url, int version) {
grpc_core::MutexLock lock(&ads_mu_);
resource_type_min_versions_[type_url] = version;
}
void UnsetResource(const std::string& type_url, const std::string& name) {
grpc_core::MutexLock lock(&ads_mu_);
ResourceTypeState& resource_type_state = resource_map_[type_url];
++resource_type_state.resource_type_version;
ResourceState& resource_state = resource_type_state.resource_name_map[name];
resource_state.resource_type_version =
resource_type_state.resource_type_version;
resource_state.resource.reset();
gpr_log(GPR_INFO,
"ADS[%p]: Unsetting %s resource %s; resource_type_version now %u",
this, type_url.c_str(), name.c_str(),
resource_type_state.resource_type_version);
for (SubscriptionState* subscription : resource_state.subscriptions) {
subscription->update_queue->emplace_back(type_url, name);
}
}
void SetResource(google::protobuf::Any resource, const std::string& type_url,
const std::string& name) {
grpc_core::MutexLock lock(&ads_mu_);
ResourceTypeState& resource_type_state = resource_map_[type_url];
++resource_type_state.resource_type_version;
ResourceState& resource_state = resource_type_state.resource_name_map[name];
resource_state.resource_type_version =
resource_type_state.resource_type_version;
resource_state.resource = std::move(resource);
gpr_log(GPR_INFO,
"ADS[%p]: Updating %s resource %s; resource_type_version now %u",
this, type_url.c_str(), name.c_str(),
resource_type_state.resource_type_version);
for (SubscriptionState* subscription : resource_state.subscriptions) {
subscription->update_queue->emplace_back(type_url, name);
}
}
void SetLdsResource(const Listener& listener) {
google::protobuf::Any resource;
resource.PackFrom(listener);
SetResource(std::move(resource), kLdsTypeUrl, listener.name());
}
void SetRdsResource(const RouteConfiguration& route) {
google::protobuf::Any resource;
resource.PackFrom(route);
SetResource(std::move(resource), kRdsTypeUrl, route.name());
}
void SetCdsResource(const Cluster& cluster) {
google::protobuf::Any resource;
resource.PackFrom(cluster);
SetResource(std::move(resource), kCdsTypeUrl, cluster.name());
}
void SetEdsResource(const ClusterLoadAssignment& assignment) {
google::protobuf::Any resource;
resource.PackFrom(assignment);
SetResource(std::move(resource), kEdsTypeUrl, assignment.cluster_name());
}
void Start() {
grpc_core::MutexLock lock(&ads_mu_);
ads_done_ = false;
}
void Shutdown() {
{
grpc_core::MutexLock lock(&ads_mu_);
NotifyDoneWithAdsCallLocked();
resource_type_response_state_.clear();
}
gpr_log(GPR_INFO, "ADS[%p]: shut down", this);
}
void NotifyDoneWithAdsCall() {
grpc_core::MutexLock lock(&ads_mu_);
NotifyDoneWithAdsCallLocked();
}
void NotifyDoneWithAdsCallLocked() {
if (!ads_done_) {
ads_done_ = true;
ads_cond_.SignalAll();
}
}
std::set<std::string> clients() {
grpc_core::MutexLock lock(&clients_mu_);
return clients_;
}
private:
// A queue of resource type/name pairs that have changed since the client
// subscribed to them.
using UpdateQueue = std::deque<
std::pair<std::string /* type url */, std::string /* resource name */>>;
// A struct representing a client's subscription to a particular resource.
struct SubscriptionState {
// The queue upon which to place updates when the resource is updated.
UpdateQueue* update_queue;
};
// A struct representing the a client's subscription to all the resources.
using SubscriptionNameMap =
std::map<std::string /* resource_name */, SubscriptionState>;
using SubscriptionMap =
std::map<std::string /* type_url */, SubscriptionNameMap>;
// Sent state for a given resource type.
struct SentState {
int nonce = 0;
int resource_type_version = 0;
};
// A struct representing the current state for an individual resource.
struct ResourceState {
// The resource itself, if present.
absl::optional<google::protobuf::Any> resource;
// The resource type version that this resource was last updated in.
int resource_type_version = 0;
// A list of subscriptions to this resource.
std::set<SubscriptionState*> subscriptions;
};
// The current state for all individual resources of a given type.
using ResourceNameMap =
std::map<std::string /* resource_name */, ResourceState>;
struct ResourceTypeState {
int resource_type_version = 0;
ResourceNameMap resource_name_map;
};
using ResourceMap = std::map<std::string /* type_url */, ResourceTypeState>;
template <class RpcApi, class DiscoveryRequest, class DiscoveryResponse>
class RpcService : public RpcApi::Service {
public:
using Stream = ServerReaderWriter<DiscoveryResponse, DiscoveryRequest>;
RpcService(AdsServiceImpl* parent, bool is_v2)
: parent_(parent), is_v2_(is_v2) {}
Status StreamAggregatedResources(ServerContext* context,
Stream* stream) override {
gpr_log(GPR_INFO, "ADS[%p]: StreamAggregatedResources starts", this);
parent_->AddClient(context->peer());
if (is_v2_) {
parent_->seen_v2_client_ = true;
} else {
parent_->seen_v3_client_ = true;
}
// Take a reference of the AdsServiceImpl object, which will go
// out of scope when this request handler returns. This ensures
// that the parent won't be destroyed until this stream is complete.
std::shared_ptr<AdsServiceImpl> ads_service_impl =
parent_->shared_from_this();
// Resources (type/name pairs) that have changed since the client
// subscribed to them.
UpdateQueue update_queue;
// Resources that the client will be subscribed to keyed by resource type
// url.
SubscriptionMap subscription_map;
// Sent state for each resource type.
std::map<std::string /*type_url*/, SentState> sent_state_map;
// Spawn a thread to read requests from the stream.
// Requests will be delivered to this thread in a queue.
std::deque<DiscoveryRequest> requests;
bool stream_closed = false;
std::thread reader(std::bind(&RpcService::BlockingRead, this, stream,
&requests, &stream_closed));
// Main loop to process requests and updates.
while (true) {
// Boolean to keep track if the loop received any work to do: a
// request or an update; regardless whether a response was actually
// sent out.
bool did_work = false;
// Look for new requests and and decide what to handle.
absl::optional<DiscoveryResponse> response;
{
grpc_core::MutexLock lock(&parent_->ads_mu_);
// If the stream has been closed or our parent is being shut
// down, stop immediately.
if (stream_closed || parent_->ads_done_) break;
// Otherwise, see if there's a request to read from the queue.
if (!requests.empty()) {
DiscoveryRequest request = std::move(requests.front());
requests.pop_front();
did_work = true;
gpr_log(GPR_INFO,
"ADS[%p]: Received request for type %s with content %s",
this, request.type_url().c_str(),
request.DebugString().c_str());
const std::string v3_resource_type =
TypeUrlToV3(request.type_url());
SentState& sent_state = sent_state_map[v3_resource_type];
// Process request.
ProcessRequest(request, v3_resource_type, &update_queue,
&subscription_map, &sent_state, &response);
}
}
if (response.has_value()) {
gpr_log(GPR_INFO, "ADS[%p]: Sending response: %s", this,
response->DebugString().c_str());
stream->Write(response.value());
}
response.reset();
// Look for updates and decide what to handle.
{
grpc_core::MutexLock lock(&parent_->ads_mu_);
if (!update_queue.empty()) {
const std::string resource_type =
std::move(update_queue.front().first);
const std::string resource_name =
std::move(update_queue.front().second);
update_queue.pop_front();
did_work = true;
SentState& sent_state = sent_state_map[resource_type];
ProcessUpdate(resource_type, resource_name, &subscription_map,
&sent_state, &response);
}
}
if (response.has_value()) {
gpr_log(GPR_INFO, "ADS[%p]: Sending update response: %s", this,
response->DebugString().c_str());
stream->Write(response.value());
}
// If we didn't find anything to do, delay before the next loop
// iteration; otherwise, check whether we should exit and then
// immediately continue.
gpr_timespec deadline =
grpc_timeout_milliseconds_to_deadline(did_work ? 0 : 10);
{
grpc_core::MutexLock lock(&parent_->ads_mu_);
if (!grpc_core::WaitUntilWithDeadline(
&parent_->ads_cond_, &parent_->ads_mu_,
[this] { return parent_->ads_done_; },
grpc_core::ToAbslTime(deadline))) {
break;
}
}
}
// Done with main loop. Clean up before returning.
// Join reader thread.
reader.join();
// Clean up any subscriptions that were still active when the call
// finished.
{
grpc_core::MutexLock lock(&parent_->ads_mu_);
for (auto& p : subscription_map) {
const std::string& type_url = p.first;
SubscriptionNameMap& subscription_name_map = p.second;
for (auto& q : subscription_name_map) {
const std::string& resource_name = q.first;
SubscriptionState& subscription_state = q.second;
ResourceNameMap& resource_name_map =
parent_->resource_map_[type_url].resource_name_map;
ResourceState& resource_state = resource_name_map[resource_name];
resource_state.subscriptions.erase(&subscription_state);
}
}
}
gpr_log(GPR_INFO, "ADS[%p]: StreamAggregatedResources done", this);
parent_->RemoveClient(context->peer());
return Status::OK;
}
private:
// Processes a response read from the client.
// Populates response if needed.
void ProcessRequest(const DiscoveryRequest& request,
const std::string& v3_resource_type,
UpdateQueue* update_queue,
SubscriptionMap* subscription_map,
SentState* sent_state,
absl::optional<DiscoveryResponse>* response) {
// Check the nonce sent by the client, if any.
// (This will be absent on the first request on a stream.)
if (request.response_nonce().empty()) {
int client_resource_type_version = 0;
if (!request.version_info().empty()) {
GPR_ASSERT(absl::SimpleAtoi(request.version_info(),
&client_resource_type_version));
}
EXPECT_GE(client_resource_type_version,
parent_->resource_type_min_versions_[v3_resource_type])
<< "resource_type: " << v3_resource_type;
} else {
int client_nonce;
GPR_ASSERT(absl::SimpleAtoi(request.response_nonce(), &client_nonce));
// Ignore requests with stale nonces.
if (client_nonce < sent_state->nonce) return;
// Check for ACK or NACK.
auto it = parent_->resource_type_response_state_.find(v3_resource_type);
if (it != parent_->resource_type_response_state_.end()) {
if (!request.has_error_detail()) {
it->second.state = ResponseState::ACKED;
it->second.error_message.clear();
gpr_log(GPR_INFO,
"ADS[%p]: client ACKed resource_type=%s version=%s", this,
request.type_url().c_str(), request.version_info().c_str());
} else {
it->second.state = ResponseState::NACKED;
EXPECT_EQ(request.error_detail().code(),
GRPC_STATUS_INVALID_ARGUMENT);
it->second.error_message = request.error_detail().message();
gpr_log(GPR_INFO,
"ADS[%p]: client NACKed resource_type=%s version=%s: %s",
this, request.type_url().c_str(),
request.version_info().c_str(),
it->second.error_message.c_str());
}
}
}
// Ignore resource types as requested by tests.
if (parent_->resource_types_to_ignore_.find(v3_resource_type) !=
parent_->resource_types_to_ignore_.end()) {
return;
}
// Look at all the resource names in the request.
auto& subscription_name_map = (*subscription_map)[v3_resource_type];
auto& resource_type_state = parent_->resource_map_[v3_resource_type];
auto& resource_name_map = resource_type_state.resource_name_map;
std::set<std::string> resources_in_current_request;
std::set<std::string> resources_added_to_response;
for (const std::string& resource_name : request.resource_names()) {
resources_in_current_request.emplace(resource_name);
auto& subscription_state = subscription_name_map[resource_name];
auto& resource_state = resource_name_map[resource_name];
// Subscribe if needed.
// Send the resource in the response if either (a) this is
// a new subscription or (b) there is an updated version of
// this resource to send.
if (parent_->MaybeSubscribe(v3_resource_type, resource_name,
&subscription_state, &resource_state,
update_queue) ||
ClientNeedsResourceUpdate(resource_type_state, resource_state,
sent_state->resource_type_version)) {
gpr_log(GPR_INFO, "ADS[%p]: Sending update for type=%s name=%s", this,
request.type_url().c_str(), resource_name.c_str());
resources_added_to_response.emplace(resource_name);
if (!response->has_value()) response->emplace();
if (resource_state.resource.has_value()) {
auto* resource = (*response)->add_resources();
resource->CopyFrom(resource_state.resource.value());
if (is_v2_) {
resource->set_type_url(request.type_url());
}
}
} else {
gpr_log(GPR_INFO,
"ADS[%p]: client does not need update for type=%s name=%s",
this, request.type_url().c_str(), resource_name.c_str());
}
}
// Process unsubscriptions for any resource no longer
// present in the request's resource list.
parent_->ProcessUnsubscriptions(
v3_resource_type, resources_in_current_request,
&subscription_name_map, &resource_name_map);
// Construct response if needed.
if (!resources_added_to_response.empty()) {
CompleteBuildingDiscoveryResponse(
v3_resource_type, request.type_url(),
resource_type_state.resource_type_version, subscription_name_map,
resources_added_to_response, sent_state, &response->value());
}
}
// Processes a resource update from the test.
// Populates response if needed.
void ProcessUpdate(const std::string& resource_type,
const std::string& resource_name,
SubscriptionMap* subscription_map, SentState* sent_state,
absl::optional<DiscoveryResponse>* response) {
const std::string v2_resource_type = TypeUrlToV2(resource_type);
gpr_log(GPR_INFO, "ADS[%p]: Received update for type=%s name=%s", this,
resource_type.c_str(), resource_name.c_str());
auto& subscription_name_map = (*subscription_map)[resource_type];
auto& resource_type_state = parent_->resource_map_[resource_type];
auto& resource_name_map = resource_type_state.resource_name_map;
auto it = subscription_name_map.find(resource_name);
if (it != subscription_name_map.end()) {
ResourceState& resource_state = resource_name_map[resource_name];
if (ClientNeedsResourceUpdate(resource_type_state, resource_state,
sent_state->resource_type_version)) {
gpr_log(GPR_INFO, "ADS[%p]: Sending update for type=%s name=%s", this,
resource_type.c_str(), resource_name.c_str());
response->emplace();
if (resource_state.resource.has_value()) {
auto* resource = (*response)->add_resources();
resource->CopyFrom(resource_state.resource.value());
if (is_v2_) {
resource->set_type_url(v2_resource_type);
}
}
CompleteBuildingDiscoveryResponse(
resource_type, v2_resource_type,
resource_type_state.resource_type_version, subscription_name_map,
{resource_name}, sent_state, &response->value());
}
}
}
// Starting a thread to do blocking read on the stream until cancel.
void BlockingRead(Stream* stream, std::deque<DiscoveryRequest>* requests,
bool* stream_closed) {
DiscoveryRequest request;
bool seen_first_request = false;
while (stream->Read(&request)) {
if (!seen_first_request) {
EXPECT_TRUE(request.has_node());
ASSERT_FALSE(request.node().client_features().empty());
EXPECT_EQ(request.node().client_features(0),
"envoy.lb.does_not_support_overprovisioning");
CheckBuildVersion(request);
seen_first_request = true;
}
{
grpc_core::MutexLock lock(&parent_->ads_mu_);
requests->emplace_back(std::move(request));
}
}
gpr_log(GPR_INFO, "ADS[%p]: Null read, stream closed", this);
grpc_core::MutexLock lock(&parent_->ads_mu_);
*stream_closed = true;
}
// Completing the building a DiscoveryResponse by adding common information
// for all resources and by adding all subscribed resources for LDS and CDS.
void CompleteBuildingDiscoveryResponse(
const std::string& resource_type, const std::string& v2_resource_type,
const int version, const SubscriptionNameMap& subscription_name_map,
const std::set<std::string>& resources_added_to_response,
SentState* sent_state, DiscoveryResponse* response) {
auto& response_state =
parent_->resource_type_response_state_[resource_type];
if (response_state.state == ResponseState::NOT_SENT) {
response_state.state = ResponseState::SENT;
}
response->set_type_url(is_v2_ ? v2_resource_type : resource_type);
response->set_version_info(std::to_string(version));
response->set_nonce(std::to_string(++sent_state->nonce));
if (resource_type == kLdsTypeUrl || resource_type == kCdsTypeUrl) {
// For LDS and CDS we must send back all subscribed resources
// (even the unchanged ones)
for (const auto& p : subscription_name_map) {
const std::string& resource_name = p.first;
if (resources_added_to_response.find(resource_name) ==
resources_added_to_response.end()) {
ResourceNameMap& resource_name_map =
parent_->resource_map_[resource_type].resource_name_map;
const ResourceState& resource_state =
resource_name_map[resource_name];
if (resource_state.resource.has_value()) {
auto* resource = response->add_resources();
resource->CopyFrom(resource_state.resource.value());
if (is_v2_) {
resource->set_type_url(v2_resource_type);
}
}
}
}
}
sent_state->resource_type_version = version;
}
static std::string TypeUrlToV2(const std::string& resource_type) {
if (resource_type == kLdsTypeUrl) return kLdsV2TypeUrl;
if (resource_type == kRdsTypeUrl) return kRdsV2TypeUrl;
if (resource_type == kCdsTypeUrl) return kCdsV2TypeUrl;
if (resource_type == kEdsTypeUrl) return kEdsV2TypeUrl;
return resource_type;
}
static std::string TypeUrlToV3(const std::string& resource_type) {
if (resource_type == kLdsV2TypeUrl) return kLdsTypeUrl;
if (resource_type == kRdsV2TypeUrl) return kRdsTypeUrl;
if (resource_type == kCdsV2TypeUrl) return kCdsTypeUrl;
if (resource_type == kEdsV2TypeUrl) return kEdsTypeUrl;
return resource_type;
}
static void CheckBuildVersion(
const ::envoy::api::v2::DiscoveryRequest& request) {
EXPECT_FALSE(request.node().build_version().empty());
}
static void CheckBuildVersion(
const ::envoy::service::discovery::v3::DiscoveryRequest& /*request*/) {}
AdsServiceImpl* parent_;
const bool is_v2_;
};
// Checks whether the client needs to receive a newer version of
// the resource.
static bool ClientNeedsResourceUpdate(
const ResourceTypeState& resource_type_state,
const ResourceState& resource_state, int client_resource_type_version) {
return client_resource_type_version <
resource_type_state.resource_type_version &&
resource_state.resource_type_version <=
resource_type_state.resource_type_version;
}
// Subscribes to a resource if not already subscribed:
// 1. Sets the update_queue field in subscription_state.
// 2. Adds subscription_state to resource_state->subscriptions.
bool MaybeSubscribe(const std::string& resource_type,
const std::string& resource_name,
SubscriptionState* subscription_state,
ResourceState* resource_state,
UpdateQueue* update_queue) {
// The update_queue will be null if we were not previously subscribed.
if (subscription_state->update_queue != nullptr) return false;
subscription_state->update_queue = update_queue;
resource_state->subscriptions.emplace(subscription_state);
gpr_log(GPR_INFO, "ADS[%p]: subscribe to resource type %s name %s state %p",
this, resource_type.c_str(), resource_name.c_str(),
&subscription_state);
return true;
}
// Removes subscriptions for resources no longer present in the
// current request.
void ProcessUnsubscriptions(
const std::string& resource_type,
const std::set<std::string>& resources_in_current_request,
SubscriptionNameMap* subscription_name_map,
ResourceNameMap* resource_name_map) {
for (auto it = subscription_name_map->begin();
it != subscription_name_map->end();) {
const std::string& resource_name = it->first;
SubscriptionState& subscription_state = it->second;
if (resources_in_current_request.find(resource_name) !=
resources_in_current_request.end()) {
++it;
continue;
}
gpr_log(GPR_INFO, "ADS[%p]: Unsubscribe to type=%s name=%s state=%p",
this, resource_type.c_str(), resource_name.c_str(),
&subscription_state);
auto resource_it = resource_name_map->find(resource_name);
GPR_ASSERT(resource_it != resource_name_map->end());
auto& resource_state = resource_it->second;
resource_state.subscriptions.erase(&subscription_state);
if (resource_state.subscriptions.empty() &&
!resource_state.resource.has_value()) {
resource_name_map->erase(resource_it);
}
it = subscription_name_map->erase(it);
}
}
void AddClient(const std::string& client) {
grpc_core::MutexLock lock(&clients_mu_);
clients_.insert(client);
}
void RemoveClient(const std::string& client) {
grpc_core::MutexLock lock(&clients_mu_);
clients_.erase(client);
}
RpcService<::envoy::service::discovery::v2::AggregatedDiscoveryService,
::envoy::api::v2::DiscoveryRequest,
::envoy::api::v2::DiscoveryResponse>
v2_rpc_service_;
RpcService<::envoy::service::discovery::v3::AggregatedDiscoveryService,
::envoy::service::discovery::v3::DiscoveryRequest,
::envoy::service::discovery::v3::DiscoveryResponse>
v3_rpc_service_;
std::atomic_bool seen_v2_client_{false};
std::atomic_bool seen_v3_client_{false};
grpc_core::CondVar ads_cond_;
// Protect the members below.
grpc_core::Mutex ads_mu_;
bool ads_done_ = false;
std::map<std::string /* type_url */, ResponseState>
resource_type_response_state_;
std::set<std::string /*resource_type*/> resource_types_to_ignore_;
std::map<std::string /*resource_type*/, int> resource_type_min_versions_;
// An instance data member containing the current state of all resources.
// Note that an entry will exist whenever either of the following is true:
// - The resource exists (i.e., has been created by SetResource() and has not
// yet been destroyed by UnsetResource()).
// - There is at least one subscription for the resource.
ResourceMap resource_map_;
grpc_core::Mutex clients_mu_;
std::set<std::string> clients_;
};
class LrsServiceImpl : public std::enable_shared_from_this<LrsServiceImpl> {
public:
explicit LrsServiceImpl(int client_load_reporting_interval_seconds)
: v2_rpc_service_(this),
v3_rpc_service_(this),
client_load_reporting_interval_seconds_(
client_load_reporting_interval_seconds),
cluster_names_({kDefaultClusterName}) {}
::envoy::service::load_stats::v2::LoadReportingService::Service*
v2_rpc_service() {
return &v2_rpc_service_;
}
::envoy::service::load_stats::v3::LoadReportingService::Service*
v3_rpc_service() {
return &v3_rpc_service_;
}
size_t request_count() {
return v2_rpc_service_.request_count() + v3_rpc_service_.request_count();
}
size_t response_count() {
return v2_rpc_service_.response_count() + v3_rpc_service_.response_count();
}
// Must be called before the LRS call is started.
void set_send_all_clusters(bool send_all_clusters) {
send_all_clusters_ = send_all_clusters;
}
void set_cluster_names(const std::set<std::string>& cluster_names) {
cluster_names_ = cluster_names;
}
void Start() {
lrs_done_ = false;
result_queue_.clear();
}
void Shutdown() {
{
grpc_core::MutexLock lock(&lrs_mu_);
NotifyDoneWithLrsCallLocked();
}
gpr_log(GPR_INFO, "LRS[%p]: shut down", this);
}
std::vector<ClientStats> WaitForLoadReport() {
grpc_core::MutexLock lock(&load_report_mu_);
grpc_core::CondVar cv;
if (result_queue_.empty()) {
load_report_cond_ = &cv;
grpc_core::WaitUntil(load_report_cond_, &load_report_mu_,
[this] { return !result_queue_.empty(); });
load_report_cond_ = nullptr;
}
std::vector<ClientStats> result = std::move(result_queue_.front());
result_queue_.pop_front();
return result;
}
void NotifyDoneWithLrsCall() {
grpc_core::MutexLock lock(&lrs_mu_);
NotifyDoneWithLrsCallLocked();
}
private:
template <class RpcApi, class LoadStatsRequest, class LoadStatsResponse>
class RpcService : public CountedService<typename RpcApi::Service> {
public:
using Stream = ServerReaderWriter<LoadStatsResponse, LoadStatsRequest>;
explicit RpcService(LrsServiceImpl* parent) : parent_(parent) {}
Status StreamLoadStats(ServerContext* /*context*/,
Stream* stream) override {
gpr_log(GPR_INFO, "LRS[%p]: StreamLoadStats starts", this);
EXPECT_GT(parent_->client_load_reporting_interval_seconds_, 0);
// Take a reference of the LrsServiceImpl object, reference will go
// out of scope after this method exits.
std::shared_ptr<LrsServiceImpl> lrs_service_impl =
parent_->shared_from_this();
// Read initial request.
LoadStatsRequest request;
if (stream->Read(&request)) {
CountedService<typename RpcApi::Service>::IncreaseRequestCount();
// Verify client features.
EXPECT_THAT(
request.node().client_features(),
::testing::Contains("envoy.lrs.supports_send_all_clusters"));
// Send initial response.
LoadStatsResponse response;
if (parent_->send_all_clusters_) {
response.set_send_all_clusters(true);
} else {
for (const std::string& cluster_name : parent_->cluster_names_) {
response.add_clusters(cluster_name);
}
}
response.mutable_load_reporting_interval()->set_seconds(
parent_->client_load_reporting_interval_seconds_);
stream->Write(response);
CountedService<typename RpcApi::Service>::IncreaseResponseCount();
// Wait for report.
request.Clear();
while (stream->Read(&request)) {
gpr_log(GPR_INFO, "LRS[%p]: received client load report message: %s",
this, request.DebugString().c_str());
std::vector<ClientStats> stats;
for (const auto& cluster_stats : request.cluster_stats()) {
stats.emplace_back(cluster_stats);
}
grpc_core::MutexLock lock(&parent_->load_report_mu_);
parent_->result_queue_.emplace_back(std::move(stats));
if (parent_->load_report_cond_ != nullptr) {
parent_->load_report_cond_->Signal();
}
}
// Wait until notified done.
grpc_core::MutexLock lock(&parent_->lrs_mu_);
grpc_core::WaitUntil(&parent_->lrs_cv_, &parent_->lrs_mu_,
[this] { return parent_->lrs_done_; });
}
gpr_log(GPR_INFO, "LRS[%p]: StreamLoadStats done", this);
return Status::OK;
}
private:
LrsServiceImpl* parent_;
};
void NotifyDoneWithLrsCallLocked() {
if (!lrs_done_) {
lrs_done_ = true;
lrs_cv_.SignalAll();
}
}
RpcService<::envoy::service::load_stats::v2::LoadReportingService,
::envoy::service::load_stats::v2::LoadStatsRequest,
::envoy::service::load_stats::v2::LoadStatsResponse>
v2_rpc_service_;
RpcService<::envoy::service::load_stats::v3::LoadReportingService,
::envoy::service::load_stats::v3::LoadStatsRequest,
::envoy::service::load_stats::v3::LoadStatsResponse>
v3_rpc_service_;
const int client_load_reporting_interval_seconds_;
bool send_all_clusters_ = false;
std::set<std::string> cluster_names_;
grpc_core::CondVar lrs_cv_;
grpc_core::Mutex lrs_mu_; // Protects lrs_done_.
bool lrs_done_ = false;
grpc_core::Mutex load_report_mu_; // Protects the members below.
grpc_core::CondVar* load_report_cond_ = nullptr;
std::deque<std::vector<ClientStats>> result_queue_;
};
class TestType {
public:
enum FilterConfigSetup {
// Set the fault injection filter directly from LDS
kHTTPConnectionManagerOriginal,
// Enable the fault injection filter in LDS, but override the filter config
// in route.
kRouteOverride,
};
TestType& set_use_fake_resolver() {
use_fake_resolver_ = true;
return *this;
}
TestType& set_enable_load_reporting() {
enable_load_reporting_ = true;
return *this;
}
TestType& set_enable_rds_testing() {
enable_rds_testing_ = true;
return *this;
}
TestType& set_use_v2() {
use_v2_ = true;
return *this;
}
TestType& set_use_xds_credentials() {
use_xds_credentials_ = true;
return *this;
}
TestType& set_use_csds_streaming() {
use_csds_streaming_ = true;
return *this;
}
TestType& set_filter_config_setup(const FilterConfigSetup& setup) {
filter_config_setup_ = setup;
return *this;
}
bool use_fake_resolver() const { return use_fake_resolver_; }
bool enable_load_reporting() const { return enable_load_reporting_; }
bool enable_rds_testing() const { return enable_rds_testing_; }
bool use_v2() const { return use_v2_; }
bool use_xds_credentials() const { return use_xds_credentials_; }
bool use_csds_streaming() const { return use_csds_streaming_; }
const FilterConfigSetup& filter_config_setup() const {
return filter_config_setup_;
}
std::string AsString() const {
std::string retval = (use_fake_resolver_ ? "FakeResolver" : "XdsResolver");
retval += (use_v2_ ? "V2" : "V3");
if (enable_load_reporting_) retval += "WithLoadReporting";
if (enable_rds_testing_) retval += "Rds";
if (use_xds_credentials_) retval += "XdsCreds";
if (use_csds_streaming_) retval += "CsdsStreaming";
if (filter_config_setup_ == kRouteOverride) {
retval += "FilterPerRouteOverride";
}
return retval;
}
private:
bool use_fake_resolver_ = false;
bool enable_load_reporting_ = false;
bool enable_rds_testing_ = false;
bool use_v2_ = false;
bool use_xds_credentials_ = false;
bool use_csds_streaming_ = false;
FilterConfigSetup filter_config_setup_ = kHTTPConnectionManagerOriginal;
};
std::string ReadFile(const char* file_path) {
grpc_slice slice;
GPR_ASSERT(
GRPC_LOG_IF_ERROR("load_file", grpc_load_file(file_path, 0, &slice)));
std::string file_contents(grpc_core::StringViewFromSlice(slice));
grpc_slice_unref(slice);
return file_contents;
}
grpc_core::PemKeyCertPairList ReadTlsIdentityPair(const char* key_path,
const char* cert_path) {
return grpc_core::PemKeyCertPairList{
grpc_core::PemKeyCertPair(ReadFile(key_path), ReadFile(cert_path))};
}
// Based on StaticDataCertificateProvider, but provides alternate certificates
// if the certificate name is not empty.
class FakeCertificateProvider final : public grpc_tls_certificate_provider {
public:
struct CertData {
std::string root_certificate;
grpc_core::PemKeyCertPairList identity_key_cert_pairs;
};
using CertDataMap = std::map<std::string /*cert_name */, CertData>;
explicit FakeCertificateProvider(CertDataMap cert_data_map)
: distributor_(
grpc_core::MakeRefCounted<grpc_tls_certificate_distributor>()),
cert_data_map_(std::move(cert_data_map)) {
distributor_->SetWatchStatusCallback([this](std::string cert_name,
bool root_being_watched,
bool identity_being_watched) {
if (!root_being_watched && !identity_being_watched) return;
auto it = cert_data_map_.find(cert_name);
if (it == cert_data_map_.end()) {
grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("No certificates available for cert_name \"",
cert_name, "\"")
.c_str());
distributor_->SetErrorForCert(cert_name, GRPC_ERROR_REF(error),
GRPC_ERROR_REF(error));
GRPC_ERROR_UNREF(error);
} else {
absl::optional<std::string> root_certificate;
absl::optional<grpc_core::PemKeyCertPairList> pem_key_cert_pairs;
if (root_being_watched) {
root_certificate = it->second.root_certificate;
}
if (identity_being_watched) {
pem_key_cert_pairs = it->second.identity_key_cert_pairs;
}
distributor_->SetKeyMaterials(cert_name, std::move(root_certificate),
std::move(pem_key_cert_pairs));
}
});
}
~FakeCertificateProvider() override {
distributor_->SetWatchStatusCallback(nullptr);
}
grpc_core::RefCountedPtr<grpc_tls_certificate_distributor> distributor()
const override {
return distributor_;
}
private:
grpc_core::RefCountedPtr<grpc_tls_certificate_distributor> distributor_;
CertDataMap cert_data_map_;
};
class FakeCertificateProviderFactory
: public grpc_core::CertificateProviderFactory {
public:
class Config : public grpc_core::CertificateProviderFactory::Config {
public:
explicit Config(const char* name) : name_(name) {}
const char* name() const override { return name_; }
std::string ToString() const override { return "{}"; }
private:
const char* name_;
};
FakeCertificateProviderFactory(
const char* name, FakeCertificateProvider::CertDataMap** cert_data_map)
: name_(name), cert_data_map_(cert_data_map) {
GPR_ASSERT(cert_data_map != nullptr);
}
const char* name() const override { return name_; }
grpc_core::RefCountedPtr<grpc_core::CertificateProviderFactory::Config>
CreateCertificateProviderConfig(const grpc_core::Json& /*config_json*/,
grpc_error** /*error*/) override {
return grpc_core::MakeRefCounted<Config>(name_);
}
grpc_core::RefCountedPtr<grpc_tls_certificate_provider>
CreateCertificateProvider(
grpc_core::RefCountedPtr<grpc_core::CertificateProviderFactory::Config>
/*config*/) override {
if (*cert_data_map_ == nullptr) return nullptr;
return grpc_core::MakeRefCounted<FakeCertificateProvider>(**cert_data_map_);
}
private:
const char* name_;
FakeCertificateProvider::CertDataMap** cert_data_map_;
};
// Global variables for each provider.
FakeCertificateProvider::CertDataMap* g_fake1_cert_data_map = nullptr;
FakeCertificateProvider::CertDataMap* g_fake2_cert_data_map = nullptr;
int ServerAuthCheckSchedule(void* /* config_user_data */,
grpc_tls_server_authorization_check_arg* arg) {
arg->success = 1;
arg->status = GRPC_STATUS_OK;
return 0; /* synchronous check */
}
std::shared_ptr<ChannelCredentials> CreateTlsFallbackCredentials() {
// TODO(yashykt): Switch to using C++ API once b/173823806 is fixed.
grpc_tls_credentials_options* options = grpc_tls_credentials_options_create();
grpc_tls_credentials_options_set_server_verification_option(
options, GRPC_TLS_SKIP_HOSTNAME_VERIFICATION);
grpc_tls_credentials_options_set_certificate_provider(
options,
grpc_core::MakeRefCounted<grpc_core::StaticDataCertificateProvider>(
ReadFile(kCaCertPath),
ReadTlsIdentityPair(kServerKeyPath, kServerCertPath))
.get());
grpc_tls_credentials_options_watch_root_certs(options);
grpc_tls_credentials_options_watch_identity_key_cert_pairs(options);
grpc_tls_server_authorization_check_config* check_config =
grpc_tls_server_authorization_check_config_create(
nullptr, ServerAuthCheckSchedule, nullptr, nullptr);
grpc_tls_credentials_options_set_server_authorization_check_config(
options, check_config);
auto channel_creds = std::make_shared<SecureChannelCredentials>(
grpc_tls_credentials_create(options));
grpc_tls_server_authorization_check_config_release(check_config);
return channel_creds;
}
// A No-op HTTP filter used for verifying parsing logic.
class NoOpHttpFilter : public grpc_core::XdsHttpFilterImpl {
public:
NoOpHttpFilter(std::string name, bool supported_on_clients,
bool supported_on_servers)
: name_(std::move(name)),
supported_on_clients_(supported_on_clients),
supported_on_servers_(supported_on_servers) {}
void PopulateSymtab(upb_symtab* /* symtab */) const override {}
absl::StatusOr<grpc_core::XdsHttpFilterImpl::FilterConfig>
GenerateFilterConfig(upb_strview /* serialized_filter_config */,
upb_arena* /* arena */) const override {
return grpc_core::XdsHttpFilterImpl::FilterConfig{name_, grpc_core::Json()};
}
absl::StatusOr<grpc_core::XdsHttpFilterImpl::FilterConfig>
GenerateFilterConfigOverride(upb_strview /*serialized_filter_config*/,
upb_arena* /*arena*/) const override {
return grpc_core::XdsHttpFilterImpl::FilterConfig{name_, grpc_core::Json()};
}
const grpc_channel_filter* channel_filter() const override { return nullptr; }
absl::StatusOr<grpc_core::XdsHttpFilterImpl::ServiceConfigJsonEntry>
GenerateServiceConfig(
const FilterConfig& /*hcm_filter_config*/,
const FilterConfig* /*filter_config_override*/) const override {
return grpc_core::XdsHttpFilterImpl::ServiceConfigJsonEntry{name_, ""};
}
bool IsSupportedOnClients() const override { return supported_on_clients_; }
bool IsSupportedOnServers() const override { return supported_on_servers_; }
private:
const std::string name_;
const bool supported_on_clients_;
const bool supported_on_servers_;
};
namespace {
void* response_generator_arg_copy(void* p) {
auto* generator = static_cast<grpc_core::FakeResolverResponseGenerator*>(p);
generator->Ref().release();
return p;
}
void response_generator_arg_destroy(void* p) {
auto* generator = static_cast<grpc_core::FakeResolverResponseGenerator*>(p);
generator->Unref();
}
int response_generator_cmp(void* a, void* b) { return GPR_ICMP(a, b); }
const grpc_arg_pointer_vtable
kLogicalDnsClusterResolverResponseGeneratorVtable = {
response_generator_arg_copy, response_generator_arg_destroy,
response_generator_cmp};
// There is slight difference between time fetched by GPR and by C++ system
// clock API. It's unclear if they are using the same syscall, but we do know
// GPR round the number at millisecond-level. This creates a 1ms difference,
// which could cause flake.
grpc_millis NowFromCycleCounter() {
gpr_cycle_counter now = gpr_get_cycle_counter();
return grpc_cycle_counter_to_millis_round_up(now);
}
} // namespace
class XdsEnd2endTest : public ::testing::TestWithParam<TestType> {
protected:
// TODO(roth): We currently set the number of backends and number of
// balancers on a per-test-suite basis, not a per-test-case basis.
// However, not every individual test case in a given test suite uses
// the same number of backends or balancers, so we wind up having to
// set the numbers for the test suite to the max number needed by any
// one test case in that test suite. This results in starting more
// servers (and using more ports) than we actually need. When we have
// time, change each test to directly start the number of backends and
// balancers that it needs, so that we aren't wasting resources.
XdsEnd2endTest(size_t num_backends, size_t num_balancers,
int client_load_reporting_interval_seconds = 100,
bool use_xds_enabled_server = false,
bool bootstrap_contents_from_env_var = false)
: num_backends_(num_backends),
num_balancers_(num_balancers),
client_load_reporting_interval_seconds_(
client_load_reporting_interval_seconds),
use_xds_enabled_server_(use_xds_enabled_server),
bootstrap_contents_from_env_var_(bootstrap_contents_from_env_var) {}
void SetUp() override {
if (bootstrap_contents_from_env_var_) {
gpr_setenv("GRPC_XDS_BOOTSTRAP_CONFIG",
GetParam().use_v2() ? kBootstrapFileV2 : kBootstrapFileV3);
} else {
gpr_setenv("GRPC_XDS_BOOTSTRAP", GetParam().use_v2()
? g_bootstrap_file_v2
: g_bootstrap_file_v3);
}
bool localhost_resolves_to_ipv4 = false;
bool localhost_resolves_to_ipv6 = false;
grpc_core::LocalhostResolves(&localhost_resolves_to_ipv4,
&localhost_resolves_to_ipv6);
ipv6_only_ = !localhost_resolves_to_ipv4 && localhost_resolves_to_ipv6;
// Initialize default xDS resources.
// Construct LDS resource.
default_listener_.set_name(kServerName);
HttpConnectionManager http_connection_manager;
if (!GetParam().use_v2()) {
auto* filter = http_connection_manager.add_http_filters();
filter->set_name("router");
filter->mutable_typed_config()->PackFrom(
envoy::extensions::filters::http::router::v3::Router());
}
default_listener_.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
// Construct RDS resource.
default_route_config_.set_name(kDefaultRouteConfigurationName);
auto* virtual_host = default_route_config_.add_virtual_hosts();
virtual_host->add_domains("*");
auto* route = virtual_host->add_routes();
route->mutable_match()->set_prefix("");
route->mutable_route()->set_cluster(kDefaultClusterName);
// Construct CDS resource.
default_cluster_.set_name(kDefaultClusterName);
default_cluster_.set_type(Cluster::EDS);
auto* eds_config = default_cluster_.mutable_eds_cluster_config();
eds_config->mutable_eds_config()->mutable_ads();
eds_config->set_service_name(kDefaultEdsServiceName);
default_cluster_.set_lb_policy(Cluster::ROUND_ROBIN);
if (GetParam().enable_load_reporting()) {
default_cluster_.mutable_lrs_server()->mutable_self();
}
// Start the load balancers.
for (size_t i = 0; i < num_balancers_; ++i) {
balancers_.emplace_back(
new BalancerServerThread(GetParam().enable_load_reporting()
? client_load_reporting_interval_seconds_
: 0));
balancers_.back()->Start();
// Initialize resources.
SetListenerAndRouteConfiguration(i, default_listener_,
default_route_config_);
balancers_.back()->ads_service()->SetCdsResource(default_cluster_);
}
// Initialize XdsClient state.
response_generator_ =
grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
// Inject xDS channel response generator.
lb_channel_response_generator_ =
grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
xds_channel_args_to_add_.emplace_back(
grpc_core::FakeResolverResponseGenerator::MakeChannelArg(
lb_channel_response_generator_.get()));
// Inject xDS logical cluster resolver response generator.
logical_dns_cluster_resolver_response_generator_ =
grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
if (xds_resource_does_not_exist_timeout_ms_ > 0) {
xds_channel_args_to_add_.emplace_back(grpc_channel_arg_integer_create(
const_cast<char*>(GRPC_ARG_XDS_RESOURCE_DOES_NOT_EXIST_TIMEOUT_MS),
xds_resource_does_not_exist_timeout_ms_));
}
xds_channel_args_.num_args = xds_channel_args_to_add_.size();
xds_channel_args_.args = xds_channel_args_to_add_.data();
grpc_core::internal::SetXdsChannelArgsForTest(&xds_channel_args_);
// Make sure each test creates a new XdsClient instance rather than
// reusing the one from the previous test. This avoids spurious failures
// caused when a load reporting test runs after a non-load reporting test
// and the XdsClient is still talking to the old LRS server, which fails
// because it's not expecting the client to connect. It also
// ensures that each test can independently set the global channel
// args for the xDS channel.
grpc_core::internal::UnsetGlobalXdsClientForTest();
// Start the backends.
for (size_t i = 0; i < num_backends_; ++i) {
backends_.emplace_back(new BackendServerThread(use_xds_enabled_server_));
backends_.back()->Start();
}
// Create channel and stub.
ResetStub();
}
const char* DefaultEdsServiceName() const {
return GetParam().use_fake_resolver() ? kServerName
: kDefaultEdsServiceName;
}
void TearDown() override {
ShutdownAllBackends();
for (auto& balancer : balancers_) balancer->Shutdown();
// Clear global xDS channel args, since they will go out of scope
// when this test object is destroyed.
grpc_core::internal::SetXdsChannelArgsForTest(nullptr);
gpr_unsetenv("GRPC_XDS_BOOTSTRAP");
gpr_unsetenv("GRPC_XDS_BOOTSTRAP_CONFIG");
}
void StartAllBackends() {
for (auto& backend : backends_) backend->Start();
}
void StartBackend(size_t index) { backends_[index]->Start(); }
void ShutdownAllBackends() {
for (auto& backend : backends_) backend->Shutdown();
}
void ShutdownBackend(size_t index) { backends_[index]->Shutdown(); }
void ResetStub(int failover_timeout = 0) {
channel_ = CreateChannel(failover_timeout);
stub_ = grpc::testing::EchoTestService::NewStub(channel_);
stub1_ = grpc::testing::EchoTest1Service::NewStub(channel_);
stub2_ = grpc::testing::EchoTest2Service::NewStub(channel_);
}
std::shared_ptr<Channel> CreateChannel(
int failover_timeout = 0, const char* server_name = kServerName,
grpc_core::FakeResolverResponseGenerator* response_generator = nullptr) {
ChannelArguments args;
if (failover_timeout > 0) {
args.SetInt(GRPC_ARG_PRIORITY_FAILOVER_TIMEOUT_MS, failover_timeout);
}
// If the parent channel is using the fake resolver, we inject the
// response generator here.
if (GetParam().use_fake_resolver()) {
if (response_generator == nullptr) {
response_generator = response_generator_.get();
}
args.SetPointer(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
response_generator);
}
args.SetPointerWithVtable(
GRPC_ARG_XDS_LOGICAL_DNS_CLUSTER_FAKE_RESOLVER_RESPONSE_GENERATOR,
logical_dns_cluster_resolver_response_generator_.get(),
&kLogicalDnsClusterResolverResponseGeneratorVtable);
std::string uri = absl::StrCat(
GetParam().use_fake_resolver() ? "fake" : "xds", ":///", server_name);
std::shared_ptr<ChannelCredentials> channel_creds =
GetParam().use_xds_credentials()
? experimental::XdsCredentials(CreateTlsFallbackCredentials())
: std::make_shared<SecureChannelCredentials>(
grpc_fake_transport_security_credentials_create());
return ::grpc::CreateCustomChannel(uri, channel_creds, args);
}
enum RpcService {
SERVICE_ECHO,
SERVICE_ECHO1,
SERVICE_ECHO2,
};
enum RpcMethod {
METHOD_ECHO,
METHOD_ECHO1,
METHOD_ECHO2,
};
struct RpcOptions {
RpcService service = SERVICE_ECHO;
RpcMethod method = METHOD_ECHO;
int timeout_ms = 1000;
bool wait_for_ready = false;
bool server_fail = false;
std::vector<std::pair<std::string, std::string>> metadata;
int client_cancel_after_us = 0;
bool skip_cancelled_check = false;
RpcOptions() {}
RpcOptions& set_rpc_service(RpcService rpc_service) {
service = rpc_service;
return *this;
}
RpcOptions& set_rpc_method(RpcMethod rpc_method) {
method = rpc_method;
return *this;
}
RpcOptions& set_timeout_ms(int rpc_timeout_ms) {
timeout_ms = rpc_timeout_ms;
return *this;
}
RpcOptions& set_wait_for_ready(bool rpc_wait_for_ready) {
wait_for_ready = rpc_wait_for_ready;
return *this;
}
RpcOptions& set_server_fail(bool rpc_server_fail) {
server_fail = rpc_server_fail;
return *this;
}
RpcOptions& set_skip_cancelled_check(bool rpc_skip_cancelled_check) {
skip_cancelled_check = rpc_skip_cancelled_check;
return *this;
}
RpcOptions& set_metadata(
std::vector<std::pair<std::string, std::string>> rpc_metadata) {
metadata = std::move(rpc_metadata);
return *this;
}
RpcOptions& set_client_cancel_after_us(int rpc_client_cancel_after_us) {
client_cancel_after_us = rpc_client_cancel_after_us;
return *this;
}
// Populates context and request.
void SetupRpc(ClientContext* context, EchoRequest* request) const {
for (const auto& item : metadata) {
context->AddMetadata(item.first, item.second);
}
if (timeout_ms != 0) {
context->set_deadline(
grpc_timeout_milliseconds_to_deadline(timeout_ms));
}
if (wait_for_ready) context->set_wait_for_ready(true);
request->set_message(kRequestMessage);
if (server_fail) {
request->mutable_param()->mutable_expected_error()->set_code(
GRPC_STATUS_FAILED_PRECONDITION);
}
if (client_cancel_after_us != 0) {
request->mutable_param()->set_client_cancel_after_us(
client_cancel_after_us);
}
if (skip_cancelled_check) {
request->mutable_param()->set_skip_cancelled_check(true);
}
}
};
template <typename Stub>
Status SendRpcMethod(Stub* stub, const RpcOptions& rpc_options,
ClientContext* context, EchoRequest& request,
EchoResponse* response) {
switch (rpc_options.method) {
case METHOD_ECHO:
return (*stub)->Echo(context, request, response);
case METHOD_ECHO1:
return (*stub)->Echo1(context, request, response);
case METHOD_ECHO2:
return (*stub)->Echo2(context, request, response);
}
GPR_UNREACHABLE_CODE();
}
void ResetBackendCounters(size_t start_index = 0, size_t stop_index = 0) {
if (stop_index == 0) stop_index = backends_.size();
for (size_t i = start_index; i < stop_index; ++i) {
backends_[i]->backend_service()->ResetCounters();
backends_[i]->backend_service1()->ResetCounters();
backends_[i]->backend_service2()->ResetCounters();
}
}
bool SeenAllBackends(size_t start_index = 0, size_t stop_index = 0,
const RpcOptions& rpc_options = RpcOptions()) {
if (stop_index == 0) stop_index = backends_.size();
for (size_t i = start_index; i < stop_index; ++i) {
switch (rpc_options.service) {
case SERVICE_ECHO:
if (backends_[i]->backend_service()->request_count() == 0) {
return false;
}
break;
case SERVICE_ECHO1:
if (backends_[i]->backend_service1()->request_count() == 0) {
return false;
}
break;
case SERVICE_ECHO2:
if (backends_[i]->backend_service2()->request_count() == 0) {
return false;
}
break;
}
}
return true;
}
void SendRpcAndCount(int* num_total, int* num_ok, int* num_failure,
int* num_drops,
const RpcOptions& rpc_options = RpcOptions(),
const char* drop_error_message =
"Call dropped by load balancing policy") {
const Status status = SendRpc(rpc_options);
if (status.ok()) {
++*num_ok;
} else {
if (status.error_message() == drop_error_message) {
++*num_drops;
} else {
++*num_failure;
}
}
++*num_total;
}
std::tuple<int, int, int> WaitForAllBackends(
size_t start_index = 0, size_t stop_index = 0, bool reset_counters = true,
const RpcOptions& rpc_options = RpcOptions(),
bool allow_failures = false) {
int num_ok = 0;
int num_failure = 0;
int num_drops = 0;
int num_total = 0;
while (!SeenAllBackends(start_index, stop_index, rpc_options)) {
SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_drops,
rpc_options);
}
if (reset_counters) ResetBackendCounters();
gpr_log(GPR_INFO,
"Performed %d warm up requests against the backends. "
"%d succeeded, %d failed, %d dropped.",
num_total, num_ok, num_failure, num_drops);
if (!allow_failures) EXPECT_EQ(num_failure, 0);
return std::make_tuple(num_ok, num_failure, num_drops);
}
void WaitForBackend(size_t backend_idx, bool reset_counters = true,
bool require_success = false) {
gpr_log(GPR_INFO, "========= WAITING FOR BACKEND %lu ==========",
static_cast<unsigned long>(backend_idx));
do {
Status status = SendRpc();
if (require_success) {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
}
} while (backends_[backend_idx]->backend_service()->request_count() == 0);
if (reset_counters) ResetBackendCounters();
gpr_log(GPR_INFO, "========= BACKEND %lu READY ==========",
static_cast<unsigned long>(backend_idx));
}
grpc_core::ServerAddressList CreateAddressListFromPortList(
const std::vector<int>& ports) {
grpc_core::ServerAddressList addresses;
for (int port : ports) {
absl::StatusOr<grpc_core::URI> lb_uri = grpc_core::URI::Parse(
absl::StrCat(ipv6_only_ ? "ipv6:[::1]:" : "ipv4:127.0.0.1:", port));
GPR_ASSERT(lb_uri.ok());
grpc_resolved_address address;
GPR_ASSERT(grpc_parse_uri(*lb_uri, &address));
addresses.emplace_back(address.addr, address.len, nullptr);
}
return addresses;
}
void SetNextResolution(
const std::vector<int>& ports,
grpc_core::FakeResolverResponseGenerator* response_generator = nullptr) {
if (!GetParam().use_fake_resolver()) return; // Not used with xds resolver.
grpc_core::ExecCtx exec_ctx;
grpc_core::Resolver::Result result;
result.addresses = CreateAddressListFromPortList(ports);
grpc_error* error = GRPC_ERROR_NONE;
const char* service_config_json =
GetParam().enable_load_reporting()
? kDefaultServiceConfig
: kDefaultServiceConfigWithoutLoadReporting;
result.service_config =
grpc_core::ServiceConfig::Create(nullptr, service_config_json, &error);
ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_string(error);
ASSERT_NE(result.service_config.get(), nullptr);
if (response_generator == nullptr) {
response_generator = response_generator_.get();
}
response_generator->SetResponse(std::move(result));
}
void SetNextResolutionForLbChannelAllBalancers(
const char* service_config_json = nullptr,
const char* expected_targets = nullptr) {
std::vector<int> ports;
for (size_t i = 0; i < balancers_.size(); ++i) {
ports.emplace_back(balancers_[i]->port());
}
SetNextResolutionForLbChannel(ports, service_config_json, expected_targets);
}
void SetNextResolutionForLbChannel(const std::vector<int>& ports,
const char* service_config_json = nullptr,
const char* expected_targets = nullptr) {
grpc_core::ExecCtx exec_ctx;
grpc_core::Resolver::Result result;
result.addresses = CreateAddressListFromPortList(ports);
if (service_config_json != nullptr) {
grpc_error* error = GRPC_ERROR_NONE;
result.service_config = grpc_core::ServiceConfig::Create(
nullptr, service_config_json, &error);
ASSERT_NE(result.service_config.get(), nullptr);
ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_string(error);
}
if (expected_targets != nullptr) {
grpc_arg expected_targets_arg = grpc_channel_arg_string_create(
const_cast<char*>(GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS),
const_cast<char*>(expected_targets));
result.args =
grpc_channel_args_copy_and_add(nullptr, &expected_targets_arg, 1);
}
lb_channel_response_generator_->SetResponse(std::move(result));
}
void SetNextReresolutionResponse(const std::vector<int>& ports) {
grpc_core::ExecCtx exec_ctx;
grpc_core::Resolver::Result result;
result.addresses = CreateAddressListFromPortList(ports);
response_generator_->SetReresolutionResponse(std::move(result));
}
std::vector<int> GetBackendPorts(size_t start_index = 0,
size_t stop_index = 0) const {
if (stop_index == 0) stop_index = backends_.size();
std::vector<int> backend_ports;
for (size_t i = start_index; i < stop_index; ++i) {
backend_ports.push_back(backends_[i]->port());
}
return backend_ports;
}
Status SendRpc(const RpcOptions& rpc_options = RpcOptions(),
EchoResponse* response = nullptr) {
const bool local_response = (response == nullptr);
if (local_response) response = new EchoResponse;
ClientContext context;
EchoRequest request;
rpc_options.SetupRpc(&context, &request);
Status status;
switch (rpc_options.service) {
case SERVICE_ECHO:
status =
SendRpcMethod(&stub_, rpc_options, &context, request, response);
break;
case SERVICE_ECHO1:
status =
SendRpcMethod(&stub1_, rpc_options, &context, request, response);
break;
case SERVICE_ECHO2:
status =
SendRpcMethod(&stub2_, rpc_options, &context, request, response);
break;
}
if (local_response) delete response;
return status;
}
void CheckRpcSendOk(const size_t times = 1,
const RpcOptions& rpc_options = RpcOptions()) {
for (size_t i = 0; i < times; ++i) {
EchoResponse response;
const Status status = SendRpc(rpc_options, &response);
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage);
}
}
void CheckRpcSendFailure(
const size_t times = 1, const RpcOptions& rpc_options = RpcOptions(),
const StatusCode expected_error_code = StatusCode::OK) {
for (size_t i = 0; i < times; ++i) {
const Status status = SendRpc(rpc_options);
EXPECT_FALSE(status.ok());
if (expected_error_code != StatusCode::OK) {
EXPECT_EQ(expected_error_code, status.error_code());
}
}
}
static Listener BuildListener(const RouteConfiguration& route_config) {
HttpConnectionManager http_connection_manager;
*(http_connection_manager.mutable_route_config()) = route_config;
auto* filter = http_connection_manager.add_http_filters();
filter->set_name("router");
filter->mutable_typed_config()->PackFrom(
envoy::extensions::filters::http::router::v3::Router());
Listener listener;
listener.set_name(kServerName);
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
return listener;
}
ClusterLoadAssignment BuildEdsResource(
const AdsServiceImpl::EdsResourceArgs& args,
const char* eds_service_name = kDefaultEdsServiceName) {
ClusterLoadAssignment assignment;
assignment.set_cluster_name(eds_service_name);
for (const auto& locality : args.locality_list) {
auto* endpoints = assignment.add_endpoints();
endpoints->mutable_load_balancing_weight()->set_value(locality.lb_weight);
endpoints->set_priority(locality.priority);
endpoints->mutable_locality()->set_region(kDefaultLocalityRegion);
endpoints->mutable_locality()->set_zone(kDefaultLocalityZone);
endpoints->mutable_locality()->set_sub_zone(locality.sub_zone);
for (size_t i = 0; i < locality.ports.size(); ++i) {
const int& port = locality.ports[i];
auto* lb_endpoints = endpoints->add_lb_endpoints();
if (locality.health_statuses.size() > i &&
locality.health_statuses[i] != HealthStatus::UNKNOWN) {
lb_endpoints->set_health_status(locality.health_statuses[i]);
}
auto* endpoint = lb_endpoints->mutable_endpoint();
auto* address = endpoint->mutable_address();
auto* socket_address = address->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(port);
}
}
if (!args.drop_categories.empty()) {
auto* policy = assignment.mutable_policy();
for (const auto& p : args.drop_categories) {
const std::string& name = p.first;
const uint32_t parts_per_million = p.second;
auto* drop_overload = policy->add_drop_overloads();
drop_overload->set_category(name);
auto* drop_percentage = drop_overload->mutable_drop_percentage();
drop_percentage->set_numerator(parts_per_million);
drop_percentage->set_denominator(args.drop_denominator);
}
}
return assignment;
}
void SetListenerAndRouteConfiguration(
int idx, Listener listener, const RouteConfiguration& route_config) {
auto* api_listener =
listener.mutable_api_listener()->mutable_api_listener();
HttpConnectionManager http_connection_manager;
api_listener->UnpackTo(&http_connection_manager);
if (GetParam().enable_rds_testing()) {
auto* rds = http_connection_manager.mutable_rds();
rds->set_route_config_name(kDefaultRouteConfigurationName);
rds->mutable_config_source()->mutable_ads();
balancers_[idx]->ads_service()->SetRdsResource(route_config);
} else {
*http_connection_manager.mutable_route_config() = route_config;
}
api_listener->PackFrom(http_connection_manager);
balancers_[idx]->ads_service()->SetLdsResource(listener);
}
void SetRouteConfiguration(int idx, const RouteConfiguration& route_config) {
if (GetParam().enable_rds_testing()) {
balancers_[idx]->ads_service()->SetRdsResource(route_config);
} else {
balancers_[idx]->ads_service()->SetLdsResource(
BuildListener(route_config));
}
}
AdsServiceImpl::ResponseState RouteConfigurationResponseState(int idx) const {
AdsServiceImpl* ads_service = balancers_[idx]->ads_service();
if (GetParam().enable_rds_testing()) {
return ads_service->rds_response_state();
}
return ads_service->lds_response_state();
}
public:
// This method could benefit test subclasses; to make it accessible
// via bind with a qualified name, it needs to be public.
void SetEdsResourceWithDelay(size_t i,
const ClusterLoadAssignment& assignment,
int delay_ms) {
GPR_ASSERT(delay_ms > 0);
gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(delay_ms));
balancers_[i]->ads_service()->SetEdsResource(assignment);
}
protected:
class XdsServingStatusNotifier
: public grpc::experimental::XdsServerServingStatusNotifierInterface {
public:
void OnServingStatusChange(std::string uri, grpc::Status status) override {
grpc_core::MutexLock lock(&mu_);
status_map[uri] = status;
cond_.Signal();
}
void WaitOnServingStatusChange(std::string uri,
grpc::StatusCode expected_status) {
grpc_core::MutexLock lock(&mu_);
std::map<std::string, grpc::Status>::iterator it;
while ((it = status_map.find(uri)) == status_map.end() ||
it->second.error_code() != expected_status) {
cond_.Wait(&mu_);
}
}
private:
grpc_core::Mutex mu_;
grpc_core::CondVar cond_;
std::map<std::string, grpc::Status> status_map;
};
class ServerThread {
public:
explicit ServerThread(bool use_xds_enabled_server = false)
: port_(grpc_pick_unused_port_or_die()),
use_xds_enabled_server_(use_xds_enabled_server) {}
virtual ~ServerThread(){};
void Start() {
gpr_log(GPR_INFO, "starting %s server on port %d", Type(), port_);
GPR_ASSERT(!running_);
running_ = true;
StartAllServices();
grpc_core::Mutex mu;
// We need to acquire the lock here in order to prevent the notify_one
// by ServerThread::Serve from firing before the wait below is hit.
grpc_core::MutexLock lock(&mu);
grpc_core::CondVar cond;
thread_ = absl::make_unique<std::thread>(
std::bind(&ServerThread::Serve, this, &mu, &cond));
cond.Wait(&mu);
gpr_log(GPR_INFO, "%s server startup complete", Type());
}
void Serve(grpc_core::Mutex* mu, grpc_core::CondVar* cond) {
// We need to acquire the lock here in order to prevent the notify_one
// below from firing before its corresponding wait is executed.
grpc_core::MutexLock lock(mu);
std::ostringstream server_address;
server_address << "localhost:" << port_;
if (use_xds_enabled_server_) {
experimental::XdsServerBuilder builder;
builder.set_status_notifier(¬ifier_);
builder.AddListeningPort(server_address.str(), Credentials());
RegisterAllServices(&builder);
server_ = builder.BuildAndStart();
} else {
ServerBuilder builder;
builder.AddListeningPort(server_address.str(), Credentials());
RegisterAllServices(&builder);
server_ = builder.BuildAndStart();
}
cond->Signal();
}
void Shutdown() {
if (!running_) return;
gpr_log(GPR_INFO, "%s about to shutdown", Type());
ShutdownAllServices();
server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
thread_->join();
gpr_log(GPR_INFO, "%s shutdown completed", Type());
running_ = false;
}
virtual std::shared_ptr<ServerCredentials> Credentials() {
return std::make_shared<SecureServerCredentials>(
grpc_fake_transport_security_server_credentials_create());
}
int port() const { return port_; }
bool use_xds_enabled_server() const { return use_xds_enabled_server_; }
XdsServingStatusNotifier* notifier() { return ¬ifier_; }
private:
virtual void RegisterAllServices(ServerBuilder* builder) = 0;
virtual void StartAllServices() = 0;
virtual void ShutdownAllServices() = 0;
virtual const char* Type() = 0;
const int port_;
std::unique_ptr<Server> server_;
XdsServingStatusNotifier notifier_;
std::unique_ptr<std::thread> thread_;
bool running_ = false;
const bool use_xds_enabled_server_;
};
class BackendServerThread : public ServerThread {
public:
explicit BackendServerThread(bool use_xds_enabled_server)
: ServerThread(use_xds_enabled_server) {}
BackendServiceImpl<::grpc::testing::EchoTestService::Service>*
backend_service() {
return &backend_service_;
}
BackendServiceImpl<::grpc::testing::EchoTest1Service::Service>*
backend_service1() {
return &backend_service1_;
}
BackendServiceImpl<::grpc::testing::EchoTest2Service::Service>*
backend_service2() {
return &backend_service2_;
}
std::shared_ptr<ServerCredentials> Credentials() override {
if (GetParam().use_xds_credentials()) {
if (use_xds_enabled_server()) {
// We are testing server's use of XdsServerCredentials
return experimental::XdsServerCredentials(
InsecureServerCredentials());
} else {
// We are testing client's use of XdsCredentials
std::string root_cert = ReadFile(kCaCertPath);
std::string identity_cert = ReadFile(kServerCertPath);
std::string private_key = ReadFile(kServerKeyPath);
std::vector<experimental::IdentityKeyCertPair>
identity_key_cert_pairs = {{private_key, identity_cert}};
auto certificate_provider = std::make_shared<
grpc::experimental::StaticDataCertificateProvider>(
root_cert, identity_key_cert_pairs);
grpc::experimental::TlsServerCredentialsOptions options(
certificate_provider);
options.watch_root_certs();
options.watch_identity_key_cert_pairs();
options.set_cert_request_type(
GRPC_SSL_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY);
return grpc::experimental::TlsServerCredentials(options);
}
}
return ServerThread::Credentials();
}
private:
void RegisterAllServices(ServerBuilder* builder) override {
builder->RegisterService(&backend_service_);
builder->RegisterService(&backend_service1_);
builder->RegisterService(&backend_service2_);
}
void StartAllServices() override {
backend_service_.Start();
backend_service1_.Start();
backend_service2_.Start();
}
void ShutdownAllServices() override {
backend_service_.Shutdown();
backend_service1_.Shutdown();
backend_service2_.Shutdown();
}
const char* Type() override { return "Backend"; }
BackendServiceImpl<::grpc::testing::EchoTestService::Service>
backend_service_;
BackendServiceImpl<::grpc::testing::EchoTest1Service::Service>
backend_service1_;
BackendServiceImpl<::grpc::testing::EchoTest2Service::Service>
backend_service2_;
};
class BalancerServerThread : public ServerThread {
public:
explicit BalancerServerThread(int client_load_reporting_interval = 0)
: ads_service_(new AdsServiceImpl()),
lrs_service_(new LrsServiceImpl(client_load_reporting_interval)) {}
AdsServiceImpl* ads_service() { return ads_service_.get(); }
LrsServiceImpl* lrs_service() { return lrs_service_.get(); }
private:
void RegisterAllServices(ServerBuilder* builder) override {
builder->RegisterService(ads_service_->v2_rpc_service());
builder->RegisterService(ads_service_->v3_rpc_service());
builder->RegisterService(lrs_service_->v2_rpc_service());
builder->RegisterService(lrs_service_->v3_rpc_service());
}
void StartAllServices() override {
ads_service_->Start();
lrs_service_->Start();
}
void ShutdownAllServices() override {
ads_service_->Shutdown();
lrs_service_->Shutdown();
}
const char* Type() override { return "Balancer"; }
std::shared_ptr<AdsServiceImpl> ads_service_;
std::shared_ptr<LrsServiceImpl> lrs_service_;
};
#ifndef DISABLED_XDS_PROTO_IN_CC
class AdminServerThread : public ServerThread {
private:
void RegisterAllServices(ServerBuilder* builder) override {
builder->RegisterService(&csds_service_);
}
void StartAllServices() override {}
void ShutdownAllServices() override {}
const char* Type() override { return "Admin"; }
grpc::xds::experimental::ClientStatusDiscoveryService csds_service_;
};
#endif // DISABLED_XDS_PROTO_IN_CC
class LongRunningRpc {
public:
void StartRpc(grpc::testing::EchoTestService::Stub* stub,
const RpcOptions& rpc_options =
RpcOptions().set_client_cancel_after_us(1 * 1000 *
1000)) {
sender_thread_ = std::thread([this, stub, rpc_options]() {
EchoRequest request;
EchoResponse response;
rpc_options.SetupRpc(&context_, &request);
status_ = stub->Echo(&context_, request, &response);
});
}
void CancelRpc() {
context_.TryCancel();
if (sender_thread_.joinable()) sender_thread_.join();
}
Status GetStatus() {
if (sender_thread_.joinable()) sender_thread_.join();
return status_;
}
private:
std::thread sender_thread_;
ClientContext context_;
Status status_;
};
const size_t num_backends_;
const size_t num_balancers_;
const int client_load_reporting_interval_seconds_;
bool ipv6_only_ = false;
std::shared_ptr<Channel> channel_;
std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
std::unique_ptr<grpc::testing::EchoTest1Service::Stub> stub1_;
std::unique_ptr<grpc::testing::EchoTest2Service::Stub> stub2_;
std::vector<std::unique_ptr<BackendServerThread>> backends_;
std::vector<std::unique_ptr<BalancerServerThread>> balancers_;
grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
response_generator_;
grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
lb_channel_response_generator_;
grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
logical_dns_cluster_resolver_response_generator_;
int xds_resource_does_not_exist_timeout_ms_ = 0;
absl::InlinedVector<grpc_arg, 2> xds_channel_args_to_add_;
grpc_channel_args xds_channel_args_;
Listener default_listener_;
RouteConfiguration default_route_config_;
Cluster default_cluster_;
bool use_xds_enabled_server_;
bool bootstrap_contents_from_env_var_;
};
class BasicTest : public XdsEnd2endTest {
public:
BasicTest() : XdsEnd2endTest(4, 1) {}
};
// Tests that the balancer sends the correct response to the client, and the
// client sends RPCs to the backends using the default child policy.
TEST_P(BasicTest, Vanilla) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcsPerAddress = 100;
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Make sure that trying to connect works without a call.
channel_->GetState(true /* try_to_connect */);
// We need to wait for all backends to come online.
WaitForAllBackends();
// Send kNumRpcsPerAddress RPCs per server.
CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
// Each backend should have gotten 100 requests.
for (size_t i = 0; i < backends_.size(); ++i) {
EXPECT_EQ(kNumRpcsPerAddress,
backends_[i]->backend_service()->request_count());
}
// Check LB policy name for the channel.
EXPECT_EQ(
(GetParam().use_fake_resolver() ? "xds_cluster_resolver_experimental"
: "xds_cluster_manager_experimental"),
channel_->GetLoadBalancingPolicyName());
}
TEST_P(BasicTest, IgnoresUnhealthyEndpoints) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcsPerAddress = 100;
AdsServiceImpl::EdsResourceArgs args({
{"locality0",
GetBackendPorts(),
kDefaultLocalityWeight,
kDefaultLocalityPriority,
{HealthStatus::DRAINING}},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Make sure that trying to connect works without a call.
channel_->GetState(true /* try_to_connect */);
// We need to wait for all backends to come online.
WaitForAllBackends(/*start_index=*/1);
// Send kNumRpcsPerAddress RPCs per server.
CheckRpcSendOk(kNumRpcsPerAddress * (num_backends_ - 1));
// Each backend should have gotten 100 requests.
for (size_t i = 1; i < backends_.size(); ++i) {
EXPECT_EQ(kNumRpcsPerAddress,
backends_[i]->backend_service()->request_count());
}
}
// Tests that subchannel sharing works when the same backend is listed multiple
// times.
TEST_P(BasicTest, SameBackendListedMultipleTimes) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Same backend listed twice.
std::vector<int> ports(2, backends_[0]->port());
AdsServiceImpl::EdsResourceArgs args({
{"locality0", ports},
});
const size_t kNumRpcsPerAddress = 10;
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// We need to wait for the backend to come online.
WaitForBackend(0);
// Send kNumRpcsPerAddress RPCs per server.
CheckRpcSendOk(kNumRpcsPerAddress * ports.size());
// Backend should have gotten 20 requests.
EXPECT_EQ(kNumRpcsPerAddress * ports.size(),
backends_[0]->backend_service()->request_count());
// And they should have come from a single client port, because of
// subchannel sharing.
EXPECT_EQ(1UL, backends_[0]->backend_service()->clients().size());
}
// Tests that RPCs will be blocked until a non-empty serverlist is received.
TEST_P(BasicTest, InitiallyEmptyServerlist) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor();
const int kCallDeadlineMs = kServerlistDelayMs * 2;
// First response is an empty serverlist, sent right away.
AdsServiceImpl::EdsResourceArgs::Locality empty_locality("locality0", {});
AdsServiceImpl::EdsResourceArgs args({
empty_locality,
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Send non-empty serverlist only after kServerlistDelayMs.
args = AdsServiceImpl::EdsResourceArgs({
{"locality0", GetBackendPorts()},
});
std::thread delayed_resource_setter(std::bind(
&BasicTest::SetEdsResourceWithDelay, this, 0,
BuildEdsResource(args, DefaultEdsServiceName()), kServerlistDelayMs));
const auto t0 = system_clock::now();
// Client will block: LB will initially send empty serverlist.
CheckRpcSendOk(
1, RpcOptions().set_timeout_ms(kCallDeadlineMs).set_wait_for_ready(true));
const auto ellapsed_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(
system_clock::now() - t0);
// but eventually, the LB sends a serverlist update that allows the call to
// proceed. The call delay must be larger than the delay in sending the
// populated serverlist but under the call's deadline (which is enforced by
// the call's deadline).
EXPECT_GT(ellapsed_ms.count(), kServerlistDelayMs);
delayed_resource_setter.join();
}
// Tests that RPCs will fail with UNAVAILABLE instead of DEADLINE_EXCEEDED if
// all the servers are unreachable.
TEST_P(BasicTest, AllServersUnreachableFailFast) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumUnreachableServers = 5;
std::vector<int> ports;
for (size_t i = 0; i < kNumUnreachableServers; ++i) {
ports.push_back(grpc_pick_unused_port_or_die());
}
AdsServiceImpl::EdsResourceArgs args({
{"locality0", ports},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
const Status status = SendRpc();
// The error shouldn't be DEADLINE_EXCEEDED.
EXPECT_EQ(StatusCode::UNAVAILABLE, status.error_code());
}
// Tests that RPCs fail when the backends are down, and will succeed again after
// the backends are restarted.
TEST_P(BasicTest, BackendsRestart) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
WaitForAllBackends();
// Stop backends. RPCs should fail.
ShutdownAllBackends();
// Sending multiple failed requests instead of just one to ensure that the
// client notices that all backends are down before we restart them. If we
// didn't do this, then a single RPC could fail here due to the race condition
// between the LB pick and the GOAWAY from the chosen backend being shut down,
// which would not actually prove that the client noticed that all of the
// backends are down. Then, when we send another request below (which we
// expect to succeed), if the callbacks happen in the wrong order, the same
// race condition could happen again due to the client not yet having noticed
// that the backends were all down.
CheckRpcSendFailure(num_backends_);
// Restart all backends. RPCs should start succeeding again.
StartAllBackends();
CheckRpcSendOk(1, RpcOptions().set_timeout_ms(2000).set_wait_for_ready(true));
}
TEST_P(BasicTest, IgnoresDuplicateUpdates) {
const size_t kNumRpcsPerAddress = 100;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait for all backends to come online.
WaitForAllBackends();
// Send kNumRpcsPerAddress RPCs per server, but send an EDS update in
// between. If the update is not ignored, this will cause the
// round_robin policy to see an update, which will randomly reset its
// position in the address list.
for (size_t i = 0; i < kNumRpcsPerAddress; ++i) {
CheckRpcSendOk(2);
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
CheckRpcSendOk(2);
}
// Each backend should have gotten the right number of requests.
for (size_t i = 1; i < backends_.size(); ++i) {
EXPECT_EQ(kNumRpcsPerAddress,
backends_[i]->backend_service()->request_count());
}
}
using XdsResolverOnlyTest = BasicTest;
TEST_P(XdsResolverOnlyTest, ResourceTypeVersionPersistsAcrossStreamRestarts) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
// Wait for backends to come online.
WaitForAllBackends(0, 1);
// Stop balancer.
balancers_[0]->Shutdown();
// Tell balancer to require minimum version 1 for all resource types.
balancers_[0]->ads_service()->SetResourceMinVersion(kLdsTypeUrl, 1);
balancers_[0]->ads_service()->SetResourceMinVersion(kRdsTypeUrl, 1);
balancers_[0]->ads_service()->SetResourceMinVersion(kCdsTypeUrl, 1);
balancers_[0]->ads_service()->SetResourceMinVersion(kEdsTypeUrl, 1);
// Update backend, just so we can be sure that the client has
// reconnected to the balancer.
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(1, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args2));
// Restart balancer.
balancers_[0]->Start();
// Make sure client has reconnected.
WaitForAllBackends(1, 2);
}
// Tests switching over from one cluster to another.
TEST_P(XdsResolverOnlyTest, ChangeClusters) {
const char* kNewClusterName = "new_cluster_name";
const char* kNewEdsServiceName = "new_eds_service_name";
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
// We need to wait for all backends to come online.
WaitForAllBackends(0, 2);
// Populate new EDS resource.
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 4)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsServiceName));
// Populate new CDS resource.
Cluster new_cluster = default_cluster_;
new_cluster.set_name(kNewClusterName);
new_cluster.mutable_eds_cluster_config()->set_service_name(
kNewEdsServiceName);
balancers_[0]->ads_service()->SetCdsResource(new_cluster);
// Change RDS resource to point to new cluster.
RouteConfiguration new_route_config = default_route_config_;
new_route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->set_cluster(kNewClusterName);
SetListenerAndRouteConfiguration(0, default_listener_, new_route_config);
// Wait for all new backends to be used.
std::tuple<int, int, int> counts = WaitForAllBackends(2, 4);
// Make sure no RPCs failed in the transition.
EXPECT_EQ(0, std::get<1>(counts));
}
// Tests that we go into TRANSIENT_FAILURE if the Cluster disappears.
TEST_P(XdsResolverOnlyTest, ClusterRemoved) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
// We need to wait for all backends to come online.
WaitForAllBackends();
// Unset CDS resource.
balancers_[0]->ads_service()->UnsetResource(kCdsTypeUrl, kDefaultClusterName);
// Wait for RPCs to start failing.
do {
} while (SendRpc(RpcOptions(), nullptr).ok());
// Make sure RPCs are still failing.
CheckRpcSendFailure(1000);
// Make sure we ACK'ed the update.
EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state().state,
AdsServiceImpl::ResponseState::ACKED);
}
// Tests that we restart all xDS requests when we reestablish the ADS call.
TEST_P(XdsResolverOnlyTest, RestartsRequestsUponReconnection) {
// Manually configure use of RDS.
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* rds = http_connection_manager.mutable_rds();
rds->set_route_config_name(kDefaultRouteConfigurationName);
rds->mutable_config_source()->mutable_ads();
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
balancers_[0]->ads_service()->SetLdsResource(listener);
balancers_[0]->ads_service()->SetRdsResource(default_route_config_);
const char* kNewClusterName = "new_cluster_name";
const char* kNewEdsServiceName = "new_eds_service_name";
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
// We need to wait for all backends to come online.
WaitForAllBackends(0, 2);
// Now shut down and restart the balancer. When the client
// reconnects, it should automatically restart the requests for all
// resource types.
balancers_[0]->Shutdown();
balancers_[0]->Start();
// Make sure things are still working.
CheckRpcSendOk(100);
// Populate new EDS resource.
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 4)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsServiceName));
// Populate new CDS resource.
Cluster new_cluster = default_cluster_;
new_cluster.set_name(kNewClusterName);
new_cluster.mutable_eds_cluster_config()->set_service_name(
kNewEdsServiceName);
balancers_[0]->ads_service()->SetCdsResource(new_cluster);
// Change RDS resource to point to new cluster.
RouteConfiguration new_route_config = default_route_config_;
new_route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->set_cluster(kNewClusterName);
balancers_[0]->ads_service()->SetRdsResource(new_route_config);
// Wait for all new backends to be used.
std::tuple<int, int, int> counts = WaitForAllBackends(2, 4);
// Make sure no RPCs failed in the transition.
EXPECT_EQ(0, std::get<1>(counts));
}
TEST_P(XdsResolverOnlyTest, DefaultRouteSpecifiesSlashPrefix) {
RouteConfiguration route_config = default_route_config_;
route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_match()
->set_prefix("/");
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
// We need to wait for all backends to come online.
WaitForAllBackends();
}
TEST_P(XdsResolverOnlyTest, CircuitBreaking) {
constexpr size_t kMaxConcurrentRequests = 10;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
// Update CDS resource to set max concurrent request.
CircuitBreakers circuit_breaks;
Cluster cluster = default_cluster_;
auto* threshold = cluster.mutable_circuit_breakers()->add_thresholds();
threshold->set_priority(RoutingPriority::DEFAULT);
threshold->mutable_max_requests()->set_value(kMaxConcurrentRequests);
balancers_[0]->ads_service()->SetCdsResource(cluster);
// Send exactly max_concurrent_requests long RPCs.
LongRunningRpc rpcs[kMaxConcurrentRequests];
for (size_t i = 0; i < kMaxConcurrentRequests; ++i) {
rpcs[i].StartRpc(stub_.get());
}
// Wait for all RPCs to be in flight.
while (backends_[0]->backend_service()->RpcsWaitingForClientCancel() <
kMaxConcurrentRequests) {
gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_micros(1 * 1000, GPR_TIMESPAN)));
}
// Sending a RPC now should fail, the error message should tell us
// we hit the max concurrent requests limit and got dropped.
Status status = SendRpc();
EXPECT_FALSE(status.ok());
EXPECT_EQ(status.error_message(), "Call dropped by load balancing policy");
// Cancel one RPC to allow another one through
rpcs[0].CancelRpc();
status = SendRpc();
EXPECT_TRUE(status.ok());
for (size_t i = 1; i < kMaxConcurrentRequests; ++i) {
rpcs[i].CancelRpc();
}
// Make sure RPCs go to the correct backend:
EXPECT_EQ(kMaxConcurrentRequests + 1,
backends_[0]->backend_service()->request_count());
}
TEST_P(XdsResolverOnlyTest, CircuitBreakingMultipleChannelsShareCallCounter) {
constexpr size_t kMaxConcurrentRequests = 10;
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
// Update CDS resource to set max concurrent request.
CircuitBreakers circuit_breaks;
Cluster cluster = default_cluster_;
auto* threshold = cluster.mutable_circuit_breakers()->add_thresholds();
threshold->set_priority(RoutingPriority::DEFAULT);
threshold->mutable_max_requests()->set_value(kMaxConcurrentRequests);
balancers_[0]->ads_service()->SetCdsResource(cluster);
// Create second channel.
auto response_generator2 =
grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
auto channel2 = CreateChannel(
/*failover_timeout=*/0, /*server_name=*/kServerName,
response_generator2.get());
auto stub2 = grpc::testing::EchoTestService::NewStub(channel2);
// Set resolution results for both channels and for the xDS channel.
SetNextResolution({});
SetNextResolution({}, response_generator2.get());
SetNextResolutionForLbChannelAllBalancers();
// Send exactly max_concurrent_requests long RPCs, alternating between
// the two channels.
LongRunningRpc rpcs[kMaxConcurrentRequests];
for (size_t i = 0; i < kMaxConcurrentRequests; ++i) {
rpcs[i].StartRpc(i % 2 == 0 ? stub_.get() : stub2.get());
}
// Wait for all RPCs to be in flight.
while (backends_[0]->backend_service()->RpcsWaitingForClientCancel() <
kMaxConcurrentRequests) {
gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_micros(1 * 1000, GPR_TIMESPAN)));
}
// Sending a RPC now should fail, the error message should tell us
// we hit the max concurrent requests limit and got dropped.
Status status = SendRpc();
EXPECT_FALSE(status.ok());
EXPECT_EQ(status.error_message(), "Call dropped by load balancing policy");
// Cancel one RPC to allow another one through
rpcs[0].CancelRpc();
status = SendRpc();
EXPECT_TRUE(status.ok());
for (size_t i = 1; i < kMaxConcurrentRequests; ++i) {
rpcs[i].CancelRpc();
}
// Make sure RPCs go to the correct backend:
EXPECT_EQ(kMaxConcurrentRequests + 1,
backends_[0]->backend_service()->request_count());
}
TEST_P(XdsResolverOnlyTest, MultipleChannelsShareXdsClient) {
const char* kNewServerName = "new-server.example.com";
Listener listener = default_listener_;
listener.set_name(kNewServerName);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
WaitForAllBackends();
// Create second channel and tell it to connect to kNewServerName.
auto channel2 = CreateChannel(/*failover_timeout=*/0, kNewServerName);
channel2->GetState(/*try_to_connect=*/true);
ASSERT_TRUE(
channel2->WaitForConnected(grpc_timeout_milliseconds_to_deadline(100)));
// Make sure there's only one client connected.
EXPECT_EQ(1UL, balancers_[0]->ads_service()->clients().size());
}
class XdsResolverLoadReportingOnlyTest : public XdsEnd2endTest {
public:
XdsResolverLoadReportingOnlyTest() : XdsEnd2endTest(4, 1, 3) {}
};
// Tests load reporting when switching over from one cluster to another.
TEST_P(XdsResolverLoadReportingOnlyTest, ChangeClusters) {
const char* kNewClusterName = "new_cluster_name";
const char* kNewEdsServiceName = "new_eds_service_name";
balancers_[0]->lrs_service()->set_cluster_names(
{kDefaultClusterName, kNewClusterName});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// cluster kDefaultClusterName -> locality0 -> backends 0 and 1
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
// cluster kNewClusterName -> locality1 -> backends 2 and 3
AdsServiceImpl::EdsResourceArgs args2({
{"locality1", GetBackendPorts(2, 4)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsServiceName));
// CDS resource for kNewClusterName.
Cluster new_cluster = default_cluster_;
new_cluster.set_name(kNewClusterName);
new_cluster.mutable_eds_cluster_config()->set_service_name(
kNewEdsServiceName);
balancers_[0]->ads_service()->SetCdsResource(new_cluster);
// Wait for all backends to come online.
int num_ok = 0;
int num_failure = 0;
int num_drops = 0;
std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends(0, 2);
// The load report received at the balancer should be correct.
std::vector<ClientStats> load_report =
balancers_[0]->lrs_service()->WaitForLoadReport();
EXPECT_THAT(
load_report,
::testing::ElementsAre(::testing::AllOf(
::testing::Property(&ClientStats::cluster_name, kDefaultClusterName),
::testing::Property(
&ClientStats::locality_stats,
::testing::ElementsAre(::testing::Pair(
"locality0",
::testing::AllOf(
::testing::Field(&ClientStats::LocalityStats::
total_successful_requests,
num_ok),
::testing::Field(&ClientStats::LocalityStats::
total_requests_in_progress,
0UL),
::testing::Field(
&ClientStats::LocalityStats::total_error_requests,
num_failure),
::testing::Field(
&ClientStats::LocalityStats::total_issued_requests,
num_failure + num_ok))))),
::testing::Property(&ClientStats::total_dropped_requests,
num_drops))));
// Change RDS resource to point to new cluster.
RouteConfiguration new_route_config = default_route_config_;
new_route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->set_cluster(kNewClusterName);
SetListenerAndRouteConfiguration(0, default_listener_, new_route_config);
// Wait for all new backends to be used.
std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends(2, 4);
// The load report received at the balancer should be correct.
load_report = balancers_[0]->lrs_service()->WaitForLoadReport();
EXPECT_THAT(
load_report,
::testing::ElementsAre(
::testing::AllOf(
::testing::Property(&ClientStats::cluster_name,
kDefaultClusterName),
::testing::Property(
&ClientStats::locality_stats,
::testing::ElementsAre(::testing::Pair(
"locality0",
::testing::AllOf(
::testing::Field(&ClientStats::LocalityStats::
total_successful_requests,
::testing::Lt(num_ok)),
::testing::Field(&ClientStats::LocalityStats::
total_requests_in_progress,
0UL),
::testing::Field(
&ClientStats::LocalityStats::total_error_requests,
::testing::Le(num_failure)),
::testing::Field(
&ClientStats::LocalityStats::
total_issued_requests,
::testing::Le(num_failure + num_ok)))))),
::testing::Property(&ClientStats::total_dropped_requests,
num_drops)),
::testing::AllOf(
::testing::Property(&ClientStats::cluster_name, kNewClusterName),
::testing::Property(
&ClientStats::locality_stats,
::testing::ElementsAre(::testing::Pair(
"locality1",
::testing::AllOf(
::testing::Field(&ClientStats::LocalityStats::
total_successful_requests,
::testing::Le(num_ok)),
::testing::Field(&ClientStats::LocalityStats::
total_requests_in_progress,
0UL),
::testing::Field(
&ClientStats::LocalityStats::total_error_requests,
::testing::Le(num_failure)),
::testing::Field(
&ClientStats::LocalityStats::
total_issued_requests,
::testing::Le(num_failure + num_ok)))))),
::testing::Property(&ClientStats::total_dropped_requests,
num_drops))));
int total_ok = 0;
int total_failure = 0;
for (const ClientStats& client_stats : load_report) {
total_ok += client_stats.total_successful_requests();
total_failure += client_stats.total_error_requests();
}
EXPECT_EQ(total_ok, num_ok);
EXPECT_EQ(total_failure, num_failure);
// The LRS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->lrs_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->lrs_service()->response_count());
}
using SecureNamingTest = BasicTest;
// Tests that secure naming check passes if target name is expected.
TEST_P(SecureNamingTest, TargetNameIsExpected) {
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()}, nullptr, "xds_server");
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
CheckRpcSendOk();
}
// Tests that secure naming check fails if target name is unexpected.
TEST_P(SecureNamingTest, TargetNameIsUnexpected) {
::testing::FLAGS_gtest_death_test_style = "threadsafe";
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()}, nullptr,
"incorrect_server_name");
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Make sure that we blow up (via abort() from the security connector) when
// the name from the balancer doesn't match expectations.
ASSERT_DEATH_IF_SUPPORTED({ CheckRpcSendOk(); }, "");
}
using LdsTest = BasicTest;
// Tests that LDS client should send a NACK if there is no API listener in the
// Listener in the LDS response.
TEST_P(LdsTest, NoApiListener) {
auto listener = default_listener_;
listener.clear_api_listener();
balancers_[0]->ads_service()->SetLdsResource(listener);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("Listener has neither address nor ApiListener"));
}
// Tests that LDS client should send a NACK if the route_specifier in the
// http_connection_manager is neither inlined route_config nor RDS.
TEST_P(LdsTest, WrongRouteSpecifier) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
http_connection_manager.mutable_scoped_routes();
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
balancers_[0]->ads_service()->SetLdsResource(listener);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr(
"HttpConnectionManager neither has inlined route_config nor RDS."));
}
// Tests that LDS client should send a NACK if the rds message in the
// http_connection_manager is missing the config_source field.
TEST_P(LdsTest, RdsMissingConfigSource) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
http_connection_manager.mutable_rds()->set_route_config_name(
kDefaultRouteConfigurationName);
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
balancers_[0]->ads_service()->SetLdsResource(listener);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"HttpConnectionManager missing config_source for RDS."));
}
// Tests that LDS client should send a NACK if the rds message in the
// http_connection_manager has a config_source field that does not specify ADS.
TEST_P(LdsTest, RdsConfigSourceDoesNotSpecifyAds) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* rds = http_connection_manager.mutable_rds();
rds->set_route_config_name(kDefaultRouteConfigurationName);
rds->mutable_config_source()->mutable_self();
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
balancers_[0]->ads_service()->SetLdsResource(listener);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr(
"HttpConnectionManager ConfigSource for RDS does not specify ADS."));
}
// Tests that the NACK for multiple bad LDS resources includes both errors.
TEST_P(LdsTest, MultipleBadResources) {
constexpr char kServerName2[] = "server.other.com";
auto listener = default_listener_;
listener.clear_api_listener();
balancers_[0]->ads_service()->SetLdsResource(listener);
listener.set_name(kServerName2);
balancers_[0]->ads_service()->SetLdsResource(listener);
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
// Need to create a second channel to subscribe to a second LDS resource.
auto channel2 = CreateChannel(0, kServerName2);
auto stub2 = grpc::testing::EchoTestService::NewStub(channel2);
ClientContext context;
EchoRequest request;
request.set_message(kRequestMessage);
EchoResponse response;
grpc::Status status = stub2->Echo(&context, request, &response);
EXPECT_FALSE(status.ok());
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::AllOf(
::testing::HasSubstr(absl::StrCat(
kServerName, ": Listener has neither address nor ApiListener")),
::testing::HasSubstr(
absl::StrCat(kServerName2,
": Listener has neither address nor ApiListener"))));
}
// Tests that we ignore filters after the router filter.
TEST_P(LdsTest, IgnoresHttpFiltersAfterRouterFilter) {
SetNextResolutionForLbChannelAllBalancers();
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* filter = http_connection_manager.add_http_filters();
filter->set_name("unknown");
filter->mutable_typed_config()->set_type_url(
"grpc.testing.client_only_http_filter");
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
WaitForAllBackends();
}
// Test that we fail RPCs if there is no router filter.
TEST_P(LdsTest, FailRpcsIfNoHttpRouterFilter) {
SetNextResolutionForLbChannelAllBalancers();
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
http_connection_manager.clear_http_filters();
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
Status status = SendRpc();
EXPECT_EQ(status.error_code(), StatusCode::UNAVAILABLE);
EXPECT_EQ(status.error_message(), "no xDS HTTP router filter configured");
// Wait until xDS server sees ACK.
while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT) {
CheckRpcSendFailure();
}
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
}
// Test that we NACK empty filter names.
TEST_P(LdsTest, RejectsEmptyHttpFilterName) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* filter = http_connection_manager.add_http_filters();
filter->mutable_typed_config()->PackFrom(Listener());
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("empty filter name at index 1"));
}
// Test that we NACK duplicate HTTP filter names.
TEST_P(LdsTest, RejectsDuplicateHttpFilterName) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
*http_connection_manager.add_http_filters() =
http_connection_manager.http_filters(0);
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("duplicate HTTP filter name: router"));
}
// Test that we NACK unknown filter types.
TEST_P(LdsTest, RejectsUnknownHttpFilterType) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* filter = http_connection_manager.add_http_filters();
filter->set_name("unknown");
filter->mutable_typed_config()->PackFrom(Listener());
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("no filter registered for config type "
"envoy.config.listener.v3.Listener"));
}
// Test that we ignore optional unknown filter types.
TEST_P(LdsTest, IgnoresOptionalUnknownHttpFilterType) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* filter = http_connection_manager.add_http_filters();
filter->set_name("unknown");
filter->mutable_typed_config()->PackFrom(Listener());
filter->set_is_optional(true);
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolutionForLbChannelAllBalancers();
WaitForAllBackends();
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state().state,
AdsServiceImpl::ResponseState::ACKED);
}
// Test that we NACK filters without configs.
TEST_P(LdsTest, RejectsHttpFilterWithoutConfig) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* filter = http_connection_manager.add_http_filters();
filter->set_name("unknown");
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"no filter config specified for filter name unknown"));
}
// Test that we ignore optional filters without configs.
TEST_P(LdsTest, IgnoresOptionalHttpFilterWithoutConfig) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* filter = http_connection_manager.add_http_filters();
filter->set_name("unknown");
filter->set_is_optional(true);
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolutionForLbChannelAllBalancers();
WaitForAllBackends();
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state().state,
AdsServiceImpl::ResponseState::ACKED);
}
// Test that we NACK unparseable filter configs.
TEST_P(LdsTest, RejectsUnparseableHttpFilterType) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* filter = http_connection_manager.add_http_filters();
filter->set_name("unknown");
filter->mutable_typed_config()->PackFrom(listener);
filter->mutable_typed_config()->set_type_url(
"type.googleapis.com/envoy.extensions.filters.http.router.v3.Router");
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr(
"filter config for type "
"envoy.extensions.filters.http.router.v3.Router failed to parse"));
}
// Test that we NACK HTTP filters unsupported on client-side.
TEST_P(LdsTest, RejectsHttpFiltersNotSupportedOnClients) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* filter = http_connection_manager.add_http_filters();
filter->set_name("grpc.testing.server_only_http_filter");
filter->mutable_typed_config()->set_type_url(
"grpc.testing.server_only_http_filter");
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("Filter grpc.testing.server_only_http_filter is not "
"supported on clients"));
}
// Test that we ignore optional HTTP filters unsupported on client-side.
TEST_P(LdsTest, IgnoresOptionalHttpFiltersNotSupportedOnClients) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* filter = http_connection_manager.add_http_filters();
filter->set_name("grpc.testing.server_only_http_filter");
filter->mutable_typed_config()->set_type_url(
"grpc.testing.server_only_http_filter");
filter->set_is_optional(true);
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
WaitForBackend(0);
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state().state,
AdsServiceImpl::ResponseState::ACKED);
}
using LdsV2Test = LdsTest;
// Tests that we ignore the HTTP filter list in v2.
// TODO(roth): The test framework is not set up to allow us to test
// the server sending v2 resources when the client requests v3, so this
// just tests a pure v2 setup. When we have time, fix this.
TEST_P(LdsV2Test, IgnoresHttpFilters) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* filter = http_connection_manager.add_http_filters();
filter->set_name("unknown");
filter->mutable_typed_config()->PackFrom(Listener());
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendOk();
}
using LdsRdsTest = BasicTest;
// Tests that LDS client should send an ACK upon correct LDS response (with
// inlined RDS result).
TEST_P(LdsRdsTest, Vanilla) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
EXPECT_EQ(RouteConfigurationResponseState(0).state,
AdsServiceImpl::ResponseState::ACKED);
// Make sure we actually used the RPC service for the right version of xDS.
EXPECT_EQ(balancers_[0]->ads_service()->seen_v2_client(),
GetParam().use_v2());
EXPECT_NE(balancers_[0]->ads_service()->seen_v3_client(),
GetParam().use_v2());
}
// Tests that we go into TRANSIENT_FAILURE if the Listener is removed.
TEST_P(LdsRdsTest, ListenerRemoved) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
// We need to wait for all backends to come online.
WaitForAllBackends();
// Unset LDS resource.
balancers_[0]->ads_service()->UnsetResource(kLdsTypeUrl, kServerName);
// Wait for RPCs to start failing.
do {
} while (SendRpc(RpcOptions(), nullptr).ok());
// Make sure RPCs are still failing.
CheckRpcSendFailure(1000);
// Make sure we ACK'ed the update.
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state().state,
AdsServiceImpl::ResponseState::ACKED);
}
// Tests that LDS client ACKs but fails if matching domain can't be found in
// the LDS response.
TEST_P(LdsRdsTest, NoMatchedDomain) {
RouteConfiguration route_config = default_route_config_;
route_config.mutable_virtual_hosts(0)->clear_domains();
route_config.mutable_virtual_hosts(0)->add_domains("unmatched_domain");
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
// Do a bit of polling, to allow the ACK to get to the ADS server.
channel_->WaitForConnected(grpc_timeout_milliseconds_to_deadline(100));
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
}
// Tests that LDS client should choose the virtual host with matching domain if
// multiple virtual hosts exist in the LDS response.
TEST_P(LdsRdsTest, ChooseMatchedDomain) {
RouteConfiguration route_config = default_route_config_;
*(route_config.add_virtual_hosts()) = route_config.virtual_hosts(0);
route_config.mutable_virtual_hosts(0)->clear_domains();
route_config.mutable_virtual_hosts(0)->add_domains("unmatched_domain");
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
EXPECT_EQ(RouteConfigurationResponseState(0).state,
AdsServiceImpl::ResponseState::ACKED);
}
// Tests that LDS client should choose the last route in the virtual host if
// multiple routes exist in the LDS response.
TEST_P(LdsRdsTest, ChooseLastRoute) {
RouteConfiguration route_config = default_route_config_;
*(route_config.mutable_virtual_hosts(0)->add_routes()) =
route_config.virtual_hosts(0).routes(0);
route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_cluster_header();
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
EXPECT_EQ(RouteConfigurationResponseState(0).state,
AdsServiceImpl::ResponseState::ACKED);
}
// Tests that LDS client should ignore route which has query_parameters.
TEST_P(LdsRdsTest, RouteMatchHasQueryParameters) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
route1->mutable_match()->add_query_parameters();
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("No valid routes specified."));
}
// Tests that LDS client should send a ACK if route match has a prefix
// that is either empty or a single slash
TEST_P(LdsRdsTest, RouteMatchHasValidPrefixEmptyOrSingleSlash) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("");
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("/");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
}
// Tests that LDS client should ignore route which has a path
// prefix string does not start with "/".
TEST_P(LdsRdsTest, RouteMatchHasInvalidPrefixNoLeadingSlash) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("grpc.testing.EchoTest1Service/");
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("No valid routes specified."));
}
// Tests that LDS client should ignore route which has a prefix
// string with more than 2 slashes.
TEST_P(LdsRdsTest, RouteMatchHasInvalidPrefixExtraContent) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/Echo1/");
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("No valid routes specified."));
}
// Tests that LDS client should ignore route which has a prefix
// string "//".
TEST_P(LdsRdsTest, RouteMatchHasInvalidPrefixDoubleSlash) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("//");
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("No valid routes specified."));
}
// Tests that LDS client should ignore route which has path
// but it's empty.
TEST_P(LdsRdsTest, RouteMatchHasInvalidPathEmptyPath) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_path("");
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("No valid routes specified."));
}
// Tests that LDS client should ignore route which has path
// string does not start with "/".
TEST_P(LdsRdsTest, RouteMatchHasInvalidPathNoLeadingSlash) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_path("grpc.testing.EchoTest1Service/Echo1");
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("No valid routes specified."));
}
// Tests that LDS client should ignore route which has path
// string that has too many slashes; for example, ends with "/".
TEST_P(LdsRdsTest, RouteMatchHasInvalidPathTooManySlashes) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/Echo1/");
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("No valid routes specified."));
}
// Tests that LDS client should ignore route which has path
// string that has only 1 slash: missing "/" between service and method.
TEST_P(LdsRdsTest, RouteMatchHasInvalidPathOnlyOneSlash) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service.Echo1");
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("No valid routes specified."));
}
// Tests that LDS client should ignore route which has path
// string that is missing service.
TEST_P(LdsRdsTest, RouteMatchHasInvalidPathMissingService) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_path("//Echo1");
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("No valid routes specified."));
}
// Tests that LDS client should ignore route which has path
// string that is missing method.
TEST_P(LdsRdsTest, RouteMatchHasInvalidPathMissingMethod) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/");
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("No valid routes specified."));
}
// Test that LDS client should reject route which has invalid path regex.
TEST_P(LdsRdsTest, RouteMatchHasInvalidPathRegex) {
const char* kNewCluster1Name = "new_cluster_1";
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->mutable_safe_regex()->set_regex("a[z-a]");
route1->mutable_route()->set_cluster(kNewCluster1Name);
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"path matcher: Invalid regex string specified in matcher."));
}
// Tests that LDS client should send a NACK if route has an action other than
// RouteAction in the LDS response.
TEST_P(LdsRdsTest, RouteHasNoRouteAction) {
RouteConfiguration route_config = default_route_config_;
route_config.mutable_virtual_hosts(0)->mutable_routes(0)->mutable_redirect();
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("No RouteAction found in route."));
}
TEST_P(LdsRdsTest, RouteActionClusterHasEmptyClusterName) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
route1->mutable_route()->set_cluster("");
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("RouteAction cluster contains empty cluster name."));
}
TEST_P(LdsRdsTest, RouteActionWeightedTargetHasIncorrectTotalWeightSet) {
const size_t kWeight75 = 75;
const char* kNewCluster1Name = "new_cluster_1";
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* weighted_cluster1 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster1->set_name(kNewCluster1Name);
weighted_cluster1->mutable_weight()->set_value(kWeight75);
route1->mutable_route()
->mutable_weighted_clusters()
->mutable_total_weight()
->set_value(kWeight75 + 1);
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"RouteAction weighted_cluster has incorrect total weight"));
}
TEST_P(LdsRdsTest, RouteActionWeightedClusterHasZeroTotalWeight) {
const char* kNewCluster1Name = "new_cluster_1";
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* weighted_cluster1 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster1->set_name(kNewCluster1Name);
weighted_cluster1->mutable_weight()->set_value(0);
route1->mutable_route()
->mutable_weighted_clusters()
->mutable_total_weight()
->set_value(0);
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr(
"RouteAction weighted_cluster has no valid clusters specified."));
}
TEST_P(LdsRdsTest, RouteActionWeightedTargetClusterHasEmptyClusterName) {
const size_t kWeight75 = 75;
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* weighted_cluster1 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster1->set_name("");
weighted_cluster1->mutable_weight()->set_value(kWeight75);
route1->mutable_route()
->mutable_weighted_clusters()
->mutable_total_weight()
->set_value(kWeight75);
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr(
"RouteAction weighted_cluster cluster contains empty cluster name."));
}
TEST_P(LdsRdsTest, RouteActionWeightedTargetClusterHasNoWeight) {
const size_t kWeight75 = 75;
const char* kNewCluster1Name = "new_cluster_1";
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* weighted_cluster1 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster1->set_name(kNewCluster1Name);
route1->mutable_route()
->mutable_weighted_clusters()
->mutable_total_weight()
->set_value(kWeight75);
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"RouteAction weighted_cluster cluster missing weight"));
}
TEST_P(LdsRdsTest, RouteHeaderMatchInvalidRegex) {
const char* kNewCluster1Name = "new_cluster_1";
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* header_matcher1 = route1->mutable_match()->add_headers();
header_matcher1->set_name("header1");
header_matcher1->mutable_safe_regex_match()->set_regex("a[z-a]");
route1->mutable_route()->set_cluster(kNewCluster1Name);
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr(
"header matcher: Invalid regex string specified in matcher."));
}
TEST_P(LdsRdsTest, RouteHeaderMatchInvalidRange) {
const char* kNewCluster1Name = "new_cluster_1";
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* header_matcher1 = route1->mutable_match()->add_headers();
header_matcher1->set_name("header1");
header_matcher1->mutable_range_match()->set_start(1001);
header_matcher1->mutable_range_match()->set_end(1000);
route1->mutable_route()->set_cluster(kNewCluster1Name);
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr(
"header matcher: Invalid range specifier specified: end cannot be "
"smaller than start."));
}
// Tests that LDS client should choose the default route (with no matching
// specified) after unable to find a match with previous routes.
TEST_P(LdsRdsTest, XdsRoutingPathMatching) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const size_t kNumEcho1Rpcs = 10;
const size_t kNumEcho2Rpcs = 20;
const size_t kNumEchoRpcs = 30;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 2)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(2, 3)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(3, 4)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
// Populating Route Configurations for LDS.
RouteConfiguration new_route_config = default_route_config_;
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/Echo1");
route1->mutable_route()->set_cluster(kNewCluster1Name);
auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
route2->mutable_match()->set_path("/grpc.testing.EchoTest2Service/Echo2");
route2->mutable_route()->set_cluster(kNewCluster2Name);
auto* route3 = new_route_config.mutable_virtual_hosts(0)->add_routes();
route3->mutable_match()->set_path("/grpc.testing.EchoTest3Service/Echo3");
route3->mutable_route()->set_cluster(kDefaultClusterName);
auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, new_route_config);
WaitForAllBackends(0, 2);
CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions()
.set_rpc_service(SERVICE_ECHO1)
.set_rpc_method(METHOD_ECHO1)
.set_wait_for_ready(true));
CheckRpcSendOk(kNumEcho2Rpcs, RpcOptions()
.set_rpc_service(SERVICE_ECHO2)
.set_rpc_method(METHOD_ECHO2)
.set_wait_for_ready(true));
// Make sure RPCs all go to the correct backend.
for (size_t i = 0; i < 2; ++i) {
EXPECT_EQ(kNumEchoRpcs / 2,
backends_[i]->backend_service()->request_count());
EXPECT_EQ(0, backends_[i]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[i]->backend_service2()->request_count());
}
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[2]->backend_service2()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
EXPECT_EQ(kNumEcho2Rpcs, backends_[3]->backend_service2()->request_count());
}
TEST_P(LdsRdsTest, XdsRoutingPathMatchingCaseInsensitive) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const size_t kNumEcho1Rpcs = 10;
const size_t kNumEchoRpcs = 30;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 3)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
// Populating Route Configurations for LDS.
RouteConfiguration new_route_config = default_route_config_;
// First route will not match, since it's case-sensitive.
// Second route will match with same path.
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_path("/GrPc.TeStInG.EcHoTeSt1SErViCe/EcHo1");
route1->mutable_route()->set_cluster(kNewCluster1Name);
auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
route2->mutable_match()->set_path("/GrPc.TeStInG.EcHoTeSt1SErViCe/EcHo1");
route2->mutable_match()->mutable_case_sensitive()->set_value(false);
route2->mutable_route()->set_cluster(kNewCluster2Name);
auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, new_route_config);
CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions()
.set_rpc_service(SERVICE_ECHO1)
.set_rpc_method(METHOD_ECHO1)
.set_wait_for_ready(true));
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
}
TEST_P(LdsRdsTest, XdsRoutingPrefixMatching) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const size_t kNumEcho1Rpcs = 10;
const size_t kNumEcho2Rpcs = 20;
const size_t kNumEchoRpcs = 30;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 2)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(2, 3)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(3, 4)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
// Populating Route Configurations for LDS.
RouteConfiguration new_route_config = default_route_config_;
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
route1->mutable_route()->set_cluster(kNewCluster1Name);
auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
route2->mutable_match()->set_prefix("/grpc.testing.EchoTest2Service/");
route2->mutable_route()->set_cluster(kNewCluster2Name);
auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, new_route_config);
WaitForAllBackends(0, 2);
CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
CheckRpcSendOk(
kNumEcho1Rpcs,
RpcOptions().set_rpc_service(SERVICE_ECHO1).set_wait_for_ready(true));
CheckRpcSendOk(
kNumEcho2Rpcs,
RpcOptions().set_rpc_service(SERVICE_ECHO2).set_wait_for_ready(true));
// Make sure RPCs all go to the correct backend.
for (size_t i = 0; i < 2; ++i) {
EXPECT_EQ(kNumEchoRpcs / 2,
backends_[i]->backend_service()->request_count());
EXPECT_EQ(0, backends_[i]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[i]->backend_service2()->request_count());
}
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[2]->backend_service2()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
EXPECT_EQ(kNumEcho2Rpcs, backends_[3]->backend_service2()->request_count());
}
TEST_P(LdsRdsTest, XdsRoutingPrefixMatchingCaseInsensitive) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const size_t kNumEcho1Rpcs = 10;
const size_t kNumEchoRpcs = 30;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 3)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
// Populating Route Configurations for LDS.
RouteConfiguration new_route_config = default_route_config_;
// First route will not match, since it's case-sensitive.
// Second route will match with same path.
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/GrPc.TeStInG.EcHoTeSt1SErViCe");
route1->mutable_route()->set_cluster(kNewCluster1Name);
auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
route2->mutable_match()->set_prefix("/GrPc.TeStInG.EcHoTeSt1SErViCe");
route2->mutable_match()->mutable_case_sensitive()->set_value(false);
route2->mutable_route()->set_cluster(kNewCluster2Name);
auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, new_route_config);
CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions()
.set_rpc_service(SERVICE_ECHO1)
.set_rpc_method(METHOD_ECHO1)
.set_wait_for_ready(true));
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
}
TEST_P(LdsRdsTest, XdsRoutingPathRegexMatching) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const size_t kNumEcho1Rpcs = 10;
const size_t kNumEcho2Rpcs = 20;
const size_t kNumEchoRpcs = 30;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 2)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(2, 3)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(3, 4)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
// Populating Route Configurations for LDS.
RouteConfiguration new_route_config = default_route_config_;
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
// Will match "/grpc.testing.EchoTest1Service/"
route1->mutable_match()->mutable_safe_regex()->set_regex(".*1.*");
route1->mutable_route()->set_cluster(kNewCluster1Name);
auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
// Will match "/grpc.testing.EchoTest2Service/"
route2->mutable_match()->mutable_safe_regex()->set_regex(".*2.*");
route2->mutable_route()->set_cluster(kNewCluster2Name);
auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, new_route_config);
WaitForAllBackends(0, 2);
CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
CheckRpcSendOk(
kNumEcho1Rpcs,
RpcOptions().set_rpc_service(SERVICE_ECHO1).set_wait_for_ready(true));
CheckRpcSendOk(
kNumEcho2Rpcs,
RpcOptions().set_rpc_service(SERVICE_ECHO2).set_wait_for_ready(true));
// Make sure RPCs all go to the correct backend.
for (size_t i = 0; i < 2; ++i) {
EXPECT_EQ(kNumEchoRpcs / 2,
backends_[i]->backend_service()->request_count());
EXPECT_EQ(0, backends_[i]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[i]->backend_service2()->request_count());
}
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[2]->backend_service2()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
EXPECT_EQ(kNumEcho2Rpcs, backends_[3]->backend_service2()->request_count());
}
TEST_P(LdsRdsTest, XdsRoutingPathRegexMatchingCaseInsensitive) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const size_t kNumEcho1Rpcs = 10;
const size_t kNumEchoRpcs = 30;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 3)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
// Populating Route Configurations for LDS.
RouteConfiguration new_route_config = default_route_config_;
// First route will not match, since it's case-sensitive.
// Second route will match with same path.
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->mutable_safe_regex()->set_regex(
".*EcHoTeSt1SErViCe.*");
route1->mutable_route()->set_cluster(kNewCluster1Name);
auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
route2->mutable_match()->mutable_safe_regex()->set_regex(
".*EcHoTeSt1SErViCe.*");
route2->mutable_match()->mutable_case_sensitive()->set_value(false);
route2->mutable_route()->set_cluster(kNewCluster2Name);
auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, new_route_config);
CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions()
.set_rpc_service(SERVICE_ECHO1)
.set_rpc_method(METHOD_ECHO1)
.set_wait_for_ready(true));
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
}
TEST_P(LdsRdsTest, XdsRoutingWeightedCluster) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const char* kNotUsedClusterName = "not_used_cluster";
const size_t kNumEcho1Rpcs = 1000;
const size_t kNumEchoRpcs = 10;
const size_t kWeight75 = 75;
const size_t kWeight25 = 25;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 3)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
// Populating Route Configurations for LDS.
RouteConfiguration new_route_config = default_route_config_;
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* weighted_cluster1 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster1->set_name(kNewCluster1Name);
weighted_cluster1->mutable_weight()->set_value(kWeight75);
auto* weighted_cluster2 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster2->set_name(kNewCluster2Name);
weighted_cluster2->mutable_weight()->set_value(kWeight25);
// Cluster with weight 0 will not be used.
auto* weighted_cluster3 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster3->set_name(kNotUsedClusterName);
weighted_cluster3->mutable_weight()->set_value(0);
route1->mutable_route()
->mutable_weighted_clusters()
->mutable_total_weight()
->set_value(kWeight75 + kWeight25);
auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, new_route_config);
WaitForAllBackends(0, 1);
WaitForAllBackends(1, 3, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
CheckRpcSendOk(kNumEchoRpcs);
CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
const int weight_75_request_count =
backends_[1]->backend_service1()->request_count();
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
const int weight_25_request_count =
backends_[2]->backend_service1()->request_count();
const double kErrorTolerance = 0.2;
EXPECT_THAT(
weight_75_request_count,
::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
kWeight75 / 100 * (1 - kErrorTolerance)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
kWeight75 / 100 * (1 + kErrorTolerance))));
// TODO(@donnadionne): Reduce tolerance: increased the tolerance to keep the
// test from flaking while debugging potential root cause.
const double kErrorToleranceSmallLoad = 0.3;
gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
weight_75_request_count, weight_25_request_count);
EXPECT_THAT(weight_25_request_count,
::testing::AllOf(
::testing::Ge(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
100 * (1 - kErrorToleranceSmallLoad)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
100 * (1 + kErrorToleranceSmallLoad))));
}
TEST_P(LdsRdsTest, RouteActionWeightedTargetDefaultRoute) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const size_t kNumEchoRpcs = 1000;
const size_t kWeight75 = 75;
const size_t kWeight25 = 25;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 3)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
// Populating Route Configurations for LDS.
RouteConfiguration new_route_config = default_route_config_;
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("");
auto* weighted_cluster1 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster1->set_name(kNewCluster1Name);
weighted_cluster1->mutable_weight()->set_value(kWeight75);
auto* weighted_cluster2 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster2->set_name(kNewCluster2Name);
weighted_cluster2->mutable_weight()->set_value(kWeight25);
route1->mutable_route()
->mutable_weighted_clusters()
->mutable_total_weight()
->set_value(kWeight75 + kWeight25);
SetRouteConfiguration(0, new_route_config);
WaitForAllBackends(1, 3);
CheckRpcSendOk(kNumEchoRpcs);
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(0, backends_[0]->backend_service()->request_count());
const int weight_75_request_count =
backends_[1]->backend_service()->request_count();
const int weight_25_request_count =
backends_[2]->backend_service()->request_count();
const double kErrorTolerance = 0.2;
EXPECT_THAT(
weight_75_request_count,
::testing::AllOf(::testing::Ge(static_cast<double>(kNumEchoRpcs) *
kWeight75 / 100 * (1 - kErrorTolerance)),
::testing::Le(static_cast<double>(kNumEchoRpcs) *
kWeight75 / 100 * (1 + kErrorTolerance))));
// TODO(@donnadionne): Reduce tolerance: increased the tolerance to keep the
// test from flaking while debugging potential root cause.
const double kErrorToleranceSmallLoad = 0.3;
gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
weight_75_request_count, weight_25_request_count);
EXPECT_THAT(weight_25_request_count,
::testing::AllOf(
::testing::Ge(static_cast<double>(kNumEchoRpcs) * kWeight25 /
100 * (1 - kErrorToleranceSmallLoad)),
::testing::Le(static_cast<double>(kNumEchoRpcs) * kWeight25 /
100 * (1 + kErrorToleranceSmallLoad))));
}
TEST_P(LdsRdsTest, XdsRoutingWeightedClusterUpdateWeights) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const char* kNewCluster3Name = "new_cluster_3";
const char* kNewEdsService3Name = "new_eds_service_name_3";
const size_t kNumEcho1Rpcs = 1000;
const size_t kNumEchoRpcs = 10;
const size_t kWeight75 = 75;
const size_t kWeight25 = 25;
const size_t kWeight50 = 50;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 3)},
});
AdsServiceImpl::EdsResourceArgs args3({
{"locality0", GetBackendPorts(3, 4)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args3, kNewEdsService3Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
Cluster new_cluster3 = default_cluster_;
new_cluster3.set_name(kNewCluster3Name);
new_cluster3.mutable_eds_cluster_config()->set_service_name(
kNewEdsService3Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster3);
// Populating Route Configurations.
RouteConfiguration new_route_config = default_route_config_;
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* weighted_cluster1 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster1->set_name(kNewCluster1Name);
weighted_cluster1->mutable_weight()->set_value(kWeight75);
auto* weighted_cluster2 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster2->set_name(kNewCluster2Name);
weighted_cluster2->mutable_weight()->set_value(kWeight25);
route1->mutable_route()
->mutable_weighted_clusters()
->mutable_total_weight()
->set_value(kWeight75 + kWeight25);
auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, new_route_config);
WaitForAllBackends(0, 1);
WaitForAllBackends(1, 3, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
CheckRpcSendOk(kNumEchoRpcs);
CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
const int weight_75_request_count =
backends_[1]->backend_service1()->request_count();
EXPECT_EQ(0, backends_[1]->backend_service2()->request_count());
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
const int weight_25_request_count =
backends_[2]->backend_service1()->request_count();
EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
const double kErrorTolerance = 0.2;
EXPECT_THAT(
weight_75_request_count,
::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
kWeight75 / 100 * (1 - kErrorTolerance)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
kWeight75 / 100 * (1 + kErrorTolerance))));
// TODO(@donnadionne): Reduce tolerance: increased the tolerance to keep the
// test from flaking while debugging potential root cause.
const double kErrorToleranceSmallLoad = 0.3;
gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
weight_75_request_count, weight_25_request_count);
EXPECT_THAT(weight_25_request_count,
::testing::AllOf(
::testing::Ge(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
100 * (1 - kErrorToleranceSmallLoad)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
100 * (1 + kErrorToleranceSmallLoad))));
// Change Route Configurations: same clusters different weights.
weighted_cluster1->mutable_weight()->set_value(kWeight50);
weighted_cluster2->mutable_weight()->set_value(kWeight50);
// Change default route to a new cluster to help to identify when new polices
// are seen by the client.
default_route->mutable_route()->set_cluster(kNewCluster3Name);
SetRouteConfiguration(0, new_route_config);
ResetBackendCounters();
WaitForAllBackends(3, 4);
CheckRpcSendOk(kNumEchoRpcs);
CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(0, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
const int weight_50_request_count_1 =
backends_[1]->backend_service1()->request_count();
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
const int weight_50_request_count_2 =
backends_[2]->backend_service1()->request_count();
EXPECT_EQ(kNumEchoRpcs, backends_[3]->backend_service()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
EXPECT_THAT(
weight_50_request_count_1,
::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
kWeight50 / 100 * (1 - kErrorTolerance)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
kWeight50 / 100 * (1 + kErrorTolerance))));
EXPECT_THAT(
weight_50_request_count_2,
::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
kWeight50 / 100 * (1 - kErrorTolerance)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
kWeight50 / 100 * (1 + kErrorTolerance))));
}
TEST_P(LdsRdsTest, XdsRoutingWeightedClusterUpdateClusters) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const char* kNewCluster3Name = "new_cluster_3";
const char* kNewEdsService3Name = "new_eds_service_name_3";
const size_t kNumEcho1Rpcs = 1000;
const size_t kNumEchoRpcs = 10;
const size_t kWeight75 = 75;
const size_t kWeight25 = 25;
const size_t kWeight50 = 50;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 3)},
});
AdsServiceImpl::EdsResourceArgs args3({
{"locality0", GetBackendPorts(3, 4)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args3, kNewEdsService3Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
Cluster new_cluster3 = default_cluster_;
new_cluster3.set_name(kNewCluster3Name);
new_cluster3.mutable_eds_cluster_config()->set_service_name(
kNewEdsService3Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster3);
// Populating Route Configurations.
RouteConfiguration new_route_config = default_route_config_;
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* weighted_cluster1 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster1->set_name(kNewCluster1Name);
weighted_cluster1->mutable_weight()->set_value(kWeight75);
auto* weighted_cluster2 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster2->set_name(kDefaultClusterName);
weighted_cluster2->mutable_weight()->set_value(kWeight25);
route1->mutable_route()
->mutable_weighted_clusters()
->mutable_total_weight()
->set_value(kWeight75 + kWeight25);
auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, new_route_config);
WaitForAllBackends(0, 1);
WaitForAllBackends(1, 2, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
CheckRpcSendOk(kNumEchoRpcs);
CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
int weight_25_request_count =
backends_[0]->backend_service1()->request_count();
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
int weight_75_request_count =
backends_[1]->backend_service1()->request_count();
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
EXPECT_EQ(0, backends_[2]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
const double kErrorTolerance = 0.2;
EXPECT_THAT(
weight_75_request_count,
::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
kWeight75 / 100 * (1 - kErrorTolerance)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
kWeight75 / 100 * (1 + kErrorTolerance))));
// TODO(@donnadionne): Reduce tolerance: increased the tolerance to keep the
// test from flaking while debugging potential root cause.
const double kErrorToleranceSmallLoad = 0.3;
gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
weight_75_request_count, weight_25_request_count);
EXPECT_THAT(weight_25_request_count,
::testing::AllOf(
::testing::Ge(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
100 * (1 - kErrorToleranceSmallLoad)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
100 * (1 + kErrorToleranceSmallLoad))));
// Change Route Configurations: new set of clusters with different weights.
weighted_cluster1->mutable_weight()->set_value(kWeight50);
weighted_cluster2->set_name(kNewCluster2Name);
weighted_cluster2->mutable_weight()->set_value(kWeight50);
SetRouteConfiguration(0, new_route_config);
ResetBackendCounters();
WaitForAllBackends(2, 3, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
CheckRpcSendOk(kNumEchoRpcs);
CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
const int weight_50_request_count_1 =
backends_[1]->backend_service1()->request_count();
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
const int weight_50_request_count_2 =
backends_[2]->backend_service1()->request_count();
EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
EXPECT_THAT(
weight_50_request_count_1,
::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
kWeight50 / 100 * (1 - kErrorTolerance)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
kWeight50 / 100 * (1 + kErrorTolerance))));
EXPECT_THAT(
weight_50_request_count_2,
::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
kWeight50 / 100 * (1 - kErrorTolerance)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
kWeight50 / 100 * (1 + kErrorTolerance))));
// Change Route Configurations.
weighted_cluster1->mutable_weight()->set_value(kWeight75);
weighted_cluster2->set_name(kNewCluster3Name);
weighted_cluster2->mutable_weight()->set_value(kWeight25);
SetRouteConfiguration(0, new_route_config);
ResetBackendCounters();
WaitForAllBackends(3, 4, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
CheckRpcSendOk(kNumEchoRpcs);
CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
weight_75_request_count = backends_[1]->backend_service1()->request_count();
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
EXPECT_EQ(0, backends_[2]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
weight_25_request_count = backends_[3]->backend_service1()->request_count();
EXPECT_THAT(
weight_75_request_count,
::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
kWeight75 / 100 * (1 - kErrorTolerance)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
kWeight75 / 100 * (1 + kErrorTolerance))));
// TODO(@donnadionne): Reduce tolerance: increased the tolerance to keep the
// test from flaking while debugging potential root cause.
gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
weight_75_request_count, weight_25_request_count);
EXPECT_THAT(weight_25_request_count,
::testing::AllOf(
::testing::Ge(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
100 * (1 - kErrorToleranceSmallLoad)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
100 * (1 + kErrorToleranceSmallLoad))));
}
TEST_P(LdsRdsTest, XdsRoutingClusterUpdateClusters) {
const char* kNewClusterName = "new_cluster";
const char* kNewEdsServiceName = "new_eds_service_name";
const size_t kNumEchoRpcs = 5;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsServiceName));
// Populate new CDS resources.
Cluster new_cluster = default_cluster_;
new_cluster.set_name(kNewClusterName);
new_cluster.mutable_eds_cluster_config()->set_service_name(
kNewEdsServiceName);
balancers_[0]->ads_service()->SetCdsResource(new_cluster);
// Send Route Configuration.
RouteConfiguration new_route_config = default_route_config_;
SetRouteConfiguration(0, new_route_config);
WaitForAllBackends(0, 1);
CheckRpcSendOk(kNumEchoRpcs);
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
// Change Route Configurations: new default cluster.
auto* default_route =
new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
default_route->mutable_route()->set_cluster(kNewClusterName);
SetRouteConfiguration(0, new_route_config);
WaitForAllBackends(1, 2);
CheckRpcSendOk(kNumEchoRpcs);
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(kNumEchoRpcs, backends_[1]->backend_service()->request_count());
}
TEST_P(LdsRdsTest, XdsRoutingClusterUpdateClustersWithPickingDelays) {
const char* kNewClusterName = "new_cluster";
const char* kNewEdsServiceName = "new_eds_service_name";
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsServiceName));
// Populate new CDS resources.
Cluster new_cluster = default_cluster_;
new_cluster.set_name(kNewClusterName);
new_cluster.mutable_eds_cluster_config()->set_service_name(
kNewEdsServiceName);
balancers_[0]->ads_service()->SetCdsResource(new_cluster);
// Bring down the current backend: 0, this will delay route picking time,
// resulting in un-committed RPCs.
ShutdownBackend(0);
// Send a RouteConfiguration with a default route that points to
// backend 0.
RouteConfiguration new_route_config = default_route_config_;
SetRouteConfiguration(0, new_route_config);
// Send exactly one RPC with no deadline and with wait_for_ready=true.
// This RPC will not complete until after backend 0 is started.
std::thread sending_rpc([this]() {
CheckRpcSendOk(1, RpcOptions().set_wait_for_ready(true).set_timeout_ms(0));
});
// Send a non-wait_for_ready RPC which should fail, this will tell us
// that the client has received the update and attempted to connect.
const Status status = SendRpc(RpcOptions().set_timeout_ms(0));
EXPECT_FALSE(status.ok());
// Send a update RouteConfiguration to use backend 1.
auto* default_route =
new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
default_route->mutable_route()->set_cluster(kNewClusterName);
SetRouteConfiguration(0, new_route_config);
// Wait for RPCs to go to the new backend: 1, this ensures that the client has
// processed the update.
WaitForAllBackends(1, 2, false, RpcOptions(), true);
// Bring up the previous backend: 0, this will allow the delayed RPC to
// finally call on_call_committed upon completion.
StartBackend(0);
sending_rpc.join();
// Make sure RPCs go to the correct backend:
EXPECT_EQ(1, backends_[0]->backend_service()->request_count());
EXPECT_EQ(1, backends_[1]->backend_service()->request_count());
}
TEST_P(LdsRdsTest, XdsRoutingApplyXdsTimeout) {
const int64_t kTimeoutMillis = 500;
const int64_t kTimeoutNano = kTimeoutMillis * 1000000;
const int64_t kTimeoutGrpcTimeoutHeaderMaxSecond = 1;
const int64_t kTimeoutMaxStreamDurationSecond = 2;
const int64_t kTimeoutHttpMaxStreamDurationSecond = 3;
const int64_t kTimeoutApplicationSecond = 4;
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const char* kNewCluster3Name = "new_cluster_3";
const char* kNewEdsService3Name = "new_eds_service_name_3";
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {grpc_pick_unused_port_or_die()}},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", {grpc_pick_unused_port_or_die()}},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", {grpc_pick_unused_port_or_die()}},
});
AdsServiceImpl::EdsResourceArgs args3({
{"locality0", {grpc_pick_unused_port_or_die()}},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args3, kNewEdsService3Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
Cluster new_cluster3 = default_cluster_;
new_cluster3.set_name(kNewCluster3Name);
new_cluster3.mutable_eds_cluster_config()->set_service_name(
kNewEdsService3Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster3);
// Construct listener.
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
// Set up HTTP max_stream_duration of 3.5 seconds
auto* duration =
http_connection_manager.mutable_common_http_protocol_options()
->mutable_max_stream_duration();
duration->set_seconds(kTimeoutHttpMaxStreamDurationSecond);
duration->set_nanos(kTimeoutNano);
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
// Construct route config.
RouteConfiguration new_route_config = default_route_config_;
// route 1: Set max_stream_duration of 2.5 seconds, Set
// grpc_timeout_header_max of 1.5
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/Echo1");
route1->mutable_route()->set_cluster(kNewCluster1Name);
auto* max_stream_duration =
route1->mutable_route()->mutable_max_stream_duration();
duration = max_stream_duration->mutable_max_stream_duration();
duration->set_seconds(kTimeoutMaxStreamDurationSecond);
duration->set_nanos(kTimeoutNano);
duration = max_stream_duration->mutable_grpc_timeout_header_max();
duration->set_seconds(kTimeoutGrpcTimeoutHeaderMaxSecond);
duration->set_nanos(kTimeoutNano);
// route 2: Set max_stream_duration of 2.5 seconds
auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
route2->mutable_match()->set_path("/grpc.testing.EchoTest2Service/Echo2");
route2->mutable_route()->set_cluster(kNewCluster2Name);
max_stream_duration = route2->mutable_route()->mutable_max_stream_duration();
duration = max_stream_duration->mutable_max_stream_duration();
duration->set_seconds(kTimeoutMaxStreamDurationSecond);
duration->set_nanos(kTimeoutNano);
// route 3: No timeout values in route configuration
auto* route3 = new_route_config.mutable_virtual_hosts(0)->add_routes();
route3->mutable_match()->set_path("/grpc.testing.EchoTestService/Echo");
route3->mutable_route()->set_cluster(kNewCluster3Name);
// Set listener and route config.
SetListenerAndRouteConfiguration(0, std::move(listener), new_route_config);
// Test grpc_timeout_header_max of 1.5 seconds applied
grpc_millis t0 = NowFromCycleCounter();
grpc_millis t1 =
t0 + kTimeoutGrpcTimeoutHeaderMaxSecond * 1000 + kTimeoutMillis;
grpc_millis t2 = t0 + kTimeoutMaxStreamDurationSecond * 1000 + kTimeoutMillis;
CheckRpcSendFailure(1,
RpcOptions()
.set_rpc_service(SERVICE_ECHO1)
.set_rpc_method(METHOD_ECHO1)
.set_wait_for_ready(true)
.set_timeout_ms(kTimeoutApplicationSecond * 1000),
StatusCode::DEADLINE_EXCEEDED);
t0 = NowFromCycleCounter();
EXPECT_GE(t0, t1);
EXPECT_LT(t0, t2);
// Test max_stream_duration of 2.5 seconds applied
t0 = NowFromCycleCounter();
t1 = t0 + kTimeoutMaxStreamDurationSecond * 1000 + kTimeoutMillis;
t2 = t0 + kTimeoutHttpMaxStreamDurationSecond * 1000 + kTimeoutMillis;
CheckRpcSendFailure(1,
RpcOptions()
.set_rpc_service(SERVICE_ECHO2)
.set_rpc_method(METHOD_ECHO2)
.set_wait_for_ready(true)
.set_timeout_ms(kTimeoutApplicationSecond * 1000),
StatusCode::DEADLINE_EXCEEDED);
t0 = NowFromCycleCounter();
EXPECT_GE(t0, t1);
EXPECT_LT(t0, t2);
// Test http_stream_duration of 3.5 seconds applied
t0 = NowFromCycleCounter();
t1 = t0 + kTimeoutHttpMaxStreamDurationSecond * 1000 + kTimeoutMillis;
t2 = t0 + kTimeoutApplicationSecond * 1000 + kTimeoutMillis;
CheckRpcSendFailure(1,
RpcOptions().set_wait_for_ready(true).set_timeout_ms(
kTimeoutApplicationSecond * 1000),
StatusCode::DEADLINE_EXCEEDED);
t0 = NowFromCycleCounter();
EXPECT_GE(t0, t1);
EXPECT_LT(t0, t2);
}
TEST_P(LdsRdsTest, XdsRoutingApplyApplicationTimeoutWhenXdsTimeoutExplicit0) {
const int64_t kTimeoutNano = 500000000;
const int64_t kTimeoutMaxStreamDurationSecond = 2;
const int64_t kTimeoutHttpMaxStreamDurationSecond = 3;
const int64_t kTimeoutApplicationSecond = 4;
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {grpc_pick_unused_port_or_die()}},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", {grpc_pick_unused_port_or_die()}},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", {grpc_pick_unused_port_or_die()}},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
// Construct listener.
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
// Set up HTTP max_stream_duration of 3.5 seconds
auto* duration =
http_connection_manager.mutable_common_http_protocol_options()
->mutable_max_stream_duration();
duration->set_seconds(kTimeoutHttpMaxStreamDurationSecond);
duration->set_nanos(kTimeoutNano);
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
// Construct route config.
RouteConfiguration new_route_config = default_route_config_;
// route 1: Set max_stream_duration of 2.5 seconds, Set
// grpc_timeout_header_max of 0
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/Echo1");
route1->mutable_route()->set_cluster(kNewCluster1Name);
auto* max_stream_duration =
route1->mutable_route()->mutable_max_stream_duration();
duration = max_stream_duration->mutable_max_stream_duration();
duration->set_seconds(kTimeoutMaxStreamDurationSecond);
duration->set_nanos(kTimeoutNano);
duration = max_stream_duration->mutable_grpc_timeout_header_max();
duration->set_seconds(0);
duration->set_nanos(0);
// route 2: Set max_stream_duration to 0
auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
route2->mutable_match()->set_path("/grpc.testing.EchoTest2Service/Echo2");
route2->mutable_route()->set_cluster(kNewCluster2Name);
max_stream_duration = route2->mutable_route()->mutable_max_stream_duration();
duration = max_stream_duration->mutable_max_stream_duration();
duration->set_seconds(0);
duration->set_nanos(0);
// Set listener and route config.
SetListenerAndRouteConfiguration(0, std::move(listener), new_route_config);
// Test application timeout is applied for route 1
auto t0 = system_clock::now();
CheckRpcSendFailure(1,
RpcOptions()
.set_rpc_service(SERVICE_ECHO1)
.set_rpc_method(METHOD_ECHO1)
.set_wait_for_ready(true)
.set_timeout_ms(kTimeoutApplicationSecond * 1000),
StatusCode::DEADLINE_EXCEEDED);
auto ellapsed_nano_seconds =
std::chrono::duration_cast<std::chrono::nanoseconds>(system_clock::now() -
t0);
EXPECT_GT(ellapsed_nano_seconds.count(),
kTimeoutApplicationSecond * 1000000000);
// Test application timeout is applied for route 2
t0 = system_clock::now();
CheckRpcSendFailure(1,
RpcOptions()
.set_rpc_service(SERVICE_ECHO2)
.set_rpc_method(METHOD_ECHO2)
.set_wait_for_ready(true)
.set_timeout_ms(kTimeoutApplicationSecond * 1000),
StatusCode::DEADLINE_EXCEEDED);
ellapsed_nano_seconds = std::chrono::duration_cast<std::chrono::nanoseconds>(
system_clock::now() - t0);
EXPECT_GT(ellapsed_nano_seconds.count(),
kTimeoutApplicationSecond * 1000000000);
}
TEST_P(LdsRdsTest, XdsRoutingApplyApplicationTimeoutWhenHttpTimeoutExplicit0) {
const int64_t kTimeoutApplicationSecond = 4;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {grpc_pick_unused_port_or_die()}},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
// Set up HTTP max_stream_duration to be explicit 0
auto* duration =
http_connection_manager.mutable_common_http_protocol_options()
->mutable_max_stream_duration();
duration->set_seconds(0);
duration->set_nanos(0);
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
// Set listener and route config.
SetListenerAndRouteConfiguration(0, std::move(listener),
default_route_config_);
// Test application timeout is applied for route 1
auto t0 = system_clock::now();
CheckRpcSendFailure(1,
RpcOptions().set_wait_for_ready(true).set_timeout_ms(
kTimeoutApplicationSecond * 1000),
StatusCode::DEADLINE_EXCEEDED);
auto ellapsed_nano_seconds =
std::chrono::duration_cast<std::chrono::nanoseconds>(system_clock::now() -
t0);
EXPECT_GT(ellapsed_nano_seconds.count(),
kTimeoutApplicationSecond * 1000000000);
}
// Test to ensure application-specified deadline won't be affected when
// the xDS config does not specify a timeout.
TEST_P(LdsRdsTest, XdsRoutingWithOnlyApplicationTimeout) {
const int64_t kTimeoutApplicationSecond = 4;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {grpc_pick_unused_port_or_die()}},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
auto t0 = system_clock::now();
CheckRpcSendFailure(1,
RpcOptions().set_wait_for_ready(true).set_timeout_ms(
kTimeoutApplicationSecond * 1000),
StatusCode::DEADLINE_EXCEEDED);
auto ellapsed_nano_seconds =
std::chrono::duration_cast<std::chrono::nanoseconds>(system_clock::now() -
t0);
EXPECT_GT(ellapsed_nano_seconds.count(),
kTimeoutApplicationSecond * 1000000000);
}
TEST_P(LdsRdsTest, XdsRoutingHeadersMatching) {
const char* kNewClusterName = "new_cluster";
const char* kNewEdsServiceName = "new_eds_service_name";
const size_t kNumEcho1Rpcs = 100;
const size_t kNumEchoRpcs = 5;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsServiceName));
// Populate new CDS resources.
Cluster new_cluster = default_cluster_;
new_cluster.set_name(kNewClusterName);
new_cluster.mutable_eds_cluster_config()->set_service_name(
kNewEdsServiceName);
balancers_[0]->ads_service()->SetCdsResource(new_cluster);
// Populating Route Configurations for LDS.
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* header_matcher1 = route1->mutable_match()->add_headers();
header_matcher1->set_name("header1");
header_matcher1->set_exact_match("POST,PUT,GET");
auto* header_matcher2 = route1->mutable_match()->add_headers();
header_matcher2->set_name("header2");
header_matcher2->mutable_safe_regex_match()->set_regex("[a-z]*");
auto* header_matcher3 = route1->mutable_match()->add_headers();
header_matcher3->set_name("header3");
header_matcher3->mutable_range_match()->set_start(1);
header_matcher3->mutable_range_match()->set_end(1000);
auto* header_matcher4 = route1->mutable_match()->add_headers();
header_matcher4->set_name("header4");
header_matcher4->set_present_match(false);
auto* header_matcher5 = route1->mutable_match()->add_headers();
header_matcher5->set_name("header5");
header_matcher5->set_present_match(true);
auto* header_matcher6 = route1->mutable_match()->add_headers();
header_matcher6->set_name("header6");
header_matcher6->set_prefix_match("/grpc");
auto* header_matcher7 = route1->mutable_match()->add_headers();
header_matcher7->set_name("header7");
header_matcher7->set_suffix_match(".cc");
header_matcher7->set_invert_match(true);
route1->mutable_route()->set_cluster(kNewClusterName);
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
std::vector<std::pair<std::string, std::string>> metadata = {
{"header1", "POST"},
{"header2", "blah"},
{"header3", "1"},
{"header5", "anything"},
{"header6", "/grpc.testing.EchoTest1Service/"},
{"header1", "PUT"},
{"header7", "grpc.java"},
{"header1", "GET"},
};
const auto header_match_rpc_options = RpcOptions()
.set_rpc_service(SERVICE_ECHO1)
.set_rpc_method(METHOD_ECHO1)
.set_metadata(std::move(metadata));
// Make sure all backends are up.
WaitForAllBackends(0, 1);
WaitForAllBackends(1, 2, true, header_match_rpc_options);
// Send RPCs.
CheckRpcSendOk(kNumEchoRpcs);
CheckRpcSendOk(kNumEcho1Rpcs, header_match_rpc_options);
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service2()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
EXPECT_EQ(kNumEcho1Rpcs, backends_[1]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service2()->request_count());
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
}
TEST_P(LdsRdsTest, XdsRoutingHeadersMatchingSpecialHeaderContentType) {
const char* kNewClusterName = "new_cluster";
const char* kNewEdsServiceName = "new_eds_service_name";
const size_t kNumEchoRpcs = 100;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsServiceName));
// Populate new CDS resources.
Cluster new_cluster = default_cluster_;
new_cluster.set_name(kNewClusterName);
new_cluster.mutable_eds_cluster_config()->set_service_name(
kNewEdsServiceName);
balancers_[0]->ads_service()->SetCdsResource(new_cluster);
// Populating Route Configurations for LDS.
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("");
auto* header_matcher1 = route1->mutable_match()->add_headers();
header_matcher1->set_name("content-type");
header_matcher1->set_exact_match("notapplication/grpc");
route1->mutable_route()->set_cluster(kNewClusterName);
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
auto* header_matcher2 = default_route->mutable_match()->add_headers();
header_matcher2->set_name("content-type");
header_matcher2->set_exact_match("application/grpc");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
// Make sure the backend is up.
WaitForAllBackends(0, 1);
// Send RPCs.
CheckRpcSendOk(kNumEchoRpcs);
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
}
TEST_P(LdsRdsTest, XdsRoutingHeadersMatchingSpecialCasesToIgnore) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const size_t kNumEchoRpcs = 100;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
// Populating Route Configurations for LDS.
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("");
auto* header_matcher1 = route1->mutable_match()->add_headers();
header_matcher1->set_name("grpc-foo-bin");
header_matcher1->set_present_match(true);
route1->mutable_route()->set_cluster(kNewCluster1Name);
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
// Send headers which will mismatch each route
std::vector<std::pair<std::string, std::string>> metadata = {
{"grpc-foo-bin", "grpc-foo-bin"},
};
WaitForAllBackends(0, 1);
CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_metadata(metadata));
// Verify that only the default backend got RPCs since all previous routes
// were mismatched.
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
}
TEST_P(LdsRdsTest, XdsRoutingRuntimeFractionMatching) {
const char* kNewClusterName = "new_cluster";
const char* kNewEdsServiceName = "new_eds_service_name";
const size_t kNumRpcs = 1000;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsServiceName));
// Populate new CDS resources.
Cluster new_cluster = default_cluster_;
new_cluster.set_name(kNewClusterName);
new_cluster.mutable_eds_cluster_config()->set_service_name(
kNewEdsServiceName);
balancers_[0]->ads_service()->SetCdsResource(new_cluster);
// Populating Route Configurations for LDS.
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()
->mutable_runtime_fraction()
->mutable_default_value()
->set_numerator(25);
route1->mutable_route()->set_cluster(kNewClusterName);
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
WaitForAllBackends(0, 2);
CheckRpcSendOk(kNumRpcs);
const int default_backend_count =
backends_[0]->backend_service()->request_count();
const int matched_backend_count =
backends_[1]->backend_service()->request_count();
const double kErrorTolerance = 0.2;
EXPECT_THAT(
default_backend_count,
::testing::AllOf(::testing::Ge(static_cast<double>(kNumRpcs) * 75 / 100 *
(1 - kErrorTolerance)),
::testing::Le(static_cast<double>(kNumRpcs) * 75 / 100 *
(1 + kErrorTolerance))));
EXPECT_THAT(
matched_backend_count,
::testing::AllOf(::testing::Ge(static_cast<double>(kNumRpcs) * 25 / 100 *
(1 - kErrorTolerance)),
::testing::Le(static_cast<double>(kNumRpcs) * 25 / 100 *
(1 + kErrorTolerance))));
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
}
TEST_P(LdsRdsTest, XdsRoutingHeadersMatchingUnmatchCases) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const char* kNewCluster3Name = "new_cluster_3";
const char* kNewEdsService3Name = "new_eds_service_name_3";
const size_t kNumEcho1Rpcs = 100;
const size_t kNumEchoRpcs = 5;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 3)},
});
AdsServiceImpl::EdsResourceArgs args3({
{"locality0", GetBackendPorts(3, 4)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args3, kNewEdsService3Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
Cluster new_cluster3 = default_cluster_;
new_cluster3.set_name(kNewCluster3Name);
new_cluster3.mutable_eds_cluster_config()->set_service_name(
kNewEdsService3Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster3);
// Populating Route Configurations for LDS.
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* header_matcher1 = route1->mutable_match()->add_headers();
header_matcher1->set_name("header1");
header_matcher1->set_exact_match("POST");
route1->mutable_route()->set_cluster(kNewCluster1Name);
auto route2 = route_config.mutable_virtual_hosts(0)->add_routes();
route2->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* header_matcher2 = route2->mutable_match()->add_headers();
header_matcher2->set_name("header2");
header_matcher2->mutable_range_match()->set_start(1);
header_matcher2->mutable_range_match()->set_end(1000);
route2->mutable_route()->set_cluster(kNewCluster2Name);
auto route3 = route_config.mutable_virtual_hosts(0)->add_routes();
route3->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* header_matcher3 = route3->mutable_match()->add_headers();
header_matcher3->set_name("header3");
header_matcher3->mutable_safe_regex_match()->set_regex("[a-z]*");
route3->mutable_route()->set_cluster(kNewCluster3Name);
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
// Send headers which will mismatch each route
std::vector<std::pair<std::string, std::string>> metadata = {
{"header1", "POST"},
{"header2", "1000"},
{"header3", "123"},
{"header1", "GET"},
};
WaitForAllBackends(0, 1);
CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_metadata(metadata));
CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions()
.set_rpc_service(SERVICE_ECHO1)
.set_rpc_method(METHOD_ECHO1)
.set_metadata(metadata));
// Verify that only the default backend got RPCs since all previous routes
// were mismatched.
for (size_t i = 1; i < 4; ++i) {
EXPECT_EQ(0, backends_[i]->backend_service()->request_count());
EXPECT_EQ(0, backends_[i]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[i]->backend_service2()->request_count());
}
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
EXPECT_EQ(kNumEcho1Rpcs, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service2()->request_count());
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
}
TEST_P(LdsRdsTest, XdsRoutingChangeRoutesWithoutChangingClusters) {
const char* kNewClusterName = "new_cluster";
const char* kNewEdsServiceName = "new_eds_service_name";
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsServiceName));
// Populate new CDS resources.
Cluster new_cluster = default_cluster_;
new_cluster.set_name(kNewClusterName);
new_cluster.mutable_eds_cluster_config()->set_service_name(
kNewEdsServiceName);
balancers_[0]->ads_service()->SetCdsResource(new_cluster);
// Populating Route Configurations for LDS.
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
route1->mutable_route()->set_cluster(kNewClusterName);
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
// Make sure all backends are up and that requests for each RPC
// service go to the right backends.
WaitForAllBackends(0, 1, false);
WaitForAllBackends(1, 2, false, RpcOptions().set_rpc_service(SERVICE_ECHO1));
WaitForAllBackends(0, 1, false, RpcOptions().set_rpc_service(SERVICE_ECHO2));
// Requests for services Echo and Echo2 should have gone to backend 0.
EXPECT_EQ(1, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(1, backends_[0]->backend_service2()->request_count());
// Requests for service Echo1 should have gone to backend 1.
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
EXPECT_EQ(1, backends_[1]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service2()->request_count());
// Now send an update that changes the first route to match a
// different RPC service, and wait for the client to make the change.
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest2Service/");
SetRouteConfiguration(0, route_config);
WaitForAllBackends(1, 2, true, RpcOptions().set_rpc_service(SERVICE_ECHO2));
// Now repeat the earlier test, making sure all traffic goes to the
// right place.
WaitForAllBackends(0, 1, false);
WaitForAllBackends(0, 1, false, RpcOptions().set_rpc_service(SERVICE_ECHO1));
WaitForAllBackends(1, 2, false, RpcOptions().set_rpc_service(SERVICE_ECHO2));
// Requests for services Echo and Echo1 should have gone to backend 0.
EXPECT_EQ(1, backends_[0]->backend_service()->request_count());
EXPECT_EQ(1, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service2()->request_count());
// Requests for service Echo2 should have gone to backend 1.
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service1()->request_count());
EXPECT_EQ(1, backends_[1]->backend_service2()->request_count());
}
// Test that we NACK unknown filter types in VirtualHost.
TEST_P(LdsRdsTest, RejectsUnknownHttpFilterTypeInVirtualHost) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config =
route_config.mutable_virtual_hosts(0)->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"].PackFrom(Listener());
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("no filter registered for config type "
"envoy.config.listener.v3.Listener"));
}
// Test that we ignore optional unknown filter types in VirtualHost.
TEST_P(LdsRdsTest, IgnoresOptionalUnknownHttpFilterTypeInVirtualHost) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config =
route_config.mutable_virtual_hosts(0)->mutable_typed_per_filter_config();
::envoy::config::route::v3::FilterConfig filter_config;
filter_config.mutable_config()->PackFrom(Listener());
filter_config.set_is_optional(true);
(*per_filter_config)["unknown"].PackFrom(filter_config);
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
WaitForAllBackends();
EXPECT_EQ(RouteConfigurationResponseState(0).state,
AdsServiceImpl::ResponseState::ACKED);
}
// Test that we NACK filters without configs in VirtualHost.
TEST_P(LdsRdsTest, RejectsHttpFilterWithoutConfigInVirtualHost) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config =
route_config.mutable_virtual_hosts(0)->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"];
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"no filter config specified for filter name unknown"));
}
// Test that we NACK filters without configs in FilterConfig in VirtualHost.
TEST_P(LdsRdsTest, RejectsHttpFilterWithoutConfigInFilterConfigInVirtualHost) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config =
route_config.mutable_virtual_hosts(0)->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"].PackFrom(
::envoy::config::route::v3::FilterConfig());
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"no filter config specified for filter name unknown"));
}
// Test that we ignore optional filters without configs in VirtualHost.
TEST_P(LdsRdsTest, IgnoresOptionalHttpFilterWithoutConfigInVirtualHost) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config =
route_config.mutable_virtual_hosts(0)->mutable_typed_per_filter_config();
::envoy::config::route::v3::FilterConfig filter_config;
filter_config.set_is_optional(true);
(*per_filter_config)["unknown"].PackFrom(filter_config);
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
WaitForAllBackends();
EXPECT_EQ(RouteConfigurationResponseState(0).state,
AdsServiceImpl::ResponseState::ACKED);
}
// Test that we NACK unparseable filter types in VirtualHost.
TEST_P(LdsRdsTest, RejectsUnparseableHttpFilterTypeInVirtualHost) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config =
route_config.mutable_virtual_hosts(0)->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"].PackFrom(
envoy::extensions::filters::http::router::v3::Router());
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("router filter does not support config override"));
}
// Test that we NACK unknown filter types in Route.
TEST_P(LdsRdsTest, RejectsUnknownHttpFilterTypeInRoute) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"].PackFrom(Listener());
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("no filter registered for config type "
"envoy.config.listener.v3.Listener"));
}
// Test that we ignore optional unknown filter types in Route.
TEST_P(LdsRdsTest, IgnoresOptionalUnknownHttpFilterTypeInRoute) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_typed_per_filter_config();
::envoy::config::route::v3::FilterConfig filter_config;
filter_config.mutable_config()->PackFrom(Listener());
filter_config.set_is_optional(true);
(*per_filter_config)["unknown"].PackFrom(filter_config);
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
WaitForAllBackends();
EXPECT_EQ(RouteConfigurationResponseState(0).state,
AdsServiceImpl::ResponseState::ACKED);
}
// Test that we NACK filters without configs in Route.
TEST_P(LdsRdsTest, RejectsHttpFilterWithoutConfigInRoute) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"];
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"no filter config specified for filter name unknown"));
}
// Test that we NACK filters without configs in FilterConfig in Route.
TEST_P(LdsRdsTest, RejectsHttpFilterWithoutConfigInFilterConfigInRoute) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"].PackFrom(
::envoy::config::route::v3::FilterConfig());
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"no filter config specified for filter name unknown"));
}
// Test that we ignore optional filters without configs in Route.
TEST_P(LdsRdsTest, IgnoresOptionalHttpFilterWithoutConfigInRoute) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_typed_per_filter_config();
::envoy::config::route::v3::FilterConfig filter_config;
filter_config.set_is_optional(true);
(*per_filter_config)["unknown"].PackFrom(filter_config);
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
WaitForAllBackends();
EXPECT_EQ(RouteConfigurationResponseState(0).state,
AdsServiceImpl::ResponseState::ACKED);
}
// Test that we NACK unparseable filter types in Route.
TEST_P(LdsRdsTest, RejectsUnparseableHttpFilterTypeInRoute) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"].PackFrom(
envoy::extensions::filters::http::router::v3::Router());
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("router filter does not support config override"));
}
// Test that we NACK unknown filter types in ClusterWeight.
TEST_P(LdsRdsTest, RejectsUnknownHttpFilterTypeInClusterWeight) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* cluster_weight = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_weighted_clusters()
->add_clusters();
cluster_weight->set_name(kDefaultClusterName);
cluster_weight->mutable_weight()->set_value(100);
auto* per_filter_config = cluster_weight->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"].PackFrom(Listener());
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("no filter registered for config type "
"envoy.config.listener.v3.Listener"));
}
// Test that we ignore optional unknown filter types in ClusterWeight.
TEST_P(LdsRdsTest, IgnoresOptionalUnknownHttpFilterTypeInClusterWeight) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* cluster_weight = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_weighted_clusters()
->add_clusters();
cluster_weight->set_name(kDefaultClusterName);
cluster_weight->mutable_weight()->set_value(100);
auto* per_filter_config = cluster_weight->mutable_typed_per_filter_config();
::envoy::config::route::v3::FilterConfig filter_config;
filter_config.mutable_config()->PackFrom(Listener());
filter_config.set_is_optional(true);
(*per_filter_config)["unknown"].PackFrom(filter_config);
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
WaitForAllBackends();
EXPECT_EQ(RouteConfigurationResponseState(0).state,
AdsServiceImpl::ResponseState::ACKED);
}
// Test that we NACK filters without configs in ClusterWeight.
TEST_P(LdsRdsTest, RejectsHttpFilterWithoutConfigInClusterWeight) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* cluster_weight = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_weighted_clusters()
->add_clusters();
cluster_weight->set_name(kDefaultClusterName);
cluster_weight->mutable_weight()->set_value(100);
auto* per_filter_config = cluster_weight->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"];
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"no filter config specified for filter name unknown"));
}
// Test that we NACK filters without configs in FilterConfig in ClusterWeight.
TEST_P(LdsRdsTest,
RejectsHttpFilterWithoutConfigInFilterConfigInClusterWeight) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* cluster_weight = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_weighted_clusters()
->add_clusters();
cluster_weight->set_name(kDefaultClusterName);
cluster_weight->mutable_weight()->set_value(100);
auto* per_filter_config = cluster_weight->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"].PackFrom(
::envoy::config::route::v3::FilterConfig());
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"no filter config specified for filter name unknown"));
}
// Test that we ignore optional filters without configs in ClusterWeight.
TEST_P(LdsRdsTest, IgnoresOptionalHttpFilterWithoutConfigInClusterWeight) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* cluster_weight = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_weighted_clusters()
->add_clusters();
cluster_weight->set_name(kDefaultClusterName);
cluster_weight->mutable_weight()->set_value(100);
auto* per_filter_config = cluster_weight->mutable_typed_per_filter_config();
::envoy::config::route::v3::FilterConfig filter_config;
filter_config.set_is_optional(true);
(*per_filter_config)["unknown"].PackFrom(filter_config);
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
WaitForAllBackends();
EXPECT_EQ(RouteConfigurationResponseState(0).state,
AdsServiceImpl::ResponseState::ACKED);
}
// Test that we NACK unparseable filter types in ClusterWeight.
TEST_P(LdsRdsTest, RejectsUnparseableHttpFilterTypeInClusterWeight) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* cluster_weight = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_weighted_clusters()
->add_clusters();
cluster_weight->set_name(kDefaultClusterName);
cluster_weight->mutable_weight()->set_value(100);
auto* per_filter_config = cluster_weight->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"].PackFrom(
envoy::extensions::filters::http::router::v3::Router());
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("router filter does not support config override"));
}
using CdsTest = BasicTest;
// Tests that CDS client should send an ACK upon correct CDS response.
TEST_P(CdsTest, Vanilla) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state().state,
AdsServiceImpl::ResponseState::ACKED);
}
TEST_P(CdsTest, LogicalDNSClusterType) {
gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
"true");
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Create Logical DNS Cluster
auto cluster = default_cluster_;
cluster.set_type(Cluster::LOGICAL_DNS);
balancers_[0]->ads_service()->SetCdsResource(cluster);
// Set Logical DNS result
{
grpc_core::ExecCtx exec_ctx;
grpc_core::Resolver::Result result;
result.addresses = CreateAddressListFromPortList(GetBackendPorts(1, 2));
logical_dns_cluster_resolver_response_generator_->SetResponse(
std::move(result));
}
// Wait for traffic to go to backend 1.
WaitForBackend(1);
gpr_unsetenv(
"GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
}
TEST_P(CdsTest, AggregateClusterType) {
gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
"true");
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 3)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
// Create Aggregate Cluster
auto cluster = default_cluster_;
CustomClusterType* custom_cluster = cluster.mutable_cluster_type();
custom_cluster->set_name("envoy.clusters.aggregate");
ClusterConfig cluster_config;
cluster_config.add_clusters(kNewCluster1Name);
cluster_config.add_clusters(kNewCluster2Name);
custom_cluster->mutable_typed_config()->PackFrom(cluster_config);
balancers_[0]->ads_service()->SetCdsResource(cluster);
// Wait for traffic to go to backend 1.
WaitForBackend(1);
// Shutdown backend 1 and wait for all traffic to go to backend 2.
ShutdownBackend(1);
WaitForBackend(2);
EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state().state,
AdsServiceImpl::ResponseState::ACKED);
// Bring backend 1 back and ensure all traffic go back to it.
StartBackend(1);
WaitForBackend(1);
gpr_unsetenv(
"GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
}
TEST_P(CdsTest, AggregateClusterEdsToLogicalDns) {
gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
"true");
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kLogicalDNSClusterName = "logical_dns_cluster";
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
// Create Logical DNS Cluster
auto logical_dns_cluster = default_cluster_;
logical_dns_cluster.set_name(kLogicalDNSClusterName);
logical_dns_cluster.set_type(Cluster::LOGICAL_DNS);
balancers_[0]->ads_service()->SetCdsResource(logical_dns_cluster);
// Create Aggregate Cluster
auto cluster = default_cluster_;
CustomClusterType* custom_cluster = cluster.mutable_cluster_type();
custom_cluster->set_name("envoy.clusters.aggregate");
ClusterConfig cluster_config;
cluster_config.add_clusters(kNewCluster1Name);
cluster_config.add_clusters(kLogicalDNSClusterName);
custom_cluster->mutable_typed_config()->PackFrom(cluster_config);
balancers_[0]->ads_service()->SetCdsResource(cluster);
// Set Logical DNS result
{
grpc_core::ExecCtx exec_ctx;
grpc_core::Resolver::Result result;
result.addresses = CreateAddressListFromPortList(GetBackendPorts(2, 3));
logical_dns_cluster_resolver_response_generator_->SetResponse(
std::move(result));
}
// Wait for traffic to go to backend 1.
WaitForBackend(1);
// Shutdown backend 1 and wait for all traffic to go to backend 2.
ShutdownBackend(1);
WaitForBackend(2);
EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state().state,
AdsServiceImpl::ResponseState::ACKED);
// Bring backend 1 back and ensure all traffic go back to it.
StartBackend(1);
WaitForBackend(1);
gpr_unsetenv(
"GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
}
TEST_P(CdsTest, AggregateClusterLogicalDnsToEds) {
gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
"true");
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const char* kLogicalDNSClusterName = "logical_dns_cluster";
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 3)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
// Populate new CDS resources.
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
// Create Logical DNS Cluster
auto logical_dns_cluster = default_cluster_;
logical_dns_cluster.set_name(kLogicalDNSClusterName);
logical_dns_cluster.set_type(Cluster::LOGICAL_DNS);
balancers_[0]->ads_service()->SetCdsResource(logical_dns_cluster);
// Create Aggregate Cluster
auto cluster = default_cluster_;
CustomClusterType* custom_cluster = cluster.mutable_cluster_type();
custom_cluster->set_name("envoy.clusters.aggregate");
ClusterConfig cluster_config;
cluster_config.add_clusters(kLogicalDNSClusterName);
cluster_config.add_clusters(kNewCluster2Name);
custom_cluster->mutable_typed_config()->PackFrom(cluster_config);
balancers_[0]->ads_service()->SetCdsResource(cluster);
// Set Logical DNS result
{
grpc_core::ExecCtx exec_ctx;
grpc_core::Resolver::Result result;
result.addresses = CreateAddressListFromPortList(GetBackendPorts(1, 2));
logical_dns_cluster_resolver_response_generator_->SetResponse(
std::move(result));
}
// Wait for traffic to go to backend 1.
WaitForBackend(1);
// Shutdown backend 1 and wait for all traffic to go to backend 2.
ShutdownBackend(1);
WaitForBackend(2);
EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state().state,
AdsServiceImpl::ResponseState::ACKED);
// Bring backend 1 back and ensure all traffic go back to it.
StartBackend(1);
WaitForBackend(1);
gpr_unsetenv(
"GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
}
// Test that CDS client should send a NACK if cluster type is Logical DNS but
// the feature is not yet supported.
TEST_P(CdsTest, LogicalDNSClusterTypeDisabled) {
auto cluster = default_cluster_;
cluster.set_type(Cluster::LOGICAL_DNS);
balancers_[0]->ads_service()->SetCdsResource(cluster);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->cds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("DiscoveryType is not valid."));
}
// Test that CDS client should send a NACK if cluster type is AGGREGATE but
// the feature is not yet supported.
TEST_P(CdsTest, AggregateClusterTypeDisabled) {
auto cluster = default_cluster_;
CustomClusterType* custom_cluster = cluster.mutable_cluster_type();
custom_cluster->set_name("envoy.clusters.aggregate");
ClusterConfig cluster_config;
cluster_config.add_clusters("cluster1");
cluster_config.add_clusters("cluster2");
custom_cluster->mutable_typed_config()->PackFrom(cluster_config);
cluster.set_type(Cluster::LOGICAL_DNS);
balancers_[0]->ads_service()->SetCdsResource(cluster);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->cds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("DiscoveryType is not valid."));
}
// Tests that CDS client should send a NACK if the cluster type in CDS response
// is unsupported.
TEST_P(CdsTest, UnsupportedClusterType) {
auto cluster = default_cluster_;
cluster.set_type(Cluster::STATIC);
balancers_[0]->ads_service()->SetCdsResource(cluster);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->cds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("DiscoveryType is not valid."));
}
// Tests that the NACK for multiple bad resources includes both errors.
TEST_P(CdsTest, MultipleBadResources) {
constexpr char kClusterName2[] = "cluster_name_2";
// Use unsupported type for default cluster.
auto cluster = default_cluster_;
cluster.set_type(Cluster::STATIC);
balancers_[0]->ads_service()->SetCdsResource(cluster);
// Add second cluster with the same error.
cluster.set_name(kClusterName2);
balancers_[0]->ads_service()->SetCdsResource(cluster);
// Change RouteConfig to point to both clusters.
RouteConfiguration route_config = default_route_config_;
auto* route = route_config.mutable_virtual_hosts(0)->add_routes();
route->mutable_match()->set_prefix("");
route->mutable_route()->set_cluster(kClusterName2);
SetRouteConfiguration(0, route_config);
// Send RPC.
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->cds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::AllOf(
::testing::HasSubstr(absl::StrCat(
kDefaultClusterName, ": DiscoveryType is not valid.")),
::testing::HasSubstr(absl::StrCat(
kClusterName2, ": DiscoveryType is not valid."))));
}
// Tests that CDS client should send a NACK if the eds_config in CDS response is
// other than ADS.
TEST_P(CdsTest, WrongEdsConfig) {
auto cluster = default_cluster_;
cluster.mutable_eds_cluster_config()->mutable_eds_config()->mutable_self();
balancers_[0]->ads_service()->SetCdsResource(cluster);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->cds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("EDS ConfigSource is not ADS."));
}
// Tests that CDS client should send a NACK if the lb_policy in CDS response is
// other than ROUND_ROBIN.
TEST_P(CdsTest, WrongLbPolicy) {
auto cluster = default_cluster_;
cluster.set_lb_policy(Cluster::LEAST_REQUEST);
balancers_[0]->ads_service()->SetCdsResource(cluster);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->cds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("LB policy is not supported."));
}
// Tests that CDS client should send a NACK if the lrs_server in CDS response is
// other than SELF.
TEST_P(CdsTest, WrongLrsServer) {
auto cluster = default_cluster_;
cluster.mutable_lrs_server()->mutable_ads();
balancers_[0]->ads_service()->SetCdsResource(cluster);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->cds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("LRS ConfigSource is not self."));
}
class XdsSecurityTest : public BasicTest {
protected:
static void SetUpTestCase() {
gpr_setenv("GRPC_XDS_EXPERIMENTAL_SECURITY_SUPPORT", "true");
BasicTest::SetUpTestCase();
}
static void TearDownTestCase() {
BasicTest::TearDownTestCase();
gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_SECURITY_SUPPORT");
}
void SetUp() override {
BasicTest::SetUp();
root_cert_ = ReadFile(kCaCertPath);
bad_root_cert_ = ReadFile(kBadClientCertPath);
identity_pair_ = ReadTlsIdentityPair(kClientKeyPath, kClientCertPath);
// TODO(yashykt): Use different client certs here instead of reusing server
// certs after https://github.com/grpc/grpc/pull/24876 is merged
fallback_identity_pair_ =
ReadTlsIdentityPair(kServerKeyPath, kServerCertPath);
bad_identity_pair_ =
ReadTlsIdentityPair(kBadClientKeyPath, kBadClientCertPath);
server_san_exact_.set_exact("*.test.google.fr");
server_san_prefix_.set_prefix("waterzooi.test.google");
server_san_suffix_.set_suffix("google.fr");
server_san_contains_.set_contains("google");
server_san_regex_.mutable_safe_regex()->mutable_google_re2();
server_san_regex_.mutable_safe_regex()->set_regex(
"(foo|waterzooi).test.google.(fr|be)");
bad_san_1_.set_exact("192.168.1.4");
bad_san_2_.set_exact("foo.test.google.in");
authenticated_identity_ = {"testclient"};
fallback_authenticated_identity_ = {"*.test.google.fr",
"waterzooi.test.google.be",
"*.test.youtube.com", "192.168.1.3"};
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolutionForLbChannelAllBalancers();
}
void TearDown() override {
g_fake1_cert_data_map = nullptr;
g_fake2_cert_data_map = nullptr;
BasicTest::TearDown();
}
// Sends CDS updates with the new security configuration and verifies that
// after propagation, this new configuration is used for connections. If \a
// identity_instance_name and \a root_instance_name are both empty,
// connections are expected to use fallback credentials.
void UpdateAndVerifyXdsSecurityConfiguration(
absl::string_view root_instance_name,
absl::string_view root_certificate_name,
absl::string_view identity_instance_name,
absl::string_view identity_certificate_name,
const std::vector<StringMatcher>& san_matchers,
const std::vector<std::string>& expected_authenticated_identity,
bool test_expects_failure = false) {
auto cluster = default_cluster_;
if (!identity_instance_name.empty() || !root_instance_name.empty()) {
auto* transport_socket = cluster.mutable_transport_socket();
transport_socket->set_name("envoy.transport_sockets.tls");
UpstreamTlsContext upstream_tls_context;
if (!identity_instance_name.empty()) {
upstream_tls_context.mutable_common_tls_context()
->mutable_tls_certificate_certificate_provider_instance()
->set_instance_name(std::string(identity_instance_name));
upstream_tls_context.mutable_common_tls_context()
->mutable_tls_certificate_certificate_provider_instance()
->set_certificate_name(std::string(identity_certificate_name));
}
if (!root_instance_name.empty()) {
upstream_tls_context.mutable_common_tls_context()
->mutable_combined_validation_context()
->mutable_validation_context_certificate_provider_instance()
->set_instance_name(std::string(root_instance_name));
upstream_tls_context.mutable_common_tls_context()
->mutable_combined_validation_context()
->mutable_validation_context_certificate_provider_instance()
->set_certificate_name(std::string(root_certificate_name));
}
if (!san_matchers.empty()) {
auto* validation_context =
upstream_tls_context.mutable_common_tls_context()
->mutable_combined_validation_context()
->mutable_default_validation_context();
for (const auto& san_matcher : san_matchers) {
*validation_context->add_match_subject_alt_names() = san_matcher;
}
}
transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
}
balancers_[0]->ads_service()->SetCdsResource(cluster);
// The updates might take time to have an effect, so use a retry loop.
constexpr int kRetryCount = 100;
int num_tries = 0;
for (; num_tries < kRetryCount; num_tries++) {
// Give some time for the updates to propagate.
gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(100));
if (test_expects_failure) {
// Restart the servers to force a reconnection so that previously
// connected subchannels are not used for the RPC.
ShutdownBackend(0);
StartBackend(0);
if (SendRpc().ok()) {
gpr_log(GPR_ERROR, "RPC succeeded. Failure expected. Trying again.");
continue;
}
} else {
WaitForBackend(0);
Status status = SendRpc();
if (!status.ok()) {
gpr_log(GPR_ERROR, "RPC failed. code=%d message=%s Trying again.",
status.error_code(), status.error_message().c_str());
continue;
}
if (backends_[0]->backend_service()->last_peer_identity() !=
expected_authenticated_identity) {
gpr_log(
GPR_ERROR,
"Expected client identity does not match. (actual) %s vs "
"(expected) %s Trying again.",
absl::StrJoin(
backends_[0]->backend_service()->last_peer_identity(), ",")
.c_str(),
absl::StrJoin(expected_authenticated_identity, ",").c_str());
continue;
}
}
break;
}
EXPECT_LT(num_tries, kRetryCount);
}
std::string root_cert_;
std::string bad_root_cert_;
grpc_core::PemKeyCertPairList identity_pair_;
grpc_core::PemKeyCertPairList fallback_identity_pair_;
grpc_core::PemKeyCertPairList bad_identity_pair_;
StringMatcher server_san_exact_;
StringMatcher server_san_prefix_;
StringMatcher server_san_suffix_;
StringMatcher server_san_contains_;
StringMatcher server_san_regex_;
StringMatcher bad_san_1_;
StringMatcher bad_san_2_;
std::vector<std::string> authenticated_identity_;
std::vector<std::string> fallback_authenticated_identity_;
};
TEST_P(XdsSecurityTest,
TLSConfigurationWithoutValidationContextCertificateProviderInstance) {
auto cluster = default_cluster_;
auto* transport_socket = cluster.mutable_transport_socket();
transport_socket->set_name("envoy.transport_sockets.tls");
balancers_[0]->ads_service()->SetCdsResource(cluster);
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->cds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"TLS configuration provided but no "
"validation_context_certificate_provider_instance found."));
}
TEST_P(
XdsSecurityTest,
MatchSubjectAltNamesProvidedWithoutValidationContextCertificateProviderInstance) {
auto cluster = default_cluster_;
auto* transport_socket = cluster.mutable_transport_socket();
transport_socket->set_name("envoy.transport_sockets.tls");
UpstreamTlsContext upstream_tls_context;
auto* validation_context = upstream_tls_context.mutable_common_tls_context()
->mutable_combined_validation_context()
->mutable_default_validation_context();
*validation_context->add_match_subject_alt_names() = server_san_exact_;
transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
balancers_[0]->ads_service()->SetCdsResource(cluster);
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->cds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"TLS configuration provided but no "
"validation_context_certificate_provider_instance found."));
}
TEST_P(
XdsSecurityTest,
TlsCertificateCertificateProviderInstanceWithoutValidationContextCertificateProviderInstance) {
auto cluster = default_cluster_;
auto* transport_socket = cluster.mutable_transport_socket();
transport_socket->set_name("envoy.transport_sockets.tls");
UpstreamTlsContext upstream_tls_context;
upstream_tls_context.mutable_common_tls_context()
->mutable_tls_certificate_certificate_provider_instance()
->set_instance_name(std::string("instance_name"));
transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
balancers_[0]->ads_service()->SetCdsResource(cluster);
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->cds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"TLS configuration provided but no "
"validation_context_certificate_provider_instance found."));
}
TEST_P(XdsSecurityTest, RegexSanMatcherDoesNotAllowIgnoreCase) {
auto cluster = default_cluster_;
auto* transport_socket = cluster.mutable_transport_socket();
transport_socket->set_name("envoy.transport_sockets.tls");
UpstreamTlsContext upstream_tls_context;
upstream_tls_context.mutable_common_tls_context()
->mutable_combined_validation_context()
->mutable_validation_context_certificate_provider_instance()
->set_instance_name(std::string("fake_plugin1"));
auto* validation_context = upstream_tls_context.mutable_common_tls_context()
->mutable_combined_validation_context()
->mutable_default_validation_context();
StringMatcher matcher;
matcher.mutable_safe_regex()->mutable_google_re2();
matcher.mutable_safe_regex()->set_regex(
"(foo|waterzooi).test.google.(fr|be)");
matcher.set_ignore_case(true);
*validation_context->add_match_subject_alt_names() = matcher;
transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
balancers_[0]->ads_service()->SetCdsResource(cluster);
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->cds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"StringMatcher: ignore_case has no effect for SAFE_REGEX."));
}
TEST_P(XdsSecurityTest, UnknownRootCertificateProvider) {
auto cluster = default_cluster_;
auto* transport_socket = cluster.mutable_transport_socket();
transport_socket->set_name("envoy.transport_sockets.tls");
UpstreamTlsContext upstream_tls_context;
upstream_tls_context.mutable_common_tls_context()
->mutable_combined_validation_context()
->mutable_validation_context_certificate_provider_instance()
->set_instance_name("unknown");
transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
balancers_[0]->ads_service()->SetCdsResource(cluster);
CheckRpcSendFailure(1, RpcOptions(), StatusCode::UNAVAILABLE);
}
TEST_P(XdsSecurityTest, UnknownIdentityCertificateProvider) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
auto cluster = default_cluster_;
auto* transport_socket = cluster.mutable_transport_socket();
transport_socket->set_name("envoy.transport_sockets.tls");
UpstreamTlsContext upstream_tls_context;
upstream_tls_context.mutable_common_tls_context()
->mutable_tls_certificate_certificate_provider_instance()
->set_instance_name("unknown");
upstream_tls_context.mutable_common_tls_context()
->mutable_combined_validation_context()
->mutable_validation_context_certificate_provider_instance()
->set_instance_name("fake_plugin1");
transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
balancers_[0]->ads_service()->SetCdsResource(cluster);
CheckRpcSendFailure(1, RpcOptions(), StatusCode::UNAVAILABLE);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithNoSanMatchers) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {}, authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithExactSanMatcher) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_exact_},
authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithPrefixSanMatcher) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_prefix_},
authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithSuffixSanMatcher) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_suffix_},
authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithContainsSanMatcher) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_contains_},
authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithRegexSanMatcher) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_regex_},
authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithSanMatchersUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration(
"fake_plugin1", "", "fake_plugin1", "",
{server_san_exact_, server_san_prefix_}, authenticated_identity_);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {bad_san_1_, bad_san_2_}, {},
true /* failure */);
UpdateAndVerifyXdsSecurityConfiguration(
"fake_plugin1", "", "fake_plugin1", "",
{server_san_prefix_, server_san_regex_}, authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithRootPluginUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
FakeCertificateProvider::CertDataMap fake2_cert_map = {
{"", {bad_root_cert_, bad_identity_pair_}}};
g_fake2_cert_data_map = &fake2_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_exact_},
authenticated_identity_);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin2" /* bad root */, "",
"fake_plugin1", "", {}, {},
true /* failure */);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_exact_},
authenticated_identity_);
g_fake1_cert_data_map = nullptr;
g_fake2_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithIdentityPluginUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
FakeCertificateProvider::CertDataMap fake2_cert_map = {
{"", {root_cert_, fallback_identity_pair_}}};
g_fake2_cert_data_map = &fake2_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_exact_},
authenticated_identity_);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin2",
"", {server_san_exact_},
fallback_authenticated_identity_);
g_fake1_cert_data_map = nullptr;
g_fake2_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithBothPluginsUpdated) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
FakeCertificateProvider::CertDataMap fake2_cert_map = {
{"", {bad_root_cert_, bad_identity_pair_}},
{"good", {root_cert_, fallback_identity_pair_}}};
g_fake2_cert_data_map = &fake2_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin2", "", "fake_plugin2",
"", {}, {}, true /* failure */);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_prefix_},
authenticated_identity_);
UpdateAndVerifyXdsSecurityConfiguration(
"fake_plugin2", "good", "fake_plugin2", "good", {server_san_prefix_},
fallback_authenticated_identity_);
g_fake1_cert_data_map = nullptr;
g_fake2_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithRootCertificateNameUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}},
{"bad", {bad_root_cert_, bad_identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_regex_},
authenticated_identity_);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "bad", "fake_plugin1",
"", {server_san_regex_}, {},
true /* failure */);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest,
TestMtlsConfigurationWithIdentityCertificateNameUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}},
{"bad", {bad_root_cert_, bad_identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_exact_},
authenticated_identity_);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"bad", {server_san_exact_}, {},
true /* failure */);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest,
TestMtlsConfigurationWithIdentityCertificateNameUpdateGoodCerts) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}},
{"good", {root_cert_, fallback_identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_exact_},
authenticated_identity_);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"good", {server_san_exact_},
fallback_authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithBothCertificateNamesUpdated) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}},
{"bad", {bad_root_cert_, bad_identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "bad", "fake_plugin1",
"bad", {server_san_prefix_}, {},
true /* failure */);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_prefix_},
authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestTlsConfigurationWithNoSanMatchers) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "", {},
{} /* unauthenticated */);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestTlsConfigurationWithSanMatchers) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration(
"fake_plugin1", "", "", "",
{server_san_exact_, server_san_prefix_, server_san_regex_},
{} /* unauthenticated */);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestTlsConfigurationWithSanMatchersUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration(
"fake_plugin1", "", "", "", {server_san_exact_, server_san_prefix_},
{} /* unauthenticated */);
UpdateAndVerifyXdsSecurityConfiguration(
"fake_plugin1", "", "", "", {bad_san_1_, bad_san_2_},
{} /* unauthenticated */, true /* failure */);
UpdateAndVerifyXdsSecurityConfiguration(
"fake_plugin1", "", "", "", {server_san_prefix_, server_san_regex_},
{} /* unauthenticated */);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestTlsConfigurationWithRootCertificateNameUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}},
{"bad", {bad_root_cert_, bad_identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
{server_san_exact_},
{} /* unauthenticated */);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "bad", "", "",
{server_san_exact_}, {},
true /* failure */);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestTlsConfigurationWithRootPluginUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
FakeCertificateProvider::CertDataMap fake2_cert_map = {
{"", {bad_root_cert_, bad_identity_pair_}}};
g_fake2_cert_data_map = &fake2_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
{server_san_exact_},
{} /* unauthenticated */);
UpdateAndVerifyXdsSecurityConfiguration(
"fake_plugin2", "", "", "", {server_san_exact_}, {}, true /* failure */);
g_fake1_cert_data_map = nullptr;
g_fake2_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestFallbackConfiguration) {
UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
fallback_authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsToTls) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_exact_},
authenticated_identity_);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
{server_san_exact_},
{} /* unauthenticated */);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsToFallback) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_exact_},
authenticated_identity_);
UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
fallback_authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestTlsToMtls) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
{server_san_exact_},
{} /* unauthenticated */);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_exact_},
authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestTlsToFallback) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
{server_san_exact_},
{} /* unauthenticated */);
UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
fallback_authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestFallbackToMtls) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
fallback_authenticated_identity_);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_exact_},
authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestFallbackToTls) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
fallback_authenticated_identity_);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
{server_san_exact_},
{} /* unauthenticated */);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestFileWatcherCertificateProvider) {
UpdateAndVerifyXdsSecurityConfiguration("file_plugin", "", "file_plugin", "",
{server_san_exact_},
authenticated_identity_);
}
class XdsEnabledServerTest : public XdsEnd2endTest {
protected:
XdsEnabledServerTest()
: XdsEnd2endTest(1, 1, 100, true /* use_xds_enabled_server */) {}
void SetUp() override {
XdsEnd2endTest::SetUp();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
}
};
TEST_P(XdsEnabledServerTest, Basic) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
listener.mutable_address()->mutable_socket_address()->set_address(
ipv6_only_ ? "::1" : "127.0.0.1");
listener.mutable_address()->mutable_socket_address()->set_port_value(
backends_[0]->port());
listener.add_filter_chains()->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
balancers_[0]->ads_service()->SetLdsResource(listener);
WaitForBackend(0);
}
TEST_P(XdsEnabledServerTest, BadLdsUpdateNoApiListenerNorAddress) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
listener.add_filter_chains()->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("Listener has neither address nor ApiListener"));
}
TEST_P(XdsEnabledServerTest, BadLdsUpdateBothApiListenerAndAddress) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
balancers_[0]->ads_service()->SetLdsResource(listener);
listener.mutable_address()->mutable_socket_address()->set_address(
ipv6_only_ ? "::1" : "127.0.0.1");
listener.mutable_address()->mutable_socket_address()->set_port_value(
backends_[0]->port());
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
listener.mutable_api_listener();
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("Listener has both address and ApiListener"));
}
TEST_P(XdsEnabledServerTest, UnsupportedL4Filter) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
balancers_[0]->ads_service()->SetLdsResource(listener);
listener.mutable_address()->mutable_socket_address()->set_address(
ipv6_only_ ? "::1" : "127.0.0.1");
listener.mutable_address()->mutable_socket_address()->set_port_value(
backends_[0]->port());
listener.add_filter_chains()->add_filters()->mutable_typed_config()->PackFrom(default_listener_ /* any proto object other than HttpConnectionManager */);
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("Unsupported filter type"));
}
TEST_P(XdsEnabledServerTest, UnsupportedHttpFilter) {
// Set env var to enable filters parsing.
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
listener.mutable_address()->mutable_socket_address()->set_address(
ipv6_only_ ? "::1" : "127.0.0.1");
listener.mutable_address()->mutable_socket_address()->set_port_value(
backends_[0]->port());
HttpConnectionManager http_connection_manager;
auto* http_filter = http_connection_manager.add_http_filters();
http_filter->set_name("grpc.testing.unsupported_http_filter");
http_filter->mutable_typed_config()->set_type_url(
"grpc.testing.unsupported_http_filter");
listener.add_filter_chains()->add_filters()->mutable_typed_config()->PackFrom(
http_connection_manager);
balancers_[0]->ads_service()->SetLdsResource(listener);
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=[::1]:",
backends_[0]->port()));
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("no filter registered for config type "
"grpc.testing.unsupported_http_filter"));
}
TEST_P(XdsEnabledServerTest, HttpFilterNotSupportedOnServer) {
// Set env var to enable filters parsing.
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
listener.mutable_address()->mutable_socket_address()->set_address(
ipv6_only_ ? "::1" : "127.0.0.1");
listener.mutable_address()->mutable_socket_address()->set_port_value(
backends_[0]->port());
HttpConnectionManager http_connection_manager;
auto* http_filter = http_connection_manager.add_http_filters();
http_filter->set_name("grpc.testing.client_only_http_filter");
http_filter->mutable_typed_config()->set_type_url(
"grpc.testing.client_only_http_filter");
listener.add_filter_chains()->add_filters()->mutable_typed_config()->PackFrom(
http_connection_manager);
balancers_[0]->ads_service()->SetLdsResource(listener);
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=[::1]:",
backends_[0]->port()));
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("Filter grpc.testing.client_only_http_filter is not "
"supported on servers"));
}
TEST_P(XdsEnabledServerTest,
HttpFilterNotSupportedOnServerIgnoredWhenOptional) {
// Set env var to enable filters parsing.
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
listener.mutable_address()->mutable_socket_address()->set_address(
ipv6_only_ ? "::1" : "127.0.0.1");
listener.mutable_address()->mutable_socket_address()->set_port_value(
backends_[0]->port());
HttpConnectionManager http_connection_manager;
auto* http_filter = http_connection_manager.add_http_filters();
http_filter->set_name("grpc.testing.client_only_http_filter");
http_filter->mutable_typed_config()->set_type_url(
"grpc.testing.client_only_http_filter");
http_filter->set_is_optional(true);
listener.add_filter_chains()->add_filters()->mutable_typed_config()->PackFrom(
http_connection_manager);
balancers_[0]->ads_service()->SetLdsResource(listener);
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=[::1]:",
backends_[0]->port()));
balancers_[0]->ads_service()->SetLdsResource(listener);
WaitForBackend(0);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
}
// Verify that a mismatch of listening address results in "not serving" status.
TEST_P(XdsEnabledServerTest, ListenerAddressMismatch) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
listener.mutable_address()->mutable_socket_address()->set_address(
ipv6_only_ ? "::1" : "127.0.0.1");
listener.mutable_address()->mutable_socket_address()->set_port_value(
backends_[0]->port());
listener.add_filter_chains()->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
balancers_[0]->ads_service()->SetLdsResource(listener);
WaitForBackend(0);
// Set a different listening address in the LDS update
listener.mutable_address()->mutable_socket_address()->set_address(
"192.168.1.1");
balancers_[0]->ads_service()->SetLdsResource(listener);
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
grpc::StatusCode::FAILED_PRECONDITION);
}
TEST_P(XdsEnabledServerTest, UseOriginalDstNotSupported) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
balancers_[0]->ads_service()->SetLdsResource(listener);
listener.mutable_address()->mutable_socket_address()->set_address(
ipv6_only_ ? "::1" : "127.0.0.1");
listener.mutable_address()->mutable_socket_address()->set_port_value(
backends_[0]->port());
listener.add_filter_chains()->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
listener.mutable_use_original_dst()->set_value(true);
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("Field \'use_original_dst\' is not supported."));
}
class XdsServerSecurityTest : public XdsEnd2endTest {
protected:
XdsServerSecurityTest()
: XdsEnd2endTest(1, 1, 100, true /* use_xds_enabled_server */) {}
static void SetUpTestCase() {
gpr_setenv("GRPC_XDS_EXPERIMENTAL_SECURITY_SUPPORT", "true");
XdsEnd2endTest::SetUpTestCase();
}
static void TearDownTestCase() {
XdsEnd2endTest::TearDownTestCase();
gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_SECURITY_SUPPORT");
}
void SetUp() override {
XdsEnd2endTest::SetUp();
root_cert_ = ReadFile(kCaCertPath);
bad_root_cert_ = ReadFile(kBadClientCertPath);
identity_pair_ = ReadTlsIdentityPair(kServerKeyPath, kServerCertPath);
bad_identity_pair_ =
ReadTlsIdentityPair(kBadClientKeyPath, kBadClientCertPath);
identity_pair_2_ = ReadTlsIdentityPair(kClientKeyPath, kClientCertPath);
server_authenticated_identity_ = {"*.test.google.fr",
"waterzooi.test.google.be",
"*.test.youtube.com", "192.168.1.3"};
server_authenticated_identity_2_ = {"testclient"};
client_authenticated_identity_ = {"*.test.google.fr",
"waterzooi.test.google.be",
"*.test.youtube.com", "192.168.1.3"};
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
}
void TearDown() override {
g_fake1_cert_data_map = nullptr;
g_fake2_cert_data_map = nullptr;
XdsEnd2endTest::TearDown();
}
void SetLdsUpdate(absl::string_view root_instance_name,
absl::string_view root_certificate_name,
absl::string_view identity_instance_name,
absl::string_view identity_certificate_name,
bool require_client_certificates) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=127.0.0.1:",
backends_[0]->port()));
listener.mutable_address()->mutable_socket_address()->set_address(
"127.0.0.1");
listener.mutable_address()->mutable_socket_address()->set_port_value(
backends_[0]->port());
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
if (!identity_instance_name.empty()) {
auto* transport_socket = filter_chain->mutable_transport_socket();
transport_socket->set_name("envoy.transport_sockets.tls");
DownstreamTlsContext downstream_tls_context;
downstream_tls_context.mutable_common_tls_context()
->mutable_tls_certificate_certificate_provider_instance()
->set_instance_name(std::string(identity_instance_name));
downstream_tls_context.mutable_common_tls_context()
->mutable_tls_certificate_certificate_provider_instance()
->set_certificate_name(std::string(identity_certificate_name));
if (!root_instance_name.empty()) {
downstream_tls_context.mutable_common_tls_context()
->mutable_combined_validation_context()
->mutable_validation_context_certificate_provider_instance()
->set_instance_name(std::string(root_instance_name));
downstream_tls_context.mutable_common_tls_context()
->mutable_combined_validation_context()
->mutable_validation_context_certificate_provider_instance()
->set_certificate_name(std::string(root_certificate_name));
downstream_tls_context.mutable_require_client_certificate()->set_value(
require_client_certificates);
}
transport_socket->mutable_typed_config()->PackFrom(
downstream_tls_context);
}
balancers_[0]->ads_service()->SetLdsResource(listener);
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=[::1]:",
backends_[0]->port()));
listener.mutable_address()->mutable_socket_address()->set_address("[::1]");
balancers_[0]->ads_service()->SetLdsResource(listener);
}
std::shared_ptr<grpc::Channel> CreateMtlsChannel() {
ChannelArguments args;
// Override target name for host name check
args.SetString(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG,
ipv6_only_ ? "::1" : "127.0.0.1");
args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, 1);
std::string uri = absl::StrCat(
ipv6_only_ ? "ipv6:[::1]:" : "ipv4:127.0.0.1:", backends_[0]->port());
// TODO(yashykt): Switch to using C++ API once b/173823806 is fixed.
grpc_tls_credentials_options* options =
grpc_tls_credentials_options_create();
grpc_tls_credentials_options_set_server_verification_option(
options, GRPC_TLS_SKIP_HOSTNAME_VERIFICATION);
grpc_tls_credentials_options_set_certificate_provider(
options,
grpc_core::MakeRefCounted<grpc_core::StaticDataCertificateProvider>(
ReadFile(kCaCertPath),
ReadTlsIdentityPair(kServerKeyPath, kServerCertPath))
.get());
grpc_tls_credentials_options_watch_root_certs(options);
grpc_tls_credentials_options_watch_identity_key_cert_pairs(options);
grpc_tls_server_authorization_check_config* check_config =
grpc_tls_server_authorization_check_config_create(
nullptr, ServerAuthCheckSchedule, nullptr, nullptr);
grpc_tls_credentials_options_set_server_authorization_check_config(
options, check_config);
auto channel_creds = std::make_shared<SecureChannelCredentials>(
grpc_tls_credentials_create(options));
grpc_tls_server_authorization_check_config_release(check_config);
return CreateCustomChannel(uri, channel_creds, args);
}
std::shared_ptr<grpc::Channel> CreateTlsChannel() {
ChannelArguments args;
// Override target name for host name check
args.SetString(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG,
ipv6_only_ ? "::1" : "127.0.0.1");
args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, 1);
std::string uri = absl::StrCat(
ipv6_only_ ? "ipv6:[::1]:" : "ipv4:127.0.0.1:", backends_[0]->port());
// TODO(yashykt): Switch to using C++ API once b/173823806 is fixed.
grpc_tls_credentials_options* options =
grpc_tls_credentials_options_create();
grpc_tls_credentials_options_set_server_verification_option(
options, GRPC_TLS_SKIP_HOSTNAME_VERIFICATION);
grpc_tls_credentials_options_set_certificate_provider(
options,
grpc_core::MakeRefCounted<grpc_core::StaticDataCertificateProvider>(
ReadFile(kCaCertPath),
ReadTlsIdentityPair(kServerKeyPath, kServerCertPath))
.get());
grpc_tls_credentials_options_watch_root_certs(options);
grpc_tls_server_authorization_check_config* check_config =
grpc_tls_server_authorization_check_config_create(
nullptr, ServerAuthCheckSchedule, nullptr, nullptr);
grpc_tls_credentials_options_set_server_authorization_check_config(
options, check_config);
auto channel_creds = std::make_shared<SecureChannelCredentials>(
grpc_tls_credentials_create(options));
grpc_tls_server_authorization_check_config_release(check_config);
return CreateCustomChannel(uri, channel_creds, args);
}
std::shared_ptr<grpc::Channel> CreateInsecureChannel() {
ChannelArguments args;
// Override target name for host name check
args.SetString(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG,
ipv6_only_ ? "::1" : "127.0.0.1");
args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, 1);
std::string uri = absl::StrCat(
ipv6_only_ ? "ipv6:[::1]:" : "ipv4:127.0.0.1:", backends_[0]->port());
return CreateCustomChannel(uri, InsecureChannelCredentials(), args);
}
void SendRpc(std::function<std::shared_ptr<grpc::Channel>()> channel_creator,
std::vector<std::string> expected_server_identity,
std::vector<std::string> expected_client_identity,
bool test_expects_failure = false) {
gpr_log(GPR_INFO, "Sending RPC");
int num_tries = 0;
constexpr int kRetryCount = 10;
for (; num_tries < kRetryCount; num_tries++) {
auto channel = channel_creator();
auto stub = grpc::testing::EchoTestService::NewStub(channel);
ClientContext context;
context.set_wait_for_ready(true);
context.set_deadline(grpc_timeout_milliseconds_to_deadline(2000));
EchoRequest request;
request.set_message(kRequestMessage);
EchoResponse response;
Status status = stub->Echo(&context, request, &response);
if (test_expects_failure) {
if (status.ok()) {
gpr_log(GPR_ERROR, "RPC succeeded. Failure expected. Trying again.");
continue;
}
} else {
if (!status.ok()) {
gpr_log(GPR_ERROR, "RPC failed. code=%d message=%s Trying again.",
status.error_code(), status.error_message().c_str());
continue;
}
EXPECT_EQ(response.message(), kRequestMessage);
std::vector<std::string> peer_identity;
for (const auto& entry : context.auth_context()->GetPeerIdentity()) {
peer_identity.emplace_back(
std::string(entry.data(), entry.size()).c_str());
}
if (peer_identity != expected_server_identity) {
gpr_log(GPR_ERROR,
"Expected server identity does not match. (actual) %s vs "
"(expected) %s Trying again.",
absl::StrJoin(peer_identity, ",").c_str(),
absl::StrJoin(expected_server_identity, ",").c_str());
continue;
}
if (backends_[0]->backend_service()->last_peer_identity() !=
expected_client_identity) {
gpr_log(
GPR_ERROR,
"Expected client identity does not match. (actual) %s vs "
"(expected) %s Trying again.",
absl::StrJoin(
backends_[0]->backend_service()->last_peer_identity(), ",")
.c_str(),
absl::StrJoin(expected_client_identity, ",").c_str());
continue;
}
}
break;
}
EXPECT_LT(num_tries, kRetryCount);
}
std::string root_cert_;
std::string bad_root_cert_;
grpc_core::PemKeyCertPairList identity_pair_;
grpc_core::PemKeyCertPairList bad_identity_pair_;
grpc_core::PemKeyCertPairList identity_pair_2_;
std::vector<std::string> server_authenticated_identity_;
std::vector<std::string> server_authenticated_identity_2_;
std::vector<std::string> client_authenticated_identity_;
};
TEST_P(XdsServerSecurityTest, TlsConfigurationWithoutRootProviderInstance) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
balancers_[0]->ads_service()->SetLdsResource(listener);
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
auto* transport_socket = filter_chain->mutable_transport_socket();
transport_socket->set_name("envoy.transport_sockets.tls");
DownstreamTlsContext downstream_tls_context;
transport_socket->mutable_typed_config()->PackFrom(downstream_tls_context);
balancers_[0]->ads_service()->SetLdsResource(listener);
CheckRpcSendFailure(1, RpcOptions().set_wait_for_ready(true));
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"TLS configuration provided but no "
"tls_certificate_certificate_provider_instance found."));
}
TEST_P(XdsServerSecurityTest, UnknownIdentityCertificateProvider) {
SetLdsUpdate("", "", "unknown", "", false);
SendRpc([this]() { return CreateTlsChannel(); }, {}, {},
true /* test_expects_failure */);
}
TEST_P(XdsServerSecurityTest, UnknownRootCertificateProvider) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
SetLdsUpdate("unknown", "", "fake_plugin1", "", false);
SendRpc([this]() { return CreateTlsChannel(); }, {}, {},
true /* test_expects_failure */);
}
TEST_P(XdsServerSecurityTest, TestMtls) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_, client_authenticated_identity_);
}
TEST_P(XdsServerSecurityTest, TestMtlsWithRootPluginUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
FakeCertificateProvider::CertDataMap fake2_cert_map = {
{"", {bad_root_cert_, bad_identity_pair_}}};
g_fake2_cert_data_map = &fake2_cert_map;
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_, client_authenticated_identity_);
SetLdsUpdate("fake_plugin2", "", "fake_plugin1", "", true);
SendRpc([this]() { return CreateMtlsChannel(); }, {}, {},
true /* test_expects_failure */);
}
TEST_P(XdsServerSecurityTest, TestMtlsWithIdentityPluginUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
FakeCertificateProvider::CertDataMap fake2_cert_map = {
{"", {root_cert_, identity_pair_2_}}};
g_fake2_cert_data_map = &fake2_cert_map;
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_, client_authenticated_identity_);
SetLdsUpdate("fake_plugin1", "", "fake_plugin2", "", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_2_, client_authenticated_identity_);
}
TEST_P(XdsServerSecurityTest, TestMtlsWithBothPluginsUpdated) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
FakeCertificateProvider::CertDataMap fake2_cert_map = {
{"good", {root_cert_, identity_pair_2_}},
{"", {bad_root_cert_, bad_identity_pair_}}};
g_fake2_cert_data_map = &fake2_cert_map;
SetLdsUpdate("fake_plugin2", "", "fake_plugin2", "", true);
SendRpc([this]() { return CreateMtlsChannel(); }, {}, {},
true /* test_expects_failure */);
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_, client_authenticated_identity_);
SetLdsUpdate("fake_plugin2", "good", "fake_plugin2", "good", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_2_, client_authenticated_identity_);
}
TEST_P(XdsServerSecurityTest, TestMtlsWithRootCertificateNameUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}},
{"bad", {bad_root_cert_, bad_identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_, client_authenticated_identity_);
SetLdsUpdate("fake_plugin1", "bad", "fake_plugin1", "", true);
SendRpc([this]() { return CreateMtlsChannel(); }, {}, {},
true /* test_expects_failure */);
}
TEST_P(XdsServerSecurityTest, TestMtlsWithIdentityCertificateNameUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}},
{"good", {root_cert_, identity_pair_2_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_, client_authenticated_identity_);
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "good", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_2_, client_authenticated_identity_);
}
TEST_P(XdsServerSecurityTest, TestMtlsWithBothCertificateNamesUpdated) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}},
{"good", {root_cert_, identity_pair_2_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_, client_authenticated_identity_);
SetLdsUpdate("fake_plugin1", "good", "fake_plugin1", "good", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_2_, client_authenticated_identity_);
}
TEST_P(XdsServerSecurityTest, TestMtlsNotRequiringButProvidingClientCerts) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", false);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_, client_authenticated_identity_);
}
TEST_P(XdsServerSecurityTest, TestMtlsNotRequiringAndNotProvidingClientCerts) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", false);
SendRpc([this]() { return CreateTlsChannel(); },
server_authenticated_identity_, {});
}
TEST_P(XdsServerSecurityTest, TestTls) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("", "", "fake_plugin1", "", false);
SendRpc([this]() { return CreateTlsChannel(); },
server_authenticated_identity_, {});
}
TEST_P(XdsServerSecurityTest, TestTlsWithIdentityPluginUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
FakeCertificateProvider::CertDataMap fake2_cert_map = {
{"", {root_cert_, identity_pair_2_}}};
g_fake2_cert_data_map = &fake2_cert_map;
SetLdsUpdate("", "", "fake_plugin1", "", false);
SendRpc([this]() { return CreateTlsChannel(); },
server_authenticated_identity_, {});
SetLdsUpdate("", "", "fake_plugin2", "", false);
SendRpc([this]() { return CreateTlsChannel(); },
server_authenticated_identity_2_, {});
}
TEST_P(XdsServerSecurityTest, TestTlsWithIdentityCertificateNameUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}},
{"good", {root_cert_, identity_pair_2_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("", "", "fake_plugin1", "", false);
SendRpc([this]() { return CreateTlsChannel(); },
server_authenticated_identity_, {});
SetLdsUpdate("", "", "fake_plugin1", "good", false);
SendRpc([this]() { return CreateTlsChannel(); },
server_authenticated_identity_2_, {});
}
TEST_P(XdsServerSecurityTest, TestFallback) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("", "", "", "", false);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsServerSecurityTest, TestMtlsToTls) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
SendRpc([this]() { return CreateTlsChannel(); }, {}, {},
true /* test_expects_failure */);
SetLdsUpdate("", "", "fake_plugin1", "", false);
SendRpc([this]() { return CreateTlsChannel(); },
server_authenticated_identity_, {});
}
TEST_P(XdsServerSecurityTest, TestTlsToMtls) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("", "", "fake_plugin1", "", false);
SendRpc([this]() { return CreateTlsChannel(); },
server_authenticated_identity_, {});
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
SendRpc([this]() { return CreateTlsChannel(); }, {}, {},
true /* test_expects_failure */);
}
TEST_P(XdsServerSecurityTest, TestMtlsToFallback) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", false);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_, client_authenticated_identity_);
SetLdsUpdate("", "", "", "", false);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsServerSecurityTest, TestFallbackToMtls) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("", "", "", "", false);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_, client_authenticated_identity_);
}
TEST_P(XdsServerSecurityTest, TestTlsToFallback) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("", "", "fake_plugin1", "", false);
SendRpc([this]() { return CreateTlsChannel(); },
server_authenticated_identity_, {});
SetLdsUpdate("", "", "", "", false);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsServerSecurityTest, TestFallbackToTls) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("", "", "", "", false);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
SetLdsUpdate("", "", "fake_plugin1", "", false);
SendRpc([this]() { return CreateTlsChannel(); },
server_authenticated_identity_, {});
}
class XdsEnabledServerStatusNotificationTest : public XdsServerSecurityTest {
protected:
void SetValidLdsUpdate() { SetLdsUpdate("", "", "", "", false); }
void SetInvalidLdsUpdate() {
Listener listener;
listener.set_name(absl::StrCat(
"grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
balancers_[0]->ads_service()->SetLdsResource(listener);
}
void UnsetLdsUpdate() {
balancers_[0]->ads_service()->UnsetResource(
kLdsTypeUrl, absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:",
backends_[0]->port()));
}
};
TEST_P(XdsEnabledServerStatusNotificationTest, ServingStatus) {
SetValidLdsUpdate();
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
grpc::StatusCode::OK);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsEnabledServerStatusNotificationTest, NotServingStatus) {
SetInvalidLdsUpdate();
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
grpc::StatusCode::UNAVAILABLE);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
true /* test_expects_failure */);
}
TEST_P(XdsEnabledServerStatusNotificationTest, ErrorUpdateWhenAlreadyServing) {
SetValidLdsUpdate();
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
grpc::StatusCode::OK);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
// Invalid update does not lead to a change in the serving status.
SetInvalidLdsUpdate();
do {
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
grpc::StatusCode::OK);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsEnabledServerStatusNotificationTest,
NotServingStatusToServingStatusTransition) {
SetInvalidLdsUpdate();
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
grpc::StatusCode::UNAVAILABLE);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
true /* test_expects_failure */);
// Send a valid LDS update to change to serving status
SetValidLdsUpdate();
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
grpc::StatusCode::OK);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
// This test verifies that the resource getting deleted when already serving
// results in future connections being dropped.
TEST_P(XdsEnabledServerStatusNotificationTest,
ServingStatusToNonServingStatusTransition) {
SetValidLdsUpdate();
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
grpc::StatusCode::OK);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
// Deleting the resource should result in a non-serving status.
UnsetLdsUpdate();
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
grpc::StatusCode::NOT_FOUND);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
true /* test_expects_failure */);
}
TEST_P(XdsEnabledServerStatusNotificationTest, RepeatedServingStatusChanges) {
for (int i = 0; i < 5; i++) {
// Send a valid LDS update to get the server to start listening
SetValidLdsUpdate();
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:",
backends_[0]->port()),
grpc::StatusCode::OK);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
// Deleting the resource will make the server start rejecting connections
UnsetLdsUpdate();
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:",
backends_[0]->port()),
grpc::StatusCode::NOT_FOUND);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
true /* test_expects_failure */);
}
}
TEST_P(XdsEnabledServerStatusNotificationTest, ExistingRpcsOnResourceDeletion) {
// Send a valid LDS update to get the server to start listening
SetValidLdsUpdate();
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
grpc::StatusCode::OK);
constexpr int kNumChannels = 10;
struct StreamingRpc {
std::shared_ptr<Channel> channel;
std::unique_ptr<grpc::testing::EchoTestService::Stub> stub;
ClientContext context;
std::unique_ptr<ClientWriter<EchoRequest>> writer;
} streaming_rpcs[kNumChannels];
EchoRequest request;
EchoResponse response;
request.set_message("Hello");
for (int i = 0; i < kNumChannels; i++) {
streaming_rpcs[i].channel = CreateInsecureChannel();
streaming_rpcs[i].stub =
grpc::testing::EchoTestService::NewStub(streaming_rpcs[i].channel);
streaming_rpcs[i].context.set_wait_for_ready(true);
streaming_rpcs[i].writer = streaming_rpcs[i].stub->RequestStream(
&streaming_rpcs[i].context, &response);
EXPECT_TRUE(streaming_rpcs[i].writer->Write(request));
}
// Deleting the resource will make the server start rejecting connections
UnsetLdsUpdate();
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
grpc::StatusCode::NOT_FOUND);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
true /* test_expects_failure */);
for (int i = 0; i < kNumChannels; i++) {
EXPECT_TRUE(streaming_rpcs[i].writer->Write(request));
EXPECT_TRUE(streaming_rpcs[i].writer->WritesDone());
EXPECT_TRUE(streaming_rpcs[i].writer->Finish().ok());
// New RPCs on the existing channels should fail.
ClientContext new_context;
new_context.set_deadline(grpc_timeout_milliseconds_to_deadline(1000));
EXPECT_FALSE(
streaming_rpcs[i].stub->Echo(&new_context, request, &response).ok());
}
}
using XdsServerFilterChainMatchTest = XdsServerSecurityTest;
TEST_P(XdsServerFilterChainMatchTest,
DefaultFilterChainUsedWhenNoFilterChainMentioned) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
listener.mutable_default_filter_chain()
->add_filters()
->mutable_typed_config()
->PackFrom(HttpConnectionManager());
balancers_[0]->ads_service()->SetLdsResource(listener);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsServerFilterChainMatchTest,
DefaultFilterChainUsedWhenOtherFilterChainsDontMatch) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add a filter chain that will never get matched
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()
->mutable_destination_port()
->set_value(8080);
// Add default filter chain that should get used
listener.mutable_default_filter_chain()
->add_filters()
->mutable_typed_config()
->PackFrom(HttpConnectionManager());
balancers_[0]->ads_service()->SetLdsResource(listener);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsServerFilterChainMatchTest,
FilterChainsWithDestinationPortDontMatch) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with destination port that should never get matched
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()
->mutable_destination_port()
->set_value(8080);
balancers_[0]->ads_service()->SetLdsResource(listener);
// RPC should fail since no matching filter chain was found and no default
// filter chain is configured.
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
true /* test_expects_failure */);
}
TEST_P(XdsServerFilterChainMatchTest, FilterChainsWithServerNamesDontMatch) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with server name that should never get matched
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->add_server_names("server_name");
balancers_[0]->ads_service()->SetLdsResource(listener);
// RPC should fail since no matching filter chain was found and no default
// filter chain is configured.
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
true /* test_expects_failure */);
}
TEST_P(XdsServerFilterChainMatchTest,
FilterChainsWithTransportProtocolsOtherThanRawBufferDontMatch) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with transport protocol "tls" that should never match
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->set_transport_protocol("tls");
balancers_[0]->ads_service()->SetLdsResource(listener);
// RPC should fail since no matching filter chain was found and no default
// filter chain is configured.
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
true /* test_expects_failure */);
}
TEST_P(XdsServerFilterChainMatchTest,
FilterChainsWithApplicationProtocolsDontMatch) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with application protocol that should never get matched
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->add_application_protocols("h2");
balancers_[0]->ads_service()->SetLdsResource(listener);
// RPC should fail since no matching filter chain was found and no default
// filter chain is configured.
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
true /* test_expects_failure */);
}
TEST_P(XdsServerFilterChainMatchTest,
FilterChainsWithTransportProtocolRawBufferIsPreferred) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with "raw_buffer" transport protocol
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->set_transport_protocol(
"raw_buffer");
// Add another filter chain with no transport protocol set but application
// protocol set (fails match)
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->add_application_protocols("h2");
balancers_[0]->ads_service()->SetLdsResource(listener);
// A successful RPC proves that filter chains that mention "raw_buffer" as the
// transport protocol are chosen as the best match in the round.
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsServerFilterChainMatchTest,
FilterChainsWithMoreSpecificDestinationPrefixRangesArePreferred) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with prefix range (length 4 and 16) but with server name
// mentioned. (Prefix range is matched first.)
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
auto* prefix_range =
filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(4);
prefix_range =
filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(16);
filter_chain->mutable_filter_chain_match()->add_server_names("server_name");
// Add filter chain with two prefix ranges (length 8 and 24). Since 24 is the
// highest match, it should be chosen.
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
prefix_range =
filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(8);
prefix_range =
filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(24);
// Add another filter chain with a non-matching prefix range (with length 30)
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
prefix_range =
filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
prefix_range->set_address_prefix("192.168.1.1");
prefix_range->mutable_prefix_len()->set_value(30);
filter_chain->mutable_filter_chain_match()->add_server_names("server_name");
// Add another filter chain with no prefix range mentioned
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->add_server_names("server_name");
balancers_[0]->ads_service()->SetLdsResource(listener);
// A successful RPC proves that the filter chain with the longest matching
// prefix range was the best match.
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsServerFilterChainMatchTest,
FilterChainsThatMentionSourceTypeArePreferred) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with the local source type (best match)
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->set_source_type(
FilterChainMatch::SAME_IP_OR_LOOPBACK);
// Add filter chain with the external source type but bad source port.
// Note that backends_[0]->port() will never be a match for the source port
// because it is already being used by a backend.
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->set_source_type(
FilterChainMatch::EXTERNAL);
filter_chain->mutable_filter_chain_match()->add_source_ports(
backends_[0]->port());
// Add filter chain with the default source type (ANY) but bad source port.
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->add_source_ports(
backends_[0]->port());
balancers_[0]->ads_service()->SetLdsResource(listener);
// A successful RPC proves that the filter chain with the longest matching
// prefix range was the best match.
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsServerFilterChainMatchTest,
FilterChainsWithMoreSpecificSourcePrefixRangesArePreferred) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with source prefix range (length 16) but with a bad source
// port mentioned. (Prefix range is matched first.)
// Note that backends_[0]->port() will never be a match for the source port
// because it is already being used by a backend.
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
auto* source_prefix_range =
filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
source_prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
source_prefix_range->mutable_prefix_len()->set_value(4);
source_prefix_range =
filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
source_prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
source_prefix_range->mutable_prefix_len()->set_value(16);
filter_chain->mutable_filter_chain_match()->add_source_ports(
backends_[0]->port());
// Add filter chain with two source prefix ranges (length 8 and 24). Since 24
// is the highest match, it should be chosen.
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
source_prefix_range =
filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
source_prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
source_prefix_range->mutable_prefix_len()->set_value(8);
source_prefix_range =
filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
source_prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
source_prefix_range->mutable_prefix_len()->set_value(24);
// Add another filter chain with a non-matching source prefix range (with
// length 30) and bad source port
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
source_prefix_range =
filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
source_prefix_range->set_address_prefix("192.168.1.1");
source_prefix_range->mutable_prefix_len()->set_value(30);
filter_chain->mutable_filter_chain_match()->add_source_ports(
backends_[0]->port());
// Add another filter chain with no source prefix range mentioned and bad
// source port
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->add_source_ports(
backends_[0]->port());
balancers_[0]->ads_service()->SetLdsResource(listener);
// A successful RPC proves that the filter chain with the longest matching
// source prefix range was the best match.
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsServerFilterChainMatchTest,
FilterChainsWithMoreSpecificSourcePortArePreferred) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
// Since we don't know which port will be used by the channel, just add all
// ports except for 0.
for (int i = 1; i < 65536; i++) {
filter_chain->mutable_filter_chain_match()->add_source_ports(i);
}
// Add another filter chain with no source prefix range mentioned with a bad
// DownstreamTlsContext configuration.
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
auto* transport_socket = filter_chain->mutable_transport_socket();
transport_socket->set_name("envoy.transport_sockets.tls");
DownstreamTlsContext downstream_tls_context;
downstream_tls_context.mutable_common_tls_context()
->mutable_tls_certificate_certificate_provider_instance()
->set_instance_name("unknown");
transport_socket->mutable_typed_config()->PackFrom(downstream_tls_context);
balancers_[0]->ads_service()->SetLdsResource(listener);
// A successful RPC proves that the filter chain with matching source port
// was chosen.
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsServerFilterChainMatchTest, DuplicateMatchNacked) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
// Add a duplicate filter chain
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr(
"Duplicate matching rules detected when adding filter chain: {}"));
}
TEST_P(XdsServerFilterChainMatchTest, DuplicateMatchOnPrefixRangesNacked) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with prefix range
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
auto* prefix_range =
filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(16);
prefix_range =
filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(24);
// Add a filter chain with a duplicate prefix range entry
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
prefix_range =
filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(16);
prefix_range =
filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(32);
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr(
"Duplicate matching rules detected when adding filter chain: "
"{prefix_ranges={{address_prefix=127.0.0.0:0, prefix_len=16}, "
"{address_prefix=127.0.0.1:0, prefix_len=32}}}"));
}
TEST_P(XdsServerFilterChainMatchTest, DuplicateMatchOnTransportProtocolNacked) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with "raw_buffer" transport protocol
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->set_transport_protocol(
"raw_buffer");
// Add a duplicate filter chain with the same "raw_buffer" transport protocol
// entry
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->set_transport_protocol(
"raw_buffer");
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("Duplicate matching rules detected when adding "
"filter chain: {transport_protocol=raw_buffer}"));
}
TEST_P(XdsServerFilterChainMatchTest, DuplicateMatchOnLocalSourceTypeNacked) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with the local source type
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->set_source_type(
FilterChainMatch::SAME_IP_OR_LOOPBACK);
// Add a duplicate filter chain with the same local source type entry
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->set_source_type(
FilterChainMatch::SAME_IP_OR_LOOPBACK);
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("Duplicate matching rules detected when adding "
"filter chain: {source_type=SAME_IP_OR_LOOPBACK}"));
}
TEST_P(XdsServerFilterChainMatchTest,
DuplicateMatchOnExternalSourceTypeNacked) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with the external source type
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->set_source_type(
FilterChainMatch::EXTERNAL);
// Add a duplicate filter chain with the same external source type entry
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->set_source_type(
FilterChainMatch::EXTERNAL);
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("Duplicate matching rules detected when adding "
"filter chain: {source_type=EXTERNAL}"));
}
TEST_P(XdsServerFilterChainMatchTest,
DuplicateMatchOnSourcePrefixRangesNacked) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with source prefix range
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
auto* prefix_range =
filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(16);
prefix_range =
filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(24);
// Add a filter chain with a duplicate source prefix range entry
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
prefix_range =
filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(16);
prefix_range =
filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(32);
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr(
"Duplicate matching rules detected when adding filter chain: "
"{source_prefix_ranges={{address_prefix=127.0.0.0:0, prefix_len=16}, "
"{address_prefix=127.0.0.1:0, prefix_len=32}}}"));
}
TEST_P(XdsServerFilterChainMatchTest, DuplicateMatchOnSourcePortNacked) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with the external source type
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->add_source_ports(8080);
// Add a duplicate filter chain with the same source port entry
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->add_source_ports(8080);
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("Duplicate matching rules detected when adding "
"filter chain: {source_ports={8080}}"));
}
using EdsTest = BasicTest;
// Tests that EDS client should send a NACK if the EDS update contains
// sparse priorities.
TEST_P(EdsTest, NacksSparsePriorityList) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(), kDefaultLocalityWeight, 1},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->eds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("sparse priority list"));
}
// In most of our tests, we use different names for different resource
// types, to make sure that there are no cut-and-paste errors in the code
// that cause us to look at data for the wrong resource type. So we add
// this test to make sure that the EDS resource name defaults to the
// cluster name if not specified in the CDS resource.
TEST_P(EdsTest, EdsServiceNameDefaultsToClusterName) {
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, kDefaultClusterName));
Cluster cluster = default_cluster_;
cluster.mutable_eds_cluster_config()->clear_service_name();
balancers_[0]->ads_service()->SetCdsResource(cluster);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendOk();
}
class TimeoutTest : public BasicTest {
protected:
void SetUp() override {
xds_resource_does_not_exist_timeout_ms_ = 500;
BasicTest::SetUp();
}
};
// Tests that LDS client times out when no response received.
TEST_P(TimeoutTest, Lds) {
balancers_[0]->ads_service()->SetResourceIgnore(kLdsTypeUrl);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
}
TEST_P(TimeoutTest, Rds) {
balancers_[0]->ads_service()->SetResourceIgnore(kRdsTypeUrl);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
}
// Tests that CDS client times out when no response received.
TEST_P(TimeoutTest, Cds) {
balancers_[0]->ads_service()->SetResourceIgnore(kCdsTypeUrl);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
}
TEST_P(TimeoutTest, Eds) {
balancers_[0]->ads_service()->SetResourceIgnore(kEdsTypeUrl);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
}
using LocalityMapTest = BasicTest;
// Tests that the localities in a locality map are picked according to their
// weights.
TEST_P(LocalityMapTest, WeightedRoundRobin) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 5000;
const int kLocalityWeight0 = 2;
const int kLocalityWeight1 = 8;
const int kTotalLocalityWeight = kLocalityWeight0 + kLocalityWeight1;
const double kLocalityWeightRate0 =
static_cast<double>(kLocalityWeight0) / kTotalLocalityWeight;
const double kLocalityWeightRate1 =
static_cast<double>(kLocalityWeight1) / kTotalLocalityWeight;
// ADS response contains 2 localities, each of which contains 1 backend.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1), kLocalityWeight0},
{"locality1", GetBackendPorts(1, 2), kLocalityWeight1},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait for both backends to be ready.
WaitForAllBackends(0, 2);
// Send kNumRpcs RPCs.
CheckRpcSendOk(kNumRpcs);
// The locality picking rates should be roughly equal to the expectation.
const double locality_picked_rate_0 =
static_cast<double>(backends_[0]->backend_service()->request_count()) /
kNumRpcs;
const double locality_picked_rate_1 =
static_cast<double>(backends_[1]->backend_service()->request_count()) /
kNumRpcs;
const double kErrorTolerance = 0.2;
EXPECT_THAT(locality_picked_rate_0,
::testing::AllOf(
::testing::Ge(kLocalityWeightRate0 * (1 - kErrorTolerance)),
::testing::Le(kLocalityWeightRate0 * (1 + kErrorTolerance))));
EXPECT_THAT(locality_picked_rate_1,
::testing::AllOf(
::testing::Ge(kLocalityWeightRate1 * (1 - kErrorTolerance)),
::testing::Le(kLocalityWeightRate1 * (1 + kErrorTolerance))));
}
// Tests that we correctly handle a locality containing no endpoints.
TEST_P(LocalityMapTest, LocalityContainingNoEndpoints) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 5000;
// EDS response contains 2 localities, one with no endpoints.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
{"locality1", {}},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait for both backends to be ready.
WaitForAllBackends();
// Send kNumRpcs RPCs.
CheckRpcSendOk(kNumRpcs);
// All traffic should go to the reachable locality.
EXPECT_EQ(backends_[0]->backend_service()->request_count(),
kNumRpcs / backends_.size());
EXPECT_EQ(backends_[1]->backend_service()->request_count(),
kNumRpcs / backends_.size());
EXPECT_EQ(backends_[2]->backend_service()->request_count(),
kNumRpcs / backends_.size());
EXPECT_EQ(backends_[3]->backend_service()->request_count(),
kNumRpcs / backends_.size());
}
// EDS update with no localities.
TEST_P(LocalityMapTest, NoLocalities) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource({}, DefaultEdsServiceName()));
Status status = SendRpc();
EXPECT_FALSE(status.ok());
EXPECT_EQ(status.error_code(), StatusCode::UNAVAILABLE);
}
// Tests that the locality map can work properly even when it contains a large
// number of localities.
TEST_P(LocalityMapTest, StressTest) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumLocalities = 100;
// The first ADS response contains kNumLocalities localities, each of which
// contains backend 0.
AdsServiceImpl::EdsResourceArgs args;
for (size_t i = 0; i < kNumLocalities; ++i) {
std::string name = absl::StrCat("locality", i);
AdsServiceImpl::EdsResourceArgs::Locality locality(name,
{backends_[0]->port()});
args.locality_list.emplace_back(std::move(locality));
}
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// The second ADS response contains 1 locality, which contains backend 1.
args = AdsServiceImpl::EdsResourceArgs({
{"locality0", GetBackendPorts(1, 2)},
});
std::thread delayed_resource_setter(
std::bind(&BasicTest::SetEdsResourceWithDelay, this, 0,
BuildEdsResource(args, DefaultEdsServiceName()), 60 * 1000));
// Wait until backend 0 is ready, before which kNumLocalities localities are
// received and handled by the xds policy.
WaitForBackend(0, /*reset_counters=*/false);
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
// Wait until backend 1 is ready, before which kNumLocalities localities are
// removed by the xds policy.
WaitForBackend(1);
delayed_resource_setter.join();
}
// Tests that the localities in a locality map are picked correctly after update
// (addition, modification, deletion).
TEST_P(LocalityMapTest, UpdateMap) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 3000;
// The locality weight for the first 3 localities.
const std::vector<int> kLocalityWeights0 = {2, 3, 4};
const double kTotalLocalityWeight0 =
std::accumulate(kLocalityWeights0.begin(), kLocalityWeights0.end(), 0);
std::vector<double> locality_weight_rate_0;
locality_weight_rate_0.reserve(kLocalityWeights0.size());
for (int weight : kLocalityWeights0) {
locality_weight_rate_0.push_back(weight / kTotalLocalityWeight0);
}
// Delete the first locality, keep the second locality, change the third
// locality's weight from 4 to 2, and add a new locality with weight 6.
const std::vector<int> kLocalityWeights1 = {3, 2, 6};
const double kTotalLocalityWeight1 =
std::accumulate(kLocalityWeights1.begin(), kLocalityWeights1.end(), 0);
std::vector<double> locality_weight_rate_1 = {
0 /* placeholder for locality 0 */};
for (int weight : kLocalityWeights1) {
locality_weight_rate_1.push_back(weight / kTotalLocalityWeight1);
}
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1), 2},
{"locality1", GetBackendPorts(1, 2), 3},
{"locality2", GetBackendPorts(2, 3), 4},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait for the first 3 backends to be ready.
WaitForAllBackends(0, 3);
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
// Send kNumRpcs RPCs.
CheckRpcSendOk(kNumRpcs);
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// The picking rates of the first 3 backends should be roughly equal to the
// expectation.
std::vector<double> locality_picked_rates;
for (size_t i = 0; i < 3; ++i) {
locality_picked_rates.push_back(
static_cast<double>(backends_[i]->backend_service()->request_count()) /
kNumRpcs);
}
const double kErrorTolerance = 0.2;
for (size_t i = 0; i < 3; ++i) {
gpr_log(GPR_INFO, "Locality %" PRIuPTR " rate %f", i,
locality_picked_rates[i]);
EXPECT_THAT(
locality_picked_rates[i],
::testing::AllOf(
::testing::Ge(locality_weight_rate_0[i] * (1 - kErrorTolerance)),
::testing::Le(locality_weight_rate_0[i] * (1 + kErrorTolerance))));
}
args = AdsServiceImpl::EdsResourceArgs({
{"locality1", GetBackendPorts(1, 2), 3},
{"locality2", GetBackendPorts(2, 3), 2},
{"locality3", GetBackendPorts(3, 4), 6},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Backend 3 hasn't received any request.
EXPECT_EQ(0U, backends_[3]->backend_service()->request_count());
// Wait until the locality update has been processed, as signaled by backend 3
// receiving a request.
WaitForAllBackends(3, 4);
gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
// Send kNumRpcs RPCs.
CheckRpcSendOk(kNumRpcs);
gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
// Backend 0 no longer receives any request.
EXPECT_EQ(0U, backends_[0]->backend_service()->request_count());
// The picking rates of the last 3 backends should be roughly equal to the
// expectation.
locality_picked_rates = {0 /* placeholder for backend 0 */};
for (size_t i = 1; i < 4; ++i) {
locality_picked_rates.push_back(
static_cast<double>(backends_[i]->backend_service()->request_count()) /
kNumRpcs);
}
for (size_t i = 1; i < 4; ++i) {
gpr_log(GPR_INFO, "Locality %" PRIuPTR " rate %f", i,
locality_picked_rates[i]);
EXPECT_THAT(
locality_picked_rates[i],
::testing::AllOf(
::testing::Ge(locality_weight_rate_1[i] * (1 - kErrorTolerance)),
::testing::Le(locality_weight_rate_1[i] * (1 + kErrorTolerance))));
}
}
// Tests that we don't fail RPCs when replacing all of the localities in
// a given priority.
TEST_P(LocalityMapTest, ReplaceAllLocalitiesInPriority) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
args = AdsServiceImpl::EdsResourceArgs({
{"locality1", GetBackendPorts(1, 2)},
});
std::thread delayed_resource_setter(
std::bind(&BasicTest::SetEdsResourceWithDelay, this, 0,
BuildEdsResource(args, DefaultEdsServiceName()), 5000));
// Wait for the first backend to be ready.
WaitForBackend(0);
// Keep sending RPCs until we switch over to backend 1, which tells us
// that we received the update. No RPCs should fail during this
// transition.
WaitForBackend(1, /*reset_counters=*/true, /*require_success=*/true);
delayed_resource_setter.join();
}
class FailoverTest : public BasicTest {
public:
void SetUp() override {
BasicTest::SetUp();
ResetStub(500);
}
};
// Localities with the highest priority are used when multiple priority exist.
TEST_P(FailoverTest, ChooseHighestPriority) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
WaitForBackend(3, false);
for (size_t i = 0; i < 3; ++i) {
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
}
// Does not choose priority with no endpoints.
TEST_P(FailoverTest, DoesNotUsePriorityWithNoEndpoints) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
{"locality3", {}, kDefaultLocalityWeight, 0},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
WaitForBackend(0, false);
for (size_t i = 1; i < 3; ++i) {
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
}
// Does not choose locality with no endpoints.
TEST_P(FailoverTest, DoesNotUseLocalityWithNoEndpoints) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {}, kDefaultLocalityWeight, 0},
{"locality1", GetBackendPorts(), kDefaultLocalityWeight, 0},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait for all backends to be used.
std::tuple<int, int, int> counts = WaitForAllBackends();
// Make sure no RPCs failed in the transition.
EXPECT_EQ(0, std::get<1>(counts));
}
// If the higher priority localities are not reachable, failover to the highest
// priority among the rest.
TEST_P(FailoverTest, Failover) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
});
ShutdownBackend(3);
ShutdownBackend(0);
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
WaitForBackend(1, false);
for (size_t i = 0; i < 4; ++i) {
if (i == 1) continue;
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
}
// If a locality with higher priority than the current one becomes ready,
// switch to it.
TEST_P(FailoverTest, SwitchBackToHigherPriority) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 100;
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
WaitForBackend(3);
ShutdownBackend(3);
ShutdownBackend(0);
WaitForBackend(1, false);
for (size_t i = 0; i < 4; ++i) {
if (i == 1) continue;
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
StartBackend(0);
WaitForBackend(0);
CheckRpcSendOk(kNumRpcs);
EXPECT_EQ(kNumRpcs, backends_[0]->backend_service()->request_count());
}
// The first update only contains unavailable priorities. The second update
// contains available priorities.
TEST_P(FailoverTest, UpdateInitialUnavailable) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 1},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
args = AdsServiceImpl::EdsResourceArgs({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 1},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 2},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 3},
});
ShutdownBackend(0);
ShutdownBackend(1);
std::thread delayed_resource_setter(
std::bind(&BasicTest::SetEdsResourceWithDelay, this, 0,
BuildEdsResource(args, DefaultEdsServiceName()), 1000));
gpr_timespec deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_millis(500, GPR_TIMESPAN));
// Send 0.5 second worth of RPCs.
do {
CheckRpcSendFailure();
} while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
WaitForBackend(2, false);
for (size_t i = 0; i < 4; ++i) {
if (i == 2) continue;
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
delayed_resource_setter.join();
}
// Tests that after the localities' priorities are updated, we still choose the
// highest READY priority with the updated localities.
TEST_P(FailoverTest, UpdatePriority) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 100;
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
args = AdsServiceImpl::EdsResourceArgs({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 2},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 0},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 1},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 3},
});
std::thread delayed_resource_setter(
std::bind(&BasicTest::SetEdsResourceWithDelay, this, 0,
BuildEdsResource(args, DefaultEdsServiceName()), 1000));
WaitForBackend(3, false);
for (size_t i = 0; i < 3; ++i) {
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
WaitForBackend(1);
CheckRpcSendOk(kNumRpcs);
EXPECT_EQ(kNumRpcs, backends_[1]->backend_service()->request_count());
delayed_resource_setter.join();
}
// Moves all localities in the current priority to a higher priority.
TEST_P(FailoverTest, MoveAllLocalitiesInCurrentPriorityToHigherPriority) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// First update:
// - Priority 0 is locality 0, containing backend 0, which is down.
// - Priority 1 is locality 1, containing backends 1 and 2, which are up.
ShutdownBackend(0);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
{"locality1", GetBackendPorts(1, 3), kDefaultLocalityWeight, 1},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Second update:
// - Priority 0 contains both localities 0 and 1.
// - Priority 1 is not present.
// - We add backend 3 to locality 1, just so we have a way to know
// when the update has been seen by the client.
args = AdsServiceImpl::EdsResourceArgs({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
{"locality1", GetBackendPorts(1, 4), kDefaultLocalityWeight, 0},
});
std::thread delayed_resource_setter(
std::bind(&BasicTest::SetEdsResourceWithDelay, this, 0,
BuildEdsResource(args, DefaultEdsServiceName()), 1000));
// When we get the first update, all backends in priority 0 are down,
// so we will create priority 1. Backends 1 and 2 should have traffic,
// but backend 3 should not.
WaitForAllBackends(1, 3, false);
EXPECT_EQ(0UL, backends_[3]->backend_service()->request_count());
// When backend 3 gets traffic, we know the second update has been seen.
WaitForBackend(3);
// The ADS service of balancer 0 got at least 1 response.
EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT);
delayed_resource_setter.join();
}
using DropTest = BasicTest;
// Tests that RPCs are dropped according to the drop config.
TEST_P(DropTest, Vanilla) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 5000;
const uint32_t kDropPerMillionForLb = 100000;
const uint32_t kDropPerMillionForThrottle = 200000;
const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
const double KDropRateForLbAndThrottle =
kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
// The ADS response contains two drop categories.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
{kThrottleDropType, kDropPerMillionForThrottle}};
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
WaitForAllBackends();
// Send kNumRpcs RPCs and count the drops.
size_t num_drops = 0;
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(RpcOptions(), &response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage);
}
}
// The drop rate should be roughly equal to the expectation.
const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
const double kErrorTolerance = 0.2;
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(
::testing::Ge(KDropRateForLbAndThrottle * (1 - kErrorTolerance)),
::testing::Le(KDropRateForLbAndThrottle * (1 + kErrorTolerance))));
}
// Tests that drop config is converted correctly from per hundred.
TEST_P(DropTest, DropPerHundred) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 5000;
const uint32_t kDropPerHundredForLb = 10;
const double kDropRateForLb = kDropPerHundredForLb / 100.0;
// The ADS response contains one drop category.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, kDropPerHundredForLb}};
args.drop_denominator = FractionalPercent::HUNDRED;
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
WaitForAllBackends();
// Send kNumRpcs RPCs and count the drops.
size_t num_drops = 0;
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(RpcOptions(), &response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage);
}
}
// The drop rate should be roughly equal to the expectation.
const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
const double kErrorTolerance = 0.2;
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(::testing::Ge(kDropRateForLb * (1 - kErrorTolerance)),
::testing::Le(kDropRateForLb * (1 + kErrorTolerance))));
}
// Tests that drop config is converted correctly from per ten thousand.
TEST_P(DropTest, DropPerTenThousand) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 5000;
const uint32_t kDropPerTenThousandForLb = 1000;
const double kDropRateForLb = kDropPerTenThousandForLb / 10000.0;
// The ADS response contains one drop category.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, kDropPerTenThousandForLb}};
args.drop_denominator = FractionalPercent::TEN_THOUSAND;
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
WaitForAllBackends();
// Send kNumRpcs RPCs and count the drops.
size_t num_drops = 0;
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(RpcOptions(), &response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage);
}
}
// The drop rate should be roughly equal to the expectation.
const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
const double kErrorTolerance = 0.2;
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(::testing::Ge(kDropRateForLb * (1 - kErrorTolerance)),
::testing::Le(kDropRateForLb * (1 + kErrorTolerance))));
}
// Tests that drop is working correctly after update.
TEST_P(DropTest, Update) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 3000;
const uint32_t kDropPerMillionForLb = 100000;
const uint32_t kDropPerMillionForThrottle = 200000;
const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
const double KDropRateForLbAndThrottle =
kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
// The first ADS response contains one drop category.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, kDropPerMillionForLb}};
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
WaitForAllBackends();
// Send kNumRpcs RPCs and count the drops.
size_t num_drops = 0;
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(RpcOptions(), &response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage);
}
}
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// The drop rate should be roughly equal to the expectation.
double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
gpr_log(GPR_INFO, "First batch drop rate %f", seen_drop_rate);
const double kErrorTolerance = 0.3;
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(::testing::Ge(kDropRateForLb * (1 - kErrorTolerance)),
::testing::Le(kDropRateForLb * (1 + kErrorTolerance))));
// The second ADS response contains two drop categories, send an update EDS
// response.
args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
{kThrottleDropType, kDropPerMillionForThrottle}};
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait until the drop rate increases to the middle of the two configs, which
// implies that the update has been in effect.
const double kDropRateThreshold =
(kDropRateForLb + KDropRateForLbAndThrottle) / 2;
size_t num_rpcs = kNumRpcs;
while (seen_drop_rate < kDropRateThreshold) {
EchoResponse response;
const Status status = SendRpc(RpcOptions(), &response);
++num_rpcs;
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage);
}
seen_drop_rate = static_cast<double>(num_drops) / num_rpcs;
}
// Send kNumRpcs RPCs and count the drops.
num_drops = 0;
gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(RpcOptions(), &response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage);
}
}
gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
// The new drop rate should be roughly equal to the expectation.
seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
gpr_log(GPR_INFO, "Second batch drop rate %f", seen_drop_rate);
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(
::testing::Ge(KDropRateForLbAndThrottle * (1 - kErrorTolerance)),
::testing::Le(KDropRateForLbAndThrottle * (1 + kErrorTolerance))));
}
// Tests that all the RPCs are dropped if any drop category drops 100%.
TEST_P(DropTest, DropAll) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 1000;
const uint32_t kDropPerMillionForLb = 100000;
const uint32_t kDropPerMillionForThrottle = 1000000;
// The ADS response contains two drop categories.
AdsServiceImpl::EdsResourceArgs args;
args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
{kThrottleDropType, kDropPerMillionForThrottle}};
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Send kNumRpcs RPCs and all of them are dropped.
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(RpcOptions(), &response);
EXPECT_EQ(status.error_code(), StatusCode::UNAVAILABLE);
EXPECT_EQ(status.error_message(), "Call dropped by load balancing policy");
}
}
class BalancerUpdateTest : public XdsEnd2endTest {
public:
BalancerUpdateTest() : XdsEnd2endTest(4, 3) {}
};
// Tests that the old LB call is still used after the balancer address update as
// long as that call is still alive.
TEST_P(BalancerUpdateTest, UpdateBalancersButKeepUsingOriginalBalancer) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {backends_[0]->port()}},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
args = AdsServiceImpl::EdsResourceArgs({
{"locality0", {backends_[1]->port()}},
});
balancers_[1]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait until the first backend is ready.
WaitForBackend(0);
// Send 10 requests.
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
CheckRpcSendOk(10);
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// All 10 requests should have gone to the first backend.
EXPECT_EQ(10U, backends_[0]->backend_service()->request_count());
// The ADS service of balancer 0 sent at least 1 response.
EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT);
EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[1]->ads_service()->eds_response_state().error_message;
EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[2]->ads_service()->eds_response_state().error_message;
gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
SetNextResolutionForLbChannel({balancers_[1]->port()});
gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
gpr_timespec deadline = gpr_time_add(
gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(10000, GPR_TIMESPAN));
// Send 10 seconds worth of RPCs
do {
CheckRpcSendOk();
} while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
// The current LB call is still working, so xds continued using it to the
// first balancer, which doesn't assign the second backend.
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
// The ADS service of balancer 0 sent at least 1 response.
EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT);
EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[1]->ads_service()->eds_response_state().error_message;
EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[2]->ads_service()->eds_response_state().error_message;
}
// Tests that the old LB call is still used after multiple balancer address
// updates as long as that call is still alive. Send an update with the same set
// of LBs as the one in SetUp() in order to verify that the LB channel inside
// xds keeps the initial connection (which by definition is also present in the
// update).
TEST_P(BalancerUpdateTest, Repeated) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {backends_[0]->port()}},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
args = AdsServiceImpl::EdsResourceArgs({
{"locality0", {backends_[1]->port()}},
});
balancers_[1]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait until the first backend is ready.
WaitForBackend(0);
// Send 10 requests.
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
CheckRpcSendOk(10);
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// All 10 requests should have gone to the first backend.
EXPECT_EQ(10U, backends_[0]->backend_service()->request_count());
// The ADS service of balancer 0 sent at least 1 response.
EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT);
EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[1]->ads_service()->eds_response_state().error_message;
EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[2]->ads_service()->eds_response_state().error_message;
std::vector<int> ports;
ports.emplace_back(balancers_[0]->port());
ports.emplace_back(balancers_[1]->port());
ports.emplace_back(balancers_[2]->port());
gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
SetNextResolutionForLbChannel(ports);
gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
gpr_timespec deadline = gpr_time_add(
gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(10000, GPR_TIMESPAN));
// Send 10 seconds worth of RPCs
do {
CheckRpcSendOk();
} while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
// xds continued using the original LB call to the first balancer, which
// doesn't assign the second backend.
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
ports.clear();
ports.emplace_back(balancers_[0]->port());
ports.emplace_back(balancers_[1]->port());
gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 2 ==========");
SetNextResolutionForLbChannel(ports);
gpr_log(GPR_INFO, "========= UPDATE 2 DONE ==========");
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_millis(10000, GPR_TIMESPAN));
// Send 10 seconds worth of RPCs
do {
CheckRpcSendOk();
} while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
// xds continued using the original LB call to the first balancer, which
// doesn't assign the second backend.
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
}
// Tests that if the balancer is down, the RPCs will still be sent to the
// backends according to the last balancer response, until a new balancer is
// reachable.
TEST_P(BalancerUpdateTest, DeadUpdate) {
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()});
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {backends_[0]->port()}},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
args = AdsServiceImpl::EdsResourceArgs({
{"locality0", {backends_[1]->port()}},
});
balancers_[1]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Start servers and send 10 RPCs per server.
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
CheckRpcSendOk(10);
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// All 10 requests should have gone to the first backend.
EXPECT_EQ(10U, backends_[0]->backend_service()->request_count());
// The ADS service of balancer 0 sent at least 1 response.
EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT);
EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[1]->ads_service()->eds_response_state().error_message;
EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[2]->ads_service()->eds_response_state().error_message;
// Kill balancer 0
gpr_log(GPR_INFO, "********** ABOUT TO KILL BALANCER 0 *************");
balancers_[0]->Shutdown();
gpr_log(GPR_INFO, "********** KILLED BALANCER 0 *************");
// This is serviced by the existing child policy.
gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
CheckRpcSendOk(10);
gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
// All 10 requests should again have gone to the first backend.
EXPECT_EQ(20U, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
// The ADS service of no balancers sent anything
EXPECT_EQ(balancers_[0]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[0]->ads_service()->eds_response_state().error_message;
EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[1]->ads_service()->eds_response_state().error_message;
EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[2]->ads_service()->eds_response_state().error_message;
gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
SetNextResolutionForLbChannel({balancers_[1]->port()});
gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
// Wait until update has been processed, as signaled by the second backend
// receiving a request. In the meantime, the client continues to be serviced
// (by the first backend) without interruption.
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
WaitForBackend(1);
// This is serviced by the updated RR policy
backends_[1]->backend_service()->ResetCounters();
gpr_log(GPR_INFO, "========= BEFORE THIRD BATCH ==========");
CheckRpcSendOk(10);
gpr_log(GPR_INFO, "========= DONE WITH THIRD BATCH ==========");
// All 10 requests should have gone to the second backend.
EXPECT_EQ(10U, backends_[1]->backend_service()->request_count());
// The ADS service of balancer 1 sent at least 1 response.
EXPECT_EQ(balancers_[0]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[0]->ads_service()->eds_response_state().error_message;
EXPECT_GT(balancers_[1]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT);
EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[2]->ads_service()->eds_response_state().error_message;
}
class ClientLoadReportingTest : public XdsEnd2endTest {
public:
ClientLoadReportingTest() : XdsEnd2endTest(4, 1, 3) {}
};
// Tests that the load report received at the balancer is correct.
TEST_P(ClientLoadReportingTest, Vanilla) {
if (GetParam().use_fake_resolver()) {
balancers_[0]->lrs_service()->set_cluster_names({kServerName});
}
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()});
const size_t kNumRpcsPerAddress = 10;
const size_t kNumFailuresPerAddress = 3;
// TODO(juanlishen): Partition the backends after multiple localities is
// tested.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait until all backends are ready.
int num_ok = 0;
int num_failure = 0;
int num_drops = 0;
std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
// Send kNumRpcsPerAddress RPCs per server.
CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
CheckRpcSendFailure(kNumFailuresPerAddress * num_backends_,
RpcOptions().set_server_fail(true));
// Check that each backend got the right number of requests.
for (size_t i = 0; i < backends_.size(); ++i) {
EXPECT_EQ(kNumRpcsPerAddress + kNumFailuresPerAddress,
backends_[i]->backend_service()->request_count());
}
// The load report received at the balancer should be correct.
std::vector<ClientStats> load_report =
balancers_[0]->lrs_service()->WaitForLoadReport();
ASSERT_EQ(load_report.size(), 1UL);
ClientStats& client_stats = load_report.front();
EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_ok,
client_stats.total_successful_requests());
EXPECT_EQ(0U, client_stats.total_requests_in_progress());
EXPECT_EQ((kNumRpcsPerAddress + kNumFailuresPerAddress) * num_backends_ +
num_ok + num_failure,
client_stats.total_issued_requests());
EXPECT_EQ(kNumFailuresPerAddress * num_backends_ + num_failure,
client_stats.total_error_requests());
EXPECT_EQ(0U, client_stats.total_dropped_requests());
// The LRS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->lrs_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->lrs_service()->response_count());
}
// Tests send_all_clusters.
TEST_P(ClientLoadReportingTest, SendAllClusters) {
balancers_[0]->lrs_service()->set_send_all_clusters(true);
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()});
const size_t kNumRpcsPerAddress = 10;
const size_t kNumFailuresPerAddress = 3;
// TODO(juanlishen): Partition the backends after multiple localities is
// tested.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait until all backends are ready.
int num_ok = 0;
int num_failure = 0;
int num_drops = 0;
std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
// Send kNumRpcsPerAddress RPCs per server.
CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
CheckRpcSendFailure(kNumFailuresPerAddress * num_backends_,
RpcOptions().set_server_fail(true));
// Check that each backend got the right number of requests.
for (size_t i = 0; i < backends_.size(); ++i) {
EXPECT_EQ(kNumRpcsPerAddress + kNumFailuresPerAddress,
backends_[i]->backend_service()->request_count());
}
// The load report received at the balancer should be correct.
std::vector<ClientStats> load_report =
balancers_[0]->lrs_service()->WaitForLoadReport();
ASSERT_EQ(load_report.size(), 1UL);
ClientStats& client_stats = load_report.front();
EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_ok,
client_stats.total_successful_requests());
EXPECT_EQ(0U, client_stats.total_requests_in_progress());
EXPECT_EQ((kNumRpcsPerAddress + kNumFailuresPerAddress) * num_backends_ +
num_ok + num_failure,
client_stats.total_issued_requests());
EXPECT_EQ(kNumFailuresPerAddress * num_backends_ + num_failure,
client_stats.total_error_requests());
EXPECT_EQ(0U, client_stats.total_dropped_requests());
// The LRS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->lrs_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->lrs_service()->response_count());
}
// Tests that we don't include stats for clusters that are not requested
// by the LRS server.
TEST_P(ClientLoadReportingTest, HonorsClustersRequestedByLrsServer) {
balancers_[0]->lrs_service()->set_cluster_names({"bogus"});
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()});
const size_t kNumRpcsPerAddress = 100;
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait until all backends are ready.
int num_ok = 0;
int num_failure = 0;
int num_drops = 0;
std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
// Send kNumRpcsPerAddress RPCs per server.
CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
// Each backend should have gotten 100 requests.
for (size_t i = 0; i < backends_.size(); ++i) {
EXPECT_EQ(kNumRpcsPerAddress,
backends_[i]->backend_service()->request_count());
}
// The LRS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->lrs_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->lrs_service()->response_count());
// The load report received at the balancer should be correct.
std::vector<ClientStats> load_report =
balancers_[0]->lrs_service()->WaitForLoadReport();
ASSERT_EQ(load_report.size(), 0UL);
}
// Tests that if the balancer restarts, the client load report contains the
// stats before and after the restart correctly.
TEST_P(ClientLoadReportingTest, BalancerRestart) {
if (GetParam().use_fake_resolver()) {
balancers_[0]->lrs_service()->set_cluster_names({kServerName});
}
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()});
const size_t kNumBackendsFirstPass = backends_.size() / 2;
const size_t kNumBackendsSecondPass =
backends_.size() - kNumBackendsFirstPass;
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, kNumBackendsFirstPass)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait until all backends returned by the balancer are ready.
int num_ok = 0;
int num_failure = 0;
int num_drops = 0;
std::tie(num_ok, num_failure, num_drops) =
WaitForAllBackends(/* start_index */ 0,
/* stop_index */ kNumBackendsFirstPass);
std::vector<ClientStats> load_report =
balancers_[0]->lrs_service()->WaitForLoadReport();
ASSERT_EQ(load_report.size(), 1UL);
ClientStats client_stats = std::move(load_report.front());
EXPECT_EQ(static_cast<size_t>(num_ok),
client_stats.total_successful_requests());
EXPECT_EQ(0U, client_stats.total_requests_in_progress());
EXPECT_EQ(0U, client_stats.total_error_requests());
EXPECT_EQ(0U, client_stats.total_dropped_requests());
// Shut down the balancer.
balancers_[0]->Shutdown();
// We should continue using the last EDS response we received from the
// balancer before it was shut down.
// Note: We need to use WaitForAllBackends() here instead of just
// CheckRpcSendOk(kNumBackendsFirstPass), because when the balancer
// shuts down, the XdsClient will generate an error to the
// ServiceConfigWatcher, which will cause the xds resolver to send a
// no-op update to the LB policy. When this update gets down to the
// round_robin child policy for the locality, it will generate a new
// subchannel list, which resets the start index randomly. So we need
// to be a little more permissive here to avoid spurious failures.
ResetBackendCounters();
int num_started = std::get<0>(WaitForAllBackends(
/* start_index */ 0, /* stop_index */ kNumBackendsFirstPass));
// Now restart the balancer, this time pointing to the new backends.
balancers_[0]->Start();
args = AdsServiceImpl::EdsResourceArgs({
{"locality0", GetBackendPorts(kNumBackendsFirstPass)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait for queries to start going to one of the new backends.
// This tells us that we're now using the new serverlist.
std::tie(num_ok, num_failure, num_drops) =
WaitForAllBackends(/* start_index */ kNumBackendsFirstPass);
num_started += num_ok + num_failure + num_drops;
// Send one RPC per backend.
CheckRpcSendOk(kNumBackendsSecondPass);
num_started += kNumBackendsSecondPass;
// Check client stats.
load_report = balancers_[0]->lrs_service()->WaitForLoadReport();
ASSERT_EQ(load_report.size(), 1UL);
client_stats = std::move(load_report.front());
EXPECT_EQ(num_started, client_stats.total_successful_requests());
EXPECT_EQ(0U, client_stats.total_requests_in_progress());
EXPECT_EQ(0U, client_stats.total_error_requests());
EXPECT_EQ(0U, client_stats.total_dropped_requests());
}
class ClientLoadReportingWithDropTest : public XdsEnd2endTest {
public:
ClientLoadReportingWithDropTest() : XdsEnd2endTest(4, 1, 20) {}
};
// Tests that the drop stats are correctly reported by client load reporting.
TEST_P(ClientLoadReportingWithDropTest, Vanilla) {
if (GetParam().use_fake_resolver()) {
balancers_[0]->lrs_service()->set_cluster_names({kServerName});
}
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 3000;
const uint32_t kDropPerMillionForLb = 100000;
const uint32_t kDropPerMillionForThrottle = 200000;
const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
const double KDropRateForLbAndThrottle =
kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
// The ADS response contains two drop categories.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
{kThrottleDropType, kDropPerMillionForThrottle}};
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
int num_ok = 0;
int num_failure = 0;
int num_drops = 0;
std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
const size_t num_warmup = num_ok + num_failure + num_drops;
// Send kNumRpcs RPCs and count the drops.
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(RpcOptions(), &response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage);
}
}
// The drop rate should be roughly equal to the expectation.
const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
const double kErrorTolerance = 0.2;
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(
::testing::Ge(KDropRateForLbAndThrottle * (1 - kErrorTolerance)),
::testing::Le(KDropRateForLbAndThrottle * (1 + kErrorTolerance))));
// Check client stats.
const size_t total_rpc = num_warmup + kNumRpcs;
ClientStats client_stats;
do {
std::vector<ClientStats> load_reports =
balancers_[0]->lrs_service()->WaitForLoadReport();
for (const auto& load_report : load_reports) {
client_stats += load_report;
}
} while (client_stats.total_issued_requests() +
client_stats.total_dropped_requests() <
total_rpc);
EXPECT_EQ(num_drops, client_stats.total_dropped_requests());
EXPECT_THAT(
client_stats.dropped_requests(kLbDropType),
::testing::AllOf(
::testing::Ge(total_rpc * kDropRateForLb * (1 - kErrorTolerance)),
::testing::Le(total_rpc * kDropRateForLb * (1 + kErrorTolerance))));
EXPECT_THAT(client_stats.dropped_requests(kThrottleDropType),
::testing::AllOf(
::testing::Ge(total_rpc * (1 - kDropRateForLb) *
kDropRateForThrottle * (1 - kErrorTolerance)),
::testing::Le(total_rpc * (1 - kDropRateForLb) *
kDropRateForThrottle * (1 + kErrorTolerance))));
}
class FaultInjectionTest : public XdsEnd2endTest {
public:
FaultInjectionTest() : XdsEnd2endTest(1, 1) {}
// Builds a Listener with Fault Injection filter config. If the http_fault is
// nullptr, then assign an empty filter config. This filter config is required
// to enable the fault injection features.
static Listener BuildListenerWithFaultInjection(
const HTTPFault& http_fault = HTTPFault()) {
HttpConnectionManager http_connection_manager;
Listener listener;
listener.set_name(kServerName);
HttpFilter* fault_filter = http_connection_manager.add_http_filters();
fault_filter->set_name("envoy.fault");
fault_filter->mutable_typed_config()->PackFrom(http_fault);
HttpFilter* router_filter = http_connection_manager.add_http_filters();
router_filter->set_name("router");
router_filter->mutable_typed_config()->PackFrom(
envoy::extensions::filters::http::router::v3::Router());
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
return listener;
}
RouteConfiguration BuildRouteConfigurationWithFaultInjection(
const HTTPFault& http_fault) {
// Package as Any
google::protobuf::Any filter_config;
filter_config.PackFrom(http_fault);
// Plug into the RouteConfiguration
RouteConfiguration new_route_config = default_route_config_;
auto* config_map = new_route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_typed_per_filter_config();
(*config_map)["envoy.fault"] = std::move(filter_config);
return new_route_config;
}
void SetFilterConfig(HTTPFault& http_fault) {
switch (GetParam().filter_config_setup()) {
case TestType::FilterConfigSetup::kRouteOverride: {
Listener listener = BuildListenerWithFaultInjection();
RouteConfiguration route =
BuildRouteConfigurationWithFaultInjection(http_fault);
SetListenerAndRouteConfiguration(0, listener, route);
break;
}
case TestType::FilterConfigSetup::kHTTPConnectionManagerOriginal: {
Listener listener = BuildListenerWithFaultInjection(http_fault);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
}
};
}
};
// Test to ensure the most basic fault injection config works.
TEST_P(FaultInjectionTest, XdsFaultInjectionAlwaysAbort) {
const uint32_t kAbortPercentagePerHundred = 100;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Construct the fault injection filter config
HTTPFault http_fault;
auto* abort_percentage = http_fault.mutable_abort()->mutable_percentage();
abort_percentage->set_numerator(kAbortPercentagePerHundred);
abort_percentage->set_denominator(FractionalPercent::HUNDRED);
http_fault.mutable_abort()->set_grpc_status(
static_cast<uint32_t>(StatusCode::ABORTED));
// Config fault injection via different setup
SetFilterConfig(http_fault);
// Fire several RPCs, and expect all of them to be aborted.
CheckRpcSendFailure(5, RpcOptions().set_wait_for_ready(true),
StatusCode::ABORTED);
}
// Without the listener config, the fault injection won't be enabled.
TEST_P(FaultInjectionTest, XdsFaultInjectionWithoutListenerFilter) {
const uint32_t kAbortPercentagePerHundred = 100;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Create an EDS resource
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Construct the fault injection filter config
HTTPFault http_fault;
auto* abort_percentage = http_fault.mutable_abort()->mutable_percentage();
abort_percentage->set_numerator(kAbortPercentagePerHundred);
abort_percentage->set_denominator(FractionalPercent::HUNDRED);
http_fault.mutable_abort()->set_grpc_status(
static_cast<uint32_t>(StatusCode::ABORTED));
// Turn on fault injection
RouteConfiguration route =
BuildRouteConfigurationWithFaultInjection(http_fault);
SetListenerAndRouteConfiguration(0, default_listener_, route);
// Fire several RPCs, and expect all of them to be pass.
CheckRpcSendOk(5, RpcOptions().set_wait_for_ready(true));
}
TEST_P(FaultInjectionTest, XdsFaultInjectionPercentageAbort) {
const size_t kNumRpcs = 100;
const uint32_t kAbortPercentagePerHundred = 50;
const double kAbortRate = kAbortPercentagePerHundred / 100.0;
const double kErrorTolerance = 0.2;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Create an EDS resource
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Construct the fault injection filter config
HTTPFault http_fault;
auto* abort_percentage = http_fault.mutable_abort()->mutable_percentage();
abort_percentage->set_numerator(kAbortPercentagePerHundred);
abort_percentage->set_denominator(FractionalPercent::HUNDRED);
http_fault.mutable_abort()->set_grpc_status(
static_cast<uint32_t>(StatusCode::ABORTED));
// Config fault injection via different setup
SetFilterConfig(http_fault);
// Send kNumRpcs RPCs and count the aborts.
int num_total = 0, num_ok = 0, num_failure = 0, num_aborted = 0;
for (size_t i = 0; i < kNumRpcs; ++i) {
SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_aborted,
RpcOptions(), "Fault injected");
}
EXPECT_EQ(kNumRpcs, num_total);
EXPECT_EQ(0, num_failure);
// The abort rate should be roughly equal to the expectation.
const double seen_abort_rate = static_cast<double>(num_aborted) / kNumRpcs;
EXPECT_THAT(seen_abort_rate,
::testing::AllOf(::testing::Ge(kAbortRate - kErrorTolerance),
::testing::Le(kAbortRate + kErrorTolerance)));
}
TEST_P(FaultInjectionTest, XdsFaultInjectionPercentageAbortViaHeaders) {
const size_t kNumRpcs = 100;
const uint32_t kAbortPercentageCap = 100;
const uint32_t kAbortPercentage = 50;
const double kAbortRate = kAbortPercentage / 100.0;
const double kErrorTolerance = 0.2;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Create an EDS resource
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Construct the fault injection filter config
HTTPFault http_fault;
http_fault.mutable_abort()->mutable_header_abort();
http_fault.mutable_abort()->mutable_percentage()->set_numerator(
kAbortPercentageCap);
// Config fault injection via different setup
SetFilterConfig(http_fault);
// Send kNumRpcs RPCs and count the aborts.
std::vector<std::pair<std::string, std::string>> metadata = {
{"x-envoy-fault-abort-grpc-request", "10"},
{"x-envoy-fault-abort-percentage", std::to_string(kAbortPercentage)},
};
int num_total = 0, num_ok = 0, num_failure = 0, num_aborted = 0;
RpcOptions options = RpcOptions().set_metadata(metadata);
for (size_t i = 0; i < kNumRpcs; ++i) {
SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_aborted, options,
"Fault injected");
}
EXPECT_EQ(kNumRpcs, num_total);
EXPECT_EQ(0, num_failure);
// The abort rate should be roughly equal to the expectation.
const double seen_abort_rate = static_cast<double>(num_aborted) / kNumRpcs;
EXPECT_THAT(seen_abort_rate,
::testing::AllOf(::testing::Ge(kAbortRate - kErrorTolerance),
::testing::Le(kAbortRate + kErrorTolerance)));
}
// TODO(lidiz) reduce the error tolerance to a lower level without dramatically
// increase the duration of fault injection tests.
TEST_P(FaultInjectionTest, XdsFaultInjectionPercentageDelay) {
const size_t kNumRpcs = 100;
const uint32_t kFixedDelaySeconds = 100;
const uint32_t kRpcTimeoutMilliseconds = 10; // 10 ms
const uint32_t kDelayPercentagePerHundred = 95;
const double kDelayRate = kDelayPercentagePerHundred / 100.0;
const double kErrorTolerance = 0.2;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Create an EDS resource
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Construct the fault injection filter config
HTTPFault http_fault;
auto* delay_percentage = http_fault.mutable_delay()->mutable_percentage();
delay_percentage->set_numerator(kDelayPercentagePerHundred);
delay_percentage->set_denominator(FractionalPercent::HUNDRED);
auto* fixed_delay = http_fault.mutable_delay()->mutable_fixed_delay();
fixed_delay->set_seconds(kFixedDelaySeconds);
// Config fault injection via different setup
SetFilterConfig(http_fault);
// Send kNumRpcs RPCs and count the delays.
int num_total = 0, num_ok = 0, num_delayed = 0, num_dropped = 0;
RpcOptions options = RpcOptions()
.set_timeout_ms(kRpcTimeoutMilliseconds)
.set_skip_cancelled_check(true);
for (size_t i = 0; i < kNumRpcs; ++i) {
SendRpcAndCount(&num_total, &num_ok, &num_delayed, &num_dropped, options);
}
EXPECT_EQ(kNumRpcs, num_total);
EXPECT_EQ(0, num_dropped);
// The delay rate should be roughly equal to the expectation.
const double seen_delay_rate = static_cast<double>(num_delayed) / kNumRpcs;
EXPECT_THAT(seen_delay_rate,
::testing::AllOf(::testing::Ge(kDelayRate - kErrorTolerance),
::testing::Le(kDelayRate + kErrorTolerance)));
}
TEST_P(FaultInjectionTest, XdsFaultInjectionPercentageDelayViaHeaders) {
const size_t kNumRpcs = 100;
const uint32_t kFixedDelayMilliseconds = 100000; // 100 seconds
const uint32_t kRpcTimeoutMilliseconds = 10; // 10 ms
const uint32_t kDelayPercentageCap = 100;
const uint32_t kDelayPercentage = 50;
const double kDelayRate = kDelayPercentage / 100.0;
const double kErrorTolerance = 0.2;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Create an EDS resource
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Construct the fault injection filter config
HTTPFault http_fault;
http_fault.mutable_delay()->mutable_header_delay();
http_fault.mutable_delay()->mutable_percentage()->set_numerator(
kDelayPercentageCap);
// Config fault injection via different setup
SetFilterConfig(http_fault);
// Send kNumRpcs RPCs and count the delays.
std::vector<std::pair<std::string, std::string>> metadata = {
{"x-envoy-fault-delay-request", std::to_string(kFixedDelayMilliseconds)},
{"x-envoy-fault-delay-request-percentage",
std::to_string(kDelayPercentage)},
};
int num_total = 0, num_ok = 0, num_delayed = 0, num_dropped = 0;
RpcOptions options = RpcOptions()
.set_metadata(metadata)
.set_timeout_ms(kRpcTimeoutMilliseconds)
.set_skip_cancelled_check(true);
for (size_t i = 0; i < kNumRpcs; ++i) {
SendRpcAndCount(&num_total, &num_ok, &num_delayed, &num_dropped, options);
}
// The delay rate should be roughly equal to the expectation.
const double seen_delay_rate = static_cast<double>(num_delayed) / kNumRpcs;
EXPECT_THAT(seen_delay_rate,
::testing::AllOf(::testing::Ge(kDelayRate - kErrorTolerance),
::testing::Le(kDelayRate + kErrorTolerance)));
}
TEST_P(FaultInjectionTest, XdsFaultInjectionAlwaysDelayPercentageAbort) {
const size_t kNumRpcs = 100;
const uint32_t kAbortPercentagePerHundred = 50;
const double kAbortRate = kAbortPercentagePerHundred / 100.0;
const uint32_t kFixedDelayNanos = 10 * 1000 * 1000; // 10 ms
const double kErrorTolerance = 0.2;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Create an EDS resource
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Construct the fault injection filter config
HTTPFault http_fault;
auto* abort_percentage = http_fault.mutable_abort()->mutable_percentage();
abort_percentage->set_numerator(kAbortPercentagePerHundred);
abort_percentage->set_denominator(FractionalPercent::HUNDRED);
http_fault.mutable_abort()->set_grpc_status(
static_cast<uint32_t>(StatusCode::ABORTED));
auto* delay_percentage = http_fault.mutable_delay()->mutable_percentage();
delay_percentage->set_numerator(1000000); // Always inject DELAY!
delay_percentage->set_denominator(FractionalPercent::MILLION);
auto* fixed_delay = http_fault.mutable_delay()->mutable_fixed_delay();
fixed_delay->set_nanos(kFixedDelayNanos);
// Config fault injection via different setup
SetFilterConfig(http_fault);
// Send kNumRpcs RPCs and count the aborts.
int num_total = 0, num_ok = 0, num_failure = 0, num_aborted = 0;
for (size_t i = 0; i < kNumRpcs; ++i) {
grpc_millis t0 = NowFromCycleCounter();
SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_aborted,
RpcOptions(), "Fault injected");
grpc_millis t1 = NowFromCycleCounter();
EXPECT_GE(t1, t0 + kFixedDelayNanos / 1000 / 1000);
}
EXPECT_EQ(kNumRpcs, num_total);
EXPECT_EQ(0, num_failure);
// The abort rate should be roughly equal to the expectation.
const double seen_abort_rate = static_cast<double>(num_aborted) / kNumRpcs;
EXPECT_THAT(seen_abort_rate,
::testing::AllOf(::testing::Ge(kAbortRate - kErrorTolerance),
::testing::Le(kAbortRate + kErrorTolerance)));
}
// This test and the above test apply different denominators to delay and abort.
// This ensures that we are using the right denominator for each injected fault
// in our code.
TEST_P(FaultInjectionTest,
XdsFaultInjectionAlwaysDelayPercentageAbortSwitchDenominator) {
const size_t kNumRpcs = 100;
const uint32_t kAbortPercentagePerMillion = 500000;
const double kAbortRate = kAbortPercentagePerMillion / 1000000.0;
const uint32_t kFixedDelayNanos = 10 * 1000 * 1000; // 10 ms
const double kErrorTolerance = 0.2;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Create an EDS resource
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Construct the fault injection filter config
HTTPFault http_fault;
auto* abort_percentage = http_fault.mutable_abort()->mutable_percentage();
abort_percentage->set_numerator(kAbortPercentagePerMillion);
abort_percentage->set_denominator(FractionalPercent::MILLION);
http_fault.mutable_abort()->set_grpc_status(
static_cast<uint32_t>(StatusCode::ABORTED));
auto* delay_percentage = http_fault.mutable_delay()->mutable_percentage();
delay_percentage->set_numerator(100); // Always inject DELAY!
delay_percentage->set_denominator(FractionalPercent::HUNDRED);
auto* fixed_delay = http_fault.mutable_delay()->mutable_fixed_delay();
fixed_delay->set_nanos(kFixedDelayNanos);
// Config fault injection via different setup
SetFilterConfig(http_fault);
// Send kNumRpcs RPCs and count the aborts.
int num_total = 0, num_ok = 0, num_failure = 0, num_aborted = 0;
for (size_t i = 0; i < kNumRpcs; ++i) {
grpc_millis t0 = NowFromCycleCounter();
SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_aborted,
RpcOptions(), "Fault injected");
grpc_millis t1 = NowFromCycleCounter();
EXPECT_GE(t1, t0 + kFixedDelayNanos / 1000 / 1000);
}
EXPECT_EQ(kNumRpcs, num_total);
EXPECT_EQ(0, num_failure);
// The abort rate should be roughly equal to the expectation.
const double seen_abort_rate = static_cast<double>(num_aborted) / kNumRpcs;
EXPECT_THAT(seen_abort_rate,
::testing::AllOf(::testing::Ge(kAbortRate - kErrorTolerance),
::testing::Le(kAbortRate + kErrorTolerance)));
}
TEST_P(FaultInjectionTest, XdsFaultInjectionMaxFault) {
const uint32_t kMaxFault = 10;
const uint32_t kNumRpcs = 30; // kNumRpcs should be bigger than kMaxFault
const uint32_t kRpcTimeoutMs = 2000; // 2 seconds
const uint32_t kLongDelaySeconds = 100; // 100 seconds
const uint32_t kAlwaysDelayPercentage = 100;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Create an EDS resource
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Construct the fault injection filter config
HTTPFault http_fault;
auto* delay_percentage = http_fault.mutable_delay()->mutable_percentage();
delay_percentage->set_numerator(
kAlwaysDelayPercentage); // Always inject DELAY!
delay_percentage->set_denominator(FractionalPercent::HUNDRED);
auto* fixed_delay = http_fault.mutable_delay()->mutable_fixed_delay();
fixed_delay->set_seconds(kLongDelaySeconds);
http_fault.mutable_max_active_faults()->set_value(kMaxFault);
// Config fault injection via different setup
SetFilterConfig(http_fault);
// Sends a batch of long running RPCs with long timeout to consume all
// active faults quota.
int num_ok = 0, num_delayed = 0;
LongRunningRpc rpcs[kNumRpcs];
RpcOptions rpc_options = RpcOptions().set_timeout_ms(kRpcTimeoutMs);
for (size_t i = 0; i < kNumRpcs; ++i) {
rpcs[i].StartRpc(stub_.get(), rpc_options);
}
for (size_t i = 0; i < kNumRpcs; ++i) {
Status status = rpcs[i].GetStatus();
if (status.ok()) {
++num_ok;
} else {
EXPECT_EQ(StatusCode::DEADLINE_EXCEEDED, status.error_code());
++num_delayed;
}
}
// Only kMaxFault number of RPC should be fault injected..
EXPECT_EQ(kMaxFault, num_delayed);
// Other RPCs should be ok.
EXPECT_EQ(kNumRpcs - kMaxFault, num_ok);
}
class BootstrapContentsFromEnvVarTest : public XdsEnd2endTest {
public:
BootstrapContentsFromEnvVarTest() : XdsEnd2endTest(4, 1, 100, false, true) {}
};
TEST_P(BootstrapContentsFromEnvVarTest, Vanilla) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
WaitForAllBackends();
}
#ifndef DISABLED_XDS_PROTO_IN_CC
class ClientStatusDiscoveryServiceTest : public XdsEnd2endTest {
public:
ClientStatusDiscoveryServiceTest() : XdsEnd2endTest(1, 1) {}
void SetUp() override {
XdsEnd2endTest::SetUp();
admin_server_thread_ = absl::make_unique<AdminServerThread>();
admin_server_thread_->Start();
std::string admin_server_address = absl::StrCat(
ipv6_only_ ? "[::1]:" : "127.0.0.1:", admin_server_thread_->port());
admin_channel_ = grpc::CreateChannel(
admin_server_address,
std::make_shared<SecureChannelCredentials>(
grpc_fake_transport_security_credentials_create()));
csds_stub_ =
envoy::service::status::v3::ClientStatusDiscoveryService::NewStub(
admin_channel_);
if (GetParam().use_csds_streaming()) {
stream_ = csds_stub_->StreamClientStatus(&stream_context_);
}
}
void TearDown() override {
if (stream_ != nullptr) {
EXPECT_TRUE(stream_->WritesDone());
Status status = stream_->Finish();
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
}
admin_server_thread_->Shutdown();
XdsEnd2endTest::TearDown();
}
envoy::service::status::v3::ClientStatusResponse FetchCsdsResponse() {
envoy::service::status::v3::ClientStatusResponse response;
if (!GetParam().use_csds_streaming()) {
// Fetch through unary pulls
ClientContext context;
Status status = csds_stub_->FetchClientStatus(
&context, envoy::service::status::v3::ClientStatusRequest(),
&response);
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
} else {
// Fetch through streaming pulls
EXPECT_TRUE(
stream_->Write(envoy::service::status::v3::ClientStatusRequest()));
EXPECT_TRUE(stream_->Read(&response));
}
return response;
}
private:
std::unique_ptr<AdminServerThread> admin_server_thread_;
std::shared_ptr<Channel> admin_channel_;
std::unique_ptr<
envoy::service::status::v3::ClientStatusDiscoveryService::Stub>
csds_stub_;
ClientContext stream_context_;
std::unique_ptr<
ClientReaderWriter<envoy::service::status::v3::ClientStatusRequest,
envoy::service::status::v3::ClientStatusResponse>>
stream_;
};
MATCHER_P4(EqNode, id, user_agent_name, user_agent_version, client_features,
"equals Node") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(id, arg.id(), result_listener);
ok &= ::testing::ExplainMatchResult(user_agent_name, arg.user_agent_name(),
result_listener);
ok &= ::testing::ExplainMatchResult(
user_agent_version, arg.user_agent_version(), result_listener);
ok &= ::testing::ExplainMatchResult(client_features, arg.client_features(),
result_listener);
return ok;
}
MATCHER_P2(EqListenersConfigDump, version_info, dynamic_listeners,
"equals ListenerConfigDump") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(::testing::ElementsAre(),
arg.static_listeners(), result_listener);
ok &= ::testing::ExplainMatchResult(version_info, arg.version_info(),
result_listener);
ok &= ::testing::ExplainMatchResult(dynamic_listeners,
arg.dynamic_listeners(), result_listener);
return ok;
}
MATCHER_P2(EqDynamicListenerState, version_info, listener,
"equals DynamicListenerState") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(version_info, arg.version_info(),
result_listener);
ok &=
::testing::ExplainMatchResult(listener, arg.listener(), result_listener);
return ok;
}
MATCHER_P2(EqListener, name, api_listener, "equals Listener") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(name, arg.name(), result_listener);
ok &= ::testing::ExplainMatchResult(
api_listener, arg.api_listener().api_listener(), result_listener);
return ok;
}
MATCHER_P(EqHttpConnectionManagerNotRds, route_config,
"equals HttpConnectionManager") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(route_config, arg.route_config(),
result_listener);
return ok;
}
MATCHER_P(EqRouteConfigurationName, name, "equals RouteConfiguration") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(name, arg.name(), result_listener);
return ok;
}
MATCHER_P2(EqRouteConfiguration, name, cluster_name,
"equals RouteConfiguration") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(name, arg.name(), result_listener);
ok &= ::testing::ExplainMatchResult(
::testing::ElementsAre(::testing::Property(
&envoy::config::route::v3::VirtualHost::routes,
::testing::ElementsAre(::testing::Property(
&envoy::config::route::v3::Route::route,
::testing::Property(
&envoy::config::route::v3::RouteAction::cluster,
cluster_name))))),
arg.virtual_hosts(), result_listener);
return ok;
}
MATCHER_P(EqRoutesConfigDump, dynamic_route_configs,
"equals RoutesConfigDump") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(
::testing::ElementsAre(), arg.static_route_configs(), result_listener);
ok &= ::testing::ExplainMatchResult(
dynamic_route_configs, arg.dynamic_route_configs(), result_listener);
return ok;
}
MATCHER_P2(EqClustersConfigDump, version_info, dynamic_active_clusters,
"equals ClustersConfigDump") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(::testing::ElementsAre(),
arg.static_clusters(), result_listener);
ok &= ::testing::ExplainMatchResult(::testing::ElementsAre(),
arg.dynamic_warming_clusters(),
result_listener);
ok &= ::testing::ExplainMatchResult(version_info, arg.version_info(),
result_listener);
ok &= ::testing::ExplainMatchResult(
dynamic_active_clusters, arg.dynamic_active_clusters(), result_listener);
return ok;
}
MATCHER_P(EqCluster, name, "equals Cluster") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(name, arg.name(), result_listener);
return ok;
}
MATCHER_P(EqEndpointsConfigDump, dynamic_endpoint_configs,
"equals EndpointsConfigDump") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(dynamic_endpoint_configs,
arg.dynamic_endpoint_configs(),
result_listener);
return ok;
}
MATCHER_P(EqEndpoint, port, "equals Endpoint") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(
port, arg.address().socket_address().port_value(), result_listener);
return ok;
}
MATCHER_P2(EqLocalityLbEndpoints, port, weight, "equals LocalityLbEndpoints") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(
::testing::ElementsAre(::testing::Property(
&envoy::config::endpoint::v3::LbEndpoint::endpoint,
EqEndpoint(port))),
arg.lb_endpoints(), result_listener);
ok &= ::testing::ExplainMatchResult(
weight, arg.load_balancing_weight().value(), result_listener);
return ok;
}
MATCHER_P(EqClusterLoadAssignmentName, cluster_name,
"equals ClusterLoadAssignment") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(cluster_name, arg.cluster_name(),
result_listener);
return ok;
}
MATCHER_P3(EqClusterLoadAssignment, cluster_name, port, weight,
"equals ClusterLoadAssignment") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(cluster_name, arg.cluster_name(),
result_listener);
ok &= ::testing::ExplainMatchResult(
::testing::ElementsAre(EqLocalityLbEndpoints(port, weight)),
arg.endpoints(), result_listener);
return ok;
}
MATCHER_P2(EqUpdateFailureState, details, version_info,
"equals UpdateFailureState") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(details, arg.details(), result_listener);
ok &= ::testing::ExplainMatchResult(version_info, arg.version_info(),
result_listener);
return ok;
}
MATCHER_P(UnpackListener, matcher, "is a Listener") {
Listener config;
if (!::testing::ExplainMatchResult(true, arg.UnpackTo(&config),
result_listener)) {
return false;
}
return ::testing::ExplainMatchResult(matcher, config, result_listener);
}
MATCHER_P(UnpackRouteConfiguration, matcher, "is a RouteConfiguration") {
RouteConfiguration config;
if (!::testing::ExplainMatchResult(true, arg.UnpackTo(&config),
result_listener)) {
return false;
}
return ::testing::ExplainMatchResult(matcher, config, result_listener);
}
MATCHER_P(UnpackHttpConnectionManager, matcher, "is a HttpConnectionManager") {
HttpConnectionManager config;
if (!::testing::ExplainMatchResult(true, arg.UnpackTo(&config),
result_listener)) {
return false;
}
return ::testing::ExplainMatchResult(matcher, config, result_listener);
}
MATCHER_P(UnpackCluster, matcher, "is a Cluster") {
Cluster config;
if (!::testing::ExplainMatchResult(true, arg.UnpackTo(&config),
result_listener)) {
return false;
}
return ::testing::ExplainMatchResult(matcher, config, result_listener);
}
MATCHER_P(UnpackClusterLoadAssignment, matcher, "is a ClusterLoadAssignment") {
ClusterLoadAssignment config;
if (!::testing::ExplainMatchResult(true, arg.UnpackTo(&config),
result_listener)) {
return false;
}
return ::testing::ExplainMatchResult(matcher, config, result_listener);
}
MATCHER_P5(EqDynamicListener, name, version_info, client_status,
api_listener_matcher, error_state, "equals DynamicListener") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(false, arg.has_warming_state(),
result_listener);
ok &= ::testing::ExplainMatchResult(false, arg.has_draining_state(),
result_listener);
ok &= ::testing::ExplainMatchResult(name, arg.name(), result_listener);
ok &= ::testing::ExplainMatchResult(client_status, arg.client_status(),
result_listener);
if (client_status == ClientResourceStatus::ACKED ||
client_status == ClientResourceStatus::NACKED) {
ok &= ::testing::ExplainMatchResult(
EqDynamicListenerState(version_info, UnpackListener(EqListener(
name, api_listener_matcher))),
arg.active_state(), result_listener);
}
ok &= ::testing::ExplainMatchResult(error_state, arg.error_state(),
result_listener);
return ok;
}
MATCHER_P5(EqDynamicRouteConfig, name, version_info, client_status,
cluster_name, error_state, "equals DynamicRouteConfig") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(version_info, arg.version_info(),
result_listener);
if (client_status == ClientResourceStatus::REQUESTED ||
client_status == ClientResourceStatus::DOES_NOT_EXIST) {
ok &= ::testing::ExplainMatchResult(
UnpackRouteConfiguration(EqRouteConfigurationName(name)),
arg.route_config(), result_listener);
} else {
ok &= ::testing::ExplainMatchResult(
UnpackRouteConfiguration(EqRouteConfiguration(name, cluster_name)),
arg.route_config(), result_listener);
}
ok &= ::testing::ExplainMatchResult(error_state, arg.error_state(),
result_listener);
ok &= ::testing::ExplainMatchResult(client_status, arg.client_status(),
result_listener);
return ok;
}
MATCHER_P4(EqDynamicCluster, name, version_info, client_status, error_state,
"equals DynamicCluster") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(UnpackCluster(EqCluster(name)),
arg.cluster(), result_listener);
ok &= ::testing::ExplainMatchResult(version_info, arg.version_info(),
result_listener);
ok &= ::testing::ExplainMatchResult(client_status, arg.client_status(),
result_listener);
ok &= ::testing::ExplainMatchResult(error_state, arg.error_state(),
result_listener);
return ok;
}
MATCHER_P6(EqDynamicEndpointConfig, name, version_info, client_status, port,
weight, error_state, "equals DynamicEndpointConfig") {
bool ok = true;
if (client_status == ClientResourceStatus::REQUESTED ||
client_status == ClientResourceStatus::DOES_NOT_EXIST) {
ok &= ::testing::ExplainMatchResult(
UnpackClusterLoadAssignment(EqClusterLoadAssignmentName(name)),
arg.endpoint_config(), result_listener);
} else {
ok &= ::testing::ExplainMatchResult(
UnpackClusterLoadAssignment(
EqClusterLoadAssignment(name, port, weight)),
arg.endpoint_config(), result_listener);
}
ok &= ::testing::ExplainMatchResult(version_info, arg.version_info(),
result_listener);
ok &= ::testing::ExplainMatchResult(client_status, arg.client_status(),
result_listener);
ok &= ::testing::ExplainMatchResult(error_state, arg.error_state(),
result_listener);
return ok;
}
MATCHER(IsRdsEnabledHCM, "is a RDS enabled HttpConnectionManager") {
return ::testing::ExplainMatchResult(
UnpackHttpConnectionManager(
::testing::Property(&HttpConnectionManager::has_rds, true)),
arg, result_listener);
}
MATCHER_P2(EqNoRdsHCM, route_configuration_name, cluster_name,
"equals RDS disabled HttpConnectionManager") {
return ::testing::ExplainMatchResult(
UnpackHttpConnectionManager(EqHttpConnectionManagerNotRds(
EqRouteConfiguration(route_configuration_name, cluster_name))),
arg, result_listener);
}
TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpVanilla) {
const size_t kNumRpcs = 5;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {backends_[0]->port()}},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Send several RPCs to ensure the xDS setup works
CheckRpcSendOk(kNumRpcs);
// Fetches the client config
auto csds_response = FetchCsdsResponse();
gpr_log(GPR_INFO, "xDS config dump: %s", csds_response.DebugString().c_str());
EXPECT_EQ(1, csds_response.config_size());
const auto& client_config = csds_response.config(0);
// Validate the Node information
EXPECT_THAT(client_config.node(),
EqNode("xds_end2end_test", ::testing::HasSubstr("C-core"),
::testing::HasSubstr(grpc_version_string()),
::testing::ElementsAre(
"envoy.lb.does_not_support_overprovisioning")));
// Prepare matches for RDS on or off
::testing::Matcher<google::protobuf::Any> api_listener_matcher;
::testing::Matcher<envoy::admin::v3::RoutesConfigDump>
route_config_dump_matcher;
if (GetParam().enable_rds_testing()) {
api_listener_matcher = IsRdsEnabledHCM();
route_config_dump_matcher =
EqRoutesConfigDump(::testing::ElementsAre(EqDynamicRouteConfig(
kDefaultRouteConfigurationName, "1", ClientResourceStatus::ACKED,
kDefaultClusterName, ::testing::_)));
} else {
api_listener_matcher =
EqNoRdsHCM(kDefaultRouteConfigurationName, kDefaultClusterName);
route_config_dump_matcher = EqRoutesConfigDump(::testing::ElementsAre());
}
// Validate the dumped xDS configs
EXPECT_THAT(
client_config.xds_config(),
::testing::UnorderedElementsAre(
::testing::Property(
&envoy::service::status::v3::PerXdsConfig::listener_config,
EqListenersConfigDump(
"1", ::testing::ElementsAre(EqDynamicListener(
kServerName, "1", ClientResourceStatus::ACKED,
api_listener_matcher, ::testing::_)))),
::testing::Property(
&envoy::service::status::v3::PerXdsConfig::route_config,
route_config_dump_matcher),
::testing::Property(
&envoy::service::status::v3::PerXdsConfig::cluster_config,
EqClustersConfigDump(
"1", ::testing::ElementsAre(EqDynamicCluster(
kDefaultClusterName, "1",
ClientResourceStatus::ACKED, ::testing::_)))),
::testing::Property(
&envoy::service::status::v3::PerXdsConfig::endpoint_config,
EqEndpointsConfigDump(
::testing::ElementsAre(EqDynamicEndpointConfig(
kDefaultEdsServiceName, "1", ClientResourceStatus::ACKED,
backends_[0]->port(), kDefaultLocalityWeight,
::testing::_))))));
}
TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpEmpty) {
// The CSDS service should not fail if XdsClient is not initialized or there
// is no working xDS configs.
FetchCsdsResponse();
}
TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpListenerError) {
int kFetchConfigRetries = 3;
int kFetchIntervalMilliseconds = 200;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {backends_[0]->port()}},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Ensure the xDS resolver has working configs.
CheckRpcSendOk();
// Bad Listener should be rejected.
Listener listener;
listener.set_name(kServerName);
balancers_[0]->ads_service()->SetLdsResource(listener);
// The old xDS configs should still be effective.
CheckRpcSendOk();
::testing::Matcher<google::protobuf::Any> api_listener_matcher;
if (GetParam().enable_rds_testing()) {
api_listener_matcher = IsRdsEnabledHCM();
} else {
api_listener_matcher =
EqNoRdsHCM(kDefaultRouteConfigurationName, kDefaultClusterName);
}
for (int o = 0; o < kFetchConfigRetries; o++) {
auto csds_response = FetchCsdsResponse();
// Check if error state is propagated
bool ok = ::testing::Value(
csds_response.config(0).xds_config(),
::testing::Contains(::testing::Property(
&envoy::service::status::v3::PerXdsConfig::listener_config,
EqListenersConfigDump(
"1",
::testing::ElementsAre(EqDynamicListener(
kServerName, "1", ClientResourceStatus::NACKED,
api_listener_matcher,
EqUpdateFailureState(
::testing::HasSubstr(
"Listener has neither address nor ApiListener"),
"2")))))));
if (ok) return; // TEST PASSED!
gpr_sleep_until(
grpc_timeout_milliseconds_to_deadline(kFetchIntervalMilliseconds));
}
FAIL() << "error_state not seen in CSDS responses";
}
TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpRouteError) {
int kFetchConfigRetries = 3;
int kFetchIntervalMilliseconds = 200;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {backends_[0]->port()}},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Ensure the xDS resolver has working configs.
CheckRpcSendOk();
// Bad route config will be rejected.
RouteConfiguration route_config;
route_config.set_name(kDefaultRouteConfigurationName);
route_config.add_virtual_hosts();
SetRouteConfiguration(0, route_config);
// The old xDS configs should still be effective.
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendOk();
for (int o = 0; o < kFetchConfigRetries; o++) {
auto csds_response = FetchCsdsResponse();
bool ok = false;
if (GetParam().enable_rds_testing()) {
ok = ::testing::Value(
csds_response.config(0).xds_config(),
::testing::Contains(::testing::Property(
&envoy::service::status::v3::PerXdsConfig::route_config,
EqRoutesConfigDump(::testing::ElementsAre(EqDynamicRouteConfig(
kDefaultRouteConfigurationName, "1",
ClientResourceStatus::NACKED, kDefaultClusterName,
EqUpdateFailureState(
::testing::HasSubstr("VirtualHost has no domains"),
"2")))))));
} else {
ok = ::testing::Value(
csds_response.config(0).xds_config(),
::testing::Contains(::testing::Property(
&envoy::service::status::v3::PerXdsConfig::listener_config,
EqListenersConfigDump(
"1",
::testing::ElementsAre(EqDynamicListener(
kServerName, "1", ClientResourceStatus::NACKED,
EqNoRdsHCM(kDefaultRouteConfigurationName,
kDefaultClusterName),
EqUpdateFailureState(
::testing::HasSubstr("VirtualHost has no domains"),
"2")))))));
}
if (ok) return; // TEST PASSED!
gpr_sleep_until(
grpc_timeout_milliseconds_to_deadline(kFetchIntervalMilliseconds));
}
FAIL() << "error_state not seen in CSDS responses";
}
TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpClusterError) {
int kFetchConfigRetries = 3;
int kFetchIntervalMilliseconds = 200;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {backends_[0]->port()}},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Ensure the xDS resolver has working configs.
CheckRpcSendOk();
// Listener without any route, will be rejected.
Cluster cluster;
cluster.set_name(kDefaultClusterName);
balancers_[0]->ads_service()->SetCdsResource(cluster);
// The old xDS configs should still be effective.
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendOk();
for (int o = 0; o < kFetchConfigRetries; o++) {
auto csds_response = FetchCsdsResponse();
// Check if error state is propagated
bool ok = ::testing::Value(
csds_response.config(0).xds_config(),
::testing::Contains(::testing::Property(
&envoy::service::status::v3::PerXdsConfig::cluster_config,
EqClustersConfigDump(
"1", ::testing::ElementsAre(EqDynamicCluster(
kDefaultClusterName, "1", ClientResourceStatus::NACKED,
EqUpdateFailureState(
::testing::HasSubstr("DiscoveryType not found"),
"2")))))));
if (ok) return; // TEST PASSED!
gpr_sleep_until(
grpc_timeout_milliseconds_to_deadline(kFetchIntervalMilliseconds));
}
FAIL() << "error_state not seen in CSDS responses";
}
TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpEndpointError) {
int kFetchConfigRetries = 3;
int kFetchIntervalMilliseconds = 200;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {backends_[0]->port()}},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Ensure the xDS resolver has working configs.
CheckRpcSendOk();
// Bad endpoint config will be rejected.
ClusterLoadAssignment cluster_load_assignment;
cluster_load_assignment.set_cluster_name(kDefaultEdsServiceName);
auto* endpoints = cluster_load_assignment.add_endpoints();
endpoints->mutable_load_balancing_weight()->set_value(1);
auto* endpoint = endpoints->add_lb_endpoints()->mutable_endpoint();
endpoint->mutable_address()->mutable_socket_address()->set_port_value(1 << 1);
balancers_[0]->ads_service()->SetEdsResource(cluster_load_assignment);
// The old xDS configs should still be effective.
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendOk();
for (int o = 0; o < kFetchConfigRetries; o++) {
auto csds_response = FetchCsdsResponse();
// Check if error state is propagated
bool ok = ::testing::Value(
csds_response.config(0).xds_config(),
::testing::Contains(::testing::Property(
&envoy::service::status::v3::PerXdsConfig::endpoint_config,
EqEndpointsConfigDump(
::testing::ElementsAre(EqDynamicEndpointConfig(
kDefaultEdsServiceName, "1", ClientResourceStatus::NACKED,
backends_[0]->port(), kDefaultLocalityWeight,
EqUpdateFailureState(::testing::HasSubstr("Empty locality"),
"2")))))));
if (ok) return; // TEST PASSED!
gpr_sleep_until(
grpc_timeout_milliseconds_to_deadline(kFetchIntervalMilliseconds));
}
FAIL() << "error_state not seen in CSDS responses";
}
TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpListenerRequested) {
int kTimeoutMillisecond = 1000;
balancers_[0]->ads_service()->UnsetResource(kLdsTypeUrl, kServerName);
CheckRpcSendFailure(1, RpcOptions().set_timeout_ms(kTimeoutMillisecond),
grpc::DEADLINE_EXCEEDED);
auto csds_response = FetchCsdsResponse();
EXPECT_THAT(csds_response.config(0).xds_config(),
::testing::Contains(::testing::Property(
&envoy::service::status::v3::PerXdsConfig::listener_config,
EqListenersConfigDump(
::testing::_, ::testing::ElementsAre(EqDynamicListener(
kServerName, ::testing::_,
ClientResourceStatus::REQUESTED,
::testing::_, ::testing::_))))));
}
TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpClusterRequested) {
int kTimeoutMillisecond = 1000;
std::string kClusterName1 = "cluster-1";
std::string kClusterName2 = "cluster-2";
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Create a route config requesting two non-existing clusters
RouteConfiguration route_config;
route_config.set_name(kDefaultRouteConfigurationName);
auto* vh = route_config.add_virtual_hosts();
// The VirtualHost must match the domain name, otherwise will cause resolver
// transient failure.
vh->add_domains("*");
auto* routes1 = vh->add_routes();
routes1->mutable_match()->set_prefix("");
routes1->mutable_route()->set_cluster(kClusterName1);
auto* routes2 = vh->add_routes();
routes2->mutable_match()->set_prefix("");
routes2->mutable_route()->set_cluster(kClusterName2);
SetRouteConfiguration(0, route_config);
// Try to get the configs plumb through
CheckRpcSendFailure(1, RpcOptions().set_timeout_ms(kTimeoutMillisecond),
grpc::DEADLINE_EXCEEDED);
auto csds_response = FetchCsdsResponse();
EXPECT_THAT(csds_response.config(0).xds_config(),
::testing::Contains(::testing::Property(
&envoy::service::status::v3::PerXdsConfig::cluster_config,
EqClustersConfigDump(
::testing::_,
::testing::UnorderedElementsAre(
EqDynamicCluster(kClusterName1, ::testing::_,
ClientResourceStatus::REQUESTED,
::testing::_),
EqDynamicCluster(kClusterName2, ::testing::_,
ClientResourceStatus::REQUESTED,
::testing::_))))));
}
class CsdsShortAdsTimeoutTest : public ClientStatusDiscoveryServiceTest {
void SetUp() override {
// Shorten the ADS subscription timeout to speed up the test run.
xds_resource_does_not_exist_timeout_ms_ = 500;
ClientStatusDiscoveryServiceTest::SetUp();
}
};
TEST_P(CsdsShortAdsTimeoutTest, XdsConfigDumpListenerDoesNotExist) {
int kTimeoutMillisecond = 1000000; // 1000s wait for the transient failure.
balancers_[0]->ads_service()->UnsetResource(kLdsTypeUrl, kServerName);
CheckRpcSendFailure(1, RpcOptions().set_timeout_ms(kTimeoutMillisecond),
grpc::UNAVAILABLE);
auto csds_response = FetchCsdsResponse();
EXPECT_THAT(csds_response.config(0).xds_config(),
::testing::Contains(::testing::Property(
&envoy::service::status::v3::PerXdsConfig::listener_config,
EqListenersConfigDump(
::testing::_, ::testing::ElementsAre(EqDynamicListener(
kServerName, ::testing::_,
ClientResourceStatus::DOES_NOT_EXIST,
::testing::_, ::testing::_))))));
}
TEST_P(CsdsShortAdsTimeoutTest, XdsConfigDumpRouteConfigDoesNotExist) {
if (!GetParam().enable_rds_testing()) return;
int kTimeoutMillisecond = 1000000; // 1000s wait for the transient failure.
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
balancers_[0]->ads_service()->UnsetResource(kRdsTypeUrl,
kDefaultRouteConfigurationName);
CheckRpcSendFailure(1, RpcOptions().set_timeout_ms(kTimeoutMillisecond),
grpc::UNAVAILABLE);
auto csds_response = FetchCsdsResponse();
EXPECT_THAT(
csds_response.config(0).xds_config(),
::testing::Contains(::testing::Property(
&envoy::service::status::v3::PerXdsConfig::route_config,
EqRoutesConfigDump(::testing::ElementsAre(
EqDynamicRouteConfig(kDefaultRouteConfigurationName, ::testing::_,
ClientResourceStatus::DOES_NOT_EXIST,
::testing::_, ::testing::_))))));
}
TEST_P(CsdsShortAdsTimeoutTest, XdsConfigDumpClusterDoesNotExist) {
int kTimeoutMillisecond = 1000000; // 1000s wait for the transient failure.
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
balancers_[0]->ads_service()->UnsetResource(kCdsTypeUrl, kDefaultClusterName);
CheckRpcSendFailure(1, RpcOptions().set_timeout_ms(kTimeoutMillisecond),
grpc::UNAVAILABLE);
auto csds_response = FetchCsdsResponse();
EXPECT_THAT(csds_response.config(0).xds_config(),
::testing::Contains(::testing::Property(
&envoy::service::status::v3::PerXdsConfig::cluster_config,
EqClustersConfigDump(::testing::_,
::testing::ElementsAre(EqDynamicCluster(
kDefaultClusterName, ::testing::_,
ClientResourceStatus::DOES_NOT_EXIST,
::testing::_))))));
}
TEST_P(CsdsShortAdsTimeoutTest, XdsConfigDumpEndpointDoesNotExist) {
int kTimeoutMillisecond = 1000000; // 1000s wait for the transient failure.
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
balancers_[0]->ads_service()->UnsetResource(kEdsTypeUrl,
kDefaultEdsServiceName);
CheckRpcSendFailure(1, RpcOptions().set_timeout_ms(kTimeoutMillisecond),
grpc::UNAVAILABLE);
auto csds_response = FetchCsdsResponse();
EXPECT_THAT(
csds_response.config(0).xds_config(),
::testing::Contains(::testing::Property(
&envoy::service::status::v3::PerXdsConfig::endpoint_config,
EqEndpointsConfigDump(::testing::ElementsAre(EqDynamicEndpointConfig(
kDefaultEdsServiceName, ::testing::_,
ClientResourceStatus::DOES_NOT_EXIST, ::testing::_, ::testing::_,
::testing::_))))));
}
#endif // DISABLED_XDS_PROTO_IN_CC
std::string TestTypeName(const ::testing::TestParamInfo<TestType>& info) {
return info.param.AsString();
}
// Run with all combinations of xds/fake resolver and enabling load reporting.
INSTANTIATE_TEST_SUITE_P(
XdsTest, BasicTest,
::testing::Values(
TestType(), TestType().set_enable_load_reporting(),
TestType().set_use_fake_resolver(),
TestType().set_use_fake_resolver().set_enable_load_reporting()),
&TestTypeName);
// Run with both fake resolver and xds resolver.
// Don't run with load reporting or v2 or RDS, since they are irrelevant to
// the tests.
INSTANTIATE_TEST_SUITE_P(XdsTest, SecureNamingTest,
::testing::Values(TestType(),
TestType().set_use_fake_resolver()),
&TestTypeName);
// LDS depends on XdsResolver.
INSTANTIATE_TEST_SUITE_P(XdsTest, LdsTest, ::testing::Values(TestType()),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(XdsTest, LdsV2Test,
::testing::Values(TestType().set_use_v2()),
&TestTypeName);
// LDS/RDS commmon tests depend on XdsResolver.
INSTANTIATE_TEST_SUITE_P(
XdsTest, LdsRdsTest,
::testing::Values(TestType(), TestType().set_enable_rds_testing(),
// Also test with xDS v2.
TestType().set_enable_rds_testing().set_use_v2()),
&TestTypeName);
// CDS depends on XdsResolver.
INSTANTIATE_TEST_SUITE_P(
XdsTest, CdsTest,
::testing::Values(TestType(), TestType().set_enable_load_reporting()),
&TestTypeName);
// CDS depends on XdsResolver.
// Security depends on v3.
// Not enabling load reporting or RDS, since those are irrelevant to these
// tests.
INSTANTIATE_TEST_SUITE_P(
XdsTest, XdsSecurityTest,
::testing::Values(TestType().set_use_xds_credentials()), &TestTypeName);
// We are only testing the server here.
INSTANTIATE_TEST_SUITE_P(XdsTest, XdsEnabledServerTest,
::testing::Values(TestType()), &TestTypeName);
// We are only testing the server here.
INSTANTIATE_TEST_SUITE_P(XdsTest, XdsServerSecurityTest,
::testing::Values(TestType()
.set_use_fake_resolver()
.set_use_xds_credentials()),
&TestTypeName);
// We are only testing the server here.
INSTANTIATE_TEST_SUITE_P(XdsTest, XdsEnabledServerStatusNotificationTest,
::testing::Values(TestType()
.set_use_fake_resolver()
.set_use_xds_credentials()),
&TestTypeName);
// We are only testing the server here.
INSTANTIATE_TEST_SUITE_P(XdsTest, XdsServerFilterChainMatchTest,
::testing::Values(TestType()
.set_use_fake_resolver()
.set_use_xds_credentials()),
&TestTypeName);
// EDS could be tested with or without XdsResolver, but the tests would
// be the same either way, so we test it only with XdsResolver.
INSTANTIATE_TEST_SUITE_P(
XdsTest, EdsTest,
::testing::Values(TestType(), TestType().set_enable_load_reporting()),
&TestTypeName);
// Test initial resource timeouts for each resource type.
// Do this only for XdsResolver with RDS enabled, so that we can test
// all resource types.
// Run with V3 only, since the functionality is no different in V2.
INSTANTIATE_TEST_SUITE_P(XdsTest, TimeoutTest,
::testing::Values(TestType().set_enable_rds_testing()),
&TestTypeName);
// XdsResolverOnlyTest depends on XdsResolver.
INSTANTIATE_TEST_SUITE_P(
XdsTest, XdsResolverOnlyTest,
::testing::Values(TestType(), TestType().set_enable_load_reporting()),
&TestTypeName);
// XdsResolverLoadReprtingOnlyTest depends on XdsResolver and load reporting.
INSTANTIATE_TEST_SUITE_P(
XdsTest, XdsResolverLoadReportingOnlyTest,
::testing::Values(TestType().set_enable_load_reporting()), &TestTypeName);
INSTANTIATE_TEST_SUITE_P(
XdsTest, LocalityMapTest,
::testing::Values(
TestType(), TestType().set_enable_load_reporting(),
TestType().set_use_fake_resolver(),
TestType().set_use_fake_resolver().set_enable_load_reporting()),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(
XdsTest, FailoverTest,
::testing::Values(
TestType(), TestType().set_enable_load_reporting(),
TestType().set_use_fake_resolver(),
TestType().set_use_fake_resolver().set_enable_load_reporting()),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(
XdsTest, DropTest,
::testing::Values(
TestType(), TestType().set_enable_load_reporting(),
TestType().set_use_fake_resolver(),
TestType().set_use_fake_resolver().set_enable_load_reporting()),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(
XdsTest, BalancerUpdateTest,
::testing::Values(
TestType().set_use_fake_resolver(),
TestType().set_use_fake_resolver().set_enable_load_reporting(),
TestType().set_enable_load_reporting()),
&TestTypeName);
// Load reporting tests are not run with load reporting disabled.
INSTANTIATE_TEST_SUITE_P(
XdsTest, ClientLoadReportingTest,
::testing::Values(
TestType().set_enable_load_reporting(),
TestType().set_enable_load_reporting().set_use_fake_resolver()),
&TestTypeName);
// Load reporting tests are not run with load reporting disabled.
INSTANTIATE_TEST_SUITE_P(
XdsTest, ClientLoadReportingWithDropTest,
::testing::Values(
TestType().set_enable_load_reporting(),
TestType().set_enable_load_reporting().set_use_fake_resolver()),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(
XdsTest, FaultInjectionTest,
::testing::Values(
TestType(), TestType().set_enable_rds_testing(),
TestType().set_filter_config_setup(
TestType::FilterConfigSetup::kRouteOverride),
TestType().set_enable_rds_testing().set_filter_config_setup(
TestType::FilterConfigSetup::kRouteOverride)),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(XdsTest, BootstrapContentsFromEnvVarTest,
::testing::Values(TestType()), &TestTypeName);
#ifndef DISABLED_XDS_PROTO_IN_CC
// Run CSDS tests with RDS enabled and disabled.
INSTANTIATE_TEST_SUITE_P(
XdsTest, ClientStatusDiscoveryServiceTest,
::testing::Values(
TestType(), TestType().set_enable_rds_testing(),
TestType().set_use_csds_streaming(),
TestType().set_enable_rds_testing().set_use_csds_streaming()),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(
XdsTest, CsdsShortAdsTimeoutTest,
::testing::Values(
TestType(), TestType().set_enable_rds_testing(),
TestType().set_use_csds_streaming(),
TestType().set_enable_rds_testing().set_use_csds_streaming()),
&TestTypeName);
#endif // DISABLED_XDS_PROTO_IN_CC
} // namespace
} // namespace testing
} // namespace grpc
int main(int argc, char** argv) {
grpc::testing::TestEnvironment env(argc, argv);
::testing::InitGoogleTest(&argc, argv);
grpc::testing::WriteBootstrapFiles();
// Make the backup poller poll very frequently in order to pick up
// updates from all the subchannels's FDs.
GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms, 1);
#if TARGET_OS_IPHONE
// Workaround Apple CFStream bug
gpr_setenv("grpc_cfstream", "0");
#endif
grpc_core::CertificateProviderRegistry::RegisterCertificateProviderFactory(
absl::make_unique<grpc::testing::FakeCertificateProviderFactory>(
"fake1", &grpc::testing::g_fake1_cert_data_map));
grpc_core::CertificateProviderRegistry::RegisterCertificateProviderFactory(
absl::make_unique<grpc::testing::FakeCertificateProviderFactory>(
"fake2", &grpc::testing::g_fake2_cert_data_map));
grpc_init();
grpc_core::XdsHttpFilterRegistry::RegisterFilter(
absl::make_unique<grpc::testing::NoOpHttpFilter>(
"grpc.testing.client_only_http_filter", true, false),
{"grpc.testing.client_only_http_filter"});
grpc_core::XdsHttpFilterRegistry::RegisterFilter(
absl::make_unique<grpc::testing::NoOpHttpFilter>(
"grpc.testing.server_only_http_filter", false, true),
{"grpc.testing.server_only_http_filter"});
const auto result = RUN_ALL_TESTS();
grpc_shutdown();
return result;
}
Increase the retry count for XdsServerSecurityTest (#25830)
/*
*
* Copyright 2017 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <deque>
#include <memory>
#include <mutex>
#include <numeric>
#include <set>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/functional/bind_front.h"
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/types/optional.h"
#include <grpc/grpc.h>
#include <grpc/grpc_security.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/time.h>
#include <grpcpp/channel.h>
#include <grpcpp/client_context.h>
#include <grpcpp/create_channel.h>
#include <grpcpp/security/tls_certificate_provider.h>
#include <grpcpp/server.h>
#include <grpcpp/server_builder.h>
#include <grpcpp/xds_server_builder.h>
#include "src/core/ext/filters/client_channel/backup_poller.h"
#include "src/core/ext/filters/client_channel/lb_policy/xds/xds_channel_args.h"
#include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
#include "src/core/ext/filters/client_channel/server_address.h"
#include "src/core/ext/xds/certificate_provider_registry.h"
#include "src/core/ext/xds/xds_api.h"
#include "src/core/ext/xds/xds_channel_args.h"
#include "src/core/ext/xds/xds_client.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/gpr/env.h"
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gpr/time_precise.h"
#include "src/core/lib/gpr/tmpfile.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/gprpp/time_util.h"
#include "src/core/lib/iomgr/load_file.h"
#include "src/core/lib/iomgr/parse_address.h"
#include "src/core/lib/iomgr/sockaddr.h"
#include "src/core/lib/security/credentials/fake/fake_credentials.h"
#include "src/cpp/client/secure_credentials.h"
#include "src/cpp/server/secure_server_credentials.h"
#include "src/proto/grpc/testing/echo.grpc.pb.h"
#include "src/proto/grpc/testing/xds/ads_for_test.grpc.pb.h"
#include "src/proto/grpc/testing/xds/cds_for_test.grpc.pb.h"
#include "src/proto/grpc/testing/xds/eds_for_test.grpc.pb.h"
#include "src/proto/grpc/testing/xds/lds_rds_for_test.grpc.pb.h"
#include "src/proto/grpc/testing/xds/lrs_for_test.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/ads.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/aggregate_cluster.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/cluster.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/discovery.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/endpoint.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/fault.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/http_connection_manager.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/listener.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/lrs.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/route.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/router.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/tls.grpc.pb.h"
#include "test/core/util/port.h"
#include "test/core/util/resolve_localhost_ip46.h"
#include "test/core/util/test_config.h"
#include "test/cpp/end2end/test_service_impl.h"
#ifndef DISABLED_XDS_PROTO_IN_CC
#include "src/cpp/server/csds/csds.h"
#include "src/proto/grpc/testing/xds/v3/csds.grpc.pb.h"
#endif // DISABLED_XDS_PROTO_IN_CC
namespace grpc {
namespace testing {
namespace {
using std::chrono::system_clock;
#ifndef DISABLED_XDS_PROTO_IN_CC
using ::envoy::admin::v3::ClientResourceStatus;
#endif // DISABLED_XDS_PROTO_IN_CC
using ::envoy::config::cluster::v3::CircuitBreakers;
using ::envoy::config::cluster::v3::Cluster;
using ::envoy::config::cluster::v3::CustomClusterType;
using ::envoy::config::cluster::v3::RoutingPriority;
using ::envoy::config::endpoint::v3::ClusterLoadAssignment;
using ::envoy::config::endpoint::v3::HealthStatus;
using ::envoy::config::listener::v3::FilterChainMatch;
using ::envoy::config::listener::v3::Listener;
using ::envoy::config::route::v3::RouteConfiguration;
using ::envoy::extensions::clusters::aggregate::v3::ClusterConfig;
using ::envoy::extensions::filters::http::fault::v3::HTTPFault;
using ::envoy::extensions::filters::network::http_connection_manager::v3::
HttpConnectionManager;
using ::envoy::extensions::filters::network::http_connection_manager::v3::
HttpFilter;
using ::envoy::extensions::transport_sockets::tls::v3::DownstreamTlsContext;
using ::envoy::extensions::transport_sockets::tls::v3::UpstreamTlsContext;
using ::envoy::type::matcher::v3::StringMatcher;
using ::envoy::type::v3::FractionalPercent;
constexpr char kLdsTypeUrl[] =
"type.googleapis.com/envoy.config.listener.v3.Listener";
constexpr char kRdsTypeUrl[] =
"type.googleapis.com/envoy.config.route.v3.RouteConfiguration";
constexpr char kCdsTypeUrl[] =
"type.googleapis.com/envoy.config.cluster.v3.Cluster";
constexpr char kEdsTypeUrl[] =
"type.googleapis.com/envoy.config.endpoint.v3.ClusterLoadAssignment";
constexpr char kLdsV2TypeUrl[] = "type.googleapis.com/envoy.api.v2.Listener";
constexpr char kRdsV2TypeUrl[] =
"type.googleapis.com/envoy.api.v2.RouteConfiguration";
constexpr char kCdsV2TypeUrl[] = "type.googleapis.com/envoy.api.v2.Cluster";
constexpr char kEdsV2TypeUrl[] =
"type.googleapis.com/envoy.api.v2.ClusterLoadAssignment";
constexpr char kDefaultLocalityRegion[] = "xds_default_locality_region";
constexpr char kDefaultLocalityZone[] = "xds_default_locality_zone";
constexpr char kLbDropType[] = "lb";
constexpr char kThrottleDropType[] = "throttle";
constexpr char kServerName[] = "server.example.com";
constexpr char kDefaultRouteConfigurationName[] = "route_config_name";
constexpr char kDefaultClusterName[] = "cluster_name";
constexpr char kDefaultEdsServiceName[] = "eds_service_name";
constexpr int kDefaultLocalityWeight = 3;
constexpr int kDefaultLocalityPriority = 0;
constexpr char kRequestMessage[] = "Live long and prosper.";
constexpr char kDefaultServiceConfig[] =
"{\n"
" \"loadBalancingConfig\":[\n"
" { \"does_not_exist\":{} },\n"
" { \"xds_cluster_resolver_experimental\":{\n"
" \"discoveryMechanisms\": [\n"
" { \"clusterName\": \"server.example.com\",\n"
" \"type\": \"EDS\",\n"
" \"lrsLoadReportingServerName\": \"\"\n"
" } ]\n"
" } }\n"
" ]\n"
"}";
constexpr char kDefaultServiceConfigWithoutLoadReporting[] =
"{\n"
" \"loadBalancingConfig\":[\n"
" { \"does_not_exist\":{} },\n"
" { \"xds_cluster_resolver_experimental\":{\n"
" \"discoveryMechanisms\": [\n"
" { \"clusterName\": \"server.example.com\",\n"
" \"type\": \"EDS\"\n"
" } ]\n"
" } }\n"
" ]\n"
"}";
constexpr char kBootstrapFileV3[] =
"{\n"
" \"xds_servers\": [\n"
" {\n"
" \"server_uri\": \"fake:///xds_server\",\n"
" \"channel_creds\": [\n"
" {\n"
" \"type\": \"fake\"\n"
" }\n"
" ],\n"
" \"server_features\": [\"xds_v3\"]\n"
" }\n"
" ],\n"
" \"node\": {\n"
" \"id\": \"xds_end2end_test\",\n"
" \"cluster\": \"test\",\n"
" \"metadata\": {\n"
" \"foo\": \"bar\"\n"
" },\n"
" \"locality\": {\n"
" \"region\": \"corp\",\n"
" \"zone\": \"svl\",\n"
" \"sub_zone\": \"mp3\"\n"
" }\n"
" },\n"
" \"server_listener_resource_name_template\": "
"\"grpc/server?xds.resource.listening_address=%s\",\n"
" \"certificate_providers\": {\n"
" \"fake_plugin1\": {\n"
" \"plugin_name\": \"fake1\"\n"
" },\n"
" \"fake_plugin2\": {\n"
" \"plugin_name\": \"fake2\"\n"
" },\n"
" \"file_plugin\": {\n"
" \"plugin_name\": \"file_watcher\",\n"
" \"config\": {\n"
" \"certificate_file\": \"src/core/tsi/test_creds/client.pem\",\n"
" \"private_key_file\": \"src/core/tsi/test_creds/client.key\",\n"
" \"ca_certificate_file\": \"src/core/tsi/test_creds/ca.pem\"\n"
" }"
" }\n"
" }\n"
"}\n";
constexpr char kBootstrapFileV2[] =
"{\n"
" \"xds_servers\": [\n"
" {\n"
" \"server_uri\": \"fake:///xds_server\",\n"
" \"channel_creds\": [\n"
" {\n"
" \"type\": \"fake\"\n"
" }\n"
" ]\n"
" }\n"
" ],\n"
" \"node\": {\n"
" \"id\": \"xds_end2end_test\",\n"
" \"cluster\": \"test\",\n"
" \"metadata\": {\n"
" \"foo\": \"bar\"\n"
" },\n"
" \"locality\": {\n"
" \"region\": \"corp\",\n"
" \"zone\": \"svl\",\n"
" \"sub_zone\": \"mp3\"\n"
" }\n"
" }\n"
"}\n";
constexpr char kCaCertPath[] = "src/core/tsi/test_creds/ca.pem";
constexpr char kServerCertPath[] = "src/core/tsi/test_creds/server1.pem";
constexpr char kServerKeyPath[] = "src/core/tsi/test_creds/server1.key";
constexpr char kClientCertPath[] = "src/core/tsi/test_creds/client.pem";
constexpr char kClientKeyPath[] = "src/core/tsi/test_creds/client.key";
constexpr char kBadClientCertPath[] = "src/core/tsi/test_creds/badclient.pem";
constexpr char kBadClientKeyPath[] = "src/core/tsi/test_creds/badclient.key";
char* g_bootstrap_file_v3;
char* g_bootstrap_file_v2;
void WriteBootstrapFiles() {
char* bootstrap_file;
FILE* out = gpr_tmpfile("xds_bootstrap_v3", &bootstrap_file);
fputs(kBootstrapFileV3, out);
fclose(out);
g_bootstrap_file_v3 = bootstrap_file;
out = gpr_tmpfile("xds_bootstrap_v2", &bootstrap_file);
fputs(kBootstrapFileV2, out);
fclose(out);
g_bootstrap_file_v2 = bootstrap_file;
}
template <typename ServiceType>
class CountedService : public ServiceType {
public:
size_t request_count() {
grpc_core::MutexLock lock(&mu_);
return request_count_;
}
size_t response_count() {
grpc_core::MutexLock lock(&mu_);
return response_count_;
}
void IncreaseResponseCount() {
grpc_core::MutexLock lock(&mu_);
++response_count_;
}
void IncreaseRequestCount() {
grpc_core::MutexLock lock(&mu_);
++request_count_;
}
void ResetCounters() {
grpc_core::MutexLock lock(&mu_);
request_count_ = 0;
response_count_ = 0;
}
private:
grpc_core::Mutex mu_;
size_t request_count_ = 0;
size_t response_count_ = 0;
};
template <typename RpcService>
class BackendServiceImpl
: public CountedService<TestMultipleServiceImpl<RpcService>> {
public:
BackendServiceImpl() {}
Status Echo(ServerContext* context, const EchoRequest* request,
EchoResponse* response) override {
auto peer_identity = context->auth_context()->GetPeerIdentity();
CountedService<TestMultipleServiceImpl<RpcService>>::IncreaseRequestCount();
const auto status =
TestMultipleServiceImpl<RpcService>::Echo(context, request, response);
CountedService<
TestMultipleServiceImpl<RpcService>>::IncreaseResponseCount();
{
grpc_core::MutexLock lock(&mu_);
clients_.insert(context->peer());
last_peer_identity_.clear();
for (const auto& entry : peer_identity) {
last_peer_identity_.emplace_back(entry.data(), entry.size());
}
}
return status;
}
Status Echo1(ServerContext* context, const EchoRequest* request,
EchoResponse* response) override {
return Echo(context, request, response);
}
Status Echo2(ServerContext* context, const EchoRequest* request,
EchoResponse* response) override {
return Echo(context, request, response);
}
void Start() {}
void Shutdown() {}
std::set<std::string> clients() {
grpc_core::MutexLock lock(&mu_);
return clients_;
}
const std::vector<std::string>& last_peer_identity() {
grpc_core::MutexLock lock(&mu_);
return last_peer_identity_;
}
private:
grpc_core::Mutex mu_;
std::set<std::string> clients_;
std::vector<std::string> last_peer_identity_;
};
class ClientStats {
public:
struct LocalityStats {
LocalityStats() {}
// Converts from proto message class.
template <class UpstreamLocalityStats>
explicit LocalityStats(const UpstreamLocalityStats& upstream_locality_stats)
: total_successful_requests(
upstream_locality_stats.total_successful_requests()),
total_requests_in_progress(
upstream_locality_stats.total_requests_in_progress()),
total_error_requests(upstream_locality_stats.total_error_requests()),
total_issued_requests(
upstream_locality_stats.total_issued_requests()) {}
LocalityStats& operator+=(const LocalityStats& other) {
total_successful_requests += other.total_successful_requests;
total_requests_in_progress += other.total_requests_in_progress;
total_error_requests += other.total_error_requests;
total_issued_requests += other.total_issued_requests;
return *this;
}
uint64_t total_successful_requests = 0;
uint64_t total_requests_in_progress = 0;
uint64_t total_error_requests = 0;
uint64_t total_issued_requests = 0;
};
ClientStats() {}
// Converts from proto message class.
template <class ClusterStats>
explicit ClientStats(const ClusterStats& cluster_stats)
: cluster_name_(cluster_stats.cluster_name()),
total_dropped_requests_(cluster_stats.total_dropped_requests()) {
for (const auto& input_locality_stats :
cluster_stats.upstream_locality_stats()) {
locality_stats_.emplace(input_locality_stats.locality().sub_zone(),
LocalityStats(input_locality_stats));
}
for (const auto& input_dropped_requests :
cluster_stats.dropped_requests()) {
dropped_requests_.emplace(input_dropped_requests.category(),
input_dropped_requests.dropped_count());
}
}
const std::string& cluster_name() const { return cluster_name_; }
const std::map<std::string, LocalityStats>& locality_stats() const {
return locality_stats_;
}
uint64_t total_successful_requests() const {
uint64_t sum = 0;
for (auto& p : locality_stats_) {
sum += p.second.total_successful_requests;
}
return sum;
}
uint64_t total_requests_in_progress() const {
uint64_t sum = 0;
for (auto& p : locality_stats_) {
sum += p.second.total_requests_in_progress;
}
return sum;
}
uint64_t total_error_requests() const {
uint64_t sum = 0;
for (auto& p : locality_stats_) {
sum += p.second.total_error_requests;
}
return sum;
}
uint64_t total_issued_requests() const {
uint64_t sum = 0;
for (auto& p : locality_stats_) {
sum += p.second.total_issued_requests;
}
return sum;
}
uint64_t total_dropped_requests() const { return total_dropped_requests_; }
uint64_t dropped_requests(const std::string& category) const {
auto iter = dropped_requests_.find(category);
GPR_ASSERT(iter != dropped_requests_.end());
return iter->second;
}
ClientStats& operator+=(const ClientStats& other) {
for (const auto& p : other.locality_stats_) {
locality_stats_[p.first] += p.second;
}
total_dropped_requests_ += other.total_dropped_requests_;
for (const auto& p : other.dropped_requests_) {
dropped_requests_[p.first] += p.second;
}
return *this;
}
private:
std::string cluster_name_;
std::map<std::string, LocalityStats> locality_stats_;
uint64_t total_dropped_requests_ = 0;
std::map<std::string, uint64_t> dropped_requests_;
};
class AdsServiceImpl : public std::enable_shared_from_this<AdsServiceImpl> {
public:
struct ResponseState {
enum State { NOT_SENT, SENT, ACKED, NACKED };
State state = NOT_SENT;
std::string error_message;
};
struct EdsResourceArgs {
struct Locality {
Locality(std::string sub_zone, std::vector<int> ports,
int lb_weight = kDefaultLocalityWeight,
int priority = kDefaultLocalityPriority,
std::vector<HealthStatus> health_statuses = {})
: sub_zone(std::move(sub_zone)),
ports(std::move(ports)),
lb_weight(lb_weight),
priority(priority),
health_statuses(std::move(health_statuses)) {}
const std::string sub_zone;
std::vector<int> ports;
int lb_weight;
int priority;
std::vector<HealthStatus> health_statuses;
};
EdsResourceArgs() = default;
explicit EdsResourceArgs(std::vector<Locality> locality_list)
: locality_list(std::move(locality_list)) {}
std::vector<Locality> locality_list;
std::map<std::string, uint32_t> drop_categories;
FractionalPercent::DenominatorType drop_denominator =
FractionalPercent::MILLION;
};
AdsServiceImpl()
: v2_rpc_service_(this, /*is_v2=*/true),
v3_rpc_service_(this, /*is_v2=*/false) {}
bool seen_v2_client() const { return seen_v2_client_; }
bool seen_v3_client() const { return seen_v3_client_; }
::envoy::service::discovery::v2::AggregatedDiscoveryService::Service*
v2_rpc_service() {
return &v2_rpc_service_;
}
::envoy::service::discovery::v3::AggregatedDiscoveryService::Service*
v3_rpc_service() {
return &v3_rpc_service_;
}
ResponseState lds_response_state() {
grpc_core::MutexLock lock(&ads_mu_);
return resource_type_response_state_[kLdsTypeUrl];
}
ResponseState rds_response_state() {
grpc_core::MutexLock lock(&ads_mu_);
return resource_type_response_state_[kRdsTypeUrl];
}
ResponseState cds_response_state() {
grpc_core::MutexLock lock(&ads_mu_);
return resource_type_response_state_[kCdsTypeUrl];
}
ResponseState eds_response_state() {
grpc_core::MutexLock lock(&ads_mu_);
return resource_type_response_state_[kEdsTypeUrl];
}
void SetResourceIgnore(const std::string& type_url) {
grpc_core::MutexLock lock(&ads_mu_);
resource_types_to_ignore_.emplace(type_url);
}
void SetResourceMinVersion(const std::string& type_url, int version) {
grpc_core::MutexLock lock(&ads_mu_);
resource_type_min_versions_[type_url] = version;
}
void UnsetResource(const std::string& type_url, const std::string& name) {
grpc_core::MutexLock lock(&ads_mu_);
ResourceTypeState& resource_type_state = resource_map_[type_url];
++resource_type_state.resource_type_version;
ResourceState& resource_state = resource_type_state.resource_name_map[name];
resource_state.resource_type_version =
resource_type_state.resource_type_version;
resource_state.resource.reset();
gpr_log(GPR_INFO,
"ADS[%p]: Unsetting %s resource %s; resource_type_version now %u",
this, type_url.c_str(), name.c_str(),
resource_type_state.resource_type_version);
for (SubscriptionState* subscription : resource_state.subscriptions) {
subscription->update_queue->emplace_back(type_url, name);
}
}
void SetResource(google::protobuf::Any resource, const std::string& type_url,
const std::string& name) {
grpc_core::MutexLock lock(&ads_mu_);
ResourceTypeState& resource_type_state = resource_map_[type_url];
++resource_type_state.resource_type_version;
ResourceState& resource_state = resource_type_state.resource_name_map[name];
resource_state.resource_type_version =
resource_type_state.resource_type_version;
resource_state.resource = std::move(resource);
gpr_log(GPR_INFO,
"ADS[%p]: Updating %s resource %s; resource_type_version now %u",
this, type_url.c_str(), name.c_str(),
resource_type_state.resource_type_version);
for (SubscriptionState* subscription : resource_state.subscriptions) {
subscription->update_queue->emplace_back(type_url, name);
}
}
void SetLdsResource(const Listener& listener) {
google::protobuf::Any resource;
resource.PackFrom(listener);
SetResource(std::move(resource), kLdsTypeUrl, listener.name());
}
void SetRdsResource(const RouteConfiguration& route) {
google::protobuf::Any resource;
resource.PackFrom(route);
SetResource(std::move(resource), kRdsTypeUrl, route.name());
}
void SetCdsResource(const Cluster& cluster) {
google::protobuf::Any resource;
resource.PackFrom(cluster);
SetResource(std::move(resource), kCdsTypeUrl, cluster.name());
}
void SetEdsResource(const ClusterLoadAssignment& assignment) {
google::protobuf::Any resource;
resource.PackFrom(assignment);
SetResource(std::move(resource), kEdsTypeUrl, assignment.cluster_name());
}
void Start() {
grpc_core::MutexLock lock(&ads_mu_);
ads_done_ = false;
}
void Shutdown() {
{
grpc_core::MutexLock lock(&ads_mu_);
NotifyDoneWithAdsCallLocked();
resource_type_response_state_.clear();
}
gpr_log(GPR_INFO, "ADS[%p]: shut down", this);
}
void NotifyDoneWithAdsCall() {
grpc_core::MutexLock lock(&ads_mu_);
NotifyDoneWithAdsCallLocked();
}
void NotifyDoneWithAdsCallLocked() {
if (!ads_done_) {
ads_done_ = true;
ads_cond_.SignalAll();
}
}
std::set<std::string> clients() {
grpc_core::MutexLock lock(&clients_mu_);
return clients_;
}
private:
// A queue of resource type/name pairs that have changed since the client
// subscribed to them.
using UpdateQueue = std::deque<
std::pair<std::string /* type url */, std::string /* resource name */>>;
// A struct representing a client's subscription to a particular resource.
struct SubscriptionState {
// The queue upon which to place updates when the resource is updated.
UpdateQueue* update_queue;
};
// A struct representing the a client's subscription to all the resources.
using SubscriptionNameMap =
std::map<std::string /* resource_name */, SubscriptionState>;
using SubscriptionMap =
std::map<std::string /* type_url */, SubscriptionNameMap>;
// Sent state for a given resource type.
struct SentState {
int nonce = 0;
int resource_type_version = 0;
};
// A struct representing the current state for an individual resource.
struct ResourceState {
// The resource itself, if present.
absl::optional<google::protobuf::Any> resource;
// The resource type version that this resource was last updated in.
int resource_type_version = 0;
// A list of subscriptions to this resource.
std::set<SubscriptionState*> subscriptions;
};
// The current state for all individual resources of a given type.
using ResourceNameMap =
std::map<std::string /* resource_name */, ResourceState>;
struct ResourceTypeState {
int resource_type_version = 0;
ResourceNameMap resource_name_map;
};
using ResourceMap = std::map<std::string /* type_url */, ResourceTypeState>;
template <class RpcApi, class DiscoveryRequest, class DiscoveryResponse>
class RpcService : public RpcApi::Service {
public:
using Stream = ServerReaderWriter<DiscoveryResponse, DiscoveryRequest>;
RpcService(AdsServiceImpl* parent, bool is_v2)
: parent_(parent), is_v2_(is_v2) {}
Status StreamAggregatedResources(ServerContext* context,
Stream* stream) override {
gpr_log(GPR_INFO, "ADS[%p]: StreamAggregatedResources starts", this);
parent_->AddClient(context->peer());
if (is_v2_) {
parent_->seen_v2_client_ = true;
} else {
parent_->seen_v3_client_ = true;
}
// Take a reference of the AdsServiceImpl object, which will go
// out of scope when this request handler returns. This ensures
// that the parent won't be destroyed until this stream is complete.
std::shared_ptr<AdsServiceImpl> ads_service_impl =
parent_->shared_from_this();
// Resources (type/name pairs) that have changed since the client
// subscribed to them.
UpdateQueue update_queue;
// Resources that the client will be subscribed to keyed by resource type
// url.
SubscriptionMap subscription_map;
// Sent state for each resource type.
std::map<std::string /*type_url*/, SentState> sent_state_map;
// Spawn a thread to read requests from the stream.
// Requests will be delivered to this thread in a queue.
std::deque<DiscoveryRequest> requests;
bool stream_closed = false;
std::thread reader(std::bind(&RpcService::BlockingRead, this, stream,
&requests, &stream_closed));
// Main loop to process requests and updates.
while (true) {
// Boolean to keep track if the loop received any work to do: a
// request or an update; regardless whether a response was actually
// sent out.
bool did_work = false;
// Look for new requests and and decide what to handle.
absl::optional<DiscoveryResponse> response;
{
grpc_core::MutexLock lock(&parent_->ads_mu_);
// If the stream has been closed or our parent is being shut
// down, stop immediately.
if (stream_closed || parent_->ads_done_) break;
// Otherwise, see if there's a request to read from the queue.
if (!requests.empty()) {
DiscoveryRequest request = std::move(requests.front());
requests.pop_front();
did_work = true;
gpr_log(GPR_INFO,
"ADS[%p]: Received request for type %s with content %s",
this, request.type_url().c_str(),
request.DebugString().c_str());
const std::string v3_resource_type =
TypeUrlToV3(request.type_url());
SentState& sent_state = sent_state_map[v3_resource_type];
// Process request.
ProcessRequest(request, v3_resource_type, &update_queue,
&subscription_map, &sent_state, &response);
}
}
if (response.has_value()) {
gpr_log(GPR_INFO, "ADS[%p]: Sending response: %s", this,
response->DebugString().c_str());
stream->Write(response.value());
}
response.reset();
// Look for updates and decide what to handle.
{
grpc_core::MutexLock lock(&parent_->ads_mu_);
if (!update_queue.empty()) {
const std::string resource_type =
std::move(update_queue.front().first);
const std::string resource_name =
std::move(update_queue.front().second);
update_queue.pop_front();
did_work = true;
SentState& sent_state = sent_state_map[resource_type];
ProcessUpdate(resource_type, resource_name, &subscription_map,
&sent_state, &response);
}
}
if (response.has_value()) {
gpr_log(GPR_INFO, "ADS[%p]: Sending update response: %s", this,
response->DebugString().c_str());
stream->Write(response.value());
}
// If we didn't find anything to do, delay before the next loop
// iteration; otherwise, check whether we should exit and then
// immediately continue.
gpr_timespec deadline =
grpc_timeout_milliseconds_to_deadline(did_work ? 0 : 10);
{
grpc_core::MutexLock lock(&parent_->ads_mu_);
if (!grpc_core::WaitUntilWithDeadline(
&parent_->ads_cond_, &parent_->ads_mu_,
[this] { return parent_->ads_done_; },
grpc_core::ToAbslTime(deadline))) {
break;
}
}
}
// Done with main loop. Clean up before returning.
// Join reader thread.
reader.join();
// Clean up any subscriptions that were still active when the call
// finished.
{
grpc_core::MutexLock lock(&parent_->ads_mu_);
for (auto& p : subscription_map) {
const std::string& type_url = p.first;
SubscriptionNameMap& subscription_name_map = p.second;
for (auto& q : subscription_name_map) {
const std::string& resource_name = q.first;
SubscriptionState& subscription_state = q.second;
ResourceNameMap& resource_name_map =
parent_->resource_map_[type_url].resource_name_map;
ResourceState& resource_state = resource_name_map[resource_name];
resource_state.subscriptions.erase(&subscription_state);
}
}
}
gpr_log(GPR_INFO, "ADS[%p]: StreamAggregatedResources done", this);
parent_->RemoveClient(context->peer());
return Status::OK;
}
private:
// Processes a response read from the client.
// Populates response if needed.
void ProcessRequest(const DiscoveryRequest& request,
const std::string& v3_resource_type,
UpdateQueue* update_queue,
SubscriptionMap* subscription_map,
SentState* sent_state,
absl::optional<DiscoveryResponse>* response) {
// Check the nonce sent by the client, if any.
// (This will be absent on the first request on a stream.)
if (request.response_nonce().empty()) {
int client_resource_type_version = 0;
if (!request.version_info().empty()) {
GPR_ASSERT(absl::SimpleAtoi(request.version_info(),
&client_resource_type_version));
}
EXPECT_GE(client_resource_type_version,
parent_->resource_type_min_versions_[v3_resource_type])
<< "resource_type: " << v3_resource_type;
} else {
int client_nonce;
GPR_ASSERT(absl::SimpleAtoi(request.response_nonce(), &client_nonce));
// Ignore requests with stale nonces.
if (client_nonce < sent_state->nonce) return;
// Check for ACK or NACK.
auto it = parent_->resource_type_response_state_.find(v3_resource_type);
if (it != parent_->resource_type_response_state_.end()) {
if (!request.has_error_detail()) {
it->second.state = ResponseState::ACKED;
it->second.error_message.clear();
gpr_log(GPR_INFO,
"ADS[%p]: client ACKed resource_type=%s version=%s", this,
request.type_url().c_str(), request.version_info().c_str());
} else {
it->second.state = ResponseState::NACKED;
EXPECT_EQ(request.error_detail().code(),
GRPC_STATUS_INVALID_ARGUMENT);
it->second.error_message = request.error_detail().message();
gpr_log(GPR_INFO,
"ADS[%p]: client NACKed resource_type=%s version=%s: %s",
this, request.type_url().c_str(),
request.version_info().c_str(),
it->second.error_message.c_str());
}
}
}
// Ignore resource types as requested by tests.
if (parent_->resource_types_to_ignore_.find(v3_resource_type) !=
parent_->resource_types_to_ignore_.end()) {
return;
}
// Look at all the resource names in the request.
auto& subscription_name_map = (*subscription_map)[v3_resource_type];
auto& resource_type_state = parent_->resource_map_[v3_resource_type];
auto& resource_name_map = resource_type_state.resource_name_map;
std::set<std::string> resources_in_current_request;
std::set<std::string> resources_added_to_response;
for (const std::string& resource_name : request.resource_names()) {
resources_in_current_request.emplace(resource_name);
auto& subscription_state = subscription_name_map[resource_name];
auto& resource_state = resource_name_map[resource_name];
// Subscribe if needed.
// Send the resource in the response if either (a) this is
// a new subscription or (b) there is an updated version of
// this resource to send.
if (parent_->MaybeSubscribe(v3_resource_type, resource_name,
&subscription_state, &resource_state,
update_queue) ||
ClientNeedsResourceUpdate(resource_type_state, resource_state,
sent_state->resource_type_version)) {
gpr_log(GPR_INFO, "ADS[%p]: Sending update for type=%s name=%s", this,
request.type_url().c_str(), resource_name.c_str());
resources_added_to_response.emplace(resource_name);
if (!response->has_value()) response->emplace();
if (resource_state.resource.has_value()) {
auto* resource = (*response)->add_resources();
resource->CopyFrom(resource_state.resource.value());
if (is_v2_) {
resource->set_type_url(request.type_url());
}
}
} else {
gpr_log(GPR_INFO,
"ADS[%p]: client does not need update for type=%s name=%s",
this, request.type_url().c_str(), resource_name.c_str());
}
}
// Process unsubscriptions for any resource no longer
// present in the request's resource list.
parent_->ProcessUnsubscriptions(
v3_resource_type, resources_in_current_request,
&subscription_name_map, &resource_name_map);
// Construct response if needed.
if (!resources_added_to_response.empty()) {
CompleteBuildingDiscoveryResponse(
v3_resource_type, request.type_url(),
resource_type_state.resource_type_version, subscription_name_map,
resources_added_to_response, sent_state, &response->value());
}
}
// Processes a resource update from the test.
// Populates response if needed.
void ProcessUpdate(const std::string& resource_type,
const std::string& resource_name,
SubscriptionMap* subscription_map, SentState* sent_state,
absl::optional<DiscoveryResponse>* response) {
const std::string v2_resource_type = TypeUrlToV2(resource_type);
gpr_log(GPR_INFO, "ADS[%p]: Received update for type=%s name=%s", this,
resource_type.c_str(), resource_name.c_str());
auto& subscription_name_map = (*subscription_map)[resource_type];
auto& resource_type_state = parent_->resource_map_[resource_type];
auto& resource_name_map = resource_type_state.resource_name_map;
auto it = subscription_name_map.find(resource_name);
if (it != subscription_name_map.end()) {
ResourceState& resource_state = resource_name_map[resource_name];
if (ClientNeedsResourceUpdate(resource_type_state, resource_state,
sent_state->resource_type_version)) {
gpr_log(GPR_INFO, "ADS[%p]: Sending update for type=%s name=%s", this,
resource_type.c_str(), resource_name.c_str());
response->emplace();
if (resource_state.resource.has_value()) {
auto* resource = (*response)->add_resources();
resource->CopyFrom(resource_state.resource.value());
if (is_v2_) {
resource->set_type_url(v2_resource_type);
}
}
CompleteBuildingDiscoveryResponse(
resource_type, v2_resource_type,
resource_type_state.resource_type_version, subscription_name_map,
{resource_name}, sent_state, &response->value());
}
}
}
// Starting a thread to do blocking read on the stream until cancel.
void BlockingRead(Stream* stream, std::deque<DiscoveryRequest>* requests,
bool* stream_closed) {
DiscoveryRequest request;
bool seen_first_request = false;
while (stream->Read(&request)) {
if (!seen_first_request) {
EXPECT_TRUE(request.has_node());
ASSERT_FALSE(request.node().client_features().empty());
EXPECT_EQ(request.node().client_features(0),
"envoy.lb.does_not_support_overprovisioning");
CheckBuildVersion(request);
seen_first_request = true;
}
{
grpc_core::MutexLock lock(&parent_->ads_mu_);
requests->emplace_back(std::move(request));
}
}
gpr_log(GPR_INFO, "ADS[%p]: Null read, stream closed", this);
grpc_core::MutexLock lock(&parent_->ads_mu_);
*stream_closed = true;
}
// Completing the building a DiscoveryResponse by adding common information
// for all resources and by adding all subscribed resources for LDS and CDS.
void CompleteBuildingDiscoveryResponse(
const std::string& resource_type, const std::string& v2_resource_type,
const int version, const SubscriptionNameMap& subscription_name_map,
const std::set<std::string>& resources_added_to_response,
SentState* sent_state, DiscoveryResponse* response) {
auto& response_state =
parent_->resource_type_response_state_[resource_type];
if (response_state.state == ResponseState::NOT_SENT) {
response_state.state = ResponseState::SENT;
}
response->set_type_url(is_v2_ ? v2_resource_type : resource_type);
response->set_version_info(std::to_string(version));
response->set_nonce(std::to_string(++sent_state->nonce));
if (resource_type == kLdsTypeUrl || resource_type == kCdsTypeUrl) {
// For LDS and CDS we must send back all subscribed resources
// (even the unchanged ones)
for (const auto& p : subscription_name_map) {
const std::string& resource_name = p.first;
if (resources_added_to_response.find(resource_name) ==
resources_added_to_response.end()) {
ResourceNameMap& resource_name_map =
parent_->resource_map_[resource_type].resource_name_map;
const ResourceState& resource_state =
resource_name_map[resource_name];
if (resource_state.resource.has_value()) {
auto* resource = response->add_resources();
resource->CopyFrom(resource_state.resource.value());
if (is_v2_) {
resource->set_type_url(v2_resource_type);
}
}
}
}
}
sent_state->resource_type_version = version;
}
static std::string TypeUrlToV2(const std::string& resource_type) {
if (resource_type == kLdsTypeUrl) return kLdsV2TypeUrl;
if (resource_type == kRdsTypeUrl) return kRdsV2TypeUrl;
if (resource_type == kCdsTypeUrl) return kCdsV2TypeUrl;
if (resource_type == kEdsTypeUrl) return kEdsV2TypeUrl;
return resource_type;
}
static std::string TypeUrlToV3(const std::string& resource_type) {
if (resource_type == kLdsV2TypeUrl) return kLdsTypeUrl;
if (resource_type == kRdsV2TypeUrl) return kRdsTypeUrl;
if (resource_type == kCdsV2TypeUrl) return kCdsTypeUrl;
if (resource_type == kEdsV2TypeUrl) return kEdsTypeUrl;
return resource_type;
}
static void CheckBuildVersion(
const ::envoy::api::v2::DiscoveryRequest& request) {
EXPECT_FALSE(request.node().build_version().empty());
}
static void CheckBuildVersion(
const ::envoy::service::discovery::v3::DiscoveryRequest& /*request*/) {}
AdsServiceImpl* parent_;
const bool is_v2_;
};
// Checks whether the client needs to receive a newer version of
// the resource.
static bool ClientNeedsResourceUpdate(
const ResourceTypeState& resource_type_state,
const ResourceState& resource_state, int client_resource_type_version) {
return client_resource_type_version <
resource_type_state.resource_type_version &&
resource_state.resource_type_version <=
resource_type_state.resource_type_version;
}
// Subscribes to a resource if not already subscribed:
// 1. Sets the update_queue field in subscription_state.
// 2. Adds subscription_state to resource_state->subscriptions.
bool MaybeSubscribe(const std::string& resource_type,
const std::string& resource_name,
SubscriptionState* subscription_state,
ResourceState* resource_state,
UpdateQueue* update_queue) {
// The update_queue will be null if we were not previously subscribed.
if (subscription_state->update_queue != nullptr) return false;
subscription_state->update_queue = update_queue;
resource_state->subscriptions.emplace(subscription_state);
gpr_log(GPR_INFO, "ADS[%p]: subscribe to resource type %s name %s state %p",
this, resource_type.c_str(), resource_name.c_str(),
&subscription_state);
return true;
}
// Removes subscriptions for resources no longer present in the
// current request.
void ProcessUnsubscriptions(
const std::string& resource_type,
const std::set<std::string>& resources_in_current_request,
SubscriptionNameMap* subscription_name_map,
ResourceNameMap* resource_name_map) {
for (auto it = subscription_name_map->begin();
it != subscription_name_map->end();) {
const std::string& resource_name = it->first;
SubscriptionState& subscription_state = it->second;
if (resources_in_current_request.find(resource_name) !=
resources_in_current_request.end()) {
++it;
continue;
}
gpr_log(GPR_INFO, "ADS[%p]: Unsubscribe to type=%s name=%s state=%p",
this, resource_type.c_str(), resource_name.c_str(),
&subscription_state);
auto resource_it = resource_name_map->find(resource_name);
GPR_ASSERT(resource_it != resource_name_map->end());
auto& resource_state = resource_it->second;
resource_state.subscriptions.erase(&subscription_state);
if (resource_state.subscriptions.empty() &&
!resource_state.resource.has_value()) {
resource_name_map->erase(resource_it);
}
it = subscription_name_map->erase(it);
}
}
void AddClient(const std::string& client) {
grpc_core::MutexLock lock(&clients_mu_);
clients_.insert(client);
}
void RemoveClient(const std::string& client) {
grpc_core::MutexLock lock(&clients_mu_);
clients_.erase(client);
}
RpcService<::envoy::service::discovery::v2::AggregatedDiscoveryService,
::envoy::api::v2::DiscoveryRequest,
::envoy::api::v2::DiscoveryResponse>
v2_rpc_service_;
RpcService<::envoy::service::discovery::v3::AggregatedDiscoveryService,
::envoy::service::discovery::v3::DiscoveryRequest,
::envoy::service::discovery::v3::DiscoveryResponse>
v3_rpc_service_;
std::atomic_bool seen_v2_client_{false};
std::atomic_bool seen_v3_client_{false};
grpc_core::CondVar ads_cond_;
// Protect the members below.
grpc_core::Mutex ads_mu_;
bool ads_done_ = false;
std::map<std::string /* type_url */, ResponseState>
resource_type_response_state_;
std::set<std::string /*resource_type*/> resource_types_to_ignore_;
std::map<std::string /*resource_type*/, int> resource_type_min_versions_;
// An instance data member containing the current state of all resources.
// Note that an entry will exist whenever either of the following is true:
// - The resource exists (i.e., has been created by SetResource() and has not
// yet been destroyed by UnsetResource()).
// - There is at least one subscription for the resource.
ResourceMap resource_map_;
grpc_core::Mutex clients_mu_;
std::set<std::string> clients_;
};
class LrsServiceImpl : public std::enable_shared_from_this<LrsServiceImpl> {
public:
explicit LrsServiceImpl(int client_load_reporting_interval_seconds)
: v2_rpc_service_(this),
v3_rpc_service_(this),
client_load_reporting_interval_seconds_(
client_load_reporting_interval_seconds),
cluster_names_({kDefaultClusterName}) {}
::envoy::service::load_stats::v2::LoadReportingService::Service*
v2_rpc_service() {
return &v2_rpc_service_;
}
::envoy::service::load_stats::v3::LoadReportingService::Service*
v3_rpc_service() {
return &v3_rpc_service_;
}
size_t request_count() {
return v2_rpc_service_.request_count() + v3_rpc_service_.request_count();
}
size_t response_count() {
return v2_rpc_service_.response_count() + v3_rpc_service_.response_count();
}
// Must be called before the LRS call is started.
void set_send_all_clusters(bool send_all_clusters) {
send_all_clusters_ = send_all_clusters;
}
void set_cluster_names(const std::set<std::string>& cluster_names) {
cluster_names_ = cluster_names;
}
void Start() {
lrs_done_ = false;
result_queue_.clear();
}
void Shutdown() {
{
grpc_core::MutexLock lock(&lrs_mu_);
NotifyDoneWithLrsCallLocked();
}
gpr_log(GPR_INFO, "LRS[%p]: shut down", this);
}
std::vector<ClientStats> WaitForLoadReport() {
grpc_core::MutexLock lock(&load_report_mu_);
grpc_core::CondVar cv;
if (result_queue_.empty()) {
load_report_cond_ = &cv;
grpc_core::WaitUntil(load_report_cond_, &load_report_mu_,
[this] { return !result_queue_.empty(); });
load_report_cond_ = nullptr;
}
std::vector<ClientStats> result = std::move(result_queue_.front());
result_queue_.pop_front();
return result;
}
void NotifyDoneWithLrsCall() {
grpc_core::MutexLock lock(&lrs_mu_);
NotifyDoneWithLrsCallLocked();
}
private:
template <class RpcApi, class LoadStatsRequest, class LoadStatsResponse>
class RpcService : public CountedService<typename RpcApi::Service> {
public:
using Stream = ServerReaderWriter<LoadStatsResponse, LoadStatsRequest>;
explicit RpcService(LrsServiceImpl* parent) : parent_(parent) {}
Status StreamLoadStats(ServerContext* /*context*/,
Stream* stream) override {
gpr_log(GPR_INFO, "LRS[%p]: StreamLoadStats starts", this);
EXPECT_GT(parent_->client_load_reporting_interval_seconds_, 0);
// Take a reference of the LrsServiceImpl object, reference will go
// out of scope after this method exits.
std::shared_ptr<LrsServiceImpl> lrs_service_impl =
parent_->shared_from_this();
// Read initial request.
LoadStatsRequest request;
if (stream->Read(&request)) {
CountedService<typename RpcApi::Service>::IncreaseRequestCount();
// Verify client features.
EXPECT_THAT(
request.node().client_features(),
::testing::Contains("envoy.lrs.supports_send_all_clusters"));
// Send initial response.
LoadStatsResponse response;
if (parent_->send_all_clusters_) {
response.set_send_all_clusters(true);
} else {
for (const std::string& cluster_name : parent_->cluster_names_) {
response.add_clusters(cluster_name);
}
}
response.mutable_load_reporting_interval()->set_seconds(
parent_->client_load_reporting_interval_seconds_);
stream->Write(response);
CountedService<typename RpcApi::Service>::IncreaseResponseCount();
// Wait for report.
request.Clear();
while (stream->Read(&request)) {
gpr_log(GPR_INFO, "LRS[%p]: received client load report message: %s",
this, request.DebugString().c_str());
std::vector<ClientStats> stats;
for (const auto& cluster_stats : request.cluster_stats()) {
stats.emplace_back(cluster_stats);
}
grpc_core::MutexLock lock(&parent_->load_report_mu_);
parent_->result_queue_.emplace_back(std::move(stats));
if (parent_->load_report_cond_ != nullptr) {
parent_->load_report_cond_->Signal();
}
}
// Wait until notified done.
grpc_core::MutexLock lock(&parent_->lrs_mu_);
grpc_core::WaitUntil(&parent_->lrs_cv_, &parent_->lrs_mu_,
[this] { return parent_->lrs_done_; });
}
gpr_log(GPR_INFO, "LRS[%p]: StreamLoadStats done", this);
return Status::OK;
}
private:
LrsServiceImpl* parent_;
};
void NotifyDoneWithLrsCallLocked() {
if (!lrs_done_) {
lrs_done_ = true;
lrs_cv_.SignalAll();
}
}
RpcService<::envoy::service::load_stats::v2::LoadReportingService,
::envoy::service::load_stats::v2::LoadStatsRequest,
::envoy::service::load_stats::v2::LoadStatsResponse>
v2_rpc_service_;
RpcService<::envoy::service::load_stats::v3::LoadReportingService,
::envoy::service::load_stats::v3::LoadStatsRequest,
::envoy::service::load_stats::v3::LoadStatsResponse>
v3_rpc_service_;
const int client_load_reporting_interval_seconds_;
bool send_all_clusters_ = false;
std::set<std::string> cluster_names_;
grpc_core::CondVar lrs_cv_;
grpc_core::Mutex lrs_mu_; // Protects lrs_done_.
bool lrs_done_ = false;
grpc_core::Mutex load_report_mu_; // Protects the members below.
grpc_core::CondVar* load_report_cond_ = nullptr;
std::deque<std::vector<ClientStats>> result_queue_;
};
class TestType {
public:
enum FilterConfigSetup {
// Set the fault injection filter directly from LDS
kHTTPConnectionManagerOriginal,
// Enable the fault injection filter in LDS, but override the filter config
// in route.
kRouteOverride,
};
TestType& set_use_fake_resolver() {
use_fake_resolver_ = true;
return *this;
}
TestType& set_enable_load_reporting() {
enable_load_reporting_ = true;
return *this;
}
TestType& set_enable_rds_testing() {
enable_rds_testing_ = true;
return *this;
}
TestType& set_use_v2() {
use_v2_ = true;
return *this;
}
TestType& set_use_xds_credentials() {
use_xds_credentials_ = true;
return *this;
}
TestType& set_use_csds_streaming() {
use_csds_streaming_ = true;
return *this;
}
TestType& set_filter_config_setup(const FilterConfigSetup& setup) {
filter_config_setup_ = setup;
return *this;
}
bool use_fake_resolver() const { return use_fake_resolver_; }
bool enable_load_reporting() const { return enable_load_reporting_; }
bool enable_rds_testing() const { return enable_rds_testing_; }
bool use_v2() const { return use_v2_; }
bool use_xds_credentials() const { return use_xds_credentials_; }
bool use_csds_streaming() const { return use_csds_streaming_; }
const FilterConfigSetup& filter_config_setup() const {
return filter_config_setup_;
}
std::string AsString() const {
std::string retval = (use_fake_resolver_ ? "FakeResolver" : "XdsResolver");
retval += (use_v2_ ? "V2" : "V3");
if (enable_load_reporting_) retval += "WithLoadReporting";
if (enable_rds_testing_) retval += "Rds";
if (use_xds_credentials_) retval += "XdsCreds";
if (use_csds_streaming_) retval += "CsdsStreaming";
if (filter_config_setup_ == kRouteOverride) {
retval += "FilterPerRouteOverride";
}
return retval;
}
private:
bool use_fake_resolver_ = false;
bool enable_load_reporting_ = false;
bool enable_rds_testing_ = false;
bool use_v2_ = false;
bool use_xds_credentials_ = false;
bool use_csds_streaming_ = false;
FilterConfigSetup filter_config_setup_ = kHTTPConnectionManagerOriginal;
};
std::string ReadFile(const char* file_path) {
grpc_slice slice;
GPR_ASSERT(
GRPC_LOG_IF_ERROR("load_file", grpc_load_file(file_path, 0, &slice)));
std::string file_contents(grpc_core::StringViewFromSlice(slice));
grpc_slice_unref(slice);
return file_contents;
}
grpc_core::PemKeyCertPairList ReadTlsIdentityPair(const char* key_path,
const char* cert_path) {
return grpc_core::PemKeyCertPairList{
grpc_core::PemKeyCertPair(ReadFile(key_path), ReadFile(cert_path))};
}
// Based on StaticDataCertificateProvider, but provides alternate certificates
// if the certificate name is not empty.
class FakeCertificateProvider final : public grpc_tls_certificate_provider {
public:
struct CertData {
std::string root_certificate;
grpc_core::PemKeyCertPairList identity_key_cert_pairs;
};
using CertDataMap = std::map<std::string /*cert_name */, CertData>;
explicit FakeCertificateProvider(CertDataMap cert_data_map)
: distributor_(
grpc_core::MakeRefCounted<grpc_tls_certificate_distributor>()),
cert_data_map_(std::move(cert_data_map)) {
distributor_->SetWatchStatusCallback([this](std::string cert_name,
bool root_being_watched,
bool identity_being_watched) {
if (!root_being_watched && !identity_being_watched) return;
auto it = cert_data_map_.find(cert_name);
if (it == cert_data_map_.end()) {
grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("No certificates available for cert_name \"",
cert_name, "\"")
.c_str());
distributor_->SetErrorForCert(cert_name, GRPC_ERROR_REF(error),
GRPC_ERROR_REF(error));
GRPC_ERROR_UNREF(error);
} else {
absl::optional<std::string> root_certificate;
absl::optional<grpc_core::PemKeyCertPairList> pem_key_cert_pairs;
if (root_being_watched) {
root_certificate = it->second.root_certificate;
}
if (identity_being_watched) {
pem_key_cert_pairs = it->second.identity_key_cert_pairs;
}
distributor_->SetKeyMaterials(cert_name, std::move(root_certificate),
std::move(pem_key_cert_pairs));
}
});
}
~FakeCertificateProvider() override {
distributor_->SetWatchStatusCallback(nullptr);
}
grpc_core::RefCountedPtr<grpc_tls_certificate_distributor> distributor()
const override {
return distributor_;
}
private:
grpc_core::RefCountedPtr<grpc_tls_certificate_distributor> distributor_;
CertDataMap cert_data_map_;
};
class FakeCertificateProviderFactory
: public grpc_core::CertificateProviderFactory {
public:
class Config : public grpc_core::CertificateProviderFactory::Config {
public:
explicit Config(const char* name) : name_(name) {}
const char* name() const override { return name_; }
std::string ToString() const override { return "{}"; }
private:
const char* name_;
};
FakeCertificateProviderFactory(
const char* name, FakeCertificateProvider::CertDataMap** cert_data_map)
: name_(name), cert_data_map_(cert_data_map) {
GPR_ASSERT(cert_data_map != nullptr);
}
const char* name() const override { return name_; }
grpc_core::RefCountedPtr<grpc_core::CertificateProviderFactory::Config>
CreateCertificateProviderConfig(const grpc_core::Json& /*config_json*/,
grpc_error** /*error*/) override {
return grpc_core::MakeRefCounted<Config>(name_);
}
grpc_core::RefCountedPtr<grpc_tls_certificate_provider>
CreateCertificateProvider(
grpc_core::RefCountedPtr<grpc_core::CertificateProviderFactory::Config>
/*config*/) override {
if (*cert_data_map_ == nullptr) return nullptr;
return grpc_core::MakeRefCounted<FakeCertificateProvider>(**cert_data_map_);
}
private:
const char* name_;
FakeCertificateProvider::CertDataMap** cert_data_map_;
};
// Global variables for each provider.
FakeCertificateProvider::CertDataMap* g_fake1_cert_data_map = nullptr;
FakeCertificateProvider::CertDataMap* g_fake2_cert_data_map = nullptr;
int ServerAuthCheckSchedule(void* /* config_user_data */,
grpc_tls_server_authorization_check_arg* arg) {
arg->success = 1;
arg->status = GRPC_STATUS_OK;
return 0; /* synchronous check */
}
std::shared_ptr<ChannelCredentials> CreateTlsFallbackCredentials() {
// TODO(yashykt): Switch to using C++ API once b/173823806 is fixed.
grpc_tls_credentials_options* options = grpc_tls_credentials_options_create();
grpc_tls_credentials_options_set_server_verification_option(
options, GRPC_TLS_SKIP_HOSTNAME_VERIFICATION);
grpc_tls_credentials_options_set_certificate_provider(
options,
grpc_core::MakeRefCounted<grpc_core::StaticDataCertificateProvider>(
ReadFile(kCaCertPath),
ReadTlsIdentityPair(kServerKeyPath, kServerCertPath))
.get());
grpc_tls_credentials_options_watch_root_certs(options);
grpc_tls_credentials_options_watch_identity_key_cert_pairs(options);
grpc_tls_server_authorization_check_config* check_config =
grpc_tls_server_authorization_check_config_create(
nullptr, ServerAuthCheckSchedule, nullptr, nullptr);
grpc_tls_credentials_options_set_server_authorization_check_config(
options, check_config);
auto channel_creds = std::make_shared<SecureChannelCredentials>(
grpc_tls_credentials_create(options));
grpc_tls_server_authorization_check_config_release(check_config);
return channel_creds;
}
// A No-op HTTP filter used for verifying parsing logic.
class NoOpHttpFilter : public grpc_core::XdsHttpFilterImpl {
public:
NoOpHttpFilter(std::string name, bool supported_on_clients,
bool supported_on_servers)
: name_(std::move(name)),
supported_on_clients_(supported_on_clients),
supported_on_servers_(supported_on_servers) {}
void PopulateSymtab(upb_symtab* /* symtab */) const override {}
absl::StatusOr<grpc_core::XdsHttpFilterImpl::FilterConfig>
GenerateFilterConfig(upb_strview /* serialized_filter_config */,
upb_arena* /* arena */) const override {
return grpc_core::XdsHttpFilterImpl::FilterConfig{name_, grpc_core::Json()};
}
absl::StatusOr<grpc_core::XdsHttpFilterImpl::FilterConfig>
GenerateFilterConfigOverride(upb_strview /*serialized_filter_config*/,
upb_arena* /*arena*/) const override {
return grpc_core::XdsHttpFilterImpl::FilterConfig{name_, grpc_core::Json()};
}
const grpc_channel_filter* channel_filter() const override { return nullptr; }
absl::StatusOr<grpc_core::XdsHttpFilterImpl::ServiceConfigJsonEntry>
GenerateServiceConfig(
const FilterConfig& /*hcm_filter_config*/,
const FilterConfig* /*filter_config_override*/) const override {
return grpc_core::XdsHttpFilterImpl::ServiceConfigJsonEntry{name_, ""};
}
bool IsSupportedOnClients() const override { return supported_on_clients_; }
bool IsSupportedOnServers() const override { return supported_on_servers_; }
private:
const std::string name_;
const bool supported_on_clients_;
const bool supported_on_servers_;
};
namespace {
void* response_generator_arg_copy(void* p) {
auto* generator = static_cast<grpc_core::FakeResolverResponseGenerator*>(p);
generator->Ref().release();
return p;
}
void response_generator_arg_destroy(void* p) {
auto* generator = static_cast<grpc_core::FakeResolverResponseGenerator*>(p);
generator->Unref();
}
int response_generator_cmp(void* a, void* b) { return GPR_ICMP(a, b); }
const grpc_arg_pointer_vtable
kLogicalDnsClusterResolverResponseGeneratorVtable = {
response_generator_arg_copy, response_generator_arg_destroy,
response_generator_cmp};
// There is slight difference between time fetched by GPR and by C++ system
// clock API. It's unclear if they are using the same syscall, but we do know
// GPR round the number at millisecond-level. This creates a 1ms difference,
// which could cause flake.
grpc_millis NowFromCycleCounter() {
gpr_cycle_counter now = gpr_get_cycle_counter();
return grpc_cycle_counter_to_millis_round_up(now);
}
} // namespace
class XdsEnd2endTest : public ::testing::TestWithParam<TestType> {
protected:
// TODO(roth): We currently set the number of backends and number of
// balancers on a per-test-suite basis, not a per-test-case basis.
// However, not every individual test case in a given test suite uses
// the same number of backends or balancers, so we wind up having to
// set the numbers for the test suite to the max number needed by any
// one test case in that test suite. This results in starting more
// servers (and using more ports) than we actually need. When we have
// time, change each test to directly start the number of backends and
// balancers that it needs, so that we aren't wasting resources.
XdsEnd2endTest(size_t num_backends, size_t num_balancers,
int client_load_reporting_interval_seconds = 100,
bool use_xds_enabled_server = false,
bool bootstrap_contents_from_env_var = false)
: num_backends_(num_backends),
num_balancers_(num_balancers),
client_load_reporting_interval_seconds_(
client_load_reporting_interval_seconds),
use_xds_enabled_server_(use_xds_enabled_server),
bootstrap_contents_from_env_var_(bootstrap_contents_from_env_var) {}
void SetUp() override {
if (bootstrap_contents_from_env_var_) {
gpr_setenv("GRPC_XDS_BOOTSTRAP_CONFIG",
GetParam().use_v2() ? kBootstrapFileV2 : kBootstrapFileV3);
} else {
gpr_setenv("GRPC_XDS_BOOTSTRAP", GetParam().use_v2()
? g_bootstrap_file_v2
: g_bootstrap_file_v3);
}
bool localhost_resolves_to_ipv4 = false;
bool localhost_resolves_to_ipv6 = false;
grpc_core::LocalhostResolves(&localhost_resolves_to_ipv4,
&localhost_resolves_to_ipv6);
ipv6_only_ = !localhost_resolves_to_ipv4 && localhost_resolves_to_ipv6;
// Initialize default xDS resources.
// Construct LDS resource.
default_listener_.set_name(kServerName);
HttpConnectionManager http_connection_manager;
if (!GetParam().use_v2()) {
auto* filter = http_connection_manager.add_http_filters();
filter->set_name("router");
filter->mutable_typed_config()->PackFrom(
envoy::extensions::filters::http::router::v3::Router());
}
default_listener_.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
// Construct RDS resource.
default_route_config_.set_name(kDefaultRouteConfigurationName);
auto* virtual_host = default_route_config_.add_virtual_hosts();
virtual_host->add_domains("*");
auto* route = virtual_host->add_routes();
route->mutable_match()->set_prefix("");
route->mutable_route()->set_cluster(kDefaultClusterName);
// Construct CDS resource.
default_cluster_.set_name(kDefaultClusterName);
default_cluster_.set_type(Cluster::EDS);
auto* eds_config = default_cluster_.mutable_eds_cluster_config();
eds_config->mutable_eds_config()->mutable_ads();
eds_config->set_service_name(kDefaultEdsServiceName);
default_cluster_.set_lb_policy(Cluster::ROUND_ROBIN);
if (GetParam().enable_load_reporting()) {
default_cluster_.mutable_lrs_server()->mutable_self();
}
// Start the load balancers.
for (size_t i = 0; i < num_balancers_; ++i) {
balancers_.emplace_back(
new BalancerServerThread(GetParam().enable_load_reporting()
? client_load_reporting_interval_seconds_
: 0));
balancers_.back()->Start();
// Initialize resources.
SetListenerAndRouteConfiguration(i, default_listener_,
default_route_config_);
balancers_.back()->ads_service()->SetCdsResource(default_cluster_);
}
// Initialize XdsClient state.
response_generator_ =
grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
// Inject xDS channel response generator.
lb_channel_response_generator_ =
grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
xds_channel_args_to_add_.emplace_back(
grpc_core::FakeResolverResponseGenerator::MakeChannelArg(
lb_channel_response_generator_.get()));
// Inject xDS logical cluster resolver response generator.
logical_dns_cluster_resolver_response_generator_ =
grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
if (xds_resource_does_not_exist_timeout_ms_ > 0) {
xds_channel_args_to_add_.emplace_back(grpc_channel_arg_integer_create(
const_cast<char*>(GRPC_ARG_XDS_RESOURCE_DOES_NOT_EXIST_TIMEOUT_MS),
xds_resource_does_not_exist_timeout_ms_));
}
xds_channel_args_.num_args = xds_channel_args_to_add_.size();
xds_channel_args_.args = xds_channel_args_to_add_.data();
grpc_core::internal::SetXdsChannelArgsForTest(&xds_channel_args_);
// Make sure each test creates a new XdsClient instance rather than
// reusing the one from the previous test. This avoids spurious failures
// caused when a load reporting test runs after a non-load reporting test
// and the XdsClient is still talking to the old LRS server, which fails
// because it's not expecting the client to connect. It also
// ensures that each test can independently set the global channel
// args for the xDS channel.
grpc_core::internal::UnsetGlobalXdsClientForTest();
// Start the backends.
for (size_t i = 0; i < num_backends_; ++i) {
backends_.emplace_back(new BackendServerThread(use_xds_enabled_server_));
backends_.back()->Start();
}
// Create channel and stub.
ResetStub();
}
const char* DefaultEdsServiceName() const {
return GetParam().use_fake_resolver() ? kServerName
: kDefaultEdsServiceName;
}
void TearDown() override {
ShutdownAllBackends();
for (auto& balancer : balancers_) balancer->Shutdown();
// Clear global xDS channel args, since they will go out of scope
// when this test object is destroyed.
grpc_core::internal::SetXdsChannelArgsForTest(nullptr);
gpr_unsetenv("GRPC_XDS_BOOTSTRAP");
gpr_unsetenv("GRPC_XDS_BOOTSTRAP_CONFIG");
}
void StartAllBackends() {
for (auto& backend : backends_) backend->Start();
}
void StartBackend(size_t index) { backends_[index]->Start(); }
void ShutdownAllBackends() {
for (auto& backend : backends_) backend->Shutdown();
}
void ShutdownBackend(size_t index) { backends_[index]->Shutdown(); }
void ResetStub(int failover_timeout = 0) {
channel_ = CreateChannel(failover_timeout);
stub_ = grpc::testing::EchoTestService::NewStub(channel_);
stub1_ = grpc::testing::EchoTest1Service::NewStub(channel_);
stub2_ = grpc::testing::EchoTest2Service::NewStub(channel_);
}
std::shared_ptr<Channel> CreateChannel(
int failover_timeout = 0, const char* server_name = kServerName,
grpc_core::FakeResolverResponseGenerator* response_generator = nullptr) {
ChannelArguments args;
if (failover_timeout > 0) {
args.SetInt(GRPC_ARG_PRIORITY_FAILOVER_TIMEOUT_MS, failover_timeout);
}
// If the parent channel is using the fake resolver, we inject the
// response generator here.
if (GetParam().use_fake_resolver()) {
if (response_generator == nullptr) {
response_generator = response_generator_.get();
}
args.SetPointer(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
response_generator);
}
args.SetPointerWithVtable(
GRPC_ARG_XDS_LOGICAL_DNS_CLUSTER_FAKE_RESOLVER_RESPONSE_GENERATOR,
logical_dns_cluster_resolver_response_generator_.get(),
&kLogicalDnsClusterResolverResponseGeneratorVtable);
std::string uri = absl::StrCat(
GetParam().use_fake_resolver() ? "fake" : "xds", ":///", server_name);
std::shared_ptr<ChannelCredentials> channel_creds =
GetParam().use_xds_credentials()
? experimental::XdsCredentials(CreateTlsFallbackCredentials())
: std::make_shared<SecureChannelCredentials>(
grpc_fake_transport_security_credentials_create());
return ::grpc::CreateCustomChannel(uri, channel_creds, args);
}
enum RpcService {
SERVICE_ECHO,
SERVICE_ECHO1,
SERVICE_ECHO2,
};
enum RpcMethod {
METHOD_ECHO,
METHOD_ECHO1,
METHOD_ECHO2,
};
struct RpcOptions {
RpcService service = SERVICE_ECHO;
RpcMethod method = METHOD_ECHO;
int timeout_ms = 1000;
bool wait_for_ready = false;
bool server_fail = false;
std::vector<std::pair<std::string, std::string>> metadata;
int client_cancel_after_us = 0;
bool skip_cancelled_check = false;
RpcOptions() {}
RpcOptions& set_rpc_service(RpcService rpc_service) {
service = rpc_service;
return *this;
}
RpcOptions& set_rpc_method(RpcMethod rpc_method) {
method = rpc_method;
return *this;
}
RpcOptions& set_timeout_ms(int rpc_timeout_ms) {
timeout_ms = rpc_timeout_ms;
return *this;
}
RpcOptions& set_wait_for_ready(bool rpc_wait_for_ready) {
wait_for_ready = rpc_wait_for_ready;
return *this;
}
RpcOptions& set_server_fail(bool rpc_server_fail) {
server_fail = rpc_server_fail;
return *this;
}
RpcOptions& set_skip_cancelled_check(bool rpc_skip_cancelled_check) {
skip_cancelled_check = rpc_skip_cancelled_check;
return *this;
}
RpcOptions& set_metadata(
std::vector<std::pair<std::string, std::string>> rpc_metadata) {
metadata = std::move(rpc_metadata);
return *this;
}
RpcOptions& set_client_cancel_after_us(int rpc_client_cancel_after_us) {
client_cancel_after_us = rpc_client_cancel_after_us;
return *this;
}
// Populates context and request.
void SetupRpc(ClientContext* context, EchoRequest* request) const {
for (const auto& item : metadata) {
context->AddMetadata(item.first, item.second);
}
if (timeout_ms != 0) {
context->set_deadline(
grpc_timeout_milliseconds_to_deadline(timeout_ms));
}
if (wait_for_ready) context->set_wait_for_ready(true);
request->set_message(kRequestMessage);
if (server_fail) {
request->mutable_param()->mutable_expected_error()->set_code(
GRPC_STATUS_FAILED_PRECONDITION);
}
if (client_cancel_after_us != 0) {
request->mutable_param()->set_client_cancel_after_us(
client_cancel_after_us);
}
if (skip_cancelled_check) {
request->mutable_param()->set_skip_cancelled_check(true);
}
}
};
template <typename Stub>
Status SendRpcMethod(Stub* stub, const RpcOptions& rpc_options,
ClientContext* context, EchoRequest& request,
EchoResponse* response) {
switch (rpc_options.method) {
case METHOD_ECHO:
return (*stub)->Echo(context, request, response);
case METHOD_ECHO1:
return (*stub)->Echo1(context, request, response);
case METHOD_ECHO2:
return (*stub)->Echo2(context, request, response);
}
GPR_UNREACHABLE_CODE();
}
void ResetBackendCounters(size_t start_index = 0, size_t stop_index = 0) {
if (stop_index == 0) stop_index = backends_.size();
for (size_t i = start_index; i < stop_index; ++i) {
backends_[i]->backend_service()->ResetCounters();
backends_[i]->backend_service1()->ResetCounters();
backends_[i]->backend_service2()->ResetCounters();
}
}
bool SeenAllBackends(size_t start_index = 0, size_t stop_index = 0,
const RpcOptions& rpc_options = RpcOptions()) {
if (stop_index == 0) stop_index = backends_.size();
for (size_t i = start_index; i < stop_index; ++i) {
switch (rpc_options.service) {
case SERVICE_ECHO:
if (backends_[i]->backend_service()->request_count() == 0) {
return false;
}
break;
case SERVICE_ECHO1:
if (backends_[i]->backend_service1()->request_count() == 0) {
return false;
}
break;
case SERVICE_ECHO2:
if (backends_[i]->backend_service2()->request_count() == 0) {
return false;
}
break;
}
}
return true;
}
void SendRpcAndCount(int* num_total, int* num_ok, int* num_failure,
int* num_drops,
const RpcOptions& rpc_options = RpcOptions(),
const char* drop_error_message =
"Call dropped by load balancing policy") {
const Status status = SendRpc(rpc_options);
if (status.ok()) {
++*num_ok;
} else {
if (status.error_message() == drop_error_message) {
++*num_drops;
} else {
++*num_failure;
}
}
++*num_total;
}
std::tuple<int, int, int> WaitForAllBackends(
size_t start_index = 0, size_t stop_index = 0, bool reset_counters = true,
const RpcOptions& rpc_options = RpcOptions(),
bool allow_failures = false) {
int num_ok = 0;
int num_failure = 0;
int num_drops = 0;
int num_total = 0;
while (!SeenAllBackends(start_index, stop_index, rpc_options)) {
SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_drops,
rpc_options);
}
if (reset_counters) ResetBackendCounters();
gpr_log(GPR_INFO,
"Performed %d warm up requests against the backends. "
"%d succeeded, %d failed, %d dropped.",
num_total, num_ok, num_failure, num_drops);
if (!allow_failures) EXPECT_EQ(num_failure, 0);
return std::make_tuple(num_ok, num_failure, num_drops);
}
void WaitForBackend(size_t backend_idx, bool reset_counters = true,
bool require_success = false) {
gpr_log(GPR_INFO, "========= WAITING FOR BACKEND %lu ==========",
static_cast<unsigned long>(backend_idx));
do {
Status status = SendRpc();
if (require_success) {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
}
} while (backends_[backend_idx]->backend_service()->request_count() == 0);
if (reset_counters) ResetBackendCounters();
gpr_log(GPR_INFO, "========= BACKEND %lu READY ==========",
static_cast<unsigned long>(backend_idx));
}
grpc_core::ServerAddressList CreateAddressListFromPortList(
const std::vector<int>& ports) {
grpc_core::ServerAddressList addresses;
for (int port : ports) {
absl::StatusOr<grpc_core::URI> lb_uri = grpc_core::URI::Parse(
absl::StrCat(ipv6_only_ ? "ipv6:[::1]:" : "ipv4:127.0.0.1:", port));
GPR_ASSERT(lb_uri.ok());
grpc_resolved_address address;
GPR_ASSERT(grpc_parse_uri(*lb_uri, &address));
addresses.emplace_back(address.addr, address.len, nullptr);
}
return addresses;
}
void SetNextResolution(
const std::vector<int>& ports,
grpc_core::FakeResolverResponseGenerator* response_generator = nullptr) {
if (!GetParam().use_fake_resolver()) return; // Not used with xds resolver.
grpc_core::ExecCtx exec_ctx;
grpc_core::Resolver::Result result;
result.addresses = CreateAddressListFromPortList(ports);
grpc_error* error = GRPC_ERROR_NONE;
const char* service_config_json =
GetParam().enable_load_reporting()
? kDefaultServiceConfig
: kDefaultServiceConfigWithoutLoadReporting;
result.service_config =
grpc_core::ServiceConfig::Create(nullptr, service_config_json, &error);
ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_string(error);
ASSERT_NE(result.service_config.get(), nullptr);
if (response_generator == nullptr) {
response_generator = response_generator_.get();
}
response_generator->SetResponse(std::move(result));
}
void SetNextResolutionForLbChannelAllBalancers(
const char* service_config_json = nullptr,
const char* expected_targets = nullptr) {
std::vector<int> ports;
for (size_t i = 0; i < balancers_.size(); ++i) {
ports.emplace_back(balancers_[i]->port());
}
SetNextResolutionForLbChannel(ports, service_config_json, expected_targets);
}
void SetNextResolutionForLbChannel(const std::vector<int>& ports,
const char* service_config_json = nullptr,
const char* expected_targets = nullptr) {
grpc_core::ExecCtx exec_ctx;
grpc_core::Resolver::Result result;
result.addresses = CreateAddressListFromPortList(ports);
if (service_config_json != nullptr) {
grpc_error* error = GRPC_ERROR_NONE;
result.service_config = grpc_core::ServiceConfig::Create(
nullptr, service_config_json, &error);
ASSERT_NE(result.service_config.get(), nullptr);
ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_string(error);
}
if (expected_targets != nullptr) {
grpc_arg expected_targets_arg = grpc_channel_arg_string_create(
const_cast<char*>(GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS),
const_cast<char*>(expected_targets));
result.args =
grpc_channel_args_copy_and_add(nullptr, &expected_targets_arg, 1);
}
lb_channel_response_generator_->SetResponse(std::move(result));
}
void SetNextReresolutionResponse(const std::vector<int>& ports) {
grpc_core::ExecCtx exec_ctx;
grpc_core::Resolver::Result result;
result.addresses = CreateAddressListFromPortList(ports);
response_generator_->SetReresolutionResponse(std::move(result));
}
std::vector<int> GetBackendPorts(size_t start_index = 0,
size_t stop_index = 0) const {
if (stop_index == 0) stop_index = backends_.size();
std::vector<int> backend_ports;
for (size_t i = start_index; i < stop_index; ++i) {
backend_ports.push_back(backends_[i]->port());
}
return backend_ports;
}
Status SendRpc(const RpcOptions& rpc_options = RpcOptions(),
EchoResponse* response = nullptr) {
const bool local_response = (response == nullptr);
if (local_response) response = new EchoResponse;
ClientContext context;
EchoRequest request;
rpc_options.SetupRpc(&context, &request);
Status status;
switch (rpc_options.service) {
case SERVICE_ECHO:
status =
SendRpcMethod(&stub_, rpc_options, &context, request, response);
break;
case SERVICE_ECHO1:
status =
SendRpcMethod(&stub1_, rpc_options, &context, request, response);
break;
case SERVICE_ECHO2:
status =
SendRpcMethod(&stub2_, rpc_options, &context, request, response);
break;
}
if (local_response) delete response;
return status;
}
void CheckRpcSendOk(const size_t times = 1,
const RpcOptions& rpc_options = RpcOptions()) {
for (size_t i = 0; i < times; ++i) {
EchoResponse response;
const Status status = SendRpc(rpc_options, &response);
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage);
}
}
void CheckRpcSendFailure(
const size_t times = 1, const RpcOptions& rpc_options = RpcOptions(),
const StatusCode expected_error_code = StatusCode::OK) {
for (size_t i = 0; i < times; ++i) {
const Status status = SendRpc(rpc_options);
EXPECT_FALSE(status.ok());
if (expected_error_code != StatusCode::OK) {
EXPECT_EQ(expected_error_code, status.error_code());
}
}
}
static Listener BuildListener(const RouteConfiguration& route_config) {
HttpConnectionManager http_connection_manager;
*(http_connection_manager.mutable_route_config()) = route_config;
auto* filter = http_connection_manager.add_http_filters();
filter->set_name("router");
filter->mutable_typed_config()->PackFrom(
envoy::extensions::filters::http::router::v3::Router());
Listener listener;
listener.set_name(kServerName);
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
return listener;
}
ClusterLoadAssignment BuildEdsResource(
const AdsServiceImpl::EdsResourceArgs& args,
const char* eds_service_name = kDefaultEdsServiceName) {
ClusterLoadAssignment assignment;
assignment.set_cluster_name(eds_service_name);
for (const auto& locality : args.locality_list) {
auto* endpoints = assignment.add_endpoints();
endpoints->mutable_load_balancing_weight()->set_value(locality.lb_weight);
endpoints->set_priority(locality.priority);
endpoints->mutable_locality()->set_region(kDefaultLocalityRegion);
endpoints->mutable_locality()->set_zone(kDefaultLocalityZone);
endpoints->mutable_locality()->set_sub_zone(locality.sub_zone);
for (size_t i = 0; i < locality.ports.size(); ++i) {
const int& port = locality.ports[i];
auto* lb_endpoints = endpoints->add_lb_endpoints();
if (locality.health_statuses.size() > i &&
locality.health_statuses[i] != HealthStatus::UNKNOWN) {
lb_endpoints->set_health_status(locality.health_statuses[i]);
}
auto* endpoint = lb_endpoints->mutable_endpoint();
auto* address = endpoint->mutable_address();
auto* socket_address = address->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(port);
}
}
if (!args.drop_categories.empty()) {
auto* policy = assignment.mutable_policy();
for (const auto& p : args.drop_categories) {
const std::string& name = p.first;
const uint32_t parts_per_million = p.second;
auto* drop_overload = policy->add_drop_overloads();
drop_overload->set_category(name);
auto* drop_percentage = drop_overload->mutable_drop_percentage();
drop_percentage->set_numerator(parts_per_million);
drop_percentage->set_denominator(args.drop_denominator);
}
}
return assignment;
}
void SetListenerAndRouteConfiguration(
int idx, Listener listener, const RouteConfiguration& route_config) {
auto* api_listener =
listener.mutable_api_listener()->mutable_api_listener();
HttpConnectionManager http_connection_manager;
api_listener->UnpackTo(&http_connection_manager);
if (GetParam().enable_rds_testing()) {
auto* rds = http_connection_manager.mutable_rds();
rds->set_route_config_name(kDefaultRouteConfigurationName);
rds->mutable_config_source()->mutable_ads();
balancers_[idx]->ads_service()->SetRdsResource(route_config);
} else {
*http_connection_manager.mutable_route_config() = route_config;
}
api_listener->PackFrom(http_connection_manager);
balancers_[idx]->ads_service()->SetLdsResource(listener);
}
void SetRouteConfiguration(int idx, const RouteConfiguration& route_config) {
if (GetParam().enable_rds_testing()) {
balancers_[idx]->ads_service()->SetRdsResource(route_config);
} else {
balancers_[idx]->ads_service()->SetLdsResource(
BuildListener(route_config));
}
}
AdsServiceImpl::ResponseState RouteConfigurationResponseState(int idx) const {
AdsServiceImpl* ads_service = balancers_[idx]->ads_service();
if (GetParam().enable_rds_testing()) {
return ads_service->rds_response_state();
}
return ads_service->lds_response_state();
}
public:
// This method could benefit test subclasses; to make it accessible
// via bind with a qualified name, it needs to be public.
void SetEdsResourceWithDelay(size_t i,
const ClusterLoadAssignment& assignment,
int delay_ms) {
GPR_ASSERT(delay_ms > 0);
gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(delay_ms));
balancers_[i]->ads_service()->SetEdsResource(assignment);
}
protected:
class XdsServingStatusNotifier
: public grpc::experimental::XdsServerServingStatusNotifierInterface {
public:
void OnServingStatusChange(std::string uri, grpc::Status status) override {
grpc_core::MutexLock lock(&mu_);
status_map[uri] = status;
cond_.Signal();
}
void WaitOnServingStatusChange(std::string uri,
grpc::StatusCode expected_status) {
grpc_core::MutexLock lock(&mu_);
std::map<std::string, grpc::Status>::iterator it;
while ((it = status_map.find(uri)) == status_map.end() ||
it->second.error_code() != expected_status) {
cond_.Wait(&mu_);
}
}
private:
grpc_core::Mutex mu_;
grpc_core::CondVar cond_;
std::map<std::string, grpc::Status> status_map;
};
class ServerThread {
public:
explicit ServerThread(bool use_xds_enabled_server = false)
: port_(grpc_pick_unused_port_or_die()),
use_xds_enabled_server_(use_xds_enabled_server) {}
virtual ~ServerThread(){};
void Start() {
gpr_log(GPR_INFO, "starting %s server on port %d", Type(), port_);
GPR_ASSERT(!running_);
running_ = true;
StartAllServices();
grpc_core::Mutex mu;
// We need to acquire the lock here in order to prevent the notify_one
// by ServerThread::Serve from firing before the wait below is hit.
grpc_core::MutexLock lock(&mu);
grpc_core::CondVar cond;
thread_ = absl::make_unique<std::thread>(
std::bind(&ServerThread::Serve, this, &mu, &cond));
cond.Wait(&mu);
gpr_log(GPR_INFO, "%s server startup complete", Type());
}
void Serve(grpc_core::Mutex* mu, grpc_core::CondVar* cond) {
// We need to acquire the lock here in order to prevent the notify_one
// below from firing before its corresponding wait is executed.
grpc_core::MutexLock lock(mu);
std::ostringstream server_address;
server_address << "localhost:" << port_;
if (use_xds_enabled_server_) {
experimental::XdsServerBuilder builder;
builder.set_status_notifier(¬ifier_);
builder.AddListeningPort(server_address.str(), Credentials());
RegisterAllServices(&builder);
server_ = builder.BuildAndStart();
} else {
ServerBuilder builder;
builder.AddListeningPort(server_address.str(), Credentials());
RegisterAllServices(&builder);
server_ = builder.BuildAndStart();
}
cond->Signal();
}
void Shutdown() {
if (!running_) return;
gpr_log(GPR_INFO, "%s about to shutdown", Type());
ShutdownAllServices();
server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
thread_->join();
gpr_log(GPR_INFO, "%s shutdown completed", Type());
running_ = false;
}
virtual std::shared_ptr<ServerCredentials> Credentials() {
return std::make_shared<SecureServerCredentials>(
grpc_fake_transport_security_server_credentials_create());
}
int port() const { return port_; }
bool use_xds_enabled_server() const { return use_xds_enabled_server_; }
XdsServingStatusNotifier* notifier() { return ¬ifier_; }
private:
virtual void RegisterAllServices(ServerBuilder* builder) = 0;
virtual void StartAllServices() = 0;
virtual void ShutdownAllServices() = 0;
virtual const char* Type() = 0;
const int port_;
std::unique_ptr<Server> server_;
XdsServingStatusNotifier notifier_;
std::unique_ptr<std::thread> thread_;
bool running_ = false;
const bool use_xds_enabled_server_;
};
class BackendServerThread : public ServerThread {
public:
explicit BackendServerThread(bool use_xds_enabled_server)
: ServerThread(use_xds_enabled_server) {}
BackendServiceImpl<::grpc::testing::EchoTestService::Service>*
backend_service() {
return &backend_service_;
}
BackendServiceImpl<::grpc::testing::EchoTest1Service::Service>*
backend_service1() {
return &backend_service1_;
}
BackendServiceImpl<::grpc::testing::EchoTest2Service::Service>*
backend_service2() {
return &backend_service2_;
}
std::shared_ptr<ServerCredentials> Credentials() override {
if (GetParam().use_xds_credentials()) {
if (use_xds_enabled_server()) {
// We are testing server's use of XdsServerCredentials
return experimental::XdsServerCredentials(
InsecureServerCredentials());
} else {
// We are testing client's use of XdsCredentials
std::string root_cert = ReadFile(kCaCertPath);
std::string identity_cert = ReadFile(kServerCertPath);
std::string private_key = ReadFile(kServerKeyPath);
std::vector<experimental::IdentityKeyCertPair>
identity_key_cert_pairs = {{private_key, identity_cert}};
auto certificate_provider = std::make_shared<
grpc::experimental::StaticDataCertificateProvider>(
root_cert, identity_key_cert_pairs);
grpc::experimental::TlsServerCredentialsOptions options(
certificate_provider);
options.watch_root_certs();
options.watch_identity_key_cert_pairs();
options.set_cert_request_type(
GRPC_SSL_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY);
return grpc::experimental::TlsServerCredentials(options);
}
}
return ServerThread::Credentials();
}
private:
void RegisterAllServices(ServerBuilder* builder) override {
builder->RegisterService(&backend_service_);
builder->RegisterService(&backend_service1_);
builder->RegisterService(&backend_service2_);
}
void StartAllServices() override {
backend_service_.Start();
backend_service1_.Start();
backend_service2_.Start();
}
void ShutdownAllServices() override {
backend_service_.Shutdown();
backend_service1_.Shutdown();
backend_service2_.Shutdown();
}
const char* Type() override { return "Backend"; }
BackendServiceImpl<::grpc::testing::EchoTestService::Service>
backend_service_;
BackendServiceImpl<::grpc::testing::EchoTest1Service::Service>
backend_service1_;
BackendServiceImpl<::grpc::testing::EchoTest2Service::Service>
backend_service2_;
};
class BalancerServerThread : public ServerThread {
public:
explicit BalancerServerThread(int client_load_reporting_interval = 0)
: ads_service_(new AdsServiceImpl()),
lrs_service_(new LrsServiceImpl(client_load_reporting_interval)) {}
AdsServiceImpl* ads_service() { return ads_service_.get(); }
LrsServiceImpl* lrs_service() { return lrs_service_.get(); }
private:
void RegisterAllServices(ServerBuilder* builder) override {
builder->RegisterService(ads_service_->v2_rpc_service());
builder->RegisterService(ads_service_->v3_rpc_service());
builder->RegisterService(lrs_service_->v2_rpc_service());
builder->RegisterService(lrs_service_->v3_rpc_service());
}
void StartAllServices() override {
ads_service_->Start();
lrs_service_->Start();
}
void ShutdownAllServices() override {
ads_service_->Shutdown();
lrs_service_->Shutdown();
}
const char* Type() override { return "Balancer"; }
std::shared_ptr<AdsServiceImpl> ads_service_;
std::shared_ptr<LrsServiceImpl> lrs_service_;
};
#ifndef DISABLED_XDS_PROTO_IN_CC
class AdminServerThread : public ServerThread {
private:
void RegisterAllServices(ServerBuilder* builder) override {
builder->RegisterService(&csds_service_);
}
void StartAllServices() override {}
void ShutdownAllServices() override {}
const char* Type() override { return "Admin"; }
grpc::xds::experimental::ClientStatusDiscoveryService csds_service_;
};
#endif // DISABLED_XDS_PROTO_IN_CC
class LongRunningRpc {
public:
void StartRpc(grpc::testing::EchoTestService::Stub* stub,
const RpcOptions& rpc_options =
RpcOptions().set_client_cancel_after_us(1 * 1000 *
1000)) {
sender_thread_ = std::thread([this, stub, rpc_options]() {
EchoRequest request;
EchoResponse response;
rpc_options.SetupRpc(&context_, &request);
status_ = stub->Echo(&context_, request, &response);
});
}
void CancelRpc() {
context_.TryCancel();
if (sender_thread_.joinable()) sender_thread_.join();
}
Status GetStatus() {
if (sender_thread_.joinable()) sender_thread_.join();
return status_;
}
private:
std::thread sender_thread_;
ClientContext context_;
Status status_;
};
const size_t num_backends_;
const size_t num_balancers_;
const int client_load_reporting_interval_seconds_;
bool ipv6_only_ = false;
std::shared_ptr<Channel> channel_;
std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
std::unique_ptr<grpc::testing::EchoTest1Service::Stub> stub1_;
std::unique_ptr<grpc::testing::EchoTest2Service::Stub> stub2_;
std::vector<std::unique_ptr<BackendServerThread>> backends_;
std::vector<std::unique_ptr<BalancerServerThread>> balancers_;
grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
response_generator_;
grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
lb_channel_response_generator_;
grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
logical_dns_cluster_resolver_response_generator_;
int xds_resource_does_not_exist_timeout_ms_ = 0;
absl::InlinedVector<grpc_arg, 2> xds_channel_args_to_add_;
grpc_channel_args xds_channel_args_;
Listener default_listener_;
RouteConfiguration default_route_config_;
Cluster default_cluster_;
bool use_xds_enabled_server_;
bool bootstrap_contents_from_env_var_;
};
class BasicTest : public XdsEnd2endTest {
public:
BasicTest() : XdsEnd2endTest(4, 1) {}
};
// Tests that the balancer sends the correct response to the client, and the
// client sends RPCs to the backends using the default child policy.
TEST_P(BasicTest, Vanilla) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcsPerAddress = 100;
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Make sure that trying to connect works without a call.
channel_->GetState(true /* try_to_connect */);
// We need to wait for all backends to come online.
WaitForAllBackends();
// Send kNumRpcsPerAddress RPCs per server.
CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
// Each backend should have gotten 100 requests.
for (size_t i = 0; i < backends_.size(); ++i) {
EXPECT_EQ(kNumRpcsPerAddress,
backends_[i]->backend_service()->request_count());
}
// Check LB policy name for the channel.
EXPECT_EQ(
(GetParam().use_fake_resolver() ? "xds_cluster_resolver_experimental"
: "xds_cluster_manager_experimental"),
channel_->GetLoadBalancingPolicyName());
}
TEST_P(BasicTest, IgnoresUnhealthyEndpoints) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcsPerAddress = 100;
AdsServiceImpl::EdsResourceArgs args({
{"locality0",
GetBackendPorts(),
kDefaultLocalityWeight,
kDefaultLocalityPriority,
{HealthStatus::DRAINING}},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Make sure that trying to connect works without a call.
channel_->GetState(true /* try_to_connect */);
// We need to wait for all backends to come online.
WaitForAllBackends(/*start_index=*/1);
// Send kNumRpcsPerAddress RPCs per server.
CheckRpcSendOk(kNumRpcsPerAddress * (num_backends_ - 1));
// Each backend should have gotten 100 requests.
for (size_t i = 1; i < backends_.size(); ++i) {
EXPECT_EQ(kNumRpcsPerAddress,
backends_[i]->backend_service()->request_count());
}
}
// Tests that subchannel sharing works when the same backend is listed multiple
// times.
TEST_P(BasicTest, SameBackendListedMultipleTimes) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Same backend listed twice.
std::vector<int> ports(2, backends_[0]->port());
AdsServiceImpl::EdsResourceArgs args({
{"locality0", ports},
});
const size_t kNumRpcsPerAddress = 10;
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// We need to wait for the backend to come online.
WaitForBackend(0);
// Send kNumRpcsPerAddress RPCs per server.
CheckRpcSendOk(kNumRpcsPerAddress * ports.size());
// Backend should have gotten 20 requests.
EXPECT_EQ(kNumRpcsPerAddress * ports.size(),
backends_[0]->backend_service()->request_count());
// And they should have come from a single client port, because of
// subchannel sharing.
EXPECT_EQ(1UL, backends_[0]->backend_service()->clients().size());
}
// Tests that RPCs will be blocked until a non-empty serverlist is received.
TEST_P(BasicTest, InitiallyEmptyServerlist) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor();
const int kCallDeadlineMs = kServerlistDelayMs * 2;
// First response is an empty serverlist, sent right away.
AdsServiceImpl::EdsResourceArgs::Locality empty_locality("locality0", {});
AdsServiceImpl::EdsResourceArgs args({
empty_locality,
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Send non-empty serverlist only after kServerlistDelayMs.
args = AdsServiceImpl::EdsResourceArgs({
{"locality0", GetBackendPorts()},
});
std::thread delayed_resource_setter(std::bind(
&BasicTest::SetEdsResourceWithDelay, this, 0,
BuildEdsResource(args, DefaultEdsServiceName()), kServerlistDelayMs));
const auto t0 = system_clock::now();
// Client will block: LB will initially send empty serverlist.
CheckRpcSendOk(
1, RpcOptions().set_timeout_ms(kCallDeadlineMs).set_wait_for_ready(true));
const auto ellapsed_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(
system_clock::now() - t0);
// but eventually, the LB sends a serverlist update that allows the call to
// proceed. The call delay must be larger than the delay in sending the
// populated serverlist but under the call's deadline (which is enforced by
// the call's deadline).
EXPECT_GT(ellapsed_ms.count(), kServerlistDelayMs);
delayed_resource_setter.join();
}
// Tests that RPCs will fail with UNAVAILABLE instead of DEADLINE_EXCEEDED if
// all the servers are unreachable.
TEST_P(BasicTest, AllServersUnreachableFailFast) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumUnreachableServers = 5;
std::vector<int> ports;
for (size_t i = 0; i < kNumUnreachableServers; ++i) {
ports.push_back(grpc_pick_unused_port_or_die());
}
AdsServiceImpl::EdsResourceArgs args({
{"locality0", ports},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
const Status status = SendRpc();
// The error shouldn't be DEADLINE_EXCEEDED.
EXPECT_EQ(StatusCode::UNAVAILABLE, status.error_code());
}
// Tests that RPCs fail when the backends are down, and will succeed again after
// the backends are restarted.
TEST_P(BasicTest, BackendsRestart) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
WaitForAllBackends();
// Stop backends. RPCs should fail.
ShutdownAllBackends();
// Sending multiple failed requests instead of just one to ensure that the
// client notices that all backends are down before we restart them. If we
// didn't do this, then a single RPC could fail here due to the race condition
// between the LB pick and the GOAWAY from the chosen backend being shut down,
// which would not actually prove that the client noticed that all of the
// backends are down. Then, when we send another request below (which we
// expect to succeed), if the callbacks happen in the wrong order, the same
// race condition could happen again due to the client not yet having noticed
// that the backends were all down.
CheckRpcSendFailure(num_backends_);
// Restart all backends. RPCs should start succeeding again.
StartAllBackends();
CheckRpcSendOk(1, RpcOptions().set_timeout_ms(2000).set_wait_for_ready(true));
}
TEST_P(BasicTest, IgnoresDuplicateUpdates) {
const size_t kNumRpcsPerAddress = 100;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait for all backends to come online.
WaitForAllBackends();
// Send kNumRpcsPerAddress RPCs per server, but send an EDS update in
// between. If the update is not ignored, this will cause the
// round_robin policy to see an update, which will randomly reset its
// position in the address list.
for (size_t i = 0; i < kNumRpcsPerAddress; ++i) {
CheckRpcSendOk(2);
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
CheckRpcSendOk(2);
}
// Each backend should have gotten the right number of requests.
for (size_t i = 1; i < backends_.size(); ++i) {
EXPECT_EQ(kNumRpcsPerAddress,
backends_[i]->backend_service()->request_count());
}
}
using XdsResolverOnlyTest = BasicTest;
TEST_P(XdsResolverOnlyTest, ResourceTypeVersionPersistsAcrossStreamRestarts) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
// Wait for backends to come online.
WaitForAllBackends(0, 1);
// Stop balancer.
balancers_[0]->Shutdown();
// Tell balancer to require minimum version 1 for all resource types.
balancers_[0]->ads_service()->SetResourceMinVersion(kLdsTypeUrl, 1);
balancers_[0]->ads_service()->SetResourceMinVersion(kRdsTypeUrl, 1);
balancers_[0]->ads_service()->SetResourceMinVersion(kCdsTypeUrl, 1);
balancers_[0]->ads_service()->SetResourceMinVersion(kEdsTypeUrl, 1);
// Update backend, just so we can be sure that the client has
// reconnected to the balancer.
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(1, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args2));
// Restart balancer.
balancers_[0]->Start();
// Make sure client has reconnected.
WaitForAllBackends(1, 2);
}
// Tests switching over from one cluster to another.
TEST_P(XdsResolverOnlyTest, ChangeClusters) {
const char* kNewClusterName = "new_cluster_name";
const char* kNewEdsServiceName = "new_eds_service_name";
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
// We need to wait for all backends to come online.
WaitForAllBackends(0, 2);
// Populate new EDS resource.
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 4)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsServiceName));
// Populate new CDS resource.
Cluster new_cluster = default_cluster_;
new_cluster.set_name(kNewClusterName);
new_cluster.mutable_eds_cluster_config()->set_service_name(
kNewEdsServiceName);
balancers_[0]->ads_service()->SetCdsResource(new_cluster);
// Change RDS resource to point to new cluster.
RouteConfiguration new_route_config = default_route_config_;
new_route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->set_cluster(kNewClusterName);
SetListenerAndRouteConfiguration(0, default_listener_, new_route_config);
// Wait for all new backends to be used.
std::tuple<int, int, int> counts = WaitForAllBackends(2, 4);
// Make sure no RPCs failed in the transition.
EXPECT_EQ(0, std::get<1>(counts));
}
// Tests that we go into TRANSIENT_FAILURE if the Cluster disappears.
TEST_P(XdsResolverOnlyTest, ClusterRemoved) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
// We need to wait for all backends to come online.
WaitForAllBackends();
// Unset CDS resource.
balancers_[0]->ads_service()->UnsetResource(kCdsTypeUrl, kDefaultClusterName);
// Wait for RPCs to start failing.
do {
} while (SendRpc(RpcOptions(), nullptr).ok());
// Make sure RPCs are still failing.
CheckRpcSendFailure(1000);
// Make sure we ACK'ed the update.
EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state().state,
AdsServiceImpl::ResponseState::ACKED);
}
// Tests that we restart all xDS requests when we reestablish the ADS call.
TEST_P(XdsResolverOnlyTest, RestartsRequestsUponReconnection) {
// Manually configure use of RDS.
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* rds = http_connection_manager.mutable_rds();
rds->set_route_config_name(kDefaultRouteConfigurationName);
rds->mutable_config_source()->mutable_ads();
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
balancers_[0]->ads_service()->SetLdsResource(listener);
balancers_[0]->ads_service()->SetRdsResource(default_route_config_);
const char* kNewClusterName = "new_cluster_name";
const char* kNewEdsServiceName = "new_eds_service_name";
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
// We need to wait for all backends to come online.
WaitForAllBackends(0, 2);
// Now shut down and restart the balancer. When the client
// reconnects, it should automatically restart the requests for all
// resource types.
balancers_[0]->Shutdown();
balancers_[0]->Start();
// Make sure things are still working.
CheckRpcSendOk(100);
// Populate new EDS resource.
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 4)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsServiceName));
// Populate new CDS resource.
Cluster new_cluster = default_cluster_;
new_cluster.set_name(kNewClusterName);
new_cluster.mutable_eds_cluster_config()->set_service_name(
kNewEdsServiceName);
balancers_[0]->ads_service()->SetCdsResource(new_cluster);
// Change RDS resource to point to new cluster.
RouteConfiguration new_route_config = default_route_config_;
new_route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->set_cluster(kNewClusterName);
balancers_[0]->ads_service()->SetRdsResource(new_route_config);
// Wait for all new backends to be used.
std::tuple<int, int, int> counts = WaitForAllBackends(2, 4);
// Make sure no RPCs failed in the transition.
EXPECT_EQ(0, std::get<1>(counts));
}
TEST_P(XdsResolverOnlyTest, DefaultRouteSpecifiesSlashPrefix) {
RouteConfiguration route_config = default_route_config_;
route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_match()
->set_prefix("/");
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
// We need to wait for all backends to come online.
WaitForAllBackends();
}
TEST_P(XdsResolverOnlyTest, CircuitBreaking) {
constexpr size_t kMaxConcurrentRequests = 10;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
// Update CDS resource to set max concurrent request.
CircuitBreakers circuit_breaks;
Cluster cluster = default_cluster_;
auto* threshold = cluster.mutable_circuit_breakers()->add_thresholds();
threshold->set_priority(RoutingPriority::DEFAULT);
threshold->mutable_max_requests()->set_value(kMaxConcurrentRequests);
balancers_[0]->ads_service()->SetCdsResource(cluster);
// Send exactly max_concurrent_requests long RPCs.
LongRunningRpc rpcs[kMaxConcurrentRequests];
for (size_t i = 0; i < kMaxConcurrentRequests; ++i) {
rpcs[i].StartRpc(stub_.get());
}
// Wait for all RPCs to be in flight.
while (backends_[0]->backend_service()->RpcsWaitingForClientCancel() <
kMaxConcurrentRequests) {
gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_micros(1 * 1000, GPR_TIMESPAN)));
}
// Sending a RPC now should fail, the error message should tell us
// we hit the max concurrent requests limit and got dropped.
Status status = SendRpc();
EXPECT_FALSE(status.ok());
EXPECT_EQ(status.error_message(), "Call dropped by load balancing policy");
// Cancel one RPC to allow another one through
rpcs[0].CancelRpc();
status = SendRpc();
EXPECT_TRUE(status.ok());
for (size_t i = 1; i < kMaxConcurrentRequests; ++i) {
rpcs[i].CancelRpc();
}
// Make sure RPCs go to the correct backend:
EXPECT_EQ(kMaxConcurrentRequests + 1,
backends_[0]->backend_service()->request_count());
}
TEST_P(XdsResolverOnlyTest, CircuitBreakingMultipleChannelsShareCallCounter) {
constexpr size_t kMaxConcurrentRequests = 10;
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
// Update CDS resource to set max concurrent request.
CircuitBreakers circuit_breaks;
Cluster cluster = default_cluster_;
auto* threshold = cluster.mutable_circuit_breakers()->add_thresholds();
threshold->set_priority(RoutingPriority::DEFAULT);
threshold->mutable_max_requests()->set_value(kMaxConcurrentRequests);
balancers_[0]->ads_service()->SetCdsResource(cluster);
// Create second channel.
auto response_generator2 =
grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
auto channel2 = CreateChannel(
/*failover_timeout=*/0, /*server_name=*/kServerName,
response_generator2.get());
auto stub2 = grpc::testing::EchoTestService::NewStub(channel2);
// Set resolution results for both channels and for the xDS channel.
SetNextResolution({});
SetNextResolution({}, response_generator2.get());
SetNextResolutionForLbChannelAllBalancers();
// Send exactly max_concurrent_requests long RPCs, alternating between
// the two channels.
LongRunningRpc rpcs[kMaxConcurrentRequests];
for (size_t i = 0; i < kMaxConcurrentRequests; ++i) {
rpcs[i].StartRpc(i % 2 == 0 ? stub_.get() : stub2.get());
}
// Wait for all RPCs to be in flight.
while (backends_[0]->backend_service()->RpcsWaitingForClientCancel() <
kMaxConcurrentRequests) {
gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_micros(1 * 1000, GPR_TIMESPAN)));
}
// Sending a RPC now should fail, the error message should tell us
// we hit the max concurrent requests limit and got dropped.
Status status = SendRpc();
EXPECT_FALSE(status.ok());
EXPECT_EQ(status.error_message(), "Call dropped by load balancing policy");
// Cancel one RPC to allow another one through
rpcs[0].CancelRpc();
status = SendRpc();
EXPECT_TRUE(status.ok());
for (size_t i = 1; i < kMaxConcurrentRequests; ++i) {
rpcs[i].CancelRpc();
}
// Make sure RPCs go to the correct backend:
EXPECT_EQ(kMaxConcurrentRequests + 1,
backends_[0]->backend_service()->request_count());
}
TEST_P(XdsResolverOnlyTest, MultipleChannelsShareXdsClient) {
const char* kNewServerName = "new-server.example.com";
Listener listener = default_listener_;
listener.set_name(kNewServerName);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
WaitForAllBackends();
// Create second channel and tell it to connect to kNewServerName.
auto channel2 = CreateChannel(/*failover_timeout=*/0, kNewServerName);
channel2->GetState(/*try_to_connect=*/true);
ASSERT_TRUE(
channel2->WaitForConnected(grpc_timeout_milliseconds_to_deadline(100)));
// Make sure there's only one client connected.
EXPECT_EQ(1UL, balancers_[0]->ads_service()->clients().size());
}
class XdsResolverLoadReportingOnlyTest : public XdsEnd2endTest {
public:
XdsResolverLoadReportingOnlyTest() : XdsEnd2endTest(4, 1, 3) {}
};
// Tests load reporting when switching over from one cluster to another.
TEST_P(XdsResolverLoadReportingOnlyTest, ChangeClusters) {
const char* kNewClusterName = "new_cluster_name";
const char* kNewEdsServiceName = "new_eds_service_name";
balancers_[0]->lrs_service()->set_cluster_names(
{kDefaultClusterName, kNewClusterName});
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// cluster kDefaultClusterName -> locality0 -> backends 0 and 1
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
// cluster kNewClusterName -> locality1 -> backends 2 and 3
AdsServiceImpl::EdsResourceArgs args2({
{"locality1", GetBackendPorts(2, 4)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsServiceName));
// CDS resource for kNewClusterName.
Cluster new_cluster = default_cluster_;
new_cluster.set_name(kNewClusterName);
new_cluster.mutable_eds_cluster_config()->set_service_name(
kNewEdsServiceName);
balancers_[0]->ads_service()->SetCdsResource(new_cluster);
// Wait for all backends to come online.
int num_ok = 0;
int num_failure = 0;
int num_drops = 0;
std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends(0, 2);
// The load report received at the balancer should be correct.
std::vector<ClientStats> load_report =
balancers_[0]->lrs_service()->WaitForLoadReport();
EXPECT_THAT(
load_report,
::testing::ElementsAre(::testing::AllOf(
::testing::Property(&ClientStats::cluster_name, kDefaultClusterName),
::testing::Property(
&ClientStats::locality_stats,
::testing::ElementsAre(::testing::Pair(
"locality0",
::testing::AllOf(
::testing::Field(&ClientStats::LocalityStats::
total_successful_requests,
num_ok),
::testing::Field(&ClientStats::LocalityStats::
total_requests_in_progress,
0UL),
::testing::Field(
&ClientStats::LocalityStats::total_error_requests,
num_failure),
::testing::Field(
&ClientStats::LocalityStats::total_issued_requests,
num_failure + num_ok))))),
::testing::Property(&ClientStats::total_dropped_requests,
num_drops))));
// Change RDS resource to point to new cluster.
RouteConfiguration new_route_config = default_route_config_;
new_route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->set_cluster(kNewClusterName);
SetListenerAndRouteConfiguration(0, default_listener_, new_route_config);
// Wait for all new backends to be used.
std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends(2, 4);
// The load report received at the balancer should be correct.
load_report = balancers_[0]->lrs_service()->WaitForLoadReport();
EXPECT_THAT(
load_report,
::testing::ElementsAre(
::testing::AllOf(
::testing::Property(&ClientStats::cluster_name,
kDefaultClusterName),
::testing::Property(
&ClientStats::locality_stats,
::testing::ElementsAre(::testing::Pair(
"locality0",
::testing::AllOf(
::testing::Field(&ClientStats::LocalityStats::
total_successful_requests,
::testing::Lt(num_ok)),
::testing::Field(&ClientStats::LocalityStats::
total_requests_in_progress,
0UL),
::testing::Field(
&ClientStats::LocalityStats::total_error_requests,
::testing::Le(num_failure)),
::testing::Field(
&ClientStats::LocalityStats::
total_issued_requests,
::testing::Le(num_failure + num_ok)))))),
::testing::Property(&ClientStats::total_dropped_requests,
num_drops)),
::testing::AllOf(
::testing::Property(&ClientStats::cluster_name, kNewClusterName),
::testing::Property(
&ClientStats::locality_stats,
::testing::ElementsAre(::testing::Pair(
"locality1",
::testing::AllOf(
::testing::Field(&ClientStats::LocalityStats::
total_successful_requests,
::testing::Le(num_ok)),
::testing::Field(&ClientStats::LocalityStats::
total_requests_in_progress,
0UL),
::testing::Field(
&ClientStats::LocalityStats::total_error_requests,
::testing::Le(num_failure)),
::testing::Field(
&ClientStats::LocalityStats::
total_issued_requests,
::testing::Le(num_failure + num_ok)))))),
::testing::Property(&ClientStats::total_dropped_requests,
num_drops))));
int total_ok = 0;
int total_failure = 0;
for (const ClientStats& client_stats : load_report) {
total_ok += client_stats.total_successful_requests();
total_failure += client_stats.total_error_requests();
}
EXPECT_EQ(total_ok, num_ok);
EXPECT_EQ(total_failure, num_failure);
// The LRS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->lrs_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->lrs_service()->response_count());
}
using SecureNamingTest = BasicTest;
// Tests that secure naming check passes if target name is expected.
TEST_P(SecureNamingTest, TargetNameIsExpected) {
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()}, nullptr, "xds_server");
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
CheckRpcSendOk();
}
// Tests that secure naming check fails if target name is unexpected.
TEST_P(SecureNamingTest, TargetNameIsUnexpected) {
::testing::FLAGS_gtest_death_test_style = "threadsafe";
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()}, nullptr,
"incorrect_server_name");
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Make sure that we blow up (via abort() from the security connector) when
// the name from the balancer doesn't match expectations.
ASSERT_DEATH_IF_SUPPORTED({ CheckRpcSendOk(); }, "");
}
using LdsTest = BasicTest;
// Tests that LDS client should send a NACK if there is no API listener in the
// Listener in the LDS response.
TEST_P(LdsTest, NoApiListener) {
auto listener = default_listener_;
listener.clear_api_listener();
balancers_[0]->ads_service()->SetLdsResource(listener);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("Listener has neither address nor ApiListener"));
}
// Tests that LDS client should send a NACK if the route_specifier in the
// http_connection_manager is neither inlined route_config nor RDS.
TEST_P(LdsTest, WrongRouteSpecifier) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
http_connection_manager.mutable_scoped_routes();
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
balancers_[0]->ads_service()->SetLdsResource(listener);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr(
"HttpConnectionManager neither has inlined route_config nor RDS."));
}
// Tests that LDS client should send a NACK if the rds message in the
// http_connection_manager is missing the config_source field.
TEST_P(LdsTest, RdsMissingConfigSource) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
http_connection_manager.mutable_rds()->set_route_config_name(
kDefaultRouteConfigurationName);
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
balancers_[0]->ads_service()->SetLdsResource(listener);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"HttpConnectionManager missing config_source for RDS."));
}
// Tests that LDS client should send a NACK if the rds message in the
// http_connection_manager has a config_source field that does not specify ADS.
TEST_P(LdsTest, RdsConfigSourceDoesNotSpecifyAds) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* rds = http_connection_manager.mutable_rds();
rds->set_route_config_name(kDefaultRouteConfigurationName);
rds->mutable_config_source()->mutable_self();
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
balancers_[0]->ads_service()->SetLdsResource(listener);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr(
"HttpConnectionManager ConfigSource for RDS does not specify ADS."));
}
// Tests that the NACK for multiple bad LDS resources includes both errors.
TEST_P(LdsTest, MultipleBadResources) {
constexpr char kServerName2[] = "server.other.com";
auto listener = default_listener_;
listener.clear_api_listener();
balancers_[0]->ads_service()->SetLdsResource(listener);
listener.set_name(kServerName2);
balancers_[0]->ads_service()->SetLdsResource(listener);
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
// Need to create a second channel to subscribe to a second LDS resource.
auto channel2 = CreateChannel(0, kServerName2);
auto stub2 = grpc::testing::EchoTestService::NewStub(channel2);
ClientContext context;
EchoRequest request;
request.set_message(kRequestMessage);
EchoResponse response;
grpc::Status status = stub2->Echo(&context, request, &response);
EXPECT_FALSE(status.ok());
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::AllOf(
::testing::HasSubstr(absl::StrCat(
kServerName, ": Listener has neither address nor ApiListener")),
::testing::HasSubstr(
absl::StrCat(kServerName2,
": Listener has neither address nor ApiListener"))));
}
// Tests that we ignore filters after the router filter.
TEST_P(LdsTest, IgnoresHttpFiltersAfterRouterFilter) {
SetNextResolutionForLbChannelAllBalancers();
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* filter = http_connection_manager.add_http_filters();
filter->set_name("unknown");
filter->mutable_typed_config()->set_type_url(
"grpc.testing.client_only_http_filter");
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
WaitForAllBackends();
}
// Test that we fail RPCs if there is no router filter.
TEST_P(LdsTest, FailRpcsIfNoHttpRouterFilter) {
SetNextResolutionForLbChannelAllBalancers();
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
http_connection_manager.clear_http_filters();
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
Status status = SendRpc();
EXPECT_EQ(status.error_code(), StatusCode::UNAVAILABLE);
EXPECT_EQ(status.error_message(), "no xDS HTTP router filter configured");
// Wait until xDS server sees ACK.
while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT) {
CheckRpcSendFailure();
}
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
}
// Test that we NACK empty filter names.
TEST_P(LdsTest, RejectsEmptyHttpFilterName) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* filter = http_connection_manager.add_http_filters();
filter->mutable_typed_config()->PackFrom(Listener());
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("empty filter name at index 1"));
}
// Test that we NACK duplicate HTTP filter names.
TEST_P(LdsTest, RejectsDuplicateHttpFilterName) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
*http_connection_manager.add_http_filters() =
http_connection_manager.http_filters(0);
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("duplicate HTTP filter name: router"));
}
// Test that we NACK unknown filter types.
TEST_P(LdsTest, RejectsUnknownHttpFilterType) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* filter = http_connection_manager.add_http_filters();
filter->set_name("unknown");
filter->mutable_typed_config()->PackFrom(Listener());
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("no filter registered for config type "
"envoy.config.listener.v3.Listener"));
}
// Test that we ignore optional unknown filter types.
TEST_P(LdsTest, IgnoresOptionalUnknownHttpFilterType) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* filter = http_connection_manager.add_http_filters();
filter->set_name("unknown");
filter->mutable_typed_config()->PackFrom(Listener());
filter->set_is_optional(true);
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolutionForLbChannelAllBalancers();
WaitForAllBackends();
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state().state,
AdsServiceImpl::ResponseState::ACKED);
}
// Test that we NACK filters without configs.
TEST_P(LdsTest, RejectsHttpFilterWithoutConfig) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* filter = http_connection_manager.add_http_filters();
filter->set_name("unknown");
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"no filter config specified for filter name unknown"));
}
// Test that we ignore optional filters without configs.
TEST_P(LdsTest, IgnoresOptionalHttpFilterWithoutConfig) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* filter = http_connection_manager.add_http_filters();
filter->set_name("unknown");
filter->set_is_optional(true);
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolutionForLbChannelAllBalancers();
WaitForAllBackends();
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state().state,
AdsServiceImpl::ResponseState::ACKED);
}
// Test that we NACK unparseable filter configs.
TEST_P(LdsTest, RejectsUnparseableHttpFilterType) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* filter = http_connection_manager.add_http_filters();
filter->set_name("unknown");
filter->mutable_typed_config()->PackFrom(listener);
filter->mutable_typed_config()->set_type_url(
"type.googleapis.com/envoy.extensions.filters.http.router.v3.Router");
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr(
"filter config for type "
"envoy.extensions.filters.http.router.v3.Router failed to parse"));
}
// Test that we NACK HTTP filters unsupported on client-side.
TEST_P(LdsTest, RejectsHttpFiltersNotSupportedOnClients) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* filter = http_connection_manager.add_http_filters();
filter->set_name("grpc.testing.server_only_http_filter");
filter->mutable_typed_config()->set_type_url(
"grpc.testing.server_only_http_filter");
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("Filter grpc.testing.server_only_http_filter is not "
"supported on clients"));
}
// Test that we ignore optional HTTP filters unsupported on client-side.
TEST_P(LdsTest, IgnoresOptionalHttpFiltersNotSupportedOnClients) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* filter = http_connection_manager.add_http_filters();
filter->set_name("grpc.testing.server_only_http_filter");
filter->mutable_typed_config()->set_type_url(
"grpc.testing.server_only_http_filter");
filter->set_is_optional(true);
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
WaitForBackend(0);
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state().state,
AdsServiceImpl::ResponseState::ACKED);
}
using LdsV2Test = LdsTest;
// Tests that we ignore the HTTP filter list in v2.
// TODO(roth): The test framework is not set up to allow us to test
// the server sending v2 resources when the client requests v3, so this
// just tests a pure v2 setup. When we have time, fix this.
TEST_P(LdsV2Test, IgnoresHttpFilters) {
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
auto* filter = http_connection_manager.add_http_filters();
filter->set_name("unknown");
filter->mutable_typed_config()->PackFrom(Listener());
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendOk();
}
using LdsRdsTest = BasicTest;
// Tests that LDS client should send an ACK upon correct LDS response (with
// inlined RDS result).
TEST_P(LdsRdsTest, Vanilla) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
EXPECT_EQ(RouteConfigurationResponseState(0).state,
AdsServiceImpl::ResponseState::ACKED);
// Make sure we actually used the RPC service for the right version of xDS.
EXPECT_EQ(balancers_[0]->ads_service()->seen_v2_client(),
GetParam().use_v2());
EXPECT_NE(balancers_[0]->ads_service()->seen_v3_client(),
GetParam().use_v2());
}
// Tests that we go into TRANSIENT_FAILURE if the Listener is removed.
TEST_P(LdsRdsTest, ListenerRemoved) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
// We need to wait for all backends to come online.
WaitForAllBackends();
// Unset LDS resource.
balancers_[0]->ads_service()->UnsetResource(kLdsTypeUrl, kServerName);
// Wait for RPCs to start failing.
do {
} while (SendRpc(RpcOptions(), nullptr).ok());
// Make sure RPCs are still failing.
CheckRpcSendFailure(1000);
// Make sure we ACK'ed the update.
EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state().state,
AdsServiceImpl::ResponseState::ACKED);
}
// Tests that LDS client ACKs but fails if matching domain can't be found in
// the LDS response.
TEST_P(LdsRdsTest, NoMatchedDomain) {
RouteConfiguration route_config = default_route_config_;
route_config.mutable_virtual_hosts(0)->clear_domains();
route_config.mutable_virtual_hosts(0)->add_domains("unmatched_domain");
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
// Do a bit of polling, to allow the ACK to get to the ADS server.
channel_->WaitForConnected(grpc_timeout_milliseconds_to_deadline(100));
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
}
// Tests that LDS client should choose the virtual host with matching domain if
// multiple virtual hosts exist in the LDS response.
TEST_P(LdsRdsTest, ChooseMatchedDomain) {
RouteConfiguration route_config = default_route_config_;
*(route_config.add_virtual_hosts()) = route_config.virtual_hosts(0);
route_config.mutable_virtual_hosts(0)->clear_domains();
route_config.mutable_virtual_hosts(0)->add_domains("unmatched_domain");
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
EXPECT_EQ(RouteConfigurationResponseState(0).state,
AdsServiceImpl::ResponseState::ACKED);
}
// Tests that LDS client should choose the last route in the virtual host if
// multiple routes exist in the LDS response.
TEST_P(LdsRdsTest, ChooseLastRoute) {
RouteConfiguration route_config = default_route_config_;
*(route_config.mutable_virtual_hosts(0)->add_routes()) =
route_config.virtual_hosts(0).routes(0);
route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_cluster_header();
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
EXPECT_EQ(RouteConfigurationResponseState(0).state,
AdsServiceImpl::ResponseState::ACKED);
}
// Tests that LDS client should ignore route which has query_parameters.
TEST_P(LdsRdsTest, RouteMatchHasQueryParameters) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
route1->mutable_match()->add_query_parameters();
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("No valid routes specified."));
}
// Tests that LDS client should send a ACK if route match has a prefix
// that is either empty or a single slash
TEST_P(LdsRdsTest, RouteMatchHasValidPrefixEmptyOrSingleSlash) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("");
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("/");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
}
// Tests that LDS client should ignore route which has a path
// prefix string does not start with "/".
TEST_P(LdsRdsTest, RouteMatchHasInvalidPrefixNoLeadingSlash) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("grpc.testing.EchoTest1Service/");
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("No valid routes specified."));
}
// Tests that LDS client should ignore route which has a prefix
// string with more than 2 slashes.
TEST_P(LdsRdsTest, RouteMatchHasInvalidPrefixExtraContent) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/Echo1/");
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("No valid routes specified."));
}
// Tests that LDS client should ignore route which has a prefix
// string "//".
TEST_P(LdsRdsTest, RouteMatchHasInvalidPrefixDoubleSlash) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("//");
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("No valid routes specified."));
}
// Tests that LDS client should ignore route which has path
// but it's empty.
TEST_P(LdsRdsTest, RouteMatchHasInvalidPathEmptyPath) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_path("");
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("No valid routes specified."));
}
// Tests that LDS client should ignore route which has path
// string does not start with "/".
TEST_P(LdsRdsTest, RouteMatchHasInvalidPathNoLeadingSlash) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_path("grpc.testing.EchoTest1Service/Echo1");
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("No valid routes specified."));
}
// Tests that LDS client should ignore route which has path
// string that has too many slashes; for example, ends with "/".
TEST_P(LdsRdsTest, RouteMatchHasInvalidPathTooManySlashes) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/Echo1/");
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("No valid routes specified."));
}
// Tests that LDS client should ignore route which has path
// string that has only 1 slash: missing "/" between service and method.
TEST_P(LdsRdsTest, RouteMatchHasInvalidPathOnlyOneSlash) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service.Echo1");
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("No valid routes specified."));
}
// Tests that LDS client should ignore route which has path
// string that is missing service.
TEST_P(LdsRdsTest, RouteMatchHasInvalidPathMissingService) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_path("//Echo1");
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("No valid routes specified."));
}
// Tests that LDS client should ignore route which has path
// string that is missing method.
TEST_P(LdsRdsTest, RouteMatchHasInvalidPathMissingMethod) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/");
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("No valid routes specified."));
}
// Test that LDS client should reject route which has invalid path regex.
TEST_P(LdsRdsTest, RouteMatchHasInvalidPathRegex) {
const char* kNewCluster1Name = "new_cluster_1";
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->mutable_safe_regex()->set_regex("a[z-a]");
route1->mutable_route()->set_cluster(kNewCluster1Name);
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"path matcher: Invalid regex string specified in matcher."));
}
// Tests that LDS client should send a NACK if route has an action other than
// RouteAction in the LDS response.
TEST_P(LdsRdsTest, RouteHasNoRouteAction) {
RouteConfiguration route_config = default_route_config_;
route_config.mutable_virtual_hosts(0)->mutable_routes(0)->mutable_redirect();
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("No RouteAction found in route."));
}
TEST_P(LdsRdsTest, RouteActionClusterHasEmptyClusterName) {
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
route1->mutable_route()->set_cluster("");
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("RouteAction cluster contains empty cluster name."));
}
TEST_P(LdsRdsTest, RouteActionWeightedTargetHasIncorrectTotalWeightSet) {
const size_t kWeight75 = 75;
const char* kNewCluster1Name = "new_cluster_1";
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* weighted_cluster1 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster1->set_name(kNewCluster1Name);
weighted_cluster1->mutable_weight()->set_value(kWeight75);
route1->mutable_route()
->mutable_weighted_clusters()
->mutable_total_weight()
->set_value(kWeight75 + 1);
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"RouteAction weighted_cluster has incorrect total weight"));
}
TEST_P(LdsRdsTest, RouteActionWeightedClusterHasZeroTotalWeight) {
const char* kNewCluster1Name = "new_cluster_1";
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* weighted_cluster1 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster1->set_name(kNewCluster1Name);
weighted_cluster1->mutable_weight()->set_value(0);
route1->mutable_route()
->mutable_weighted_clusters()
->mutable_total_weight()
->set_value(0);
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr(
"RouteAction weighted_cluster has no valid clusters specified."));
}
TEST_P(LdsRdsTest, RouteActionWeightedTargetClusterHasEmptyClusterName) {
const size_t kWeight75 = 75;
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* weighted_cluster1 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster1->set_name("");
weighted_cluster1->mutable_weight()->set_value(kWeight75);
route1->mutable_route()
->mutable_weighted_clusters()
->mutable_total_weight()
->set_value(kWeight75);
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr(
"RouteAction weighted_cluster cluster contains empty cluster name."));
}
TEST_P(LdsRdsTest, RouteActionWeightedTargetClusterHasNoWeight) {
const size_t kWeight75 = 75;
const char* kNewCluster1Name = "new_cluster_1";
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* weighted_cluster1 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster1->set_name(kNewCluster1Name);
route1->mutable_route()
->mutable_weighted_clusters()
->mutable_total_weight()
->set_value(kWeight75);
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"RouteAction weighted_cluster cluster missing weight"));
}
TEST_P(LdsRdsTest, RouteHeaderMatchInvalidRegex) {
const char* kNewCluster1Name = "new_cluster_1";
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* header_matcher1 = route1->mutable_match()->add_headers();
header_matcher1->set_name("header1");
header_matcher1->mutable_safe_regex_match()->set_regex("a[z-a]");
route1->mutable_route()->set_cluster(kNewCluster1Name);
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr(
"header matcher: Invalid regex string specified in matcher."));
}
TEST_P(LdsRdsTest, RouteHeaderMatchInvalidRange) {
const char* kNewCluster1Name = "new_cluster_1";
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* header_matcher1 = route1->mutable_match()->add_headers();
header_matcher1->set_name("header1");
header_matcher1->mutable_range_match()->set_start(1001);
header_matcher1->mutable_range_match()->set_end(1000);
route1->mutable_route()->set_cluster(kNewCluster1Name);
SetRouteConfiguration(0, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr(
"header matcher: Invalid range specifier specified: end cannot be "
"smaller than start."));
}
// Tests that LDS client should choose the default route (with no matching
// specified) after unable to find a match with previous routes.
TEST_P(LdsRdsTest, XdsRoutingPathMatching) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const size_t kNumEcho1Rpcs = 10;
const size_t kNumEcho2Rpcs = 20;
const size_t kNumEchoRpcs = 30;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 2)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(2, 3)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(3, 4)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
// Populating Route Configurations for LDS.
RouteConfiguration new_route_config = default_route_config_;
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/Echo1");
route1->mutable_route()->set_cluster(kNewCluster1Name);
auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
route2->mutable_match()->set_path("/grpc.testing.EchoTest2Service/Echo2");
route2->mutable_route()->set_cluster(kNewCluster2Name);
auto* route3 = new_route_config.mutable_virtual_hosts(0)->add_routes();
route3->mutable_match()->set_path("/grpc.testing.EchoTest3Service/Echo3");
route3->mutable_route()->set_cluster(kDefaultClusterName);
auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, new_route_config);
WaitForAllBackends(0, 2);
CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions()
.set_rpc_service(SERVICE_ECHO1)
.set_rpc_method(METHOD_ECHO1)
.set_wait_for_ready(true));
CheckRpcSendOk(kNumEcho2Rpcs, RpcOptions()
.set_rpc_service(SERVICE_ECHO2)
.set_rpc_method(METHOD_ECHO2)
.set_wait_for_ready(true));
// Make sure RPCs all go to the correct backend.
for (size_t i = 0; i < 2; ++i) {
EXPECT_EQ(kNumEchoRpcs / 2,
backends_[i]->backend_service()->request_count());
EXPECT_EQ(0, backends_[i]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[i]->backend_service2()->request_count());
}
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[2]->backend_service2()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
EXPECT_EQ(kNumEcho2Rpcs, backends_[3]->backend_service2()->request_count());
}
TEST_P(LdsRdsTest, XdsRoutingPathMatchingCaseInsensitive) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const size_t kNumEcho1Rpcs = 10;
const size_t kNumEchoRpcs = 30;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 3)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
// Populating Route Configurations for LDS.
RouteConfiguration new_route_config = default_route_config_;
// First route will not match, since it's case-sensitive.
// Second route will match with same path.
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_path("/GrPc.TeStInG.EcHoTeSt1SErViCe/EcHo1");
route1->mutable_route()->set_cluster(kNewCluster1Name);
auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
route2->mutable_match()->set_path("/GrPc.TeStInG.EcHoTeSt1SErViCe/EcHo1");
route2->mutable_match()->mutable_case_sensitive()->set_value(false);
route2->mutable_route()->set_cluster(kNewCluster2Name);
auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, new_route_config);
CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions()
.set_rpc_service(SERVICE_ECHO1)
.set_rpc_method(METHOD_ECHO1)
.set_wait_for_ready(true));
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
}
TEST_P(LdsRdsTest, XdsRoutingPrefixMatching) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const size_t kNumEcho1Rpcs = 10;
const size_t kNumEcho2Rpcs = 20;
const size_t kNumEchoRpcs = 30;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 2)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(2, 3)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(3, 4)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
// Populating Route Configurations for LDS.
RouteConfiguration new_route_config = default_route_config_;
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
route1->mutable_route()->set_cluster(kNewCluster1Name);
auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
route2->mutable_match()->set_prefix("/grpc.testing.EchoTest2Service/");
route2->mutable_route()->set_cluster(kNewCluster2Name);
auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, new_route_config);
WaitForAllBackends(0, 2);
CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
CheckRpcSendOk(
kNumEcho1Rpcs,
RpcOptions().set_rpc_service(SERVICE_ECHO1).set_wait_for_ready(true));
CheckRpcSendOk(
kNumEcho2Rpcs,
RpcOptions().set_rpc_service(SERVICE_ECHO2).set_wait_for_ready(true));
// Make sure RPCs all go to the correct backend.
for (size_t i = 0; i < 2; ++i) {
EXPECT_EQ(kNumEchoRpcs / 2,
backends_[i]->backend_service()->request_count());
EXPECT_EQ(0, backends_[i]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[i]->backend_service2()->request_count());
}
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[2]->backend_service2()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
EXPECT_EQ(kNumEcho2Rpcs, backends_[3]->backend_service2()->request_count());
}
TEST_P(LdsRdsTest, XdsRoutingPrefixMatchingCaseInsensitive) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const size_t kNumEcho1Rpcs = 10;
const size_t kNumEchoRpcs = 30;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 3)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
// Populating Route Configurations for LDS.
RouteConfiguration new_route_config = default_route_config_;
// First route will not match, since it's case-sensitive.
// Second route will match with same path.
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/GrPc.TeStInG.EcHoTeSt1SErViCe");
route1->mutable_route()->set_cluster(kNewCluster1Name);
auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
route2->mutable_match()->set_prefix("/GrPc.TeStInG.EcHoTeSt1SErViCe");
route2->mutable_match()->mutable_case_sensitive()->set_value(false);
route2->mutable_route()->set_cluster(kNewCluster2Name);
auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, new_route_config);
CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions()
.set_rpc_service(SERVICE_ECHO1)
.set_rpc_method(METHOD_ECHO1)
.set_wait_for_ready(true));
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
}
TEST_P(LdsRdsTest, XdsRoutingPathRegexMatching) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const size_t kNumEcho1Rpcs = 10;
const size_t kNumEcho2Rpcs = 20;
const size_t kNumEchoRpcs = 30;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 2)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(2, 3)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(3, 4)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
// Populating Route Configurations for LDS.
RouteConfiguration new_route_config = default_route_config_;
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
// Will match "/grpc.testing.EchoTest1Service/"
route1->mutable_match()->mutable_safe_regex()->set_regex(".*1.*");
route1->mutable_route()->set_cluster(kNewCluster1Name);
auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
// Will match "/grpc.testing.EchoTest2Service/"
route2->mutable_match()->mutable_safe_regex()->set_regex(".*2.*");
route2->mutable_route()->set_cluster(kNewCluster2Name);
auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, new_route_config);
WaitForAllBackends(0, 2);
CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
CheckRpcSendOk(
kNumEcho1Rpcs,
RpcOptions().set_rpc_service(SERVICE_ECHO1).set_wait_for_ready(true));
CheckRpcSendOk(
kNumEcho2Rpcs,
RpcOptions().set_rpc_service(SERVICE_ECHO2).set_wait_for_ready(true));
// Make sure RPCs all go to the correct backend.
for (size_t i = 0; i < 2; ++i) {
EXPECT_EQ(kNumEchoRpcs / 2,
backends_[i]->backend_service()->request_count());
EXPECT_EQ(0, backends_[i]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[i]->backend_service2()->request_count());
}
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[2]->backend_service2()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
EXPECT_EQ(kNumEcho2Rpcs, backends_[3]->backend_service2()->request_count());
}
TEST_P(LdsRdsTest, XdsRoutingPathRegexMatchingCaseInsensitive) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const size_t kNumEcho1Rpcs = 10;
const size_t kNumEchoRpcs = 30;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 3)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
// Populating Route Configurations for LDS.
RouteConfiguration new_route_config = default_route_config_;
// First route will not match, since it's case-sensitive.
// Second route will match with same path.
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->mutable_safe_regex()->set_regex(
".*EcHoTeSt1SErViCe.*");
route1->mutable_route()->set_cluster(kNewCluster1Name);
auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
route2->mutable_match()->mutable_safe_regex()->set_regex(
".*EcHoTeSt1SErViCe.*");
route2->mutable_match()->mutable_case_sensitive()->set_value(false);
route2->mutable_route()->set_cluster(kNewCluster2Name);
auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, new_route_config);
CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions()
.set_rpc_service(SERVICE_ECHO1)
.set_rpc_method(METHOD_ECHO1)
.set_wait_for_ready(true));
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
}
TEST_P(LdsRdsTest, XdsRoutingWeightedCluster) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const char* kNotUsedClusterName = "not_used_cluster";
const size_t kNumEcho1Rpcs = 1000;
const size_t kNumEchoRpcs = 10;
const size_t kWeight75 = 75;
const size_t kWeight25 = 25;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 3)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
// Populating Route Configurations for LDS.
RouteConfiguration new_route_config = default_route_config_;
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* weighted_cluster1 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster1->set_name(kNewCluster1Name);
weighted_cluster1->mutable_weight()->set_value(kWeight75);
auto* weighted_cluster2 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster2->set_name(kNewCluster2Name);
weighted_cluster2->mutable_weight()->set_value(kWeight25);
// Cluster with weight 0 will not be used.
auto* weighted_cluster3 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster3->set_name(kNotUsedClusterName);
weighted_cluster3->mutable_weight()->set_value(0);
route1->mutable_route()
->mutable_weighted_clusters()
->mutable_total_weight()
->set_value(kWeight75 + kWeight25);
auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, new_route_config);
WaitForAllBackends(0, 1);
WaitForAllBackends(1, 3, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
CheckRpcSendOk(kNumEchoRpcs);
CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
const int weight_75_request_count =
backends_[1]->backend_service1()->request_count();
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
const int weight_25_request_count =
backends_[2]->backend_service1()->request_count();
const double kErrorTolerance = 0.2;
EXPECT_THAT(
weight_75_request_count,
::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
kWeight75 / 100 * (1 - kErrorTolerance)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
kWeight75 / 100 * (1 + kErrorTolerance))));
// TODO(@donnadionne): Reduce tolerance: increased the tolerance to keep the
// test from flaking while debugging potential root cause.
const double kErrorToleranceSmallLoad = 0.3;
gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
weight_75_request_count, weight_25_request_count);
EXPECT_THAT(weight_25_request_count,
::testing::AllOf(
::testing::Ge(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
100 * (1 - kErrorToleranceSmallLoad)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
100 * (1 + kErrorToleranceSmallLoad))));
}
TEST_P(LdsRdsTest, RouteActionWeightedTargetDefaultRoute) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const size_t kNumEchoRpcs = 1000;
const size_t kWeight75 = 75;
const size_t kWeight25 = 25;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 3)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
// Populating Route Configurations for LDS.
RouteConfiguration new_route_config = default_route_config_;
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("");
auto* weighted_cluster1 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster1->set_name(kNewCluster1Name);
weighted_cluster1->mutable_weight()->set_value(kWeight75);
auto* weighted_cluster2 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster2->set_name(kNewCluster2Name);
weighted_cluster2->mutable_weight()->set_value(kWeight25);
route1->mutable_route()
->mutable_weighted_clusters()
->mutable_total_weight()
->set_value(kWeight75 + kWeight25);
SetRouteConfiguration(0, new_route_config);
WaitForAllBackends(1, 3);
CheckRpcSendOk(kNumEchoRpcs);
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(0, backends_[0]->backend_service()->request_count());
const int weight_75_request_count =
backends_[1]->backend_service()->request_count();
const int weight_25_request_count =
backends_[2]->backend_service()->request_count();
const double kErrorTolerance = 0.2;
EXPECT_THAT(
weight_75_request_count,
::testing::AllOf(::testing::Ge(static_cast<double>(kNumEchoRpcs) *
kWeight75 / 100 * (1 - kErrorTolerance)),
::testing::Le(static_cast<double>(kNumEchoRpcs) *
kWeight75 / 100 * (1 + kErrorTolerance))));
// TODO(@donnadionne): Reduce tolerance: increased the tolerance to keep the
// test from flaking while debugging potential root cause.
const double kErrorToleranceSmallLoad = 0.3;
gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
weight_75_request_count, weight_25_request_count);
EXPECT_THAT(weight_25_request_count,
::testing::AllOf(
::testing::Ge(static_cast<double>(kNumEchoRpcs) * kWeight25 /
100 * (1 - kErrorToleranceSmallLoad)),
::testing::Le(static_cast<double>(kNumEchoRpcs) * kWeight25 /
100 * (1 + kErrorToleranceSmallLoad))));
}
TEST_P(LdsRdsTest, XdsRoutingWeightedClusterUpdateWeights) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const char* kNewCluster3Name = "new_cluster_3";
const char* kNewEdsService3Name = "new_eds_service_name_3";
const size_t kNumEcho1Rpcs = 1000;
const size_t kNumEchoRpcs = 10;
const size_t kWeight75 = 75;
const size_t kWeight25 = 25;
const size_t kWeight50 = 50;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 3)},
});
AdsServiceImpl::EdsResourceArgs args3({
{"locality0", GetBackendPorts(3, 4)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args3, kNewEdsService3Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
Cluster new_cluster3 = default_cluster_;
new_cluster3.set_name(kNewCluster3Name);
new_cluster3.mutable_eds_cluster_config()->set_service_name(
kNewEdsService3Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster3);
// Populating Route Configurations.
RouteConfiguration new_route_config = default_route_config_;
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* weighted_cluster1 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster1->set_name(kNewCluster1Name);
weighted_cluster1->mutable_weight()->set_value(kWeight75);
auto* weighted_cluster2 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster2->set_name(kNewCluster2Name);
weighted_cluster2->mutable_weight()->set_value(kWeight25);
route1->mutable_route()
->mutable_weighted_clusters()
->mutable_total_weight()
->set_value(kWeight75 + kWeight25);
auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, new_route_config);
WaitForAllBackends(0, 1);
WaitForAllBackends(1, 3, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
CheckRpcSendOk(kNumEchoRpcs);
CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
const int weight_75_request_count =
backends_[1]->backend_service1()->request_count();
EXPECT_EQ(0, backends_[1]->backend_service2()->request_count());
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
const int weight_25_request_count =
backends_[2]->backend_service1()->request_count();
EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
const double kErrorTolerance = 0.2;
EXPECT_THAT(
weight_75_request_count,
::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
kWeight75 / 100 * (1 - kErrorTolerance)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
kWeight75 / 100 * (1 + kErrorTolerance))));
// TODO(@donnadionne): Reduce tolerance: increased the tolerance to keep the
// test from flaking while debugging potential root cause.
const double kErrorToleranceSmallLoad = 0.3;
gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
weight_75_request_count, weight_25_request_count);
EXPECT_THAT(weight_25_request_count,
::testing::AllOf(
::testing::Ge(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
100 * (1 - kErrorToleranceSmallLoad)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
100 * (1 + kErrorToleranceSmallLoad))));
// Change Route Configurations: same clusters different weights.
weighted_cluster1->mutable_weight()->set_value(kWeight50);
weighted_cluster2->mutable_weight()->set_value(kWeight50);
// Change default route to a new cluster to help to identify when new polices
// are seen by the client.
default_route->mutable_route()->set_cluster(kNewCluster3Name);
SetRouteConfiguration(0, new_route_config);
ResetBackendCounters();
WaitForAllBackends(3, 4);
CheckRpcSendOk(kNumEchoRpcs);
CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(0, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
const int weight_50_request_count_1 =
backends_[1]->backend_service1()->request_count();
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
const int weight_50_request_count_2 =
backends_[2]->backend_service1()->request_count();
EXPECT_EQ(kNumEchoRpcs, backends_[3]->backend_service()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
EXPECT_THAT(
weight_50_request_count_1,
::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
kWeight50 / 100 * (1 - kErrorTolerance)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
kWeight50 / 100 * (1 + kErrorTolerance))));
EXPECT_THAT(
weight_50_request_count_2,
::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
kWeight50 / 100 * (1 - kErrorTolerance)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
kWeight50 / 100 * (1 + kErrorTolerance))));
}
TEST_P(LdsRdsTest, XdsRoutingWeightedClusterUpdateClusters) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const char* kNewCluster3Name = "new_cluster_3";
const char* kNewEdsService3Name = "new_eds_service_name_3";
const size_t kNumEcho1Rpcs = 1000;
const size_t kNumEchoRpcs = 10;
const size_t kWeight75 = 75;
const size_t kWeight25 = 25;
const size_t kWeight50 = 50;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 3)},
});
AdsServiceImpl::EdsResourceArgs args3({
{"locality0", GetBackendPorts(3, 4)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args3, kNewEdsService3Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
Cluster new_cluster3 = default_cluster_;
new_cluster3.set_name(kNewCluster3Name);
new_cluster3.mutable_eds_cluster_config()->set_service_name(
kNewEdsService3Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster3);
// Populating Route Configurations.
RouteConfiguration new_route_config = default_route_config_;
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* weighted_cluster1 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster1->set_name(kNewCluster1Name);
weighted_cluster1->mutable_weight()->set_value(kWeight75);
auto* weighted_cluster2 =
route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
weighted_cluster2->set_name(kDefaultClusterName);
weighted_cluster2->mutable_weight()->set_value(kWeight25);
route1->mutable_route()
->mutable_weighted_clusters()
->mutable_total_weight()
->set_value(kWeight75 + kWeight25);
auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, new_route_config);
WaitForAllBackends(0, 1);
WaitForAllBackends(1, 2, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
CheckRpcSendOk(kNumEchoRpcs);
CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
int weight_25_request_count =
backends_[0]->backend_service1()->request_count();
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
int weight_75_request_count =
backends_[1]->backend_service1()->request_count();
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
EXPECT_EQ(0, backends_[2]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
const double kErrorTolerance = 0.2;
EXPECT_THAT(
weight_75_request_count,
::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
kWeight75 / 100 * (1 - kErrorTolerance)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
kWeight75 / 100 * (1 + kErrorTolerance))));
// TODO(@donnadionne): Reduce tolerance: increased the tolerance to keep the
// test from flaking while debugging potential root cause.
const double kErrorToleranceSmallLoad = 0.3;
gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
weight_75_request_count, weight_25_request_count);
EXPECT_THAT(weight_25_request_count,
::testing::AllOf(
::testing::Ge(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
100 * (1 - kErrorToleranceSmallLoad)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
100 * (1 + kErrorToleranceSmallLoad))));
// Change Route Configurations: new set of clusters with different weights.
weighted_cluster1->mutable_weight()->set_value(kWeight50);
weighted_cluster2->set_name(kNewCluster2Name);
weighted_cluster2->mutable_weight()->set_value(kWeight50);
SetRouteConfiguration(0, new_route_config);
ResetBackendCounters();
WaitForAllBackends(2, 3, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
CheckRpcSendOk(kNumEchoRpcs);
CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
const int weight_50_request_count_1 =
backends_[1]->backend_service1()->request_count();
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
const int weight_50_request_count_2 =
backends_[2]->backend_service1()->request_count();
EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
EXPECT_THAT(
weight_50_request_count_1,
::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
kWeight50 / 100 * (1 - kErrorTolerance)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
kWeight50 / 100 * (1 + kErrorTolerance))));
EXPECT_THAT(
weight_50_request_count_2,
::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
kWeight50 / 100 * (1 - kErrorTolerance)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
kWeight50 / 100 * (1 + kErrorTolerance))));
// Change Route Configurations.
weighted_cluster1->mutable_weight()->set_value(kWeight75);
weighted_cluster2->set_name(kNewCluster3Name);
weighted_cluster2->mutable_weight()->set_value(kWeight25);
SetRouteConfiguration(0, new_route_config);
ResetBackendCounters();
WaitForAllBackends(3, 4, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
CheckRpcSendOk(kNumEchoRpcs);
CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
weight_75_request_count = backends_[1]->backend_service1()->request_count();
EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
EXPECT_EQ(0, backends_[2]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
weight_25_request_count = backends_[3]->backend_service1()->request_count();
EXPECT_THAT(
weight_75_request_count,
::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
kWeight75 / 100 * (1 - kErrorTolerance)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
kWeight75 / 100 * (1 + kErrorTolerance))));
// TODO(@donnadionne): Reduce tolerance: increased the tolerance to keep the
// test from flaking while debugging potential root cause.
gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
weight_75_request_count, weight_25_request_count);
EXPECT_THAT(weight_25_request_count,
::testing::AllOf(
::testing::Ge(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
100 * (1 - kErrorToleranceSmallLoad)),
::testing::Le(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
100 * (1 + kErrorToleranceSmallLoad))));
}
TEST_P(LdsRdsTest, XdsRoutingClusterUpdateClusters) {
const char* kNewClusterName = "new_cluster";
const char* kNewEdsServiceName = "new_eds_service_name";
const size_t kNumEchoRpcs = 5;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsServiceName));
// Populate new CDS resources.
Cluster new_cluster = default_cluster_;
new_cluster.set_name(kNewClusterName);
new_cluster.mutable_eds_cluster_config()->set_service_name(
kNewEdsServiceName);
balancers_[0]->ads_service()->SetCdsResource(new_cluster);
// Send Route Configuration.
RouteConfiguration new_route_config = default_route_config_;
SetRouteConfiguration(0, new_route_config);
WaitForAllBackends(0, 1);
CheckRpcSendOk(kNumEchoRpcs);
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
// Change Route Configurations: new default cluster.
auto* default_route =
new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
default_route->mutable_route()->set_cluster(kNewClusterName);
SetRouteConfiguration(0, new_route_config);
WaitForAllBackends(1, 2);
CheckRpcSendOk(kNumEchoRpcs);
// Make sure RPCs all go to the correct backend.
EXPECT_EQ(kNumEchoRpcs, backends_[1]->backend_service()->request_count());
}
TEST_P(LdsRdsTest, XdsRoutingClusterUpdateClustersWithPickingDelays) {
const char* kNewClusterName = "new_cluster";
const char* kNewEdsServiceName = "new_eds_service_name";
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsServiceName));
// Populate new CDS resources.
Cluster new_cluster = default_cluster_;
new_cluster.set_name(kNewClusterName);
new_cluster.mutable_eds_cluster_config()->set_service_name(
kNewEdsServiceName);
balancers_[0]->ads_service()->SetCdsResource(new_cluster);
// Bring down the current backend: 0, this will delay route picking time,
// resulting in un-committed RPCs.
ShutdownBackend(0);
// Send a RouteConfiguration with a default route that points to
// backend 0.
RouteConfiguration new_route_config = default_route_config_;
SetRouteConfiguration(0, new_route_config);
// Send exactly one RPC with no deadline and with wait_for_ready=true.
// This RPC will not complete until after backend 0 is started.
std::thread sending_rpc([this]() {
CheckRpcSendOk(1, RpcOptions().set_wait_for_ready(true).set_timeout_ms(0));
});
// Send a non-wait_for_ready RPC which should fail, this will tell us
// that the client has received the update and attempted to connect.
const Status status = SendRpc(RpcOptions().set_timeout_ms(0));
EXPECT_FALSE(status.ok());
// Send a update RouteConfiguration to use backend 1.
auto* default_route =
new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
default_route->mutable_route()->set_cluster(kNewClusterName);
SetRouteConfiguration(0, new_route_config);
// Wait for RPCs to go to the new backend: 1, this ensures that the client has
// processed the update.
WaitForAllBackends(1, 2, false, RpcOptions(), true);
// Bring up the previous backend: 0, this will allow the delayed RPC to
// finally call on_call_committed upon completion.
StartBackend(0);
sending_rpc.join();
// Make sure RPCs go to the correct backend:
EXPECT_EQ(1, backends_[0]->backend_service()->request_count());
EXPECT_EQ(1, backends_[1]->backend_service()->request_count());
}
TEST_P(LdsRdsTest, XdsRoutingApplyXdsTimeout) {
const int64_t kTimeoutMillis = 500;
const int64_t kTimeoutNano = kTimeoutMillis * 1000000;
const int64_t kTimeoutGrpcTimeoutHeaderMaxSecond = 1;
const int64_t kTimeoutMaxStreamDurationSecond = 2;
const int64_t kTimeoutHttpMaxStreamDurationSecond = 3;
const int64_t kTimeoutApplicationSecond = 4;
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const char* kNewCluster3Name = "new_cluster_3";
const char* kNewEdsService3Name = "new_eds_service_name_3";
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {grpc_pick_unused_port_or_die()}},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", {grpc_pick_unused_port_or_die()}},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", {grpc_pick_unused_port_or_die()}},
});
AdsServiceImpl::EdsResourceArgs args3({
{"locality0", {grpc_pick_unused_port_or_die()}},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args3, kNewEdsService3Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
Cluster new_cluster3 = default_cluster_;
new_cluster3.set_name(kNewCluster3Name);
new_cluster3.mutable_eds_cluster_config()->set_service_name(
kNewEdsService3Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster3);
// Construct listener.
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
// Set up HTTP max_stream_duration of 3.5 seconds
auto* duration =
http_connection_manager.mutable_common_http_protocol_options()
->mutable_max_stream_duration();
duration->set_seconds(kTimeoutHttpMaxStreamDurationSecond);
duration->set_nanos(kTimeoutNano);
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
// Construct route config.
RouteConfiguration new_route_config = default_route_config_;
// route 1: Set max_stream_duration of 2.5 seconds, Set
// grpc_timeout_header_max of 1.5
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/Echo1");
route1->mutable_route()->set_cluster(kNewCluster1Name);
auto* max_stream_duration =
route1->mutable_route()->mutable_max_stream_duration();
duration = max_stream_duration->mutable_max_stream_duration();
duration->set_seconds(kTimeoutMaxStreamDurationSecond);
duration->set_nanos(kTimeoutNano);
duration = max_stream_duration->mutable_grpc_timeout_header_max();
duration->set_seconds(kTimeoutGrpcTimeoutHeaderMaxSecond);
duration->set_nanos(kTimeoutNano);
// route 2: Set max_stream_duration of 2.5 seconds
auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
route2->mutable_match()->set_path("/grpc.testing.EchoTest2Service/Echo2");
route2->mutable_route()->set_cluster(kNewCluster2Name);
max_stream_duration = route2->mutable_route()->mutable_max_stream_duration();
duration = max_stream_duration->mutable_max_stream_duration();
duration->set_seconds(kTimeoutMaxStreamDurationSecond);
duration->set_nanos(kTimeoutNano);
// route 3: No timeout values in route configuration
auto* route3 = new_route_config.mutable_virtual_hosts(0)->add_routes();
route3->mutable_match()->set_path("/grpc.testing.EchoTestService/Echo");
route3->mutable_route()->set_cluster(kNewCluster3Name);
// Set listener and route config.
SetListenerAndRouteConfiguration(0, std::move(listener), new_route_config);
// Test grpc_timeout_header_max of 1.5 seconds applied
grpc_millis t0 = NowFromCycleCounter();
grpc_millis t1 =
t0 + kTimeoutGrpcTimeoutHeaderMaxSecond * 1000 + kTimeoutMillis;
grpc_millis t2 = t0 + kTimeoutMaxStreamDurationSecond * 1000 + kTimeoutMillis;
CheckRpcSendFailure(1,
RpcOptions()
.set_rpc_service(SERVICE_ECHO1)
.set_rpc_method(METHOD_ECHO1)
.set_wait_for_ready(true)
.set_timeout_ms(kTimeoutApplicationSecond * 1000),
StatusCode::DEADLINE_EXCEEDED);
t0 = NowFromCycleCounter();
EXPECT_GE(t0, t1);
EXPECT_LT(t0, t2);
// Test max_stream_duration of 2.5 seconds applied
t0 = NowFromCycleCounter();
t1 = t0 + kTimeoutMaxStreamDurationSecond * 1000 + kTimeoutMillis;
t2 = t0 + kTimeoutHttpMaxStreamDurationSecond * 1000 + kTimeoutMillis;
CheckRpcSendFailure(1,
RpcOptions()
.set_rpc_service(SERVICE_ECHO2)
.set_rpc_method(METHOD_ECHO2)
.set_wait_for_ready(true)
.set_timeout_ms(kTimeoutApplicationSecond * 1000),
StatusCode::DEADLINE_EXCEEDED);
t0 = NowFromCycleCounter();
EXPECT_GE(t0, t1);
EXPECT_LT(t0, t2);
// Test http_stream_duration of 3.5 seconds applied
t0 = NowFromCycleCounter();
t1 = t0 + kTimeoutHttpMaxStreamDurationSecond * 1000 + kTimeoutMillis;
t2 = t0 + kTimeoutApplicationSecond * 1000 + kTimeoutMillis;
CheckRpcSendFailure(1,
RpcOptions().set_wait_for_ready(true).set_timeout_ms(
kTimeoutApplicationSecond * 1000),
StatusCode::DEADLINE_EXCEEDED);
t0 = NowFromCycleCounter();
EXPECT_GE(t0, t1);
EXPECT_LT(t0, t2);
}
TEST_P(LdsRdsTest, XdsRoutingApplyApplicationTimeoutWhenXdsTimeoutExplicit0) {
const int64_t kTimeoutNano = 500000000;
const int64_t kTimeoutMaxStreamDurationSecond = 2;
const int64_t kTimeoutHttpMaxStreamDurationSecond = 3;
const int64_t kTimeoutApplicationSecond = 4;
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {grpc_pick_unused_port_or_die()}},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", {grpc_pick_unused_port_or_die()}},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", {grpc_pick_unused_port_or_die()}},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
// Construct listener.
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
// Set up HTTP max_stream_duration of 3.5 seconds
auto* duration =
http_connection_manager.mutable_common_http_protocol_options()
->mutable_max_stream_duration();
duration->set_seconds(kTimeoutHttpMaxStreamDurationSecond);
duration->set_nanos(kTimeoutNano);
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
// Construct route config.
RouteConfiguration new_route_config = default_route_config_;
// route 1: Set max_stream_duration of 2.5 seconds, Set
// grpc_timeout_header_max of 0
auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/Echo1");
route1->mutable_route()->set_cluster(kNewCluster1Name);
auto* max_stream_duration =
route1->mutable_route()->mutable_max_stream_duration();
duration = max_stream_duration->mutable_max_stream_duration();
duration->set_seconds(kTimeoutMaxStreamDurationSecond);
duration->set_nanos(kTimeoutNano);
duration = max_stream_duration->mutable_grpc_timeout_header_max();
duration->set_seconds(0);
duration->set_nanos(0);
// route 2: Set max_stream_duration to 0
auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
route2->mutable_match()->set_path("/grpc.testing.EchoTest2Service/Echo2");
route2->mutable_route()->set_cluster(kNewCluster2Name);
max_stream_duration = route2->mutable_route()->mutable_max_stream_duration();
duration = max_stream_duration->mutable_max_stream_duration();
duration->set_seconds(0);
duration->set_nanos(0);
// Set listener and route config.
SetListenerAndRouteConfiguration(0, std::move(listener), new_route_config);
// Test application timeout is applied for route 1
auto t0 = system_clock::now();
CheckRpcSendFailure(1,
RpcOptions()
.set_rpc_service(SERVICE_ECHO1)
.set_rpc_method(METHOD_ECHO1)
.set_wait_for_ready(true)
.set_timeout_ms(kTimeoutApplicationSecond * 1000),
StatusCode::DEADLINE_EXCEEDED);
auto ellapsed_nano_seconds =
std::chrono::duration_cast<std::chrono::nanoseconds>(system_clock::now() -
t0);
EXPECT_GT(ellapsed_nano_seconds.count(),
kTimeoutApplicationSecond * 1000000000);
// Test application timeout is applied for route 2
t0 = system_clock::now();
CheckRpcSendFailure(1,
RpcOptions()
.set_rpc_service(SERVICE_ECHO2)
.set_rpc_method(METHOD_ECHO2)
.set_wait_for_ready(true)
.set_timeout_ms(kTimeoutApplicationSecond * 1000),
StatusCode::DEADLINE_EXCEEDED);
ellapsed_nano_seconds = std::chrono::duration_cast<std::chrono::nanoseconds>(
system_clock::now() - t0);
EXPECT_GT(ellapsed_nano_seconds.count(),
kTimeoutApplicationSecond * 1000000000);
}
TEST_P(LdsRdsTest, XdsRoutingApplyApplicationTimeoutWhenHttpTimeoutExplicit0) {
const int64_t kTimeoutApplicationSecond = 4;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {grpc_pick_unused_port_or_die()}},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
auto listener = default_listener_;
HttpConnectionManager http_connection_manager;
listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
&http_connection_manager);
// Set up HTTP max_stream_duration to be explicit 0
auto* duration =
http_connection_manager.mutable_common_http_protocol_options()
->mutable_max_stream_duration();
duration->set_seconds(0);
duration->set_nanos(0);
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
// Set listener and route config.
SetListenerAndRouteConfiguration(0, std::move(listener),
default_route_config_);
// Test application timeout is applied for route 1
auto t0 = system_clock::now();
CheckRpcSendFailure(1,
RpcOptions().set_wait_for_ready(true).set_timeout_ms(
kTimeoutApplicationSecond * 1000),
StatusCode::DEADLINE_EXCEEDED);
auto ellapsed_nano_seconds =
std::chrono::duration_cast<std::chrono::nanoseconds>(system_clock::now() -
t0);
EXPECT_GT(ellapsed_nano_seconds.count(),
kTimeoutApplicationSecond * 1000000000);
}
// Test to ensure application-specified deadline won't be affected when
// the xDS config does not specify a timeout.
TEST_P(LdsRdsTest, XdsRoutingWithOnlyApplicationTimeout) {
const int64_t kTimeoutApplicationSecond = 4;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {grpc_pick_unused_port_or_die()}},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
auto t0 = system_clock::now();
CheckRpcSendFailure(1,
RpcOptions().set_wait_for_ready(true).set_timeout_ms(
kTimeoutApplicationSecond * 1000),
StatusCode::DEADLINE_EXCEEDED);
auto ellapsed_nano_seconds =
std::chrono::duration_cast<std::chrono::nanoseconds>(system_clock::now() -
t0);
EXPECT_GT(ellapsed_nano_seconds.count(),
kTimeoutApplicationSecond * 1000000000);
}
TEST_P(LdsRdsTest, XdsRoutingHeadersMatching) {
const char* kNewClusterName = "new_cluster";
const char* kNewEdsServiceName = "new_eds_service_name";
const size_t kNumEcho1Rpcs = 100;
const size_t kNumEchoRpcs = 5;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsServiceName));
// Populate new CDS resources.
Cluster new_cluster = default_cluster_;
new_cluster.set_name(kNewClusterName);
new_cluster.mutable_eds_cluster_config()->set_service_name(
kNewEdsServiceName);
balancers_[0]->ads_service()->SetCdsResource(new_cluster);
// Populating Route Configurations for LDS.
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* header_matcher1 = route1->mutable_match()->add_headers();
header_matcher1->set_name("header1");
header_matcher1->set_exact_match("POST,PUT,GET");
auto* header_matcher2 = route1->mutable_match()->add_headers();
header_matcher2->set_name("header2");
header_matcher2->mutable_safe_regex_match()->set_regex("[a-z]*");
auto* header_matcher3 = route1->mutable_match()->add_headers();
header_matcher3->set_name("header3");
header_matcher3->mutable_range_match()->set_start(1);
header_matcher3->mutable_range_match()->set_end(1000);
auto* header_matcher4 = route1->mutable_match()->add_headers();
header_matcher4->set_name("header4");
header_matcher4->set_present_match(false);
auto* header_matcher5 = route1->mutable_match()->add_headers();
header_matcher5->set_name("header5");
header_matcher5->set_present_match(true);
auto* header_matcher6 = route1->mutable_match()->add_headers();
header_matcher6->set_name("header6");
header_matcher6->set_prefix_match("/grpc");
auto* header_matcher7 = route1->mutable_match()->add_headers();
header_matcher7->set_name("header7");
header_matcher7->set_suffix_match(".cc");
header_matcher7->set_invert_match(true);
route1->mutable_route()->set_cluster(kNewClusterName);
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
std::vector<std::pair<std::string, std::string>> metadata = {
{"header1", "POST"},
{"header2", "blah"},
{"header3", "1"},
{"header5", "anything"},
{"header6", "/grpc.testing.EchoTest1Service/"},
{"header1", "PUT"},
{"header7", "grpc.java"},
{"header1", "GET"},
};
const auto header_match_rpc_options = RpcOptions()
.set_rpc_service(SERVICE_ECHO1)
.set_rpc_method(METHOD_ECHO1)
.set_metadata(std::move(metadata));
// Make sure all backends are up.
WaitForAllBackends(0, 1);
WaitForAllBackends(1, 2, true, header_match_rpc_options);
// Send RPCs.
CheckRpcSendOk(kNumEchoRpcs);
CheckRpcSendOk(kNumEcho1Rpcs, header_match_rpc_options);
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service2()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
EXPECT_EQ(kNumEcho1Rpcs, backends_[1]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service2()->request_count());
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
}
TEST_P(LdsRdsTest, XdsRoutingHeadersMatchingSpecialHeaderContentType) {
const char* kNewClusterName = "new_cluster";
const char* kNewEdsServiceName = "new_eds_service_name";
const size_t kNumEchoRpcs = 100;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsServiceName));
// Populate new CDS resources.
Cluster new_cluster = default_cluster_;
new_cluster.set_name(kNewClusterName);
new_cluster.mutable_eds_cluster_config()->set_service_name(
kNewEdsServiceName);
balancers_[0]->ads_service()->SetCdsResource(new_cluster);
// Populating Route Configurations for LDS.
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("");
auto* header_matcher1 = route1->mutable_match()->add_headers();
header_matcher1->set_name("content-type");
header_matcher1->set_exact_match("notapplication/grpc");
route1->mutable_route()->set_cluster(kNewClusterName);
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
auto* header_matcher2 = default_route->mutable_match()->add_headers();
header_matcher2->set_name("content-type");
header_matcher2->set_exact_match("application/grpc");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
// Make sure the backend is up.
WaitForAllBackends(0, 1);
// Send RPCs.
CheckRpcSendOk(kNumEchoRpcs);
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
}
TEST_P(LdsRdsTest, XdsRoutingHeadersMatchingSpecialCasesToIgnore) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const size_t kNumEchoRpcs = 100;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
// Populating Route Configurations for LDS.
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("");
auto* header_matcher1 = route1->mutable_match()->add_headers();
header_matcher1->set_name("grpc-foo-bin");
header_matcher1->set_present_match(true);
route1->mutable_route()->set_cluster(kNewCluster1Name);
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
// Send headers which will mismatch each route
std::vector<std::pair<std::string, std::string>> metadata = {
{"grpc-foo-bin", "grpc-foo-bin"},
};
WaitForAllBackends(0, 1);
CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_metadata(metadata));
// Verify that only the default backend got RPCs since all previous routes
// were mismatched.
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
}
TEST_P(LdsRdsTest, XdsRoutingRuntimeFractionMatching) {
const char* kNewClusterName = "new_cluster";
const char* kNewEdsServiceName = "new_eds_service_name";
const size_t kNumRpcs = 1000;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsServiceName));
// Populate new CDS resources.
Cluster new_cluster = default_cluster_;
new_cluster.set_name(kNewClusterName);
new_cluster.mutable_eds_cluster_config()->set_service_name(
kNewEdsServiceName);
balancers_[0]->ads_service()->SetCdsResource(new_cluster);
// Populating Route Configurations for LDS.
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()
->mutable_runtime_fraction()
->mutable_default_value()
->set_numerator(25);
route1->mutable_route()->set_cluster(kNewClusterName);
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
WaitForAllBackends(0, 2);
CheckRpcSendOk(kNumRpcs);
const int default_backend_count =
backends_[0]->backend_service()->request_count();
const int matched_backend_count =
backends_[1]->backend_service()->request_count();
const double kErrorTolerance = 0.2;
EXPECT_THAT(
default_backend_count,
::testing::AllOf(::testing::Ge(static_cast<double>(kNumRpcs) * 75 / 100 *
(1 - kErrorTolerance)),
::testing::Le(static_cast<double>(kNumRpcs) * 75 / 100 *
(1 + kErrorTolerance))));
EXPECT_THAT(
matched_backend_count,
::testing::AllOf(::testing::Ge(static_cast<double>(kNumRpcs) * 25 / 100 *
(1 - kErrorTolerance)),
::testing::Le(static_cast<double>(kNumRpcs) * 25 / 100 *
(1 + kErrorTolerance))));
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
}
TEST_P(LdsRdsTest, XdsRoutingHeadersMatchingUnmatchCases) {
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const char* kNewCluster3Name = "new_cluster_3";
const char* kNewEdsService3Name = "new_eds_service_name_3";
const size_t kNumEcho1Rpcs = 100;
const size_t kNumEchoRpcs = 5;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 3)},
});
AdsServiceImpl::EdsResourceArgs args3({
{"locality0", GetBackendPorts(3, 4)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args3, kNewEdsService3Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
Cluster new_cluster3 = default_cluster_;
new_cluster3.set_name(kNewCluster3Name);
new_cluster3.mutable_eds_cluster_config()->set_service_name(
kNewEdsService3Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster3);
// Populating Route Configurations for LDS.
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* header_matcher1 = route1->mutable_match()->add_headers();
header_matcher1->set_name("header1");
header_matcher1->set_exact_match("POST");
route1->mutable_route()->set_cluster(kNewCluster1Name);
auto route2 = route_config.mutable_virtual_hosts(0)->add_routes();
route2->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* header_matcher2 = route2->mutable_match()->add_headers();
header_matcher2->set_name("header2");
header_matcher2->mutable_range_match()->set_start(1);
header_matcher2->mutable_range_match()->set_end(1000);
route2->mutable_route()->set_cluster(kNewCluster2Name);
auto route3 = route_config.mutable_virtual_hosts(0)->add_routes();
route3->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
auto* header_matcher3 = route3->mutable_match()->add_headers();
header_matcher3->set_name("header3");
header_matcher3->mutable_safe_regex_match()->set_regex("[a-z]*");
route3->mutable_route()->set_cluster(kNewCluster3Name);
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
// Send headers which will mismatch each route
std::vector<std::pair<std::string, std::string>> metadata = {
{"header1", "POST"},
{"header2", "1000"},
{"header3", "123"},
{"header1", "GET"},
};
WaitForAllBackends(0, 1);
CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_metadata(metadata));
CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions()
.set_rpc_service(SERVICE_ECHO1)
.set_rpc_method(METHOD_ECHO1)
.set_metadata(metadata));
// Verify that only the default backend got RPCs since all previous routes
// were mismatched.
for (size_t i = 1; i < 4; ++i) {
EXPECT_EQ(0, backends_[i]->backend_service()->request_count());
EXPECT_EQ(0, backends_[i]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[i]->backend_service2()->request_count());
}
EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
EXPECT_EQ(kNumEcho1Rpcs, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service2()->request_count());
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
}
TEST_P(LdsRdsTest, XdsRoutingChangeRoutesWithoutChangingClusters) {
const char* kNewClusterName = "new_cluster";
const char* kNewEdsServiceName = "new_eds_service_name";
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsServiceName));
// Populate new CDS resources.
Cluster new_cluster = default_cluster_;
new_cluster.set_name(kNewClusterName);
new_cluster.mutable_eds_cluster_config()->set_service_name(
kNewEdsServiceName);
balancers_[0]->ads_service()->SetCdsResource(new_cluster);
// Populating Route Configurations for LDS.
RouteConfiguration route_config = default_route_config_;
auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
route1->mutable_route()->set_cluster(kNewClusterName);
auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
default_route->mutable_match()->set_prefix("");
default_route->mutable_route()->set_cluster(kDefaultClusterName);
SetRouteConfiguration(0, route_config);
// Make sure all backends are up and that requests for each RPC
// service go to the right backends.
WaitForAllBackends(0, 1, false);
WaitForAllBackends(1, 2, false, RpcOptions().set_rpc_service(SERVICE_ECHO1));
WaitForAllBackends(0, 1, false, RpcOptions().set_rpc_service(SERVICE_ECHO2));
// Requests for services Echo and Echo2 should have gone to backend 0.
EXPECT_EQ(1, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(1, backends_[0]->backend_service2()->request_count());
// Requests for service Echo1 should have gone to backend 1.
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
EXPECT_EQ(1, backends_[1]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service2()->request_count());
// Now send an update that changes the first route to match a
// different RPC service, and wait for the client to make the change.
route1->mutable_match()->set_prefix("/grpc.testing.EchoTest2Service/");
SetRouteConfiguration(0, route_config);
WaitForAllBackends(1, 2, true, RpcOptions().set_rpc_service(SERVICE_ECHO2));
// Now repeat the earlier test, making sure all traffic goes to the
// right place.
WaitForAllBackends(0, 1, false);
WaitForAllBackends(0, 1, false, RpcOptions().set_rpc_service(SERVICE_ECHO1));
WaitForAllBackends(1, 2, false, RpcOptions().set_rpc_service(SERVICE_ECHO2));
// Requests for services Echo and Echo1 should have gone to backend 0.
EXPECT_EQ(1, backends_[0]->backend_service()->request_count());
EXPECT_EQ(1, backends_[0]->backend_service1()->request_count());
EXPECT_EQ(0, backends_[0]->backend_service2()->request_count());
// Requests for service Echo2 should have gone to backend 1.
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service1()->request_count());
EXPECT_EQ(1, backends_[1]->backend_service2()->request_count());
}
// Test that we NACK unknown filter types in VirtualHost.
TEST_P(LdsRdsTest, RejectsUnknownHttpFilterTypeInVirtualHost) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config =
route_config.mutable_virtual_hosts(0)->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"].PackFrom(Listener());
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("no filter registered for config type "
"envoy.config.listener.v3.Listener"));
}
// Test that we ignore optional unknown filter types in VirtualHost.
TEST_P(LdsRdsTest, IgnoresOptionalUnknownHttpFilterTypeInVirtualHost) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config =
route_config.mutable_virtual_hosts(0)->mutable_typed_per_filter_config();
::envoy::config::route::v3::FilterConfig filter_config;
filter_config.mutable_config()->PackFrom(Listener());
filter_config.set_is_optional(true);
(*per_filter_config)["unknown"].PackFrom(filter_config);
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
WaitForAllBackends();
EXPECT_EQ(RouteConfigurationResponseState(0).state,
AdsServiceImpl::ResponseState::ACKED);
}
// Test that we NACK filters without configs in VirtualHost.
TEST_P(LdsRdsTest, RejectsHttpFilterWithoutConfigInVirtualHost) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config =
route_config.mutable_virtual_hosts(0)->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"];
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"no filter config specified for filter name unknown"));
}
// Test that we NACK filters without configs in FilterConfig in VirtualHost.
TEST_P(LdsRdsTest, RejectsHttpFilterWithoutConfigInFilterConfigInVirtualHost) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config =
route_config.mutable_virtual_hosts(0)->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"].PackFrom(
::envoy::config::route::v3::FilterConfig());
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"no filter config specified for filter name unknown"));
}
// Test that we ignore optional filters without configs in VirtualHost.
TEST_P(LdsRdsTest, IgnoresOptionalHttpFilterWithoutConfigInVirtualHost) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config =
route_config.mutable_virtual_hosts(0)->mutable_typed_per_filter_config();
::envoy::config::route::v3::FilterConfig filter_config;
filter_config.set_is_optional(true);
(*per_filter_config)["unknown"].PackFrom(filter_config);
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
WaitForAllBackends();
EXPECT_EQ(RouteConfigurationResponseState(0).state,
AdsServiceImpl::ResponseState::ACKED);
}
// Test that we NACK unparseable filter types in VirtualHost.
TEST_P(LdsRdsTest, RejectsUnparseableHttpFilterTypeInVirtualHost) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config =
route_config.mutable_virtual_hosts(0)->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"].PackFrom(
envoy::extensions::filters::http::router::v3::Router());
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("router filter does not support config override"));
}
// Test that we NACK unknown filter types in Route.
TEST_P(LdsRdsTest, RejectsUnknownHttpFilterTypeInRoute) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"].PackFrom(Listener());
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("no filter registered for config type "
"envoy.config.listener.v3.Listener"));
}
// Test that we ignore optional unknown filter types in Route.
TEST_P(LdsRdsTest, IgnoresOptionalUnknownHttpFilterTypeInRoute) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_typed_per_filter_config();
::envoy::config::route::v3::FilterConfig filter_config;
filter_config.mutable_config()->PackFrom(Listener());
filter_config.set_is_optional(true);
(*per_filter_config)["unknown"].PackFrom(filter_config);
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
WaitForAllBackends();
EXPECT_EQ(RouteConfigurationResponseState(0).state,
AdsServiceImpl::ResponseState::ACKED);
}
// Test that we NACK filters without configs in Route.
TEST_P(LdsRdsTest, RejectsHttpFilterWithoutConfigInRoute) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"];
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"no filter config specified for filter name unknown"));
}
// Test that we NACK filters without configs in FilterConfig in Route.
TEST_P(LdsRdsTest, RejectsHttpFilterWithoutConfigInFilterConfigInRoute) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"].PackFrom(
::envoy::config::route::v3::FilterConfig());
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"no filter config specified for filter name unknown"));
}
// Test that we ignore optional filters without configs in Route.
TEST_P(LdsRdsTest, IgnoresOptionalHttpFilterWithoutConfigInRoute) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_typed_per_filter_config();
::envoy::config::route::v3::FilterConfig filter_config;
filter_config.set_is_optional(true);
(*per_filter_config)["unknown"].PackFrom(filter_config);
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
WaitForAllBackends();
EXPECT_EQ(RouteConfigurationResponseState(0).state,
AdsServiceImpl::ResponseState::ACKED);
}
// Test that we NACK unparseable filter types in Route.
TEST_P(LdsRdsTest, RejectsUnparseableHttpFilterTypeInRoute) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* per_filter_config = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"].PackFrom(
envoy::extensions::filters::http::router::v3::Router());
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("router filter does not support config override"));
}
// Test that we NACK unknown filter types in ClusterWeight.
TEST_P(LdsRdsTest, RejectsUnknownHttpFilterTypeInClusterWeight) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* cluster_weight = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_weighted_clusters()
->add_clusters();
cluster_weight->set_name(kDefaultClusterName);
cluster_weight->mutable_weight()->set_value(100);
auto* per_filter_config = cluster_weight->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"].PackFrom(Listener());
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("no filter registered for config type "
"envoy.config.listener.v3.Listener"));
}
// Test that we ignore optional unknown filter types in ClusterWeight.
TEST_P(LdsRdsTest, IgnoresOptionalUnknownHttpFilterTypeInClusterWeight) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* cluster_weight = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_weighted_clusters()
->add_clusters();
cluster_weight->set_name(kDefaultClusterName);
cluster_weight->mutable_weight()->set_value(100);
auto* per_filter_config = cluster_weight->mutable_typed_per_filter_config();
::envoy::config::route::v3::FilterConfig filter_config;
filter_config.mutable_config()->PackFrom(Listener());
filter_config.set_is_optional(true);
(*per_filter_config)["unknown"].PackFrom(filter_config);
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
WaitForAllBackends();
EXPECT_EQ(RouteConfigurationResponseState(0).state,
AdsServiceImpl::ResponseState::ACKED);
}
// Test that we NACK filters without configs in ClusterWeight.
TEST_P(LdsRdsTest, RejectsHttpFilterWithoutConfigInClusterWeight) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* cluster_weight = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_weighted_clusters()
->add_clusters();
cluster_weight->set_name(kDefaultClusterName);
cluster_weight->mutable_weight()->set_value(100);
auto* per_filter_config = cluster_weight->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"];
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"no filter config specified for filter name unknown"));
}
// Test that we NACK filters without configs in FilterConfig in ClusterWeight.
TEST_P(LdsRdsTest,
RejectsHttpFilterWithoutConfigInFilterConfigInClusterWeight) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* cluster_weight = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_weighted_clusters()
->add_clusters();
cluster_weight->set_name(kDefaultClusterName);
cluster_weight->mutable_weight()->set_value(100);
auto* per_filter_config = cluster_weight->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"].PackFrom(
::envoy::config::route::v3::FilterConfig());
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"no filter config specified for filter name unknown"));
}
// Test that we ignore optional filters without configs in ClusterWeight.
TEST_P(LdsRdsTest, IgnoresOptionalHttpFilterWithoutConfigInClusterWeight) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* cluster_weight = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_weighted_clusters()
->add_clusters();
cluster_weight->set_name(kDefaultClusterName);
cluster_weight->mutable_weight()->set_value(100);
auto* per_filter_config = cluster_weight->mutable_typed_per_filter_config();
::envoy::config::route::v3::FilterConfig filter_config;
filter_config.set_is_optional(true);
(*per_filter_config)["unknown"].PackFrom(filter_config);
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
WaitForAllBackends();
EXPECT_EQ(RouteConfigurationResponseState(0).state,
AdsServiceImpl::ResponseState::ACKED);
}
// Test that we NACK unparseable filter types in ClusterWeight.
TEST_P(LdsRdsTest, RejectsUnparseableHttpFilterTypeInClusterWeight) {
if (GetParam().use_v2()) return; // Filters supported in v3 only.
RouteConfiguration route_config = default_route_config_;
auto* cluster_weight = route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_weighted_clusters()
->add_clusters();
cluster_weight->set_name(kDefaultClusterName);
cluster_weight->mutable_weight()->set_value(100);
auto* per_filter_config = cluster_weight->mutable_typed_per_filter_config();
(*per_filter_config)["unknown"].PackFrom(
envoy::extensions::filters::http::router::v3::Router());
SetListenerAndRouteConfiguration(0, default_listener_, route_config);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Wait until xDS server sees NACK.
do {
CheckRpcSendFailure();
} while (RouteConfigurationResponseState(0).state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state = RouteConfigurationResponseState(0);
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("router filter does not support config override"));
}
using CdsTest = BasicTest;
// Tests that CDS client should send an ACK upon correct CDS response.
TEST_P(CdsTest, Vanilla) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
(void)SendRpc();
EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state().state,
AdsServiceImpl::ResponseState::ACKED);
}
TEST_P(CdsTest, LogicalDNSClusterType) {
gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
"true");
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Create Logical DNS Cluster
auto cluster = default_cluster_;
cluster.set_type(Cluster::LOGICAL_DNS);
balancers_[0]->ads_service()->SetCdsResource(cluster);
// Set Logical DNS result
{
grpc_core::ExecCtx exec_ctx;
grpc_core::Resolver::Result result;
result.addresses = CreateAddressListFromPortList(GetBackendPorts(1, 2));
logical_dns_cluster_resolver_response_generator_->SetResponse(
std::move(result));
}
// Wait for traffic to go to backend 1.
WaitForBackend(1);
gpr_unsetenv(
"GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
}
TEST_P(CdsTest, AggregateClusterType) {
gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
"true");
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 3)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
// Create Aggregate Cluster
auto cluster = default_cluster_;
CustomClusterType* custom_cluster = cluster.mutable_cluster_type();
custom_cluster->set_name("envoy.clusters.aggregate");
ClusterConfig cluster_config;
cluster_config.add_clusters(kNewCluster1Name);
cluster_config.add_clusters(kNewCluster2Name);
custom_cluster->mutable_typed_config()->PackFrom(cluster_config);
balancers_[0]->ads_service()->SetCdsResource(cluster);
// Wait for traffic to go to backend 1.
WaitForBackend(1);
// Shutdown backend 1 and wait for all traffic to go to backend 2.
ShutdownBackend(1);
WaitForBackend(2);
EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state().state,
AdsServiceImpl::ResponseState::ACKED);
// Bring backend 1 back and ensure all traffic go back to it.
StartBackend(1);
WaitForBackend(1);
gpr_unsetenv(
"GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
}
TEST_P(CdsTest, AggregateClusterEdsToLogicalDns) {
gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
"true");
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kLogicalDNSClusterName = "logical_dns_cluster";
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args1({
{"locality0", GetBackendPorts(1, 2)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
// Create Logical DNS Cluster
auto logical_dns_cluster = default_cluster_;
logical_dns_cluster.set_name(kLogicalDNSClusterName);
logical_dns_cluster.set_type(Cluster::LOGICAL_DNS);
balancers_[0]->ads_service()->SetCdsResource(logical_dns_cluster);
// Create Aggregate Cluster
auto cluster = default_cluster_;
CustomClusterType* custom_cluster = cluster.mutable_cluster_type();
custom_cluster->set_name("envoy.clusters.aggregate");
ClusterConfig cluster_config;
cluster_config.add_clusters(kNewCluster1Name);
cluster_config.add_clusters(kLogicalDNSClusterName);
custom_cluster->mutable_typed_config()->PackFrom(cluster_config);
balancers_[0]->ads_service()->SetCdsResource(cluster);
// Set Logical DNS result
{
grpc_core::ExecCtx exec_ctx;
grpc_core::Resolver::Result result;
result.addresses = CreateAddressListFromPortList(GetBackendPorts(2, 3));
logical_dns_cluster_resolver_response_generator_->SetResponse(
std::move(result));
}
// Wait for traffic to go to backend 1.
WaitForBackend(1);
// Shutdown backend 1 and wait for all traffic to go to backend 2.
ShutdownBackend(1);
WaitForBackend(2);
EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state().state,
AdsServiceImpl::ResponseState::ACKED);
// Bring backend 1 back and ensure all traffic go back to it.
StartBackend(1);
WaitForBackend(1);
gpr_unsetenv(
"GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
}
TEST_P(CdsTest, AggregateClusterLogicalDnsToEds) {
gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
"true");
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
const char* kLogicalDNSClusterName = "logical_dns_cluster";
// Populate new EDS resources.
AdsServiceImpl::EdsResourceArgs args2({
{"locality0", GetBackendPorts(2, 3)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
// Populate new CDS resources.
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
// Create Logical DNS Cluster
auto logical_dns_cluster = default_cluster_;
logical_dns_cluster.set_name(kLogicalDNSClusterName);
logical_dns_cluster.set_type(Cluster::LOGICAL_DNS);
balancers_[0]->ads_service()->SetCdsResource(logical_dns_cluster);
// Create Aggregate Cluster
auto cluster = default_cluster_;
CustomClusterType* custom_cluster = cluster.mutable_cluster_type();
custom_cluster->set_name("envoy.clusters.aggregate");
ClusterConfig cluster_config;
cluster_config.add_clusters(kLogicalDNSClusterName);
cluster_config.add_clusters(kNewCluster2Name);
custom_cluster->mutable_typed_config()->PackFrom(cluster_config);
balancers_[0]->ads_service()->SetCdsResource(cluster);
// Set Logical DNS result
{
grpc_core::ExecCtx exec_ctx;
grpc_core::Resolver::Result result;
result.addresses = CreateAddressListFromPortList(GetBackendPorts(1, 2));
logical_dns_cluster_resolver_response_generator_->SetResponse(
std::move(result));
}
// Wait for traffic to go to backend 1.
WaitForBackend(1);
// Shutdown backend 1 and wait for all traffic to go to backend 2.
ShutdownBackend(1);
WaitForBackend(2);
EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state().state,
AdsServiceImpl::ResponseState::ACKED);
// Bring backend 1 back and ensure all traffic go back to it.
StartBackend(1);
WaitForBackend(1);
gpr_unsetenv(
"GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
}
// Test that CDS client should send a NACK if cluster type is Logical DNS but
// the feature is not yet supported.
TEST_P(CdsTest, LogicalDNSClusterTypeDisabled) {
auto cluster = default_cluster_;
cluster.set_type(Cluster::LOGICAL_DNS);
balancers_[0]->ads_service()->SetCdsResource(cluster);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->cds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("DiscoveryType is not valid."));
}
// Test that CDS client should send a NACK if cluster type is AGGREGATE but
// the feature is not yet supported.
TEST_P(CdsTest, AggregateClusterTypeDisabled) {
auto cluster = default_cluster_;
CustomClusterType* custom_cluster = cluster.mutable_cluster_type();
custom_cluster->set_name("envoy.clusters.aggregate");
ClusterConfig cluster_config;
cluster_config.add_clusters("cluster1");
cluster_config.add_clusters("cluster2");
custom_cluster->mutable_typed_config()->PackFrom(cluster_config);
cluster.set_type(Cluster::LOGICAL_DNS);
balancers_[0]->ads_service()->SetCdsResource(cluster);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->cds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("DiscoveryType is not valid."));
}
// Tests that CDS client should send a NACK if the cluster type in CDS response
// is unsupported.
TEST_P(CdsTest, UnsupportedClusterType) {
auto cluster = default_cluster_;
cluster.set_type(Cluster::STATIC);
balancers_[0]->ads_service()->SetCdsResource(cluster);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->cds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("DiscoveryType is not valid."));
}
// Tests that the NACK for multiple bad resources includes both errors.
TEST_P(CdsTest, MultipleBadResources) {
constexpr char kClusterName2[] = "cluster_name_2";
// Use unsupported type for default cluster.
auto cluster = default_cluster_;
cluster.set_type(Cluster::STATIC);
balancers_[0]->ads_service()->SetCdsResource(cluster);
// Add second cluster with the same error.
cluster.set_name(kClusterName2);
balancers_[0]->ads_service()->SetCdsResource(cluster);
// Change RouteConfig to point to both clusters.
RouteConfiguration route_config = default_route_config_;
auto* route = route_config.mutable_virtual_hosts(0)->add_routes();
route->mutable_match()->set_prefix("");
route->mutable_route()->set_cluster(kClusterName2);
SetRouteConfiguration(0, route_config);
// Send RPC.
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->cds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::AllOf(
::testing::HasSubstr(absl::StrCat(
kDefaultClusterName, ": DiscoveryType is not valid.")),
::testing::HasSubstr(absl::StrCat(
kClusterName2, ": DiscoveryType is not valid."))));
}
// Tests that CDS client should send a NACK if the eds_config in CDS response is
// other than ADS.
TEST_P(CdsTest, WrongEdsConfig) {
auto cluster = default_cluster_;
cluster.mutable_eds_cluster_config()->mutable_eds_config()->mutable_self();
balancers_[0]->ads_service()->SetCdsResource(cluster);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->cds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("EDS ConfigSource is not ADS."));
}
// Tests that CDS client should send a NACK if the lb_policy in CDS response is
// other than ROUND_ROBIN.
TEST_P(CdsTest, WrongLbPolicy) {
auto cluster = default_cluster_;
cluster.set_lb_policy(Cluster::LEAST_REQUEST);
balancers_[0]->ads_service()->SetCdsResource(cluster);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->cds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("LB policy is not supported."));
}
// Tests that CDS client should send a NACK if the lrs_server in CDS response is
// other than SELF.
TEST_P(CdsTest, WrongLrsServer) {
auto cluster = default_cluster_;
cluster.mutable_lrs_server()->mutable_ads();
balancers_[0]->ads_service()->SetCdsResource(cluster);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->cds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("LRS ConfigSource is not self."));
}
class XdsSecurityTest : public BasicTest {
protected:
static void SetUpTestCase() {
gpr_setenv("GRPC_XDS_EXPERIMENTAL_SECURITY_SUPPORT", "true");
BasicTest::SetUpTestCase();
}
static void TearDownTestCase() {
BasicTest::TearDownTestCase();
gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_SECURITY_SUPPORT");
}
void SetUp() override {
BasicTest::SetUp();
root_cert_ = ReadFile(kCaCertPath);
bad_root_cert_ = ReadFile(kBadClientCertPath);
identity_pair_ = ReadTlsIdentityPair(kClientKeyPath, kClientCertPath);
// TODO(yashykt): Use different client certs here instead of reusing server
// certs after https://github.com/grpc/grpc/pull/24876 is merged
fallback_identity_pair_ =
ReadTlsIdentityPair(kServerKeyPath, kServerCertPath);
bad_identity_pair_ =
ReadTlsIdentityPair(kBadClientKeyPath, kBadClientCertPath);
server_san_exact_.set_exact("*.test.google.fr");
server_san_prefix_.set_prefix("waterzooi.test.google");
server_san_suffix_.set_suffix("google.fr");
server_san_contains_.set_contains("google");
server_san_regex_.mutable_safe_regex()->mutable_google_re2();
server_san_regex_.mutable_safe_regex()->set_regex(
"(foo|waterzooi).test.google.(fr|be)");
bad_san_1_.set_exact("192.168.1.4");
bad_san_2_.set_exact("foo.test.google.in");
authenticated_identity_ = {"testclient"};
fallback_authenticated_identity_ = {"*.test.google.fr",
"waterzooi.test.google.be",
"*.test.youtube.com", "192.168.1.3"};
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolutionForLbChannelAllBalancers();
}
void TearDown() override {
g_fake1_cert_data_map = nullptr;
g_fake2_cert_data_map = nullptr;
BasicTest::TearDown();
}
// Sends CDS updates with the new security configuration and verifies that
// after propagation, this new configuration is used for connections. If \a
// identity_instance_name and \a root_instance_name are both empty,
// connections are expected to use fallback credentials.
void UpdateAndVerifyXdsSecurityConfiguration(
absl::string_view root_instance_name,
absl::string_view root_certificate_name,
absl::string_view identity_instance_name,
absl::string_view identity_certificate_name,
const std::vector<StringMatcher>& san_matchers,
const std::vector<std::string>& expected_authenticated_identity,
bool test_expects_failure = false) {
auto cluster = default_cluster_;
if (!identity_instance_name.empty() || !root_instance_name.empty()) {
auto* transport_socket = cluster.mutable_transport_socket();
transport_socket->set_name("envoy.transport_sockets.tls");
UpstreamTlsContext upstream_tls_context;
if (!identity_instance_name.empty()) {
upstream_tls_context.mutable_common_tls_context()
->mutable_tls_certificate_certificate_provider_instance()
->set_instance_name(std::string(identity_instance_name));
upstream_tls_context.mutable_common_tls_context()
->mutable_tls_certificate_certificate_provider_instance()
->set_certificate_name(std::string(identity_certificate_name));
}
if (!root_instance_name.empty()) {
upstream_tls_context.mutable_common_tls_context()
->mutable_combined_validation_context()
->mutable_validation_context_certificate_provider_instance()
->set_instance_name(std::string(root_instance_name));
upstream_tls_context.mutable_common_tls_context()
->mutable_combined_validation_context()
->mutable_validation_context_certificate_provider_instance()
->set_certificate_name(std::string(root_certificate_name));
}
if (!san_matchers.empty()) {
auto* validation_context =
upstream_tls_context.mutable_common_tls_context()
->mutable_combined_validation_context()
->mutable_default_validation_context();
for (const auto& san_matcher : san_matchers) {
*validation_context->add_match_subject_alt_names() = san_matcher;
}
}
transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
}
balancers_[0]->ads_service()->SetCdsResource(cluster);
// The updates might take time to have an effect, so use a retry loop.
constexpr int kRetryCount = 100;
int num_tries = 0;
for (; num_tries < kRetryCount; num_tries++) {
// Give some time for the updates to propagate.
gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(100));
if (test_expects_failure) {
// Restart the servers to force a reconnection so that previously
// connected subchannels are not used for the RPC.
ShutdownBackend(0);
StartBackend(0);
if (SendRpc().ok()) {
gpr_log(GPR_ERROR, "RPC succeeded. Failure expected. Trying again.");
continue;
}
} else {
WaitForBackend(0);
Status status = SendRpc();
if (!status.ok()) {
gpr_log(GPR_ERROR, "RPC failed. code=%d message=%s Trying again.",
status.error_code(), status.error_message().c_str());
continue;
}
if (backends_[0]->backend_service()->last_peer_identity() !=
expected_authenticated_identity) {
gpr_log(
GPR_ERROR,
"Expected client identity does not match. (actual) %s vs "
"(expected) %s Trying again.",
absl::StrJoin(
backends_[0]->backend_service()->last_peer_identity(), ",")
.c_str(),
absl::StrJoin(expected_authenticated_identity, ",").c_str());
continue;
}
}
break;
}
EXPECT_LT(num_tries, kRetryCount);
}
std::string root_cert_;
std::string bad_root_cert_;
grpc_core::PemKeyCertPairList identity_pair_;
grpc_core::PemKeyCertPairList fallback_identity_pair_;
grpc_core::PemKeyCertPairList bad_identity_pair_;
StringMatcher server_san_exact_;
StringMatcher server_san_prefix_;
StringMatcher server_san_suffix_;
StringMatcher server_san_contains_;
StringMatcher server_san_regex_;
StringMatcher bad_san_1_;
StringMatcher bad_san_2_;
std::vector<std::string> authenticated_identity_;
std::vector<std::string> fallback_authenticated_identity_;
};
TEST_P(XdsSecurityTest,
TLSConfigurationWithoutValidationContextCertificateProviderInstance) {
auto cluster = default_cluster_;
auto* transport_socket = cluster.mutable_transport_socket();
transport_socket->set_name("envoy.transport_sockets.tls");
balancers_[0]->ads_service()->SetCdsResource(cluster);
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->cds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"TLS configuration provided but no "
"validation_context_certificate_provider_instance found."));
}
TEST_P(
XdsSecurityTest,
MatchSubjectAltNamesProvidedWithoutValidationContextCertificateProviderInstance) {
auto cluster = default_cluster_;
auto* transport_socket = cluster.mutable_transport_socket();
transport_socket->set_name("envoy.transport_sockets.tls");
UpstreamTlsContext upstream_tls_context;
auto* validation_context = upstream_tls_context.mutable_common_tls_context()
->mutable_combined_validation_context()
->mutable_default_validation_context();
*validation_context->add_match_subject_alt_names() = server_san_exact_;
transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
balancers_[0]->ads_service()->SetCdsResource(cluster);
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->cds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"TLS configuration provided but no "
"validation_context_certificate_provider_instance found."));
}
TEST_P(
XdsSecurityTest,
TlsCertificateCertificateProviderInstanceWithoutValidationContextCertificateProviderInstance) {
auto cluster = default_cluster_;
auto* transport_socket = cluster.mutable_transport_socket();
transport_socket->set_name("envoy.transport_sockets.tls");
UpstreamTlsContext upstream_tls_context;
upstream_tls_context.mutable_common_tls_context()
->mutable_tls_certificate_certificate_provider_instance()
->set_instance_name(std::string("instance_name"));
transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
balancers_[0]->ads_service()->SetCdsResource(cluster);
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->cds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"TLS configuration provided but no "
"validation_context_certificate_provider_instance found."));
}
TEST_P(XdsSecurityTest, RegexSanMatcherDoesNotAllowIgnoreCase) {
auto cluster = default_cluster_;
auto* transport_socket = cluster.mutable_transport_socket();
transport_socket->set_name("envoy.transport_sockets.tls");
UpstreamTlsContext upstream_tls_context;
upstream_tls_context.mutable_common_tls_context()
->mutable_combined_validation_context()
->mutable_validation_context_certificate_provider_instance()
->set_instance_name(std::string("fake_plugin1"));
auto* validation_context = upstream_tls_context.mutable_common_tls_context()
->mutable_combined_validation_context()
->mutable_default_validation_context();
StringMatcher matcher;
matcher.mutable_safe_regex()->mutable_google_re2();
matcher.mutable_safe_regex()->set_regex(
"(foo|waterzooi).test.google.(fr|be)");
matcher.set_ignore_case(true);
*validation_context->add_match_subject_alt_names() = matcher;
transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
balancers_[0]->ads_service()->SetCdsResource(cluster);
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->cds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"StringMatcher: ignore_case has no effect for SAFE_REGEX."));
}
TEST_P(XdsSecurityTest, UnknownRootCertificateProvider) {
auto cluster = default_cluster_;
auto* transport_socket = cluster.mutable_transport_socket();
transport_socket->set_name("envoy.transport_sockets.tls");
UpstreamTlsContext upstream_tls_context;
upstream_tls_context.mutable_common_tls_context()
->mutable_combined_validation_context()
->mutable_validation_context_certificate_provider_instance()
->set_instance_name("unknown");
transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
balancers_[0]->ads_service()->SetCdsResource(cluster);
CheckRpcSendFailure(1, RpcOptions(), StatusCode::UNAVAILABLE);
}
TEST_P(XdsSecurityTest, UnknownIdentityCertificateProvider) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
auto cluster = default_cluster_;
auto* transport_socket = cluster.mutable_transport_socket();
transport_socket->set_name("envoy.transport_sockets.tls");
UpstreamTlsContext upstream_tls_context;
upstream_tls_context.mutable_common_tls_context()
->mutable_tls_certificate_certificate_provider_instance()
->set_instance_name("unknown");
upstream_tls_context.mutable_common_tls_context()
->mutable_combined_validation_context()
->mutable_validation_context_certificate_provider_instance()
->set_instance_name("fake_plugin1");
transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
balancers_[0]->ads_service()->SetCdsResource(cluster);
CheckRpcSendFailure(1, RpcOptions(), StatusCode::UNAVAILABLE);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithNoSanMatchers) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {}, authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithExactSanMatcher) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_exact_},
authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithPrefixSanMatcher) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_prefix_},
authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithSuffixSanMatcher) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_suffix_},
authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithContainsSanMatcher) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_contains_},
authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithRegexSanMatcher) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_regex_},
authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithSanMatchersUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration(
"fake_plugin1", "", "fake_plugin1", "",
{server_san_exact_, server_san_prefix_}, authenticated_identity_);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {bad_san_1_, bad_san_2_}, {},
true /* failure */);
UpdateAndVerifyXdsSecurityConfiguration(
"fake_plugin1", "", "fake_plugin1", "",
{server_san_prefix_, server_san_regex_}, authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithRootPluginUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
FakeCertificateProvider::CertDataMap fake2_cert_map = {
{"", {bad_root_cert_, bad_identity_pair_}}};
g_fake2_cert_data_map = &fake2_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_exact_},
authenticated_identity_);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin2" /* bad root */, "",
"fake_plugin1", "", {}, {},
true /* failure */);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_exact_},
authenticated_identity_);
g_fake1_cert_data_map = nullptr;
g_fake2_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithIdentityPluginUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
FakeCertificateProvider::CertDataMap fake2_cert_map = {
{"", {root_cert_, fallback_identity_pair_}}};
g_fake2_cert_data_map = &fake2_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_exact_},
authenticated_identity_);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin2",
"", {server_san_exact_},
fallback_authenticated_identity_);
g_fake1_cert_data_map = nullptr;
g_fake2_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithBothPluginsUpdated) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
FakeCertificateProvider::CertDataMap fake2_cert_map = {
{"", {bad_root_cert_, bad_identity_pair_}},
{"good", {root_cert_, fallback_identity_pair_}}};
g_fake2_cert_data_map = &fake2_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin2", "", "fake_plugin2",
"", {}, {}, true /* failure */);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_prefix_},
authenticated_identity_);
UpdateAndVerifyXdsSecurityConfiguration(
"fake_plugin2", "good", "fake_plugin2", "good", {server_san_prefix_},
fallback_authenticated_identity_);
g_fake1_cert_data_map = nullptr;
g_fake2_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithRootCertificateNameUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}},
{"bad", {bad_root_cert_, bad_identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_regex_},
authenticated_identity_);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "bad", "fake_plugin1",
"", {server_san_regex_}, {},
true /* failure */);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest,
TestMtlsConfigurationWithIdentityCertificateNameUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}},
{"bad", {bad_root_cert_, bad_identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_exact_},
authenticated_identity_);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"bad", {server_san_exact_}, {},
true /* failure */);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest,
TestMtlsConfigurationWithIdentityCertificateNameUpdateGoodCerts) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}},
{"good", {root_cert_, fallback_identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_exact_},
authenticated_identity_);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"good", {server_san_exact_},
fallback_authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsConfigurationWithBothCertificateNamesUpdated) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}},
{"bad", {bad_root_cert_, bad_identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "bad", "fake_plugin1",
"bad", {server_san_prefix_}, {},
true /* failure */);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_prefix_},
authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestTlsConfigurationWithNoSanMatchers) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "", {},
{} /* unauthenticated */);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestTlsConfigurationWithSanMatchers) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration(
"fake_plugin1", "", "", "",
{server_san_exact_, server_san_prefix_, server_san_regex_},
{} /* unauthenticated */);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestTlsConfigurationWithSanMatchersUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration(
"fake_plugin1", "", "", "", {server_san_exact_, server_san_prefix_},
{} /* unauthenticated */);
UpdateAndVerifyXdsSecurityConfiguration(
"fake_plugin1", "", "", "", {bad_san_1_, bad_san_2_},
{} /* unauthenticated */, true /* failure */);
UpdateAndVerifyXdsSecurityConfiguration(
"fake_plugin1", "", "", "", {server_san_prefix_, server_san_regex_},
{} /* unauthenticated */);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestTlsConfigurationWithRootCertificateNameUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}},
{"bad", {bad_root_cert_, bad_identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
{server_san_exact_},
{} /* unauthenticated */);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "bad", "", "",
{server_san_exact_}, {},
true /* failure */);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestTlsConfigurationWithRootPluginUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
FakeCertificateProvider::CertDataMap fake2_cert_map = {
{"", {bad_root_cert_, bad_identity_pair_}}};
g_fake2_cert_data_map = &fake2_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
{server_san_exact_},
{} /* unauthenticated */);
UpdateAndVerifyXdsSecurityConfiguration(
"fake_plugin2", "", "", "", {server_san_exact_}, {}, true /* failure */);
g_fake1_cert_data_map = nullptr;
g_fake2_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestFallbackConfiguration) {
UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
fallback_authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsToTls) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_exact_},
authenticated_identity_);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
{server_san_exact_},
{} /* unauthenticated */);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestMtlsToFallback) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_exact_},
authenticated_identity_);
UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
fallback_authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestTlsToMtls) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
{server_san_exact_},
{} /* unauthenticated */);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_exact_},
authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestTlsToFallback) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
{server_san_exact_},
{} /* unauthenticated */);
UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
fallback_authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestFallbackToMtls) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
fallback_authenticated_identity_);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
"", {server_san_exact_},
authenticated_identity_);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestFallbackToTls) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
fallback_authenticated_identity_);
UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
{server_san_exact_},
{} /* unauthenticated */);
g_fake1_cert_data_map = nullptr;
}
TEST_P(XdsSecurityTest, TestFileWatcherCertificateProvider) {
UpdateAndVerifyXdsSecurityConfiguration("file_plugin", "", "file_plugin", "",
{server_san_exact_},
authenticated_identity_);
}
class XdsEnabledServerTest : public XdsEnd2endTest {
protected:
XdsEnabledServerTest()
: XdsEnd2endTest(1, 1, 100, true /* use_xds_enabled_server */) {}
void SetUp() override {
XdsEnd2endTest::SetUp();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
}
};
TEST_P(XdsEnabledServerTest, Basic) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
listener.mutable_address()->mutable_socket_address()->set_address(
ipv6_only_ ? "::1" : "127.0.0.1");
listener.mutable_address()->mutable_socket_address()->set_port_value(
backends_[0]->port());
listener.add_filter_chains()->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
balancers_[0]->ads_service()->SetLdsResource(listener);
WaitForBackend(0);
}
TEST_P(XdsEnabledServerTest, BadLdsUpdateNoApiListenerNorAddress) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
listener.add_filter_chains()->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("Listener has neither address nor ApiListener"));
}
TEST_P(XdsEnabledServerTest, BadLdsUpdateBothApiListenerAndAddress) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
balancers_[0]->ads_service()->SetLdsResource(listener);
listener.mutable_address()->mutable_socket_address()->set_address(
ipv6_only_ ? "::1" : "127.0.0.1");
listener.mutable_address()->mutable_socket_address()->set_port_value(
backends_[0]->port());
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
listener.mutable_api_listener();
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("Listener has both address and ApiListener"));
}
TEST_P(XdsEnabledServerTest, UnsupportedL4Filter) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
balancers_[0]->ads_service()->SetLdsResource(listener);
listener.mutable_address()->mutable_socket_address()->set_address(
ipv6_only_ ? "::1" : "127.0.0.1");
listener.mutable_address()->mutable_socket_address()->set_port_value(
backends_[0]->port());
listener.add_filter_chains()->add_filters()->mutable_typed_config()->PackFrom(default_listener_ /* any proto object other than HttpConnectionManager */);
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("Unsupported filter type"));
}
TEST_P(XdsEnabledServerTest, UnsupportedHttpFilter) {
// Set env var to enable filters parsing.
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
listener.mutable_address()->mutable_socket_address()->set_address(
ipv6_only_ ? "::1" : "127.0.0.1");
listener.mutable_address()->mutable_socket_address()->set_port_value(
backends_[0]->port());
HttpConnectionManager http_connection_manager;
auto* http_filter = http_connection_manager.add_http_filters();
http_filter->set_name("grpc.testing.unsupported_http_filter");
http_filter->mutable_typed_config()->set_type_url(
"grpc.testing.unsupported_http_filter");
listener.add_filter_chains()->add_filters()->mutable_typed_config()->PackFrom(
http_connection_manager);
balancers_[0]->ads_service()->SetLdsResource(listener);
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=[::1]:",
backends_[0]->port()));
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("no filter registered for config type "
"grpc.testing.unsupported_http_filter"));
}
TEST_P(XdsEnabledServerTest, HttpFilterNotSupportedOnServer) {
// Set env var to enable filters parsing.
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
listener.mutable_address()->mutable_socket_address()->set_address(
ipv6_only_ ? "::1" : "127.0.0.1");
listener.mutable_address()->mutable_socket_address()->set_port_value(
backends_[0]->port());
HttpConnectionManager http_connection_manager;
auto* http_filter = http_connection_manager.add_http_filters();
http_filter->set_name("grpc.testing.client_only_http_filter");
http_filter->mutable_typed_config()->set_type_url(
"grpc.testing.client_only_http_filter");
listener.add_filter_chains()->add_filters()->mutable_typed_config()->PackFrom(
http_connection_manager);
balancers_[0]->ads_service()->SetLdsResource(listener);
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=[::1]:",
backends_[0]->port()));
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("Filter grpc.testing.client_only_http_filter is not "
"supported on servers"));
}
TEST_P(XdsEnabledServerTest,
HttpFilterNotSupportedOnServerIgnoredWhenOptional) {
// Set env var to enable filters parsing.
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
listener.mutable_address()->mutable_socket_address()->set_address(
ipv6_only_ ? "::1" : "127.0.0.1");
listener.mutable_address()->mutable_socket_address()->set_port_value(
backends_[0]->port());
HttpConnectionManager http_connection_manager;
auto* http_filter = http_connection_manager.add_http_filters();
http_filter->set_name("grpc.testing.client_only_http_filter");
http_filter->mutable_typed_config()->set_type_url(
"grpc.testing.client_only_http_filter");
http_filter->set_is_optional(true);
listener.add_filter_chains()->add_filters()->mutable_typed_config()->PackFrom(
http_connection_manager);
balancers_[0]->ads_service()->SetLdsResource(listener);
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=[::1]:",
backends_[0]->port()));
balancers_[0]->ads_service()->SetLdsResource(listener);
WaitForBackend(0);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
}
// Verify that a mismatch of listening address results in "not serving" status.
TEST_P(XdsEnabledServerTest, ListenerAddressMismatch) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
listener.mutable_address()->mutable_socket_address()->set_address(
ipv6_only_ ? "::1" : "127.0.0.1");
listener.mutable_address()->mutable_socket_address()->set_port_value(
backends_[0]->port());
listener.add_filter_chains()->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
balancers_[0]->ads_service()->SetLdsResource(listener);
WaitForBackend(0);
// Set a different listening address in the LDS update
listener.mutable_address()->mutable_socket_address()->set_address(
"192.168.1.1");
balancers_[0]->ads_service()->SetLdsResource(listener);
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
grpc::StatusCode::FAILED_PRECONDITION);
}
TEST_P(XdsEnabledServerTest, UseOriginalDstNotSupported) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
balancers_[0]->ads_service()->SetLdsResource(listener);
listener.mutable_address()->mutable_socket_address()->set_address(
ipv6_only_ ? "::1" : "127.0.0.1");
listener.mutable_address()->mutable_socket_address()->set_port_value(
backends_[0]->port());
listener.add_filter_chains()->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
listener.mutable_use_original_dst()->set_value(true);
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("Field \'use_original_dst\' is not supported."));
}
class XdsServerSecurityTest : public XdsEnd2endTest {
protected:
XdsServerSecurityTest()
: XdsEnd2endTest(1, 1, 100, true /* use_xds_enabled_server */) {}
static void SetUpTestCase() {
gpr_setenv("GRPC_XDS_EXPERIMENTAL_SECURITY_SUPPORT", "true");
XdsEnd2endTest::SetUpTestCase();
}
static void TearDownTestCase() {
XdsEnd2endTest::TearDownTestCase();
gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_SECURITY_SUPPORT");
}
void SetUp() override {
XdsEnd2endTest::SetUp();
root_cert_ = ReadFile(kCaCertPath);
bad_root_cert_ = ReadFile(kBadClientCertPath);
identity_pair_ = ReadTlsIdentityPair(kServerKeyPath, kServerCertPath);
bad_identity_pair_ =
ReadTlsIdentityPair(kBadClientKeyPath, kBadClientCertPath);
identity_pair_2_ = ReadTlsIdentityPair(kClientKeyPath, kClientCertPath);
server_authenticated_identity_ = {"*.test.google.fr",
"waterzooi.test.google.be",
"*.test.youtube.com", "192.168.1.3"};
server_authenticated_identity_2_ = {"testclient"};
client_authenticated_identity_ = {"*.test.google.fr",
"waterzooi.test.google.be",
"*.test.youtube.com", "192.168.1.3"};
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
}
void TearDown() override {
g_fake1_cert_data_map = nullptr;
g_fake2_cert_data_map = nullptr;
XdsEnd2endTest::TearDown();
}
void SetLdsUpdate(absl::string_view root_instance_name,
absl::string_view root_certificate_name,
absl::string_view identity_instance_name,
absl::string_view identity_certificate_name,
bool require_client_certificates) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=127.0.0.1:",
backends_[0]->port()));
listener.mutable_address()->mutable_socket_address()->set_address(
"127.0.0.1");
listener.mutable_address()->mutable_socket_address()->set_port_value(
backends_[0]->port());
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
if (!identity_instance_name.empty()) {
auto* transport_socket = filter_chain->mutable_transport_socket();
transport_socket->set_name("envoy.transport_sockets.tls");
DownstreamTlsContext downstream_tls_context;
downstream_tls_context.mutable_common_tls_context()
->mutable_tls_certificate_certificate_provider_instance()
->set_instance_name(std::string(identity_instance_name));
downstream_tls_context.mutable_common_tls_context()
->mutable_tls_certificate_certificate_provider_instance()
->set_certificate_name(std::string(identity_certificate_name));
if (!root_instance_name.empty()) {
downstream_tls_context.mutable_common_tls_context()
->mutable_combined_validation_context()
->mutable_validation_context_certificate_provider_instance()
->set_instance_name(std::string(root_instance_name));
downstream_tls_context.mutable_common_tls_context()
->mutable_combined_validation_context()
->mutable_validation_context_certificate_provider_instance()
->set_certificate_name(std::string(root_certificate_name));
downstream_tls_context.mutable_require_client_certificate()->set_value(
require_client_certificates);
}
transport_socket->mutable_typed_config()->PackFrom(
downstream_tls_context);
}
balancers_[0]->ads_service()->SetLdsResource(listener);
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=[::1]:",
backends_[0]->port()));
listener.mutable_address()->mutable_socket_address()->set_address("[::1]");
balancers_[0]->ads_service()->SetLdsResource(listener);
}
std::shared_ptr<grpc::Channel> CreateMtlsChannel() {
ChannelArguments args;
// Override target name for host name check
args.SetString(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG,
ipv6_only_ ? "::1" : "127.0.0.1");
args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, 1);
std::string uri = absl::StrCat(
ipv6_only_ ? "ipv6:[::1]:" : "ipv4:127.0.0.1:", backends_[0]->port());
// TODO(yashykt): Switch to using C++ API once b/173823806 is fixed.
grpc_tls_credentials_options* options =
grpc_tls_credentials_options_create();
grpc_tls_credentials_options_set_server_verification_option(
options, GRPC_TLS_SKIP_HOSTNAME_VERIFICATION);
grpc_tls_credentials_options_set_certificate_provider(
options,
grpc_core::MakeRefCounted<grpc_core::StaticDataCertificateProvider>(
ReadFile(kCaCertPath),
ReadTlsIdentityPair(kServerKeyPath, kServerCertPath))
.get());
grpc_tls_credentials_options_watch_root_certs(options);
grpc_tls_credentials_options_watch_identity_key_cert_pairs(options);
grpc_tls_server_authorization_check_config* check_config =
grpc_tls_server_authorization_check_config_create(
nullptr, ServerAuthCheckSchedule, nullptr, nullptr);
grpc_tls_credentials_options_set_server_authorization_check_config(
options, check_config);
auto channel_creds = std::make_shared<SecureChannelCredentials>(
grpc_tls_credentials_create(options));
grpc_tls_server_authorization_check_config_release(check_config);
return CreateCustomChannel(uri, channel_creds, args);
}
std::shared_ptr<grpc::Channel> CreateTlsChannel() {
ChannelArguments args;
// Override target name for host name check
args.SetString(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG,
ipv6_only_ ? "::1" : "127.0.0.1");
args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, 1);
std::string uri = absl::StrCat(
ipv6_only_ ? "ipv6:[::1]:" : "ipv4:127.0.0.1:", backends_[0]->port());
// TODO(yashykt): Switch to using C++ API once b/173823806 is fixed.
grpc_tls_credentials_options* options =
grpc_tls_credentials_options_create();
grpc_tls_credentials_options_set_server_verification_option(
options, GRPC_TLS_SKIP_HOSTNAME_VERIFICATION);
grpc_tls_credentials_options_set_certificate_provider(
options,
grpc_core::MakeRefCounted<grpc_core::StaticDataCertificateProvider>(
ReadFile(kCaCertPath),
ReadTlsIdentityPair(kServerKeyPath, kServerCertPath))
.get());
grpc_tls_credentials_options_watch_root_certs(options);
grpc_tls_server_authorization_check_config* check_config =
grpc_tls_server_authorization_check_config_create(
nullptr, ServerAuthCheckSchedule, nullptr, nullptr);
grpc_tls_credentials_options_set_server_authorization_check_config(
options, check_config);
auto channel_creds = std::make_shared<SecureChannelCredentials>(
grpc_tls_credentials_create(options));
grpc_tls_server_authorization_check_config_release(check_config);
return CreateCustomChannel(uri, channel_creds, args);
}
std::shared_ptr<grpc::Channel> CreateInsecureChannel() {
ChannelArguments args;
// Override target name for host name check
args.SetString(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG,
ipv6_only_ ? "::1" : "127.0.0.1");
args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, 1);
std::string uri = absl::StrCat(
ipv6_only_ ? "ipv6:[::1]:" : "ipv4:127.0.0.1:", backends_[0]->port());
return CreateCustomChannel(uri, InsecureChannelCredentials(), args);
}
void SendRpc(std::function<std::shared_ptr<grpc::Channel>()> channel_creator,
std::vector<std::string> expected_server_identity,
std::vector<std::string> expected_client_identity,
bool test_expects_failure = false) {
gpr_log(GPR_INFO, "Sending RPC");
int num_tries = 0;
constexpr int kRetryCount = 100;
for (; num_tries < kRetryCount; num_tries++) {
auto channel = channel_creator();
auto stub = grpc::testing::EchoTestService::NewStub(channel);
ClientContext context;
context.set_wait_for_ready(true);
context.set_deadline(grpc_timeout_milliseconds_to_deadline(2000));
EchoRequest request;
request.set_message(kRequestMessage);
EchoResponse response;
Status status = stub->Echo(&context, request, &response);
if (test_expects_failure) {
if (status.ok()) {
gpr_log(GPR_ERROR, "RPC succeeded. Failure expected. Trying again.");
continue;
}
} else {
if (!status.ok()) {
gpr_log(GPR_ERROR, "RPC failed. code=%d message=%s Trying again.",
status.error_code(), status.error_message().c_str());
continue;
}
EXPECT_EQ(response.message(), kRequestMessage);
std::vector<std::string> peer_identity;
for (const auto& entry : context.auth_context()->GetPeerIdentity()) {
peer_identity.emplace_back(
std::string(entry.data(), entry.size()).c_str());
}
if (peer_identity != expected_server_identity) {
gpr_log(GPR_ERROR,
"Expected server identity does not match. (actual) %s vs "
"(expected) %s Trying again.",
absl::StrJoin(peer_identity, ",").c_str(),
absl::StrJoin(expected_server_identity, ",").c_str());
continue;
}
if (backends_[0]->backend_service()->last_peer_identity() !=
expected_client_identity) {
gpr_log(
GPR_ERROR,
"Expected client identity does not match. (actual) %s vs "
"(expected) %s Trying again.",
absl::StrJoin(
backends_[0]->backend_service()->last_peer_identity(), ",")
.c_str(),
absl::StrJoin(expected_client_identity, ",").c_str());
continue;
}
}
break;
}
EXPECT_LT(num_tries, kRetryCount);
}
std::string root_cert_;
std::string bad_root_cert_;
grpc_core::PemKeyCertPairList identity_pair_;
grpc_core::PemKeyCertPairList bad_identity_pair_;
grpc_core::PemKeyCertPairList identity_pair_2_;
std::vector<std::string> server_authenticated_identity_;
std::vector<std::string> server_authenticated_identity_2_;
std::vector<std::string> client_authenticated_identity_;
};
TEST_P(XdsServerSecurityTest, TlsConfigurationWithoutRootProviderInstance) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
balancers_[0]->ads_service()->SetLdsResource(listener);
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
auto* transport_socket = filter_chain->mutable_transport_socket();
transport_socket->set_name("envoy.transport_sockets.tls");
DownstreamTlsContext downstream_tls_context;
transport_socket->mutable_typed_config()->PackFrom(downstream_tls_context);
balancers_[0]->ads_service()->SetLdsResource(listener);
CheckRpcSendFailure(1, RpcOptions().set_wait_for_ready(true));
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr(
"TLS configuration provided but no "
"tls_certificate_certificate_provider_instance found."));
}
TEST_P(XdsServerSecurityTest, UnknownIdentityCertificateProvider) {
SetLdsUpdate("", "", "unknown", "", false);
SendRpc([this]() { return CreateTlsChannel(); }, {}, {},
true /* test_expects_failure */);
}
TEST_P(XdsServerSecurityTest, UnknownRootCertificateProvider) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
SetLdsUpdate("unknown", "", "fake_plugin1", "", false);
SendRpc([this]() { return CreateTlsChannel(); }, {}, {},
true /* test_expects_failure */);
}
TEST_P(XdsServerSecurityTest, TestMtls) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_, client_authenticated_identity_);
}
TEST_P(XdsServerSecurityTest, TestMtlsWithRootPluginUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
FakeCertificateProvider::CertDataMap fake2_cert_map = {
{"", {bad_root_cert_, bad_identity_pair_}}};
g_fake2_cert_data_map = &fake2_cert_map;
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_, client_authenticated_identity_);
SetLdsUpdate("fake_plugin2", "", "fake_plugin1", "", true);
SendRpc([this]() { return CreateMtlsChannel(); }, {}, {},
true /* test_expects_failure */);
}
TEST_P(XdsServerSecurityTest, TestMtlsWithIdentityPluginUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
FakeCertificateProvider::CertDataMap fake2_cert_map = {
{"", {root_cert_, identity_pair_2_}}};
g_fake2_cert_data_map = &fake2_cert_map;
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_, client_authenticated_identity_);
SetLdsUpdate("fake_plugin1", "", "fake_plugin2", "", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_2_, client_authenticated_identity_);
}
TEST_P(XdsServerSecurityTest, TestMtlsWithBothPluginsUpdated) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
FakeCertificateProvider::CertDataMap fake2_cert_map = {
{"good", {root_cert_, identity_pair_2_}},
{"", {bad_root_cert_, bad_identity_pair_}}};
g_fake2_cert_data_map = &fake2_cert_map;
SetLdsUpdate("fake_plugin2", "", "fake_plugin2", "", true);
SendRpc([this]() { return CreateMtlsChannel(); }, {}, {},
true /* test_expects_failure */);
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_, client_authenticated_identity_);
SetLdsUpdate("fake_plugin2", "good", "fake_plugin2", "good", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_2_, client_authenticated_identity_);
}
TEST_P(XdsServerSecurityTest, TestMtlsWithRootCertificateNameUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}},
{"bad", {bad_root_cert_, bad_identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_, client_authenticated_identity_);
SetLdsUpdate("fake_plugin1", "bad", "fake_plugin1", "", true);
SendRpc([this]() { return CreateMtlsChannel(); }, {}, {},
true /* test_expects_failure */);
}
TEST_P(XdsServerSecurityTest, TestMtlsWithIdentityCertificateNameUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}},
{"good", {root_cert_, identity_pair_2_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_, client_authenticated_identity_);
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "good", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_2_, client_authenticated_identity_);
}
TEST_P(XdsServerSecurityTest, TestMtlsWithBothCertificateNamesUpdated) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}},
{"good", {root_cert_, identity_pair_2_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_, client_authenticated_identity_);
SetLdsUpdate("fake_plugin1", "good", "fake_plugin1", "good", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_2_, client_authenticated_identity_);
}
TEST_P(XdsServerSecurityTest, TestMtlsNotRequiringButProvidingClientCerts) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", false);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_, client_authenticated_identity_);
}
TEST_P(XdsServerSecurityTest, TestMtlsNotRequiringAndNotProvidingClientCerts) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", false);
SendRpc([this]() { return CreateTlsChannel(); },
server_authenticated_identity_, {});
}
TEST_P(XdsServerSecurityTest, TestTls) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("", "", "fake_plugin1", "", false);
SendRpc([this]() { return CreateTlsChannel(); },
server_authenticated_identity_, {});
}
TEST_P(XdsServerSecurityTest, TestTlsWithIdentityPluginUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
FakeCertificateProvider::CertDataMap fake2_cert_map = {
{"", {root_cert_, identity_pair_2_}}};
g_fake2_cert_data_map = &fake2_cert_map;
SetLdsUpdate("", "", "fake_plugin1", "", false);
SendRpc([this]() { return CreateTlsChannel(); },
server_authenticated_identity_, {});
SetLdsUpdate("", "", "fake_plugin2", "", false);
SendRpc([this]() { return CreateTlsChannel(); },
server_authenticated_identity_2_, {});
}
TEST_P(XdsServerSecurityTest, TestTlsWithIdentityCertificateNameUpdate) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}},
{"good", {root_cert_, identity_pair_2_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("", "", "fake_plugin1", "", false);
SendRpc([this]() { return CreateTlsChannel(); },
server_authenticated_identity_, {});
SetLdsUpdate("", "", "fake_plugin1", "good", false);
SendRpc([this]() { return CreateTlsChannel(); },
server_authenticated_identity_2_, {});
}
TEST_P(XdsServerSecurityTest, TestFallback) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("", "", "", "", false);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsServerSecurityTest, TestMtlsToTls) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
SendRpc([this]() { return CreateTlsChannel(); }, {}, {},
true /* test_expects_failure */);
SetLdsUpdate("", "", "fake_plugin1", "", false);
SendRpc([this]() { return CreateTlsChannel(); },
server_authenticated_identity_, {});
}
TEST_P(XdsServerSecurityTest, TestTlsToMtls) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("", "", "fake_plugin1", "", false);
SendRpc([this]() { return CreateTlsChannel(); },
server_authenticated_identity_, {});
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
SendRpc([this]() { return CreateTlsChannel(); }, {}, {},
true /* test_expects_failure */);
}
TEST_P(XdsServerSecurityTest, TestMtlsToFallback) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", false);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_, client_authenticated_identity_);
SetLdsUpdate("", "", "", "", false);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsServerSecurityTest, TestFallbackToMtls) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("", "", "", "", false);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
SendRpc([this]() { return CreateMtlsChannel(); },
server_authenticated_identity_, client_authenticated_identity_);
}
TEST_P(XdsServerSecurityTest, TestTlsToFallback) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("", "", "fake_plugin1", "", false);
SendRpc([this]() { return CreateTlsChannel(); },
server_authenticated_identity_, {});
SetLdsUpdate("", "", "", "", false);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsServerSecurityTest, TestFallbackToTls) {
FakeCertificateProvider::CertDataMap fake1_cert_map = {
{"", {root_cert_, identity_pair_}}};
g_fake1_cert_data_map = &fake1_cert_map;
SetLdsUpdate("", "", "", "", false);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
SetLdsUpdate("", "", "fake_plugin1", "", false);
SendRpc([this]() { return CreateTlsChannel(); },
server_authenticated_identity_, {});
}
class XdsEnabledServerStatusNotificationTest : public XdsServerSecurityTest {
protected:
void SetValidLdsUpdate() { SetLdsUpdate("", "", "", "", false); }
void SetInvalidLdsUpdate() {
Listener listener;
listener.set_name(absl::StrCat(
"grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
balancers_[0]->ads_service()->SetLdsResource(listener);
}
void UnsetLdsUpdate() {
balancers_[0]->ads_service()->UnsetResource(
kLdsTypeUrl, absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:",
backends_[0]->port()));
}
};
TEST_P(XdsEnabledServerStatusNotificationTest, ServingStatus) {
SetValidLdsUpdate();
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
grpc::StatusCode::OK);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsEnabledServerStatusNotificationTest, NotServingStatus) {
SetInvalidLdsUpdate();
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
grpc::StatusCode::UNAVAILABLE);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
true /* test_expects_failure */);
}
TEST_P(XdsEnabledServerStatusNotificationTest, ErrorUpdateWhenAlreadyServing) {
SetValidLdsUpdate();
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
grpc::StatusCode::OK);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
// Invalid update does not lead to a change in the serving status.
SetInvalidLdsUpdate();
do {
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
grpc::StatusCode::OK);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsEnabledServerStatusNotificationTest,
NotServingStatusToServingStatusTransition) {
SetInvalidLdsUpdate();
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
grpc::StatusCode::UNAVAILABLE);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
true /* test_expects_failure */);
// Send a valid LDS update to change to serving status
SetValidLdsUpdate();
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
grpc::StatusCode::OK);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
// This test verifies that the resource getting deleted when already serving
// results in future connections being dropped.
TEST_P(XdsEnabledServerStatusNotificationTest,
ServingStatusToNonServingStatusTransition) {
SetValidLdsUpdate();
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
grpc::StatusCode::OK);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
// Deleting the resource should result in a non-serving status.
UnsetLdsUpdate();
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
grpc::StatusCode::NOT_FOUND);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
true /* test_expects_failure */);
}
TEST_P(XdsEnabledServerStatusNotificationTest, RepeatedServingStatusChanges) {
for (int i = 0; i < 5; i++) {
// Send a valid LDS update to get the server to start listening
SetValidLdsUpdate();
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:",
backends_[0]->port()),
grpc::StatusCode::OK);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
// Deleting the resource will make the server start rejecting connections
UnsetLdsUpdate();
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:",
backends_[0]->port()),
grpc::StatusCode::NOT_FOUND);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
true /* test_expects_failure */);
}
}
TEST_P(XdsEnabledServerStatusNotificationTest, ExistingRpcsOnResourceDeletion) {
// Send a valid LDS update to get the server to start listening
SetValidLdsUpdate();
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
grpc::StatusCode::OK);
constexpr int kNumChannels = 10;
struct StreamingRpc {
std::shared_ptr<Channel> channel;
std::unique_ptr<grpc::testing::EchoTestService::Stub> stub;
ClientContext context;
std::unique_ptr<ClientWriter<EchoRequest>> writer;
} streaming_rpcs[kNumChannels];
EchoRequest request;
EchoResponse response;
request.set_message("Hello");
for (int i = 0; i < kNumChannels; i++) {
streaming_rpcs[i].channel = CreateInsecureChannel();
streaming_rpcs[i].stub =
grpc::testing::EchoTestService::NewStub(streaming_rpcs[i].channel);
streaming_rpcs[i].context.set_wait_for_ready(true);
streaming_rpcs[i].writer = streaming_rpcs[i].stub->RequestStream(
&streaming_rpcs[i].context, &response);
EXPECT_TRUE(streaming_rpcs[i].writer->Write(request));
}
// Deleting the resource will make the server start rejecting connections
UnsetLdsUpdate();
backends_[0]->notifier()->WaitOnServingStatusChange(
absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
grpc::StatusCode::NOT_FOUND);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
true /* test_expects_failure */);
for (int i = 0; i < kNumChannels; i++) {
EXPECT_TRUE(streaming_rpcs[i].writer->Write(request));
EXPECT_TRUE(streaming_rpcs[i].writer->WritesDone());
EXPECT_TRUE(streaming_rpcs[i].writer->Finish().ok());
// New RPCs on the existing channels should fail.
ClientContext new_context;
new_context.set_deadline(grpc_timeout_milliseconds_to_deadline(1000));
EXPECT_FALSE(
streaming_rpcs[i].stub->Echo(&new_context, request, &response).ok());
}
}
using XdsServerFilterChainMatchTest = XdsServerSecurityTest;
TEST_P(XdsServerFilterChainMatchTest,
DefaultFilterChainUsedWhenNoFilterChainMentioned) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
listener.mutable_default_filter_chain()
->add_filters()
->mutable_typed_config()
->PackFrom(HttpConnectionManager());
balancers_[0]->ads_service()->SetLdsResource(listener);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsServerFilterChainMatchTest,
DefaultFilterChainUsedWhenOtherFilterChainsDontMatch) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add a filter chain that will never get matched
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()
->mutable_destination_port()
->set_value(8080);
// Add default filter chain that should get used
listener.mutable_default_filter_chain()
->add_filters()
->mutable_typed_config()
->PackFrom(HttpConnectionManager());
balancers_[0]->ads_service()->SetLdsResource(listener);
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsServerFilterChainMatchTest,
FilterChainsWithDestinationPortDontMatch) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with destination port that should never get matched
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()
->mutable_destination_port()
->set_value(8080);
balancers_[0]->ads_service()->SetLdsResource(listener);
// RPC should fail since no matching filter chain was found and no default
// filter chain is configured.
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
true /* test_expects_failure */);
}
TEST_P(XdsServerFilterChainMatchTest, FilterChainsWithServerNamesDontMatch) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with server name that should never get matched
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->add_server_names("server_name");
balancers_[0]->ads_service()->SetLdsResource(listener);
// RPC should fail since no matching filter chain was found and no default
// filter chain is configured.
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
true /* test_expects_failure */);
}
TEST_P(XdsServerFilterChainMatchTest,
FilterChainsWithTransportProtocolsOtherThanRawBufferDontMatch) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with transport protocol "tls" that should never match
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->set_transport_protocol("tls");
balancers_[0]->ads_service()->SetLdsResource(listener);
// RPC should fail since no matching filter chain was found and no default
// filter chain is configured.
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
true /* test_expects_failure */);
}
TEST_P(XdsServerFilterChainMatchTest,
FilterChainsWithApplicationProtocolsDontMatch) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with application protocol that should never get matched
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->add_application_protocols("h2");
balancers_[0]->ads_service()->SetLdsResource(listener);
// RPC should fail since no matching filter chain was found and no default
// filter chain is configured.
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
true /* test_expects_failure */);
}
TEST_P(XdsServerFilterChainMatchTest,
FilterChainsWithTransportProtocolRawBufferIsPreferred) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with "raw_buffer" transport protocol
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->set_transport_protocol(
"raw_buffer");
// Add another filter chain with no transport protocol set but application
// protocol set (fails match)
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->add_application_protocols("h2");
balancers_[0]->ads_service()->SetLdsResource(listener);
// A successful RPC proves that filter chains that mention "raw_buffer" as the
// transport protocol are chosen as the best match in the round.
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsServerFilterChainMatchTest,
FilterChainsWithMoreSpecificDestinationPrefixRangesArePreferred) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with prefix range (length 4 and 16) but with server name
// mentioned. (Prefix range is matched first.)
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
auto* prefix_range =
filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(4);
prefix_range =
filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(16);
filter_chain->mutable_filter_chain_match()->add_server_names("server_name");
// Add filter chain with two prefix ranges (length 8 and 24). Since 24 is the
// highest match, it should be chosen.
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
prefix_range =
filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(8);
prefix_range =
filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(24);
// Add another filter chain with a non-matching prefix range (with length 30)
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
prefix_range =
filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
prefix_range->set_address_prefix("192.168.1.1");
prefix_range->mutable_prefix_len()->set_value(30);
filter_chain->mutable_filter_chain_match()->add_server_names("server_name");
// Add another filter chain with no prefix range mentioned
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->add_server_names("server_name");
balancers_[0]->ads_service()->SetLdsResource(listener);
// A successful RPC proves that the filter chain with the longest matching
// prefix range was the best match.
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsServerFilterChainMatchTest,
FilterChainsThatMentionSourceTypeArePreferred) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with the local source type (best match)
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->set_source_type(
FilterChainMatch::SAME_IP_OR_LOOPBACK);
// Add filter chain with the external source type but bad source port.
// Note that backends_[0]->port() will never be a match for the source port
// because it is already being used by a backend.
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->set_source_type(
FilterChainMatch::EXTERNAL);
filter_chain->mutable_filter_chain_match()->add_source_ports(
backends_[0]->port());
// Add filter chain with the default source type (ANY) but bad source port.
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->add_source_ports(
backends_[0]->port());
balancers_[0]->ads_service()->SetLdsResource(listener);
// A successful RPC proves that the filter chain with the longest matching
// prefix range was the best match.
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsServerFilterChainMatchTest,
FilterChainsWithMoreSpecificSourcePrefixRangesArePreferred) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with source prefix range (length 16) but with a bad source
// port mentioned. (Prefix range is matched first.)
// Note that backends_[0]->port() will never be a match for the source port
// because it is already being used by a backend.
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
auto* source_prefix_range =
filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
source_prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
source_prefix_range->mutable_prefix_len()->set_value(4);
source_prefix_range =
filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
source_prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
source_prefix_range->mutable_prefix_len()->set_value(16);
filter_chain->mutable_filter_chain_match()->add_source_ports(
backends_[0]->port());
// Add filter chain with two source prefix ranges (length 8 and 24). Since 24
// is the highest match, it should be chosen.
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
source_prefix_range =
filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
source_prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
source_prefix_range->mutable_prefix_len()->set_value(8);
source_prefix_range =
filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
source_prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
source_prefix_range->mutable_prefix_len()->set_value(24);
// Add another filter chain with a non-matching source prefix range (with
// length 30) and bad source port
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
source_prefix_range =
filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
source_prefix_range->set_address_prefix("192.168.1.1");
source_prefix_range->mutable_prefix_len()->set_value(30);
filter_chain->mutable_filter_chain_match()->add_source_ports(
backends_[0]->port());
// Add another filter chain with no source prefix range mentioned and bad
// source port
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->add_source_ports(
backends_[0]->port());
balancers_[0]->ads_service()->SetLdsResource(listener);
// A successful RPC proves that the filter chain with the longest matching
// source prefix range was the best match.
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsServerFilterChainMatchTest,
FilterChainsWithMoreSpecificSourcePortArePreferred) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
// Since we don't know which port will be used by the channel, just add all
// ports except for 0.
for (int i = 1; i < 65536; i++) {
filter_chain->mutable_filter_chain_match()->add_source_ports(i);
}
// Add another filter chain with no source prefix range mentioned with a bad
// DownstreamTlsContext configuration.
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
auto* transport_socket = filter_chain->mutable_transport_socket();
transport_socket->set_name("envoy.transport_sockets.tls");
DownstreamTlsContext downstream_tls_context;
downstream_tls_context.mutable_common_tls_context()
->mutable_tls_certificate_certificate_provider_instance()
->set_instance_name("unknown");
transport_socket->mutable_typed_config()->PackFrom(downstream_tls_context);
balancers_[0]->ads_service()->SetLdsResource(listener);
// A successful RPC proves that the filter chain with matching source port
// was chosen.
SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
}
TEST_P(XdsServerFilterChainMatchTest, DuplicateMatchNacked) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
// Add a duplicate filter chain
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr(
"Duplicate matching rules detected when adding filter chain: {}"));
}
TEST_P(XdsServerFilterChainMatchTest, DuplicateMatchOnPrefixRangesNacked) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with prefix range
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
auto* prefix_range =
filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(16);
prefix_range =
filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(24);
// Add a filter chain with a duplicate prefix range entry
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
prefix_range =
filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(16);
prefix_range =
filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(32);
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr(
"Duplicate matching rules detected when adding filter chain: "
"{prefix_ranges={{address_prefix=127.0.0.0:0, prefix_len=16}, "
"{address_prefix=127.0.0.1:0, prefix_len=32}}}"));
}
TEST_P(XdsServerFilterChainMatchTest, DuplicateMatchOnTransportProtocolNacked) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with "raw_buffer" transport protocol
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->set_transport_protocol(
"raw_buffer");
// Add a duplicate filter chain with the same "raw_buffer" transport protocol
// entry
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->set_transport_protocol(
"raw_buffer");
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("Duplicate matching rules detected when adding "
"filter chain: {transport_protocol=raw_buffer}"));
}
TEST_P(XdsServerFilterChainMatchTest, DuplicateMatchOnLocalSourceTypeNacked) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with the local source type
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->set_source_type(
FilterChainMatch::SAME_IP_OR_LOOPBACK);
// Add a duplicate filter chain with the same local source type entry
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->set_source_type(
FilterChainMatch::SAME_IP_OR_LOOPBACK);
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("Duplicate matching rules detected when adding "
"filter chain: {source_type=SAME_IP_OR_LOOPBACK}"));
}
TEST_P(XdsServerFilterChainMatchTest,
DuplicateMatchOnExternalSourceTypeNacked) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with the external source type
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->set_source_type(
FilterChainMatch::EXTERNAL);
// Add a duplicate filter chain with the same external source type entry
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->set_source_type(
FilterChainMatch::EXTERNAL);
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("Duplicate matching rules detected when adding "
"filter chain: {source_type=EXTERNAL}"));
}
TEST_P(XdsServerFilterChainMatchTest,
DuplicateMatchOnSourcePrefixRangesNacked) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with source prefix range
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
auto* prefix_range =
filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(16);
prefix_range =
filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(24);
// Add a filter chain with a duplicate source prefix range entry
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
prefix_range =
filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(16);
prefix_range =
filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
prefix_range->set_address_prefix(ipv6_only_ ? "[::1]" : "127.0.0.1");
prefix_range->mutable_prefix_len()->set_value(32);
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr(
"Duplicate matching rules detected when adding filter chain: "
"{source_prefix_ranges={{address_prefix=127.0.0.0:0, prefix_len=16}, "
"{address_prefix=127.0.0.1:0, prefix_len=32}}}"));
}
TEST_P(XdsServerFilterChainMatchTest, DuplicateMatchOnSourcePortNacked) {
Listener listener;
listener.set_name(
absl::StrCat("grpc/server?xds.resource.listening_address=",
ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
auto* socket_address = listener.mutable_address()->mutable_socket_address();
socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
socket_address->set_port_value(backends_[0]->port());
// Add filter chain with the external source type
auto* filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->add_source_ports(8080);
// Add a duplicate filter chain with the same source port entry
filter_chain = listener.add_filter_chains();
filter_chain->add_filters()->mutable_typed_config()->PackFrom(
HttpConnectionManager());
filter_chain->mutable_filter_chain_match()->add_source_ports(8080);
balancers_[0]->ads_service()->SetLdsResource(listener);
do {
CheckRpcSendFailure();
} while (balancers_[0]->ads_service()->lds_response_state().state ==
AdsServiceImpl::ResponseState::SENT);
const auto response_state =
balancers_[0]->ads_service()->lds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(
response_state.error_message,
::testing::HasSubstr("Duplicate matching rules detected when adding "
"filter chain: {source_ports={8080}}"));
}
using EdsTest = BasicTest;
// Tests that EDS client should send a NACK if the EDS update contains
// sparse priorities.
TEST_P(EdsTest, NacksSparsePriorityList) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(), kDefaultLocalityWeight, 1},
});
balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
CheckRpcSendFailure();
const auto response_state =
balancers_[0]->ads_service()->eds_response_state();
EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
EXPECT_THAT(response_state.error_message,
::testing::HasSubstr("sparse priority list"));
}
// In most of our tests, we use different names for different resource
// types, to make sure that there are no cut-and-paste errors in the code
// that cause us to look at data for the wrong resource type. So we add
// this test to make sure that the EDS resource name defaults to the
// cluster name if not specified in the CDS resource.
TEST_P(EdsTest, EdsServiceNameDefaultsToClusterName) {
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, kDefaultClusterName));
Cluster cluster = default_cluster_;
cluster.mutable_eds_cluster_config()->clear_service_name();
balancers_[0]->ads_service()->SetCdsResource(cluster);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendOk();
}
class TimeoutTest : public BasicTest {
protected:
void SetUp() override {
xds_resource_does_not_exist_timeout_ms_ = 500;
BasicTest::SetUp();
}
};
// Tests that LDS client times out when no response received.
TEST_P(TimeoutTest, Lds) {
balancers_[0]->ads_service()->SetResourceIgnore(kLdsTypeUrl);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
}
TEST_P(TimeoutTest, Rds) {
balancers_[0]->ads_service()->SetResourceIgnore(kRdsTypeUrl);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
}
// Tests that CDS client times out when no response received.
TEST_P(TimeoutTest, Cds) {
balancers_[0]->ads_service()->SetResourceIgnore(kCdsTypeUrl);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
}
TEST_P(TimeoutTest, Eds) {
balancers_[0]->ads_service()->SetResourceIgnore(kEdsTypeUrl);
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendFailure();
}
using LocalityMapTest = BasicTest;
// Tests that the localities in a locality map are picked according to their
// weights.
TEST_P(LocalityMapTest, WeightedRoundRobin) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 5000;
const int kLocalityWeight0 = 2;
const int kLocalityWeight1 = 8;
const int kTotalLocalityWeight = kLocalityWeight0 + kLocalityWeight1;
const double kLocalityWeightRate0 =
static_cast<double>(kLocalityWeight0) / kTotalLocalityWeight;
const double kLocalityWeightRate1 =
static_cast<double>(kLocalityWeight1) / kTotalLocalityWeight;
// ADS response contains 2 localities, each of which contains 1 backend.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1), kLocalityWeight0},
{"locality1", GetBackendPorts(1, 2), kLocalityWeight1},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait for both backends to be ready.
WaitForAllBackends(0, 2);
// Send kNumRpcs RPCs.
CheckRpcSendOk(kNumRpcs);
// The locality picking rates should be roughly equal to the expectation.
const double locality_picked_rate_0 =
static_cast<double>(backends_[0]->backend_service()->request_count()) /
kNumRpcs;
const double locality_picked_rate_1 =
static_cast<double>(backends_[1]->backend_service()->request_count()) /
kNumRpcs;
const double kErrorTolerance = 0.2;
EXPECT_THAT(locality_picked_rate_0,
::testing::AllOf(
::testing::Ge(kLocalityWeightRate0 * (1 - kErrorTolerance)),
::testing::Le(kLocalityWeightRate0 * (1 + kErrorTolerance))));
EXPECT_THAT(locality_picked_rate_1,
::testing::AllOf(
::testing::Ge(kLocalityWeightRate1 * (1 - kErrorTolerance)),
::testing::Le(kLocalityWeightRate1 * (1 + kErrorTolerance))));
}
// Tests that we correctly handle a locality containing no endpoints.
TEST_P(LocalityMapTest, LocalityContainingNoEndpoints) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 5000;
// EDS response contains 2 localities, one with no endpoints.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
{"locality1", {}},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait for both backends to be ready.
WaitForAllBackends();
// Send kNumRpcs RPCs.
CheckRpcSendOk(kNumRpcs);
// All traffic should go to the reachable locality.
EXPECT_EQ(backends_[0]->backend_service()->request_count(),
kNumRpcs / backends_.size());
EXPECT_EQ(backends_[1]->backend_service()->request_count(),
kNumRpcs / backends_.size());
EXPECT_EQ(backends_[2]->backend_service()->request_count(),
kNumRpcs / backends_.size());
EXPECT_EQ(backends_[3]->backend_service()->request_count(),
kNumRpcs / backends_.size());
}
// EDS update with no localities.
TEST_P(LocalityMapTest, NoLocalities) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource({}, DefaultEdsServiceName()));
Status status = SendRpc();
EXPECT_FALSE(status.ok());
EXPECT_EQ(status.error_code(), StatusCode::UNAVAILABLE);
}
// Tests that the locality map can work properly even when it contains a large
// number of localities.
TEST_P(LocalityMapTest, StressTest) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumLocalities = 100;
// The first ADS response contains kNumLocalities localities, each of which
// contains backend 0.
AdsServiceImpl::EdsResourceArgs args;
for (size_t i = 0; i < kNumLocalities; ++i) {
std::string name = absl::StrCat("locality", i);
AdsServiceImpl::EdsResourceArgs::Locality locality(name,
{backends_[0]->port()});
args.locality_list.emplace_back(std::move(locality));
}
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// The second ADS response contains 1 locality, which contains backend 1.
args = AdsServiceImpl::EdsResourceArgs({
{"locality0", GetBackendPorts(1, 2)},
});
std::thread delayed_resource_setter(
std::bind(&BasicTest::SetEdsResourceWithDelay, this, 0,
BuildEdsResource(args, DefaultEdsServiceName()), 60 * 1000));
// Wait until backend 0 is ready, before which kNumLocalities localities are
// received and handled by the xds policy.
WaitForBackend(0, /*reset_counters=*/false);
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
// Wait until backend 1 is ready, before which kNumLocalities localities are
// removed by the xds policy.
WaitForBackend(1);
delayed_resource_setter.join();
}
// Tests that the localities in a locality map are picked correctly after update
// (addition, modification, deletion).
TEST_P(LocalityMapTest, UpdateMap) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 3000;
// The locality weight for the first 3 localities.
const std::vector<int> kLocalityWeights0 = {2, 3, 4};
const double kTotalLocalityWeight0 =
std::accumulate(kLocalityWeights0.begin(), kLocalityWeights0.end(), 0);
std::vector<double> locality_weight_rate_0;
locality_weight_rate_0.reserve(kLocalityWeights0.size());
for (int weight : kLocalityWeights0) {
locality_weight_rate_0.push_back(weight / kTotalLocalityWeight0);
}
// Delete the first locality, keep the second locality, change the third
// locality's weight from 4 to 2, and add a new locality with weight 6.
const std::vector<int> kLocalityWeights1 = {3, 2, 6};
const double kTotalLocalityWeight1 =
std::accumulate(kLocalityWeights1.begin(), kLocalityWeights1.end(), 0);
std::vector<double> locality_weight_rate_1 = {
0 /* placeholder for locality 0 */};
for (int weight : kLocalityWeights1) {
locality_weight_rate_1.push_back(weight / kTotalLocalityWeight1);
}
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1), 2},
{"locality1", GetBackendPorts(1, 2), 3},
{"locality2", GetBackendPorts(2, 3), 4},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait for the first 3 backends to be ready.
WaitForAllBackends(0, 3);
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
// Send kNumRpcs RPCs.
CheckRpcSendOk(kNumRpcs);
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// The picking rates of the first 3 backends should be roughly equal to the
// expectation.
std::vector<double> locality_picked_rates;
for (size_t i = 0; i < 3; ++i) {
locality_picked_rates.push_back(
static_cast<double>(backends_[i]->backend_service()->request_count()) /
kNumRpcs);
}
const double kErrorTolerance = 0.2;
for (size_t i = 0; i < 3; ++i) {
gpr_log(GPR_INFO, "Locality %" PRIuPTR " rate %f", i,
locality_picked_rates[i]);
EXPECT_THAT(
locality_picked_rates[i],
::testing::AllOf(
::testing::Ge(locality_weight_rate_0[i] * (1 - kErrorTolerance)),
::testing::Le(locality_weight_rate_0[i] * (1 + kErrorTolerance))));
}
args = AdsServiceImpl::EdsResourceArgs({
{"locality1", GetBackendPorts(1, 2), 3},
{"locality2", GetBackendPorts(2, 3), 2},
{"locality3", GetBackendPorts(3, 4), 6},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Backend 3 hasn't received any request.
EXPECT_EQ(0U, backends_[3]->backend_service()->request_count());
// Wait until the locality update has been processed, as signaled by backend 3
// receiving a request.
WaitForAllBackends(3, 4);
gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
// Send kNumRpcs RPCs.
CheckRpcSendOk(kNumRpcs);
gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
// Backend 0 no longer receives any request.
EXPECT_EQ(0U, backends_[0]->backend_service()->request_count());
// The picking rates of the last 3 backends should be roughly equal to the
// expectation.
locality_picked_rates = {0 /* placeholder for backend 0 */};
for (size_t i = 1; i < 4; ++i) {
locality_picked_rates.push_back(
static_cast<double>(backends_[i]->backend_service()->request_count()) /
kNumRpcs);
}
for (size_t i = 1; i < 4; ++i) {
gpr_log(GPR_INFO, "Locality %" PRIuPTR " rate %f", i,
locality_picked_rates[i]);
EXPECT_THAT(
locality_picked_rates[i],
::testing::AllOf(
::testing::Ge(locality_weight_rate_1[i] * (1 - kErrorTolerance)),
::testing::Le(locality_weight_rate_1[i] * (1 + kErrorTolerance))));
}
}
// Tests that we don't fail RPCs when replacing all of the localities in
// a given priority.
TEST_P(LocalityMapTest, ReplaceAllLocalitiesInPriority) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
args = AdsServiceImpl::EdsResourceArgs({
{"locality1", GetBackendPorts(1, 2)},
});
std::thread delayed_resource_setter(
std::bind(&BasicTest::SetEdsResourceWithDelay, this, 0,
BuildEdsResource(args, DefaultEdsServiceName()), 5000));
// Wait for the first backend to be ready.
WaitForBackend(0);
// Keep sending RPCs until we switch over to backend 1, which tells us
// that we received the update. No RPCs should fail during this
// transition.
WaitForBackend(1, /*reset_counters=*/true, /*require_success=*/true);
delayed_resource_setter.join();
}
class FailoverTest : public BasicTest {
public:
void SetUp() override {
BasicTest::SetUp();
ResetStub(500);
}
};
// Localities with the highest priority are used when multiple priority exist.
TEST_P(FailoverTest, ChooseHighestPriority) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
WaitForBackend(3, false);
for (size_t i = 0; i < 3; ++i) {
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
}
// Does not choose priority with no endpoints.
TEST_P(FailoverTest, DoesNotUsePriorityWithNoEndpoints) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
{"locality3", {}, kDefaultLocalityWeight, 0},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
WaitForBackend(0, false);
for (size_t i = 1; i < 3; ++i) {
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
}
// Does not choose locality with no endpoints.
TEST_P(FailoverTest, DoesNotUseLocalityWithNoEndpoints) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {}, kDefaultLocalityWeight, 0},
{"locality1", GetBackendPorts(), kDefaultLocalityWeight, 0},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait for all backends to be used.
std::tuple<int, int, int> counts = WaitForAllBackends();
// Make sure no RPCs failed in the transition.
EXPECT_EQ(0, std::get<1>(counts));
}
// If the higher priority localities are not reachable, failover to the highest
// priority among the rest.
TEST_P(FailoverTest, Failover) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
});
ShutdownBackend(3);
ShutdownBackend(0);
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
WaitForBackend(1, false);
for (size_t i = 0; i < 4; ++i) {
if (i == 1) continue;
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
}
// If a locality with higher priority than the current one becomes ready,
// switch to it.
TEST_P(FailoverTest, SwitchBackToHigherPriority) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 100;
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
WaitForBackend(3);
ShutdownBackend(3);
ShutdownBackend(0);
WaitForBackend(1, false);
for (size_t i = 0; i < 4; ++i) {
if (i == 1) continue;
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
StartBackend(0);
WaitForBackend(0);
CheckRpcSendOk(kNumRpcs);
EXPECT_EQ(kNumRpcs, backends_[0]->backend_service()->request_count());
}
// The first update only contains unavailable priorities. The second update
// contains available priorities.
TEST_P(FailoverTest, UpdateInitialUnavailable) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 1},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
args = AdsServiceImpl::EdsResourceArgs({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 1},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 2},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 3},
});
ShutdownBackend(0);
ShutdownBackend(1);
std::thread delayed_resource_setter(
std::bind(&BasicTest::SetEdsResourceWithDelay, this, 0,
BuildEdsResource(args, DefaultEdsServiceName()), 1000));
gpr_timespec deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_millis(500, GPR_TIMESPAN));
// Send 0.5 second worth of RPCs.
do {
CheckRpcSendFailure();
} while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
WaitForBackend(2, false);
for (size_t i = 0; i < 4; ++i) {
if (i == 2) continue;
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
delayed_resource_setter.join();
}
// Tests that after the localities' priorities are updated, we still choose the
// highest READY priority with the updated localities.
TEST_P(FailoverTest, UpdatePriority) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 100;
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
args = AdsServiceImpl::EdsResourceArgs({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 2},
{"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 0},
{"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 1},
{"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 3},
});
std::thread delayed_resource_setter(
std::bind(&BasicTest::SetEdsResourceWithDelay, this, 0,
BuildEdsResource(args, DefaultEdsServiceName()), 1000));
WaitForBackend(3, false);
for (size_t i = 0; i < 3; ++i) {
EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
}
WaitForBackend(1);
CheckRpcSendOk(kNumRpcs);
EXPECT_EQ(kNumRpcs, backends_[1]->backend_service()->request_count());
delayed_resource_setter.join();
}
// Moves all localities in the current priority to a higher priority.
TEST_P(FailoverTest, MoveAllLocalitiesInCurrentPriorityToHigherPriority) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// First update:
// - Priority 0 is locality 0, containing backend 0, which is down.
// - Priority 1 is locality 1, containing backends 1 and 2, which are up.
ShutdownBackend(0);
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
{"locality1", GetBackendPorts(1, 3), kDefaultLocalityWeight, 1},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Second update:
// - Priority 0 contains both localities 0 and 1.
// - Priority 1 is not present.
// - We add backend 3 to locality 1, just so we have a way to know
// when the update has been seen by the client.
args = AdsServiceImpl::EdsResourceArgs({
{"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
{"locality1", GetBackendPorts(1, 4), kDefaultLocalityWeight, 0},
});
std::thread delayed_resource_setter(
std::bind(&BasicTest::SetEdsResourceWithDelay, this, 0,
BuildEdsResource(args, DefaultEdsServiceName()), 1000));
// When we get the first update, all backends in priority 0 are down,
// so we will create priority 1. Backends 1 and 2 should have traffic,
// but backend 3 should not.
WaitForAllBackends(1, 3, false);
EXPECT_EQ(0UL, backends_[3]->backend_service()->request_count());
// When backend 3 gets traffic, we know the second update has been seen.
WaitForBackend(3);
// The ADS service of balancer 0 got at least 1 response.
EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT);
delayed_resource_setter.join();
}
using DropTest = BasicTest;
// Tests that RPCs are dropped according to the drop config.
TEST_P(DropTest, Vanilla) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 5000;
const uint32_t kDropPerMillionForLb = 100000;
const uint32_t kDropPerMillionForThrottle = 200000;
const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
const double KDropRateForLbAndThrottle =
kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
// The ADS response contains two drop categories.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
{kThrottleDropType, kDropPerMillionForThrottle}};
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
WaitForAllBackends();
// Send kNumRpcs RPCs and count the drops.
size_t num_drops = 0;
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(RpcOptions(), &response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage);
}
}
// The drop rate should be roughly equal to the expectation.
const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
const double kErrorTolerance = 0.2;
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(
::testing::Ge(KDropRateForLbAndThrottle * (1 - kErrorTolerance)),
::testing::Le(KDropRateForLbAndThrottle * (1 + kErrorTolerance))));
}
// Tests that drop config is converted correctly from per hundred.
TEST_P(DropTest, DropPerHundred) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 5000;
const uint32_t kDropPerHundredForLb = 10;
const double kDropRateForLb = kDropPerHundredForLb / 100.0;
// The ADS response contains one drop category.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, kDropPerHundredForLb}};
args.drop_denominator = FractionalPercent::HUNDRED;
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
WaitForAllBackends();
// Send kNumRpcs RPCs and count the drops.
size_t num_drops = 0;
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(RpcOptions(), &response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage);
}
}
// The drop rate should be roughly equal to the expectation.
const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
const double kErrorTolerance = 0.2;
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(::testing::Ge(kDropRateForLb * (1 - kErrorTolerance)),
::testing::Le(kDropRateForLb * (1 + kErrorTolerance))));
}
// Tests that drop config is converted correctly from per ten thousand.
TEST_P(DropTest, DropPerTenThousand) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 5000;
const uint32_t kDropPerTenThousandForLb = 1000;
const double kDropRateForLb = kDropPerTenThousandForLb / 10000.0;
// The ADS response contains one drop category.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, kDropPerTenThousandForLb}};
args.drop_denominator = FractionalPercent::TEN_THOUSAND;
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
WaitForAllBackends();
// Send kNumRpcs RPCs and count the drops.
size_t num_drops = 0;
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(RpcOptions(), &response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage);
}
}
// The drop rate should be roughly equal to the expectation.
const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
const double kErrorTolerance = 0.2;
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(::testing::Ge(kDropRateForLb * (1 - kErrorTolerance)),
::testing::Le(kDropRateForLb * (1 + kErrorTolerance))));
}
// Tests that drop is working correctly after update.
TEST_P(DropTest, Update) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 3000;
const uint32_t kDropPerMillionForLb = 100000;
const uint32_t kDropPerMillionForThrottle = 200000;
const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
const double KDropRateForLbAndThrottle =
kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
// The first ADS response contains one drop category.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, kDropPerMillionForLb}};
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
WaitForAllBackends();
// Send kNumRpcs RPCs and count the drops.
size_t num_drops = 0;
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(RpcOptions(), &response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage);
}
}
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// The drop rate should be roughly equal to the expectation.
double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
gpr_log(GPR_INFO, "First batch drop rate %f", seen_drop_rate);
const double kErrorTolerance = 0.3;
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(::testing::Ge(kDropRateForLb * (1 - kErrorTolerance)),
::testing::Le(kDropRateForLb * (1 + kErrorTolerance))));
// The second ADS response contains two drop categories, send an update EDS
// response.
args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
{kThrottleDropType, kDropPerMillionForThrottle}};
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait until the drop rate increases to the middle of the two configs, which
// implies that the update has been in effect.
const double kDropRateThreshold =
(kDropRateForLb + KDropRateForLbAndThrottle) / 2;
size_t num_rpcs = kNumRpcs;
while (seen_drop_rate < kDropRateThreshold) {
EchoResponse response;
const Status status = SendRpc(RpcOptions(), &response);
++num_rpcs;
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage);
}
seen_drop_rate = static_cast<double>(num_drops) / num_rpcs;
}
// Send kNumRpcs RPCs and count the drops.
num_drops = 0;
gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(RpcOptions(), &response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage);
}
}
gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
// The new drop rate should be roughly equal to the expectation.
seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
gpr_log(GPR_INFO, "Second batch drop rate %f", seen_drop_rate);
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(
::testing::Ge(KDropRateForLbAndThrottle * (1 - kErrorTolerance)),
::testing::Le(KDropRateForLbAndThrottle * (1 + kErrorTolerance))));
}
// Tests that all the RPCs are dropped if any drop category drops 100%.
TEST_P(DropTest, DropAll) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 1000;
const uint32_t kDropPerMillionForLb = 100000;
const uint32_t kDropPerMillionForThrottle = 1000000;
// The ADS response contains two drop categories.
AdsServiceImpl::EdsResourceArgs args;
args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
{kThrottleDropType, kDropPerMillionForThrottle}};
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Send kNumRpcs RPCs and all of them are dropped.
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(RpcOptions(), &response);
EXPECT_EQ(status.error_code(), StatusCode::UNAVAILABLE);
EXPECT_EQ(status.error_message(), "Call dropped by load balancing policy");
}
}
class BalancerUpdateTest : public XdsEnd2endTest {
public:
BalancerUpdateTest() : XdsEnd2endTest(4, 3) {}
};
// Tests that the old LB call is still used after the balancer address update as
// long as that call is still alive.
TEST_P(BalancerUpdateTest, UpdateBalancersButKeepUsingOriginalBalancer) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {backends_[0]->port()}},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
args = AdsServiceImpl::EdsResourceArgs({
{"locality0", {backends_[1]->port()}},
});
balancers_[1]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait until the first backend is ready.
WaitForBackend(0);
// Send 10 requests.
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
CheckRpcSendOk(10);
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// All 10 requests should have gone to the first backend.
EXPECT_EQ(10U, backends_[0]->backend_service()->request_count());
// The ADS service of balancer 0 sent at least 1 response.
EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT);
EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[1]->ads_service()->eds_response_state().error_message;
EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[2]->ads_service()->eds_response_state().error_message;
gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
SetNextResolutionForLbChannel({balancers_[1]->port()});
gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
gpr_timespec deadline = gpr_time_add(
gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(10000, GPR_TIMESPAN));
// Send 10 seconds worth of RPCs
do {
CheckRpcSendOk();
} while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
// The current LB call is still working, so xds continued using it to the
// first balancer, which doesn't assign the second backend.
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
// The ADS service of balancer 0 sent at least 1 response.
EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT);
EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[1]->ads_service()->eds_response_state().error_message;
EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[2]->ads_service()->eds_response_state().error_message;
}
// Tests that the old LB call is still used after multiple balancer address
// updates as long as that call is still alive. Send an update with the same set
// of LBs as the one in SetUp() in order to verify that the LB channel inside
// xds keeps the initial connection (which by definition is also present in the
// update).
TEST_P(BalancerUpdateTest, Repeated) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {backends_[0]->port()}},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
args = AdsServiceImpl::EdsResourceArgs({
{"locality0", {backends_[1]->port()}},
});
balancers_[1]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait until the first backend is ready.
WaitForBackend(0);
// Send 10 requests.
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
CheckRpcSendOk(10);
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// All 10 requests should have gone to the first backend.
EXPECT_EQ(10U, backends_[0]->backend_service()->request_count());
// The ADS service of balancer 0 sent at least 1 response.
EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT);
EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[1]->ads_service()->eds_response_state().error_message;
EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[2]->ads_service()->eds_response_state().error_message;
std::vector<int> ports;
ports.emplace_back(balancers_[0]->port());
ports.emplace_back(balancers_[1]->port());
ports.emplace_back(balancers_[2]->port());
gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
SetNextResolutionForLbChannel(ports);
gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
gpr_timespec deadline = gpr_time_add(
gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(10000, GPR_TIMESPAN));
// Send 10 seconds worth of RPCs
do {
CheckRpcSendOk();
} while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
// xds continued using the original LB call to the first balancer, which
// doesn't assign the second backend.
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
ports.clear();
ports.emplace_back(balancers_[0]->port());
ports.emplace_back(balancers_[1]->port());
gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 2 ==========");
SetNextResolutionForLbChannel(ports);
gpr_log(GPR_INFO, "========= UPDATE 2 DONE ==========");
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_millis(10000, GPR_TIMESPAN));
// Send 10 seconds worth of RPCs
do {
CheckRpcSendOk();
} while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
// xds continued using the original LB call to the first balancer, which
// doesn't assign the second backend.
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
}
// Tests that if the balancer is down, the RPCs will still be sent to the
// backends according to the last balancer response, until a new balancer is
// reachable.
TEST_P(BalancerUpdateTest, DeadUpdate) {
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()});
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {backends_[0]->port()}},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
args = AdsServiceImpl::EdsResourceArgs({
{"locality0", {backends_[1]->port()}},
});
balancers_[1]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Start servers and send 10 RPCs per server.
gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
CheckRpcSendOk(10);
gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
// All 10 requests should have gone to the first backend.
EXPECT_EQ(10U, backends_[0]->backend_service()->request_count());
// The ADS service of balancer 0 sent at least 1 response.
EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT);
EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[1]->ads_service()->eds_response_state().error_message;
EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[2]->ads_service()->eds_response_state().error_message;
// Kill balancer 0
gpr_log(GPR_INFO, "********** ABOUT TO KILL BALANCER 0 *************");
balancers_[0]->Shutdown();
gpr_log(GPR_INFO, "********** KILLED BALANCER 0 *************");
// This is serviced by the existing child policy.
gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
CheckRpcSendOk(10);
gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
// All 10 requests should again have gone to the first backend.
EXPECT_EQ(20U, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
// The ADS service of no balancers sent anything
EXPECT_EQ(balancers_[0]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[0]->ads_service()->eds_response_state().error_message;
EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[1]->ads_service()->eds_response_state().error_message;
EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[2]->ads_service()->eds_response_state().error_message;
gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
SetNextResolutionForLbChannel({balancers_[1]->port()});
gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
// Wait until update has been processed, as signaled by the second backend
// receiving a request. In the meantime, the client continues to be serviced
// (by the first backend) without interruption.
EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
WaitForBackend(1);
// This is serviced by the updated RR policy
backends_[1]->backend_service()->ResetCounters();
gpr_log(GPR_INFO, "========= BEFORE THIRD BATCH ==========");
CheckRpcSendOk(10);
gpr_log(GPR_INFO, "========= DONE WITH THIRD BATCH ==========");
// All 10 requests should have gone to the second backend.
EXPECT_EQ(10U, backends_[1]->backend_service()->request_count());
// The ADS service of balancer 1 sent at least 1 response.
EXPECT_EQ(balancers_[0]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[0]->ads_service()->eds_response_state().error_message;
EXPECT_GT(balancers_[1]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT);
EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
AdsServiceImpl::ResponseState::NOT_SENT)
<< "Error Message:"
<< balancers_[2]->ads_service()->eds_response_state().error_message;
}
class ClientLoadReportingTest : public XdsEnd2endTest {
public:
ClientLoadReportingTest() : XdsEnd2endTest(4, 1, 3) {}
};
// Tests that the load report received at the balancer is correct.
TEST_P(ClientLoadReportingTest, Vanilla) {
if (GetParam().use_fake_resolver()) {
balancers_[0]->lrs_service()->set_cluster_names({kServerName});
}
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()});
const size_t kNumRpcsPerAddress = 10;
const size_t kNumFailuresPerAddress = 3;
// TODO(juanlishen): Partition the backends after multiple localities is
// tested.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait until all backends are ready.
int num_ok = 0;
int num_failure = 0;
int num_drops = 0;
std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
// Send kNumRpcsPerAddress RPCs per server.
CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
CheckRpcSendFailure(kNumFailuresPerAddress * num_backends_,
RpcOptions().set_server_fail(true));
// Check that each backend got the right number of requests.
for (size_t i = 0; i < backends_.size(); ++i) {
EXPECT_EQ(kNumRpcsPerAddress + kNumFailuresPerAddress,
backends_[i]->backend_service()->request_count());
}
// The load report received at the balancer should be correct.
std::vector<ClientStats> load_report =
balancers_[0]->lrs_service()->WaitForLoadReport();
ASSERT_EQ(load_report.size(), 1UL);
ClientStats& client_stats = load_report.front();
EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_ok,
client_stats.total_successful_requests());
EXPECT_EQ(0U, client_stats.total_requests_in_progress());
EXPECT_EQ((kNumRpcsPerAddress + kNumFailuresPerAddress) * num_backends_ +
num_ok + num_failure,
client_stats.total_issued_requests());
EXPECT_EQ(kNumFailuresPerAddress * num_backends_ + num_failure,
client_stats.total_error_requests());
EXPECT_EQ(0U, client_stats.total_dropped_requests());
// The LRS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->lrs_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->lrs_service()->response_count());
}
// Tests send_all_clusters.
TEST_P(ClientLoadReportingTest, SendAllClusters) {
balancers_[0]->lrs_service()->set_send_all_clusters(true);
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()});
const size_t kNumRpcsPerAddress = 10;
const size_t kNumFailuresPerAddress = 3;
// TODO(juanlishen): Partition the backends after multiple localities is
// tested.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait until all backends are ready.
int num_ok = 0;
int num_failure = 0;
int num_drops = 0;
std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
// Send kNumRpcsPerAddress RPCs per server.
CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
CheckRpcSendFailure(kNumFailuresPerAddress * num_backends_,
RpcOptions().set_server_fail(true));
// Check that each backend got the right number of requests.
for (size_t i = 0; i < backends_.size(); ++i) {
EXPECT_EQ(kNumRpcsPerAddress + kNumFailuresPerAddress,
backends_[i]->backend_service()->request_count());
}
// The load report received at the balancer should be correct.
std::vector<ClientStats> load_report =
balancers_[0]->lrs_service()->WaitForLoadReport();
ASSERT_EQ(load_report.size(), 1UL);
ClientStats& client_stats = load_report.front();
EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_ok,
client_stats.total_successful_requests());
EXPECT_EQ(0U, client_stats.total_requests_in_progress());
EXPECT_EQ((kNumRpcsPerAddress + kNumFailuresPerAddress) * num_backends_ +
num_ok + num_failure,
client_stats.total_issued_requests());
EXPECT_EQ(kNumFailuresPerAddress * num_backends_ + num_failure,
client_stats.total_error_requests());
EXPECT_EQ(0U, client_stats.total_dropped_requests());
// The LRS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->lrs_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->lrs_service()->response_count());
}
// Tests that we don't include stats for clusters that are not requested
// by the LRS server.
TEST_P(ClientLoadReportingTest, HonorsClustersRequestedByLrsServer) {
balancers_[0]->lrs_service()->set_cluster_names({"bogus"});
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()});
const size_t kNumRpcsPerAddress = 100;
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait until all backends are ready.
int num_ok = 0;
int num_failure = 0;
int num_drops = 0;
std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
// Send kNumRpcsPerAddress RPCs per server.
CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
// Each backend should have gotten 100 requests.
for (size_t i = 0; i < backends_.size(); ++i) {
EXPECT_EQ(kNumRpcsPerAddress,
backends_[i]->backend_service()->request_count());
}
// The LRS service got a single request, and sent a single response.
EXPECT_EQ(1U, balancers_[0]->lrs_service()->request_count());
EXPECT_EQ(1U, balancers_[0]->lrs_service()->response_count());
// The load report received at the balancer should be correct.
std::vector<ClientStats> load_report =
balancers_[0]->lrs_service()->WaitForLoadReport();
ASSERT_EQ(load_report.size(), 0UL);
}
// Tests that if the balancer restarts, the client load report contains the
// stats before and after the restart correctly.
TEST_P(ClientLoadReportingTest, BalancerRestart) {
if (GetParam().use_fake_resolver()) {
balancers_[0]->lrs_service()->set_cluster_names({kServerName});
}
SetNextResolution({});
SetNextResolutionForLbChannel({balancers_[0]->port()});
const size_t kNumBackendsFirstPass = backends_.size() / 2;
const size_t kNumBackendsSecondPass =
backends_.size() - kNumBackendsFirstPass;
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts(0, kNumBackendsFirstPass)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait until all backends returned by the balancer are ready.
int num_ok = 0;
int num_failure = 0;
int num_drops = 0;
std::tie(num_ok, num_failure, num_drops) =
WaitForAllBackends(/* start_index */ 0,
/* stop_index */ kNumBackendsFirstPass);
std::vector<ClientStats> load_report =
balancers_[0]->lrs_service()->WaitForLoadReport();
ASSERT_EQ(load_report.size(), 1UL);
ClientStats client_stats = std::move(load_report.front());
EXPECT_EQ(static_cast<size_t>(num_ok),
client_stats.total_successful_requests());
EXPECT_EQ(0U, client_stats.total_requests_in_progress());
EXPECT_EQ(0U, client_stats.total_error_requests());
EXPECT_EQ(0U, client_stats.total_dropped_requests());
// Shut down the balancer.
balancers_[0]->Shutdown();
// We should continue using the last EDS response we received from the
// balancer before it was shut down.
// Note: We need to use WaitForAllBackends() here instead of just
// CheckRpcSendOk(kNumBackendsFirstPass), because when the balancer
// shuts down, the XdsClient will generate an error to the
// ServiceConfigWatcher, which will cause the xds resolver to send a
// no-op update to the LB policy. When this update gets down to the
// round_robin child policy for the locality, it will generate a new
// subchannel list, which resets the start index randomly. So we need
// to be a little more permissive here to avoid spurious failures.
ResetBackendCounters();
int num_started = std::get<0>(WaitForAllBackends(
/* start_index */ 0, /* stop_index */ kNumBackendsFirstPass));
// Now restart the balancer, this time pointing to the new backends.
balancers_[0]->Start();
args = AdsServiceImpl::EdsResourceArgs({
{"locality0", GetBackendPorts(kNumBackendsFirstPass)},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Wait for queries to start going to one of the new backends.
// This tells us that we're now using the new serverlist.
std::tie(num_ok, num_failure, num_drops) =
WaitForAllBackends(/* start_index */ kNumBackendsFirstPass);
num_started += num_ok + num_failure + num_drops;
// Send one RPC per backend.
CheckRpcSendOk(kNumBackendsSecondPass);
num_started += kNumBackendsSecondPass;
// Check client stats.
load_report = balancers_[0]->lrs_service()->WaitForLoadReport();
ASSERT_EQ(load_report.size(), 1UL);
client_stats = std::move(load_report.front());
EXPECT_EQ(num_started, client_stats.total_successful_requests());
EXPECT_EQ(0U, client_stats.total_requests_in_progress());
EXPECT_EQ(0U, client_stats.total_error_requests());
EXPECT_EQ(0U, client_stats.total_dropped_requests());
}
class ClientLoadReportingWithDropTest : public XdsEnd2endTest {
public:
ClientLoadReportingWithDropTest() : XdsEnd2endTest(4, 1, 20) {}
};
// Tests that the drop stats are correctly reported by client load reporting.
TEST_P(ClientLoadReportingWithDropTest, Vanilla) {
if (GetParam().use_fake_resolver()) {
balancers_[0]->lrs_service()->set_cluster_names({kServerName});
}
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
const size_t kNumRpcs = 3000;
const uint32_t kDropPerMillionForLb = 100000;
const uint32_t kDropPerMillionForThrottle = 200000;
const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
const double KDropRateForLbAndThrottle =
kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
// The ADS response contains two drop categories.
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
{kThrottleDropType, kDropPerMillionForThrottle}};
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
int num_ok = 0;
int num_failure = 0;
int num_drops = 0;
std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
const size_t num_warmup = num_ok + num_failure + num_drops;
// Send kNumRpcs RPCs and count the drops.
for (size_t i = 0; i < kNumRpcs; ++i) {
EchoResponse response;
const Status status = SendRpc(RpcOptions(), &response);
if (!status.ok() &&
status.error_message() == "Call dropped by load balancing policy") {
++num_drops;
} else {
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
EXPECT_EQ(response.message(), kRequestMessage);
}
}
// The drop rate should be roughly equal to the expectation.
const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
const double kErrorTolerance = 0.2;
EXPECT_THAT(
seen_drop_rate,
::testing::AllOf(
::testing::Ge(KDropRateForLbAndThrottle * (1 - kErrorTolerance)),
::testing::Le(KDropRateForLbAndThrottle * (1 + kErrorTolerance))));
// Check client stats.
const size_t total_rpc = num_warmup + kNumRpcs;
ClientStats client_stats;
do {
std::vector<ClientStats> load_reports =
balancers_[0]->lrs_service()->WaitForLoadReport();
for (const auto& load_report : load_reports) {
client_stats += load_report;
}
} while (client_stats.total_issued_requests() +
client_stats.total_dropped_requests() <
total_rpc);
EXPECT_EQ(num_drops, client_stats.total_dropped_requests());
EXPECT_THAT(
client_stats.dropped_requests(kLbDropType),
::testing::AllOf(
::testing::Ge(total_rpc * kDropRateForLb * (1 - kErrorTolerance)),
::testing::Le(total_rpc * kDropRateForLb * (1 + kErrorTolerance))));
EXPECT_THAT(client_stats.dropped_requests(kThrottleDropType),
::testing::AllOf(
::testing::Ge(total_rpc * (1 - kDropRateForLb) *
kDropRateForThrottle * (1 - kErrorTolerance)),
::testing::Le(total_rpc * (1 - kDropRateForLb) *
kDropRateForThrottle * (1 + kErrorTolerance))));
}
class FaultInjectionTest : public XdsEnd2endTest {
public:
FaultInjectionTest() : XdsEnd2endTest(1, 1) {}
// Builds a Listener with Fault Injection filter config. If the http_fault is
// nullptr, then assign an empty filter config. This filter config is required
// to enable the fault injection features.
static Listener BuildListenerWithFaultInjection(
const HTTPFault& http_fault = HTTPFault()) {
HttpConnectionManager http_connection_manager;
Listener listener;
listener.set_name(kServerName);
HttpFilter* fault_filter = http_connection_manager.add_http_filters();
fault_filter->set_name("envoy.fault");
fault_filter->mutable_typed_config()->PackFrom(http_fault);
HttpFilter* router_filter = http_connection_manager.add_http_filters();
router_filter->set_name("router");
router_filter->mutable_typed_config()->PackFrom(
envoy::extensions::filters::http::router::v3::Router());
listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
http_connection_manager);
return listener;
}
RouteConfiguration BuildRouteConfigurationWithFaultInjection(
const HTTPFault& http_fault) {
// Package as Any
google::protobuf::Any filter_config;
filter_config.PackFrom(http_fault);
// Plug into the RouteConfiguration
RouteConfiguration new_route_config = default_route_config_;
auto* config_map = new_route_config.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_typed_per_filter_config();
(*config_map)["envoy.fault"] = std::move(filter_config);
return new_route_config;
}
void SetFilterConfig(HTTPFault& http_fault) {
switch (GetParam().filter_config_setup()) {
case TestType::FilterConfigSetup::kRouteOverride: {
Listener listener = BuildListenerWithFaultInjection();
RouteConfiguration route =
BuildRouteConfigurationWithFaultInjection(http_fault);
SetListenerAndRouteConfiguration(0, listener, route);
break;
}
case TestType::FilterConfigSetup::kHTTPConnectionManagerOriginal: {
Listener listener = BuildListenerWithFaultInjection(http_fault);
SetListenerAndRouteConfiguration(0, listener, default_route_config_);
}
};
}
};
// Test to ensure the most basic fault injection config works.
TEST_P(FaultInjectionTest, XdsFaultInjectionAlwaysAbort) {
const uint32_t kAbortPercentagePerHundred = 100;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Construct the fault injection filter config
HTTPFault http_fault;
auto* abort_percentage = http_fault.mutable_abort()->mutable_percentage();
abort_percentage->set_numerator(kAbortPercentagePerHundred);
abort_percentage->set_denominator(FractionalPercent::HUNDRED);
http_fault.mutable_abort()->set_grpc_status(
static_cast<uint32_t>(StatusCode::ABORTED));
// Config fault injection via different setup
SetFilterConfig(http_fault);
// Fire several RPCs, and expect all of them to be aborted.
CheckRpcSendFailure(5, RpcOptions().set_wait_for_ready(true),
StatusCode::ABORTED);
}
// Without the listener config, the fault injection won't be enabled.
TEST_P(FaultInjectionTest, XdsFaultInjectionWithoutListenerFilter) {
const uint32_t kAbortPercentagePerHundred = 100;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Create an EDS resource
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Construct the fault injection filter config
HTTPFault http_fault;
auto* abort_percentage = http_fault.mutable_abort()->mutable_percentage();
abort_percentage->set_numerator(kAbortPercentagePerHundred);
abort_percentage->set_denominator(FractionalPercent::HUNDRED);
http_fault.mutable_abort()->set_grpc_status(
static_cast<uint32_t>(StatusCode::ABORTED));
// Turn on fault injection
RouteConfiguration route =
BuildRouteConfigurationWithFaultInjection(http_fault);
SetListenerAndRouteConfiguration(0, default_listener_, route);
// Fire several RPCs, and expect all of them to be pass.
CheckRpcSendOk(5, RpcOptions().set_wait_for_ready(true));
}
TEST_P(FaultInjectionTest, XdsFaultInjectionPercentageAbort) {
const size_t kNumRpcs = 100;
const uint32_t kAbortPercentagePerHundred = 50;
const double kAbortRate = kAbortPercentagePerHundred / 100.0;
const double kErrorTolerance = 0.2;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Create an EDS resource
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Construct the fault injection filter config
HTTPFault http_fault;
auto* abort_percentage = http_fault.mutable_abort()->mutable_percentage();
abort_percentage->set_numerator(kAbortPercentagePerHundred);
abort_percentage->set_denominator(FractionalPercent::HUNDRED);
http_fault.mutable_abort()->set_grpc_status(
static_cast<uint32_t>(StatusCode::ABORTED));
// Config fault injection via different setup
SetFilterConfig(http_fault);
// Send kNumRpcs RPCs and count the aborts.
int num_total = 0, num_ok = 0, num_failure = 0, num_aborted = 0;
for (size_t i = 0; i < kNumRpcs; ++i) {
SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_aborted,
RpcOptions(), "Fault injected");
}
EXPECT_EQ(kNumRpcs, num_total);
EXPECT_EQ(0, num_failure);
// The abort rate should be roughly equal to the expectation.
const double seen_abort_rate = static_cast<double>(num_aborted) / kNumRpcs;
EXPECT_THAT(seen_abort_rate,
::testing::AllOf(::testing::Ge(kAbortRate - kErrorTolerance),
::testing::Le(kAbortRate + kErrorTolerance)));
}
TEST_P(FaultInjectionTest, XdsFaultInjectionPercentageAbortViaHeaders) {
const size_t kNumRpcs = 100;
const uint32_t kAbortPercentageCap = 100;
const uint32_t kAbortPercentage = 50;
const double kAbortRate = kAbortPercentage / 100.0;
const double kErrorTolerance = 0.2;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Create an EDS resource
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Construct the fault injection filter config
HTTPFault http_fault;
http_fault.mutable_abort()->mutable_header_abort();
http_fault.mutable_abort()->mutable_percentage()->set_numerator(
kAbortPercentageCap);
// Config fault injection via different setup
SetFilterConfig(http_fault);
// Send kNumRpcs RPCs and count the aborts.
std::vector<std::pair<std::string, std::string>> metadata = {
{"x-envoy-fault-abort-grpc-request", "10"},
{"x-envoy-fault-abort-percentage", std::to_string(kAbortPercentage)},
};
int num_total = 0, num_ok = 0, num_failure = 0, num_aborted = 0;
RpcOptions options = RpcOptions().set_metadata(metadata);
for (size_t i = 0; i < kNumRpcs; ++i) {
SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_aborted, options,
"Fault injected");
}
EXPECT_EQ(kNumRpcs, num_total);
EXPECT_EQ(0, num_failure);
// The abort rate should be roughly equal to the expectation.
const double seen_abort_rate = static_cast<double>(num_aborted) / kNumRpcs;
EXPECT_THAT(seen_abort_rate,
::testing::AllOf(::testing::Ge(kAbortRate - kErrorTolerance),
::testing::Le(kAbortRate + kErrorTolerance)));
}
// TODO(lidiz) reduce the error tolerance to a lower level without dramatically
// increase the duration of fault injection tests.
TEST_P(FaultInjectionTest, XdsFaultInjectionPercentageDelay) {
const size_t kNumRpcs = 100;
const uint32_t kFixedDelaySeconds = 100;
const uint32_t kRpcTimeoutMilliseconds = 10; // 10 ms
const uint32_t kDelayPercentagePerHundred = 95;
const double kDelayRate = kDelayPercentagePerHundred / 100.0;
const double kErrorTolerance = 0.2;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Create an EDS resource
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Construct the fault injection filter config
HTTPFault http_fault;
auto* delay_percentage = http_fault.mutable_delay()->mutable_percentage();
delay_percentage->set_numerator(kDelayPercentagePerHundred);
delay_percentage->set_denominator(FractionalPercent::HUNDRED);
auto* fixed_delay = http_fault.mutable_delay()->mutable_fixed_delay();
fixed_delay->set_seconds(kFixedDelaySeconds);
// Config fault injection via different setup
SetFilterConfig(http_fault);
// Send kNumRpcs RPCs and count the delays.
int num_total = 0, num_ok = 0, num_delayed = 0, num_dropped = 0;
RpcOptions options = RpcOptions()
.set_timeout_ms(kRpcTimeoutMilliseconds)
.set_skip_cancelled_check(true);
for (size_t i = 0; i < kNumRpcs; ++i) {
SendRpcAndCount(&num_total, &num_ok, &num_delayed, &num_dropped, options);
}
EXPECT_EQ(kNumRpcs, num_total);
EXPECT_EQ(0, num_dropped);
// The delay rate should be roughly equal to the expectation.
const double seen_delay_rate = static_cast<double>(num_delayed) / kNumRpcs;
EXPECT_THAT(seen_delay_rate,
::testing::AllOf(::testing::Ge(kDelayRate - kErrorTolerance),
::testing::Le(kDelayRate + kErrorTolerance)));
}
TEST_P(FaultInjectionTest, XdsFaultInjectionPercentageDelayViaHeaders) {
const size_t kNumRpcs = 100;
const uint32_t kFixedDelayMilliseconds = 100000; // 100 seconds
const uint32_t kRpcTimeoutMilliseconds = 10; // 10 ms
const uint32_t kDelayPercentageCap = 100;
const uint32_t kDelayPercentage = 50;
const double kDelayRate = kDelayPercentage / 100.0;
const double kErrorTolerance = 0.2;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Create an EDS resource
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Construct the fault injection filter config
HTTPFault http_fault;
http_fault.mutable_delay()->mutable_header_delay();
http_fault.mutable_delay()->mutable_percentage()->set_numerator(
kDelayPercentageCap);
// Config fault injection via different setup
SetFilterConfig(http_fault);
// Send kNumRpcs RPCs and count the delays.
std::vector<std::pair<std::string, std::string>> metadata = {
{"x-envoy-fault-delay-request", std::to_string(kFixedDelayMilliseconds)},
{"x-envoy-fault-delay-request-percentage",
std::to_string(kDelayPercentage)},
};
int num_total = 0, num_ok = 0, num_delayed = 0, num_dropped = 0;
RpcOptions options = RpcOptions()
.set_metadata(metadata)
.set_timeout_ms(kRpcTimeoutMilliseconds)
.set_skip_cancelled_check(true);
for (size_t i = 0; i < kNumRpcs; ++i) {
SendRpcAndCount(&num_total, &num_ok, &num_delayed, &num_dropped, options);
}
// The delay rate should be roughly equal to the expectation.
const double seen_delay_rate = static_cast<double>(num_delayed) / kNumRpcs;
EXPECT_THAT(seen_delay_rate,
::testing::AllOf(::testing::Ge(kDelayRate - kErrorTolerance),
::testing::Le(kDelayRate + kErrorTolerance)));
}
TEST_P(FaultInjectionTest, XdsFaultInjectionAlwaysDelayPercentageAbort) {
const size_t kNumRpcs = 100;
const uint32_t kAbortPercentagePerHundred = 50;
const double kAbortRate = kAbortPercentagePerHundred / 100.0;
const uint32_t kFixedDelayNanos = 10 * 1000 * 1000; // 10 ms
const double kErrorTolerance = 0.2;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Create an EDS resource
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Construct the fault injection filter config
HTTPFault http_fault;
auto* abort_percentage = http_fault.mutable_abort()->mutable_percentage();
abort_percentage->set_numerator(kAbortPercentagePerHundred);
abort_percentage->set_denominator(FractionalPercent::HUNDRED);
http_fault.mutable_abort()->set_grpc_status(
static_cast<uint32_t>(StatusCode::ABORTED));
auto* delay_percentage = http_fault.mutable_delay()->mutable_percentage();
delay_percentage->set_numerator(1000000); // Always inject DELAY!
delay_percentage->set_denominator(FractionalPercent::MILLION);
auto* fixed_delay = http_fault.mutable_delay()->mutable_fixed_delay();
fixed_delay->set_nanos(kFixedDelayNanos);
// Config fault injection via different setup
SetFilterConfig(http_fault);
// Send kNumRpcs RPCs and count the aborts.
int num_total = 0, num_ok = 0, num_failure = 0, num_aborted = 0;
for (size_t i = 0; i < kNumRpcs; ++i) {
grpc_millis t0 = NowFromCycleCounter();
SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_aborted,
RpcOptions(), "Fault injected");
grpc_millis t1 = NowFromCycleCounter();
EXPECT_GE(t1, t0 + kFixedDelayNanos / 1000 / 1000);
}
EXPECT_EQ(kNumRpcs, num_total);
EXPECT_EQ(0, num_failure);
// The abort rate should be roughly equal to the expectation.
const double seen_abort_rate = static_cast<double>(num_aborted) / kNumRpcs;
EXPECT_THAT(seen_abort_rate,
::testing::AllOf(::testing::Ge(kAbortRate - kErrorTolerance),
::testing::Le(kAbortRate + kErrorTolerance)));
}
// This test and the above test apply different denominators to delay and abort.
// This ensures that we are using the right denominator for each injected fault
// in our code.
TEST_P(FaultInjectionTest,
XdsFaultInjectionAlwaysDelayPercentageAbortSwitchDenominator) {
const size_t kNumRpcs = 100;
const uint32_t kAbortPercentagePerMillion = 500000;
const double kAbortRate = kAbortPercentagePerMillion / 1000000.0;
const uint32_t kFixedDelayNanos = 10 * 1000 * 1000; // 10 ms
const double kErrorTolerance = 0.2;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Create an EDS resource
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Construct the fault injection filter config
HTTPFault http_fault;
auto* abort_percentage = http_fault.mutable_abort()->mutable_percentage();
abort_percentage->set_numerator(kAbortPercentagePerMillion);
abort_percentage->set_denominator(FractionalPercent::MILLION);
http_fault.mutable_abort()->set_grpc_status(
static_cast<uint32_t>(StatusCode::ABORTED));
auto* delay_percentage = http_fault.mutable_delay()->mutable_percentage();
delay_percentage->set_numerator(100); // Always inject DELAY!
delay_percentage->set_denominator(FractionalPercent::HUNDRED);
auto* fixed_delay = http_fault.mutable_delay()->mutable_fixed_delay();
fixed_delay->set_nanos(kFixedDelayNanos);
// Config fault injection via different setup
SetFilterConfig(http_fault);
// Send kNumRpcs RPCs and count the aborts.
int num_total = 0, num_ok = 0, num_failure = 0, num_aborted = 0;
for (size_t i = 0; i < kNumRpcs; ++i) {
grpc_millis t0 = NowFromCycleCounter();
SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_aborted,
RpcOptions(), "Fault injected");
grpc_millis t1 = NowFromCycleCounter();
EXPECT_GE(t1, t0 + kFixedDelayNanos / 1000 / 1000);
}
EXPECT_EQ(kNumRpcs, num_total);
EXPECT_EQ(0, num_failure);
// The abort rate should be roughly equal to the expectation.
const double seen_abort_rate = static_cast<double>(num_aborted) / kNumRpcs;
EXPECT_THAT(seen_abort_rate,
::testing::AllOf(::testing::Ge(kAbortRate - kErrorTolerance),
::testing::Le(kAbortRate + kErrorTolerance)));
}
TEST_P(FaultInjectionTest, XdsFaultInjectionMaxFault) {
const uint32_t kMaxFault = 10;
const uint32_t kNumRpcs = 30; // kNumRpcs should be bigger than kMaxFault
const uint32_t kRpcTimeoutMs = 2000; // 2 seconds
const uint32_t kLongDelaySeconds = 100; // 100 seconds
const uint32_t kAlwaysDelayPercentage = 100;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Create an EDS resource
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Construct the fault injection filter config
HTTPFault http_fault;
auto* delay_percentage = http_fault.mutable_delay()->mutable_percentage();
delay_percentage->set_numerator(
kAlwaysDelayPercentage); // Always inject DELAY!
delay_percentage->set_denominator(FractionalPercent::HUNDRED);
auto* fixed_delay = http_fault.mutable_delay()->mutable_fixed_delay();
fixed_delay->set_seconds(kLongDelaySeconds);
http_fault.mutable_max_active_faults()->set_value(kMaxFault);
// Config fault injection via different setup
SetFilterConfig(http_fault);
// Sends a batch of long running RPCs with long timeout to consume all
// active faults quota.
int num_ok = 0, num_delayed = 0;
LongRunningRpc rpcs[kNumRpcs];
RpcOptions rpc_options = RpcOptions().set_timeout_ms(kRpcTimeoutMs);
for (size_t i = 0; i < kNumRpcs; ++i) {
rpcs[i].StartRpc(stub_.get(), rpc_options);
}
for (size_t i = 0; i < kNumRpcs; ++i) {
Status status = rpcs[i].GetStatus();
if (status.ok()) {
++num_ok;
} else {
EXPECT_EQ(StatusCode::DEADLINE_EXCEEDED, status.error_code());
++num_delayed;
}
}
// Only kMaxFault number of RPC should be fault injected..
EXPECT_EQ(kMaxFault, num_delayed);
// Other RPCs should be ok.
EXPECT_EQ(kNumRpcs - kMaxFault, num_ok);
}
class BootstrapContentsFromEnvVarTest : public XdsEnd2endTest {
public:
BootstrapContentsFromEnvVarTest() : XdsEnd2endTest(4, 1, 100, false, true) {}
};
TEST_P(BootstrapContentsFromEnvVarTest, Vanilla) {
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", GetBackendPorts()},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
WaitForAllBackends();
}
#ifndef DISABLED_XDS_PROTO_IN_CC
class ClientStatusDiscoveryServiceTest : public XdsEnd2endTest {
public:
ClientStatusDiscoveryServiceTest() : XdsEnd2endTest(1, 1) {}
void SetUp() override {
XdsEnd2endTest::SetUp();
admin_server_thread_ = absl::make_unique<AdminServerThread>();
admin_server_thread_->Start();
std::string admin_server_address = absl::StrCat(
ipv6_only_ ? "[::1]:" : "127.0.0.1:", admin_server_thread_->port());
admin_channel_ = grpc::CreateChannel(
admin_server_address,
std::make_shared<SecureChannelCredentials>(
grpc_fake_transport_security_credentials_create()));
csds_stub_ =
envoy::service::status::v3::ClientStatusDiscoveryService::NewStub(
admin_channel_);
if (GetParam().use_csds_streaming()) {
stream_ = csds_stub_->StreamClientStatus(&stream_context_);
}
}
void TearDown() override {
if (stream_ != nullptr) {
EXPECT_TRUE(stream_->WritesDone());
Status status = stream_->Finish();
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
}
admin_server_thread_->Shutdown();
XdsEnd2endTest::TearDown();
}
envoy::service::status::v3::ClientStatusResponse FetchCsdsResponse() {
envoy::service::status::v3::ClientStatusResponse response;
if (!GetParam().use_csds_streaming()) {
// Fetch through unary pulls
ClientContext context;
Status status = csds_stub_->FetchClientStatus(
&context, envoy::service::status::v3::ClientStatusRequest(),
&response);
EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
<< " message=" << status.error_message();
} else {
// Fetch through streaming pulls
EXPECT_TRUE(
stream_->Write(envoy::service::status::v3::ClientStatusRequest()));
EXPECT_TRUE(stream_->Read(&response));
}
return response;
}
private:
std::unique_ptr<AdminServerThread> admin_server_thread_;
std::shared_ptr<Channel> admin_channel_;
std::unique_ptr<
envoy::service::status::v3::ClientStatusDiscoveryService::Stub>
csds_stub_;
ClientContext stream_context_;
std::unique_ptr<
ClientReaderWriter<envoy::service::status::v3::ClientStatusRequest,
envoy::service::status::v3::ClientStatusResponse>>
stream_;
};
MATCHER_P4(EqNode, id, user_agent_name, user_agent_version, client_features,
"equals Node") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(id, arg.id(), result_listener);
ok &= ::testing::ExplainMatchResult(user_agent_name, arg.user_agent_name(),
result_listener);
ok &= ::testing::ExplainMatchResult(
user_agent_version, arg.user_agent_version(), result_listener);
ok &= ::testing::ExplainMatchResult(client_features, arg.client_features(),
result_listener);
return ok;
}
MATCHER_P2(EqListenersConfigDump, version_info, dynamic_listeners,
"equals ListenerConfigDump") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(::testing::ElementsAre(),
arg.static_listeners(), result_listener);
ok &= ::testing::ExplainMatchResult(version_info, arg.version_info(),
result_listener);
ok &= ::testing::ExplainMatchResult(dynamic_listeners,
arg.dynamic_listeners(), result_listener);
return ok;
}
MATCHER_P2(EqDynamicListenerState, version_info, listener,
"equals DynamicListenerState") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(version_info, arg.version_info(),
result_listener);
ok &=
::testing::ExplainMatchResult(listener, arg.listener(), result_listener);
return ok;
}
MATCHER_P2(EqListener, name, api_listener, "equals Listener") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(name, arg.name(), result_listener);
ok &= ::testing::ExplainMatchResult(
api_listener, arg.api_listener().api_listener(), result_listener);
return ok;
}
MATCHER_P(EqHttpConnectionManagerNotRds, route_config,
"equals HttpConnectionManager") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(route_config, arg.route_config(),
result_listener);
return ok;
}
MATCHER_P(EqRouteConfigurationName, name, "equals RouteConfiguration") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(name, arg.name(), result_listener);
return ok;
}
MATCHER_P2(EqRouteConfiguration, name, cluster_name,
"equals RouteConfiguration") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(name, arg.name(), result_listener);
ok &= ::testing::ExplainMatchResult(
::testing::ElementsAre(::testing::Property(
&envoy::config::route::v3::VirtualHost::routes,
::testing::ElementsAre(::testing::Property(
&envoy::config::route::v3::Route::route,
::testing::Property(
&envoy::config::route::v3::RouteAction::cluster,
cluster_name))))),
arg.virtual_hosts(), result_listener);
return ok;
}
MATCHER_P(EqRoutesConfigDump, dynamic_route_configs,
"equals RoutesConfigDump") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(
::testing::ElementsAre(), arg.static_route_configs(), result_listener);
ok &= ::testing::ExplainMatchResult(
dynamic_route_configs, arg.dynamic_route_configs(), result_listener);
return ok;
}
MATCHER_P2(EqClustersConfigDump, version_info, dynamic_active_clusters,
"equals ClustersConfigDump") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(::testing::ElementsAre(),
arg.static_clusters(), result_listener);
ok &= ::testing::ExplainMatchResult(::testing::ElementsAre(),
arg.dynamic_warming_clusters(),
result_listener);
ok &= ::testing::ExplainMatchResult(version_info, arg.version_info(),
result_listener);
ok &= ::testing::ExplainMatchResult(
dynamic_active_clusters, arg.dynamic_active_clusters(), result_listener);
return ok;
}
MATCHER_P(EqCluster, name, "equals Cluster") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(name, arg.name(), result_listener);
return ok;
}
MATCHER_P(EqEndpointsConfigDump, dynamic_endpoint_configs,
"equals EndpointsConfigDump") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(dynamic_endpoint_configs,
arg.dynamic_endpoint_configs(),
result_listener);
return ok;
}
MATCHER_P(EqEndpoint, port, "equals Endpoint") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(
port, arg.address().socket_address().port_value(), result_listener);
return ok;
}
MATCHER_P2(EqLocalityLbEndpoints, port, weight, "equals LocalityLbEndpoints") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(
::testing::ElementsAre(::testing::Property(
&envoy::config::endpoint::v3::LbEndpoint::endpoint,
EqEndpoint(port))),
arg.lb_endpoints(), result_listener);
ok &= ::testing::ExplainMatchResult(
weight, arg.load_balancing_weight().value(), result_listener);
return ok;
}
MATCHER_P(EqClusterLoadAssignmentName, cluster_name,
"equals ClusterLoadAssignment") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(cluster_name, arg.cluster_name(),
result_listener);
return ok;
}
MATCHER_P3(EqClusterLoadAssignment, cluster_name, port, weight,
"equals ClusterLoadAssignment") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(cluster_name, arg.cluster_name(),
result_listener);
ok &= ::testing::ExplainMatchResult(
::testing::ElementsAre(EqLocalityLbEndpoints(port, weight)),
arg.endpoints(), result_listener);
return ok;
}
MATCHER_P2(EqUpdateFailureState, details, version_info,
"equals UpdateFailureState") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(details, arg.details(), result_listener);
ok &= ::testing::ExplainMatchResult(version_info, arg.version_info(),
result_listener);
return ok;
}
MATCHER_P(UnpackListener, matcher, "is a Listener") {
Listener config;
if (!::testing::ExplainMatchResult(true, arg.UnpackTo(&config),
result_listener)) {
return false;
}
return ::testing::ExplainMatchResult(matcher, config, result_listener);
}
MATCHER_P(UnpackRouteConfiguration, matcher, "is a RouteConfiguration") {
RouteConfiguration config;
if (!::testing::ExplainMatchResult(true, arg.UnpackTo(&config),
result_listener)) {
return false;
}
return ::testing::ExplainMatchResult(matcher, config, result_listener);
}
MATCHER_P(UnpackHttpConnectionManager, matcher, "is a HttpConnectionManager") {
HttpConnectionManager config;
if (!::testing::ExplainMatchResult(true, arg.UnpackTo(&config),
result_listener)) {
return false;
}
return ::testing::ExplainMatchResult(matcher, config, result_listener);
}
MATCHER_P(UnpackCluster, matcher, "is a Cluster") {
Cluster config;
if (!::testing::ExplainMatchResult(true, arg.UnpackTo(&config),
result_listener)) {
return false;
}
return ::testing::ExplainMatchResult(matcher, config, result_listener);
}
MATCHER_P(UnpackClusterLoadAssignment, matcher, "is a ClusterLoadAssignment") {
ClusterLoadAssignment config;
if (!::testing::ExplainMatchResult(true, arg.UnpackTo(&config),
result_listener)) {
return false;
}
return ::testing::ExplainMatchResult(matcher, config, result_listener);
}
MATCHER_P5(EqDynamicListener, name, version_info, client_status,
api_listener_matcher, error_state, "equals DynamicListener") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(false, arg.has_warming_state(),
result_listener);
ok &= ::testing::ExplainMatchResult(false, arg.has_draining_state(),
result_listener);
ok &= ::testing::ExplainMatchResult(name, arg.name(), result_listener);
ok &= ::testing::ExplainMatchResult(client_status, arg.client_status(),
result_listener);
if (client_status == ClientResourceStatus::ACKED ||
client_status == ClientResourceStatus::NACKED) {
ok &= ::testing::ExplainMatchResult(
EqDynamicListenerState(version_info, UnpackListener(EqListener(
name, api_listener_matcher))),
arg.active_state(), result_listener);
}
ok &= ::testing::ExplainMatchResult(error_state, arg.error_state(),
result_listener);
return ok;
}
MATCHER_P5(EqDynamicRouteConfig, name, version_info, client_status,
cluster_name, error_state, "equals DynamicRouteConfig") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(version_info, arg.version_info(),
result_listener);
if (client_status == ClientResourceStatus::REQUESTED ||
client_status == ClientResourceStatus::DOES_NOT_EXIST) {
ok &= ::testing::ExplainMatchResult(
UnpackRouteConfiguration(EqRouteConfigurationName(name)),
arg.route_config(), result_listener);
} else {
ok &= ::testing::ExplainMatchResult(
UnpackRouteConfiguration(EqRouteConfiguration(name, cluster_name)),
arg.route_config(), result_listener);
}
ok &= ::testing::ExplainMatchResult(error_state, arg.error_state(),
result_listener);
ok &= ::testing::ExplainMatchResult(client_status, arg.client_status(),
result_listener);
return ok;
}
MATCHER_P4(EqDynamicCluster, name, version_info, client_status, error_state,
"equals DynamicCluster") {
bool ok = true;
ok &= ::testing::ExplainMatchResult(UnpackCluster(EqCluster(name)),
arg.cluster(), result_listener);
ok &= ::testing::ExplainMatchResult(version_info, arg.version_info(),
result_listener);
ok &= ::testing::ExplainMatchResult(client_status, arg.client_status(),
result_listener);
ok &= ::testing::ExplainMatchResult(error_state, arg.error_state(),
result_listener);
return ok;
}
MATCHER_P6(EqDynamicEndpointConfig, name, version_info, client_status, port,
weight, error_state, "equals DynamicEndpointConfig") {
bool ok = true;
if (client_status == ClientResourceStatus::REQUESTED ||
client_status == ClientResourceStatus::DOES_NOT_EXIST) {
ok &= ::testing::ExplainMatchResult(
UnpackClusterLoadAssignment(EqClusterLoadAssignmentName(name)),
arg.endpoint_config(), result_listener);
} else {
ok &= ::testing::ExplainMatchResult(
UnpackClusterLoadAssignment(
EqClusterLoadAssignment(name, port, weight)),
arg.endpoint_config(), result_listener);
}
ok &= ::testing::ExplainMatchResult(version_info, arg.version_info(),
result_listener);
ok &= ::testing::ExplainMatchResult(client_status, arg.client_status(),
result_listener);
ok &= ::testing::ExplainMatchResult(error_state, arg.error_state(),
result_listener);
return ok;
}
MATCHER(IsRdsEnabledHCM, "is a RDS enabled HttpConnectionManager") {
return ::testing::ExplainMatchResult(
UnpackHttpConnectionManager(
::testing::Property(&HttpConnectionManager::has_rds, true)),
arg, result_listener);
}
MATCHER_P2(EqNoRdsHCM, route_configuration_name, cluster_name,
"equals RDS disabled HttpConnectionManager") {
return ::testing::ExplainMatchResult(
UnpackHttpConnectionManager(EqHttpConnectionManagerNotRds(
EqRouteConfiguration(route_configuration_name, cluster_name))),
arg, result_listener);
}
TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpVanilla) {
const size_t kNumRpcs = 5;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {backends_[0]->port()}},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Send several RPCs to ensure the xDS setup works
CheckRpcSendOk(kNumRpcs);
// Fetches the client config
auto csds_response = FetchCsdsResponse();
gpr_log(GPR_INFO, "xDS config dump: %s", csds_response.DebugString().c_str());
EXPECT_EQ(1, csds_response.config_size());
const auto& client_config = csds_response.config(0);
// Validate the Node information
EXPECT_THAT(client_config.node(),
EqNode("xds_end2end_test", ::testing::HasSubstr("C-core"),
::testing::HasSubstr(grpc_version_string()),
::testing::ElementsAre(
"envoy.lb.does_not_support_overprovisioning")));
// Prepare matches for RDS on or off
::testing::Matcher<google::protobuf::Any> api_listener_matcher;
::testing::Matcher<envoy::admin::v3::RoutesConfigDump>
route_config_dump_matcher;
if (GetParam().enable_rds_testing()) {
api_listener_matcher = IsRdsEnabledHCM();
route_config_dump_matcher =
EqRoutesConfigDump(::testing::ElementsAre(EqDynamicRouteConfig(
kDefaultRouteConfigurationName, "1", ClientResourceStatus::ACKED,
kDefaultClusterName, ::testing::_)));
} else {
api_listener_matcher =
EqNoRdsHCM(kDefaultRouteConfigurationName, kDefaultClusterName);
route_config_dump_matcher = EqRoutesConfigDump(::testing::ElementsAre());
}
// Validate the dumped xDS configs
EXPECT_THAT(
client_config.xds_config(),
::testing::UnorderedElementsAre(
::testing::Property(
&envoy::service::status::v3::PerXdsConfig::listener_config,
EqListenersConfigDump(
"1", ::testing::ElementsAre(EqDynamicListener(
kServerName, "1", ClientResourceStatus::ACKED,
api_listener_matcher, ::testing::_)))),
::testing::Property(
&envoy::service::status::v3::PerXdsConfig::route_config,
route_config_dump_matcher),
::testing::Property(
&envoy::service::status::v3::PerXdsConfig::cluster_config,
EqClustersConfigDump(
"1", ::testing::ElementsAre(EqDynamicCluster(
kDefaultClusterName, "1",
ClientResourceStatus::ACKED, ::testing::_)))),
::testing::Property(
&envoy::service::status::v3::PerXdsConfig::endpoint_config,
EqEndpointsConfigDump(
::testing::ElementsAre(EqDynamicEndpointConfig(
kDefaultEdsServiceName, "1", ClientResourceStatus::ACKED,
backends_[0]->port(), kDefaultLocalityWeight,
::testing::_))))));
}
TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpEmpty) {
// The CSDS service should not fail if XdsClient is not initialized or there
// is no working xDS configs.
FetchCsdsResponse();
}
TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpListenerError) {
int kFetchConfigRetries = 3;
int kFetchIntervalMilliseconds = 200;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {backends_[0]->port()}},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Ensure the xDS resolver has working configs.
CheckRpcSendOk();
// Bad Listener should be rejected.
Listener listener;
listener.set_name(kServerName);
balancers_[0]->ads_service()->SetLdsResource(listener);
// The old xDS configs should still be effective.
CheckRpcSendOk();
::testing::Matcher<google::protobuf::Any> api_listener_matcher;
if (GetParam().enable_rds_testing()) {
api_listener_matcher = IsRdsEnabledHCM();
} else {
api_listener_matcher =
EqNoRdsHCM(kDefaultRouteConfigurationName, kDefaultClusterName);
}
for (int o = 0; o < kFetchConfigRetries; o++) {
auto csds_response = FetchCsdsResponse();
// Check if error state is propagated
bool ok = ::testing::Value(
csds_response.config(0).xds_config(),
::testing::Contains(::testing::Property(
&envoy::service::status::v3::PerXdsConfig::listener_config,
EqListenersConfigDump(
"1",
::testing::ElementsAre(EqDynamicListener(
kServerName, "1", ClientResourceStatus::NACKED,
api_listener_matcher,
EqUpdateFailureState(
::testing::HasSubstr(
"Listener has neither address nor ApiListener"),
"2")))))));
if (ok) return; // TEST PASSED!
gpr_sleep_until(
grpc_timeout_milliseconds_to_deadline(kFetchIntervalMilliseconds));
}
FAIL() << "error_state not seen in CSDS responses";
}
TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpRouteError) {
int kFetchConfigRetries = 3;
int kFetchIntervalMilliseconds = 200;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {backends_[0]->port()}},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Ensure the xDS resolver has working configs.
CheckRpcSendOk();
// Bad route config will be rejected.
RouteConfiguration route_config;
route_config.set_name(kDefaultRouteConfigurationName);
route_config.add_virtual_hosts();
SetRouteConfiguration(0, route_config);
// The old xDS configs should still be effective.
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendOk();
for (int o = 0; o < kFetchConfigRetries; o++) {
auto csds_response = FetchCsdsResponse();
bool ok = false;
if (GetParam().enable_rds_testing()) {
ok = ::testing::Value(
csds_response.config(0).xds_config(),
::testing::Contains(::testing::Property(
&envoy::service::status::v3::PerXdsConfig::route_config,
EqRoutesConfigDump(::testing::ElementsAre(EqDynamicRouteConfig(
kDefaultRouteConfigurationName, "1",
ClientResourceStatus::NACKED, kDefaultClusterName,
EqUpdateFailureState(
::testing::HasSubstr("VirtualHost has no domains"),
"2")))))));
} else {
ok = ::testing::Value(
csds_response.config(0).xds_config(),
::testing::Contains(::testing::Property(
&envoy::service::status::v3::PerXdsConfig::listener_config,
EqListenersConfigDump(
"1",
::testing::ElementsAre(EqDynamicListener(
kServerName, "1", ClientResourceStatus::NACKED,
EqNoRdsHCM(kDefaultRouteConfigurationName,
kDefaultClusterName),
EqUpdateFailureState(
::testing::HasSubstr("VirtualHost has no domains"),
"2")))))));
}
if (ok) return; // TEST PASSED!
gpr_sleep_until(
grpc_timeout_milliseconds_to_deadline(kFetchIntervalMilliseconds));
}
FAIL() << "error_state not seen in CSDS responses";
}
TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpClusterError) {
int kFetchConfigRetries = 3;
int kFetchIntervalMilliseconds = 200;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {backends_[0]->port()}},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Ensure the xDS resolver has working configs.
CheckRpcSendOk();
// Listener without any route, will be rejected.
Cluster cluster;
cluster.set_name(kDefaultClusterName);
balancers_[0]->ads_service()->SetCdsResource(cluster);
// The old xDS configs should still be effective.
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendOk();
for (int o = 0; o < kFetchConfigRetries; o++) {
auto csds_response = FetchCsdsResponse();
// Check if error state is propagated
bool ok = ::testing::Value(
csds_response.config(0).xds_config(),
::testing::Contains(::testing::Property(
&envoy::service::status::v3::PerXdsConfig::cluster_config,
EqClustersConfigDump(
"1", ::testing::ElementsAre(EqDynamicCluster(
kDefaultClusterName, "1", ClientResourceStatus::NACKED,
EqUpdateFailureState(
::testing::HasSubstr("DiscoveryType not found"),
"2")))))));
if (ok) return; // TEST PASSED!
gpr_sleep_until(
grpc_timeout_milliseconds_to_deadline(kFetchIntervalMilliseconds));
}
FAIL() << "error_state not seen in CSDS responses";
}
TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpEndpointError) {
int kFetchConfigRetries = 3;
int kFetchIntervalMilliseconds = 200;
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
AdsServiceImpl::EdsResourceArgs args({
{"locality0", {backends_[0]->port()}},
});
balancers_[0]->ads_service()->SetEdsResource(
BuildEdsResource(args, DefaultEdsServiceName()));
// Ensure the xDS resolver has working configs.
CheckRpcSendOk();
// Bad endpoint config will be rejected.
ClusterLoadAssignment cluster_load_assignment;
cluster_load_assignment.set_cluster_name(kDefaultEdsServiceName);
auto* endpoints = cluster_load_assignment.add_endpoints();
endpoints->mutable_load_balancing_weight()->set_value(1);
auto* endpoint = endpoints->add_lb_endpoints()->mutable_endpoint();
endpoint->mutable_address()->mutable_socket_address()->set_port_value(1 << 1);
balancers_[0]->ads_service()->SetEdsResource(cluster_load_assignment);
// The old xDS configs should still be effective.
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
CheckRpcSendOk();
for (int o = 0; o < kFetchConfigRetries; o++) {
auto csds_response = FetchCsdsResponse();
// Check if error state is propagated
bool ok = ::testing::Value(
csds_response.config(0).xds_config(),
::testing::Contains(::testing::Property(
&envoy::service::status::v3::PerXdsConfig::endpoint_config,
EqEndpointsConfigDump(
::testing::ElementsAre(EqDynamicEndpointConfig(
kDefaultEdsServiceName, "1", ClientResourceStatus::NACKED,
backends_[0]->port(), kDefaultLocalityWeight,
EqUpdateFailureState(::testing::HasSubstr("Empty locality"),
"2")))))));
if (ok) return; // TEST PASSED!
gpr_sleep_until(
grpc_timeout_milliseconds_to_deadline(kFetchIntervalMilliseconds));
}
FAIL() << "error_state not seen in CSDS responses";
}
TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpListenerRequested) {
int kTimeoutMillisecond = 1000;
balancers_[0]->ads_service()->UnsetResource(kLdsTypeUrl, kServerName);
CheckRpcSendFailure(1, RpcOptions().set_timeout_ms(kTimeoutMillisecond),
grpc::DEADLINE_EXCEEDED);
auto csds_response = FetchCsdsResponse();
EXPECT_THAT(csds_response.config(0).xds_config(),
::testing::Contains(::testing::Property(
&envoy::service::status::v3::PerXdsConfig::listener_config,
EqListenersConfigDump(
::testing::_, ::testing::ElementsAre(EqDynamicListener(
kServerName, ::testing::_,
ClientResourceStatus::REQUESTED,
::testing::_, ::testing::_))))));
}
TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpClusterRequested) {
int kTimeoutMillisecond = 1000;
std::string kClusterName1 = "cluster-1";
std::string kClusterName2 = "cluster-2";
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
// Create a route config requesting two non-existing clusters
RouteConfiguration route_config;
route_config.set_name(kDefaultRouteConfigurationName);
auto* vh = route_config.add_virtual_hosts();
// The VirtualHost must match the domain name, otherwise will cause resolver
// transient failure.
vh->add_domains("*");
auto* routes1 = vh->add_routes();
routes1->mutable_match()->set_prefix("");
routes1->mutable_route()->set_cluster(kClusterName1);
auto* routes2 = vh->add_routes();
routes2->mutable_match()->set_prefix("");
routes2->mutable_route()->set_cluster(kClusterName2);
SetRouteConfiguration(0, route_config);
// Try to get the configs plumb through
CheckRpcSendFailure(1, RpcOptions().set_timeout_ms(kTimeoutMillisecond),
grpc::DEADLINE_EXCEEDED);
auto csds_response = FetchCsdsResponse();
EXPECT_THAT(csds_response.config(0).xds_config(),
::testing::Contains(::testing::Property(
&envoy::service::status::v3::PerXdsConfig::cluster_config,
EqClustersConfigDump(
::testing::_,
::testing::UnorderedElementsAre(
EqDynamicCluster(kClusterName1, ::testing::_,
ClientResourceStatus::REQUESTED,
::testing::_),
EqDynamicCluster(kClusterName2, ::testing::_,
ClientResourceStatus::REQUESTED,
::testing::_))))));
}
class CsdsShortAdsTimeoutTest : public ClientStatusDiscoveryServiceTest {
void SetUp() override {
// Shorten the ADS subscription timeout to speed up the test run.
xds_resource_does_not_exist_timeout_ms_ = 500;
ClientStatusDiscoveryServiceTest::SetUp();
}
};
TEST_P(CsdsShortAdsTimeoutTest, XdsConfigDumpListenerDoesNotExist) {
int kTimeoutMillisecond = 1000000; // 1000s wait for the transient failure.
balancers_[0]->ads_service()->UnsetResource(kLdsTypeUrl, kServerName);
CheckRpcSendFailure(1, RpcOptions().set_timeout_ms(kTimeoutMillisecond),
grpc::UNAVAILABLE);
auto csds_response = FetchCsdsResponse();
EXPECT_THAT(csds_response.config(0).xds_config(),
::testing::Contains(::testing::Property(
&envoy::service::status::v3::PerXdsConfig::listener_config,
EqListenersConfigDump(
::testing::_, ::testing::ElementsAre(EqDynamicListener(
kServerName, ::testing::_,
ClientResourceStatus::DOES_NOT_EXIST,
::testing::_, ::testing::_))))));
}
TEST_P(CsdsShortAdsTimeoutTest, XdsConfigDumpRouteConfigDoesNotExist) {
if (!GetParam().enable_rds_testing()) return;
int kTimeoutMillisecond = 1000000; // 1000s wait for the transient failure.
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
balancers_[0]->ads_service()->UnsetResource(kRdsTypeUrl,
kDefaultRouteConfigurationName);
CheckRpcSendFailure(1, RpcOptions().set_timeout_ms(kTimeoutMillisecond),
grpc::UNAVAILABLE);
auto csds_response = FetchCsdsResponse();
EXPECT_THAT(
csds_response.config(0).xds_config(),
::testing::Contains(::testing::Property(
&envoy::service::status::v3::PerXdsConfig::route_config,
EqRoutesConfigDump(::testing::ElementsAre(
EqDynamicRouteConfig(kDefaultRouteConfigurationName, ::testing::_,
ClientResourceStatus::DOES_NOT_EXIST,
::testing::_, ::testing::_))))));
}
TEST_P(CsdsShortAdsTimeoutTest, XdsConfigDumpClusterDoesNotExist) {
int kTimeoutMillisecond = 1000000; // 1000s wait for the transient failure.
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
balancers_[0]->ads_service()->UnsetResource(kCdsTypeUrl, kDefaultClusterName);
CheckRpcSendFailure(1, RpcOptions().set_timeout_ms(kTimeoutMillisecond),
grpc::UNAVAILABLE);
auto csds_response = FetchCsdsResponse();
EXPECT_THAT(csds_response.config(0).xds_config(),
::testing::Contains(::testing::Property(
&envoy::service::status::v3::PerXdsConfig::cluster_config,
EqClustersConfigDump(::testing::_,
::testing::ElementsAre(EqDynamicCluster(
kDefaultClusterName, ::testing::_,
ClientResourceStatus::DOES_NOT_EXIST,
::testing::_))))));
}
TEST_P(CsdsShortAdsTimeoutTest, XdsConfigDumpEndpointDoesNotExist) {
int kTimeoutMillisecond = 1000000; // 1000s wait for the transient failure.
SetNextResolution({});
SetNextResolutionForLbChannelAllBalancers();
balancers_[0]->ads_service()->UnsetResource(kEdsTypeUrl,
kDefaultEdsServiceName);
CheckRpcSendFailure(1, RpcOptions().set_timeout_ms(kTimeoutMillisecond),
grpc::UNAVAILABLE);
auto csds_response = FetchCsdsResponse();
EXPECT_THAT(
csds_response.config(0).xds_config(),
::testing::Contains(::testing::Property(
&envoy::service::status::v3::PerXdsConfig::endpoint_config,
EqEndpointsConfigDump(::testing::ElementsAre(EqDynamicEndpointConfig(
kDefaultEdsServiceName, ::testing::_,
ClientResourceStatus::DOES_NOT_EXIST, ::testing::_, ::testing::_,
::testing::_))))));
}
#endif // DISABLED_XDS_PROTO_IN_CC
std::string TestTypeName(const ::testing::TestParamInfo<TestType>& info) {
return info.param.AsString();
}
// Run with all combinations of xds/fake resolver and enabling load reporting.
INSTANTIATE_TEST_SUITE_P(
XdsTest, BasicTest,
::testing::Values(
TestType(), TestType().set_enable_load_reporting(),
TestType().set_use_fake_resolver(),
TestType().set_use_fake_resolver().set_enable_load_reporting()),
&TestTypeName);
// Run with both fake resolver and xds resolver.
// Don't run with load reporting or v2 or RDS, since they are irrelevant to
// the tests.
INSTANTIATE_TEST_SUITE_P(XdsTest, SecureNamingTest,
::testing::Values(TestType(),
TestType().set_use_fake_resolver()),
&TestTypeName);
// LDS depends on XdsResolver.
INSTANTIATE_TEST_SUITE_P(XdsTest, LdsTest, ::testing::Values(TestType()),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(XdsTest, LdsV2Test,
::testing::Values(TestType().set_use_v2()),
&TestTypeName);
// LDS/RDS commmon tests depend on XdsResolver.
INSTANTIATE_TEST_SUITE_P(
XdsTest, LdsRdsTest,
::testing::Values(TestType(), TestType().set_enable_rds_testing(),
// Also test with xDS v2.
TestType().set_enable_rds_testing().set_use_v2()),
&TestTypeName);
// CDS depends on XdsResolver.
INSTANTIATE_TEST_SUITE_P(
XdsTest, CdsTest,
::testing::Values(TestType(), TestType().set_enable_load_reporting()),
&TestTypeName);
// CDS depends on XdsResolver.
// Security depends on v3.
// Not enabling load reporting or RDS, since those are irrelevant to these
// tests.
INSTANTIATE_TEST_SUITE_P(
XdsTest, XdsSecurityTest,
::testing::Values(TestType().set_use_xds_credentials()), &TestTypeName);
// We are only testing the server here.
INSTANTIATE_TEST_SUITE_P(XdsTest, XdsEnabledServerTest,
::testing::Values(TestType()), &TestTypeName);
// We are only testing the server here.
INSTANTIATE_TEST_SUITE_P(XdsTest, XdsServerSecurityTest,
::testing::Values(TestType()
.set_use_fake_resolver()
.set_use_xds_credentials()),
&TestTypeName);
// We are only testing the server here.
INSTANTIATE_TEST_SUITE_P(XdsTest, XdsEnabledServerStatusNotificationTest,
::testing::Values(TestType()
.set_use_fake_resolver()
.set_use_xds_credentials()),
&TestTypeName);
// We are only testing the server here.
INSTANTIATE_TEST_SUITE_P(XdsTest, XdsServerFilterChainMatchTest,
::testing::Values(TestType()
.set_use_fake_resolver()
.set_use_xds_credentials()),
&TestTypeName);
// EDS could be tested with or without XdsResolver, but the tests would
// be the same either way, so we test it only with XdsResolver.
INSTANTIATE_TEST_SUITE_P(
XdsTest, EdsTest,
::testing::Values(TestType(), TestType().set_enable_load_reporting()),
&TestTypeName);
// Test initial resource timeouts for each resource type.
// Do this only for XdsResolver with RDS enabled, so that we can test
// all resource types.
// Run with V3 only, since the functionality is no different in V2.
INSTANTIATE_TEST_SUITE_P(XdsTest, TimeoutTest,
::testing::Values(TestType().set_enable_rds_testing()),
&TestTypeName);
// XdsResolverOnlyTest depends on XdsResolver.
INSTANTIATE_TEST_SUITE_P(
XdsTest, XdsResolverOnlyTest,
::testing::Values(TestType(), TestType().set_enable_load_reporting()),
&TestTypeName);
// XdsResolverLoadReprtingOnlyTest depends on XdsResolver and load reporting.
INSTANTIATE_TEST_SUITE_P(
XdsTest, XdsResolverLoadReportingOnlyTest,
::testing::Values(TestType().set_enable_load_reporting()), &TestTypeName);
INSTANTIATE_TEST_SUITE_P(
XdsTest, LocalityMapTest,
::testing::Values(
TestType(), TestType().set_enable_load_reporting(),
TestType().set_use_fake_resolver(),
TestType().set_use_fake_resolver().set_enable_load_reporting()),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(
XdsTest, FailoverTest,
::testing::Values(
TestType(), TestType().set_enable_load_reporting(),
TestType().set_use_fake_resolver(),
TestType().set_use_fake_resolver().set_enable_load_reporting()),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(
XdsTest, DropTest,
::testing::Values(
TestType(), TestType().set_enable_load_reporting(),
TestType().set_use_fake_resolver(),
TestType().set_use_fake_resolver().set_enable_load_reporting()),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(
XdsTest, BalancerUpdateTest,
::testing::Values(
TestType().set_use_fake_resolver(),
TestType().set_use_fake_resolver().set_enable_load_reporting(),
TestType().set_enable_load_reporting()),
&TestTypeName);
// Load reporting tests are not run with load reporting disabled.
INSTANTIATE_TEST_SUITE_P(
XdsTest, ClientLoadReportingTest,
::testing::Values(
TestType().set_enable_load_reporting(),
TestType().set_enable_load_reporting().set_use_fake_resolver()),
&TestTypeName);
// Load reporting tests are not run with load reporting disabled.
INSTANTIATE_TEST_SUITE_P(
XdsTest, ClientLoadReportingWithDropTest,
::testing::Values(
TestType().set_enable_load_reporting(),
TestType().set_enable_load_reporting().set_use_fake_resolver()),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(
XdsTest, FaultInjectionTest,
::testing::Values(
TestType(), TestType().set_enable_rds_testing(),
TestType().set_filter_config_setup(
TestType::FilterConfigSetup::kRouteOverride),
TestType().set_enable_rds_testing().set_filter_config_setup(
TestType::FilterConfigSetup::kRouteOverride)),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(XdsTest, BootstrapContentsFromEnvVarTest,
::testing::Values(TestType()), &TestTypeName);
#ifndef DISABLED_XDS_PROTO_IN_CC
// Run CSDS tests with RDS enabled and disabled.
INSTANTIATE_TEST_SUITE_P(
XdsTest, ClientStatusDiscoveryServiceTest,
::testing::Values(
TestType(), TestType().set_enable_rds_testing(),
TestType().set_use_csds_streaming(),
TestType().set_enable_rds_testing().set_use_csds_streaming()),
&TestTypeName);
INSTANTIATE_TEST_SUITE_P(
XdsTest, CsdsShortAdsTimeoutTest,
::testing::Values(
TestType(), TestType().set_enable_rds_testing(),
TestType().set_use_csds_streaming(),
TestType().set_enable_rds_testing().set_use_csds_streaming()),
&TestTypeName);
#endif // DISABLED_XDS_PROTO_IN_CC
} // namespace
} // namespace testing
} // namespace grpc
int main(int argc, char** argv) {
grpc::testing::TestEnvironment env(argc, argv);
::testing::InitGoogleTest(&argc, argv);
grpc::testing::WriteBootstrapFiles();
// Make the backup poller poll very frequently in order to pick up
// updates from all the subchannels's FDs.
GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms, 1);
#if TARGET_OS_IPHONE
// Workaround Apple CFStream bug
gpr_setenv("grpc_cfstream", "0");
#endif
grpc_core::CertificateProviderRegistry::RegisterCertificateProviderFactory(
absl::make_unique<grpc::testing::FakeCertificateProviderFactory>(
"fake1", &grpc::testing::g_fake1_cert_data_map));
grpc_core::CertificateProviderRegistry::RegisterCertificateProviderFactory(
absl::make_unique<grpc::testing::FakeCertificateProviderFactory>(
"fake2", &grpc::testing::g_fake2_cert_data_map));
grpc_init();
grpc_core::XdsHttpFilterRegistry::RegisterFilter(
absl::make_unique<grpc::testing::NoOpHttpFilter>(
"grpc.testing.client_only_http_filter", true, false),
{"grpc.testing.client_only_http_filter"});
grpc_core::XdsHttpFilterRegistry::RegisterFilter(
absl::make_unique<grpc::testing::NoOpHttpFilter>(
"grpc.testing.server_only_http_filter", false, true),
{"grpc.testing.server_only_http_filter"});
const auto result = RUN_ALL_TESTS();
grpc_shutdown();
return result;
}
|
// Copyright (c) 2011 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 "base/process_util.h"
#include "chrome/browser/extensions/crashed_extension_infobar.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/confirm_infobar_delegate.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/result_codes.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/renderer_host/render_process_host.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
class ExtensionCrashRecoveryTest : public ExtensionBrowserTest {
protected:
ExtensionService* GetExtensionService() {
return browser()->profile()->GetExtensionService();
}
ExtensionProcessManager* GetExtensionProcessManager() {
return browser()->profile()->GetExtensionProcessManager();
}
ConfirmInfoBarDelegate* GetInfoBarDelegate(size_t index) {
TabContents* current_tab = browser()->GetSelectedTabContents();
EXPECT_LT(index, current_tab->infobar_count());
return current_tab->GetInfoBarDelegateAt(index)->AsConfirmInfoBarDelegate();
}
void AcceptInfoBar(size_t index) {
ConfirmInfoBarDelegate* infobar = GetInfoBarDelegate(index);
ASSERT_TRUE(infobar);
infobar->Accept();
WaitForExtensionLoad();
}
void CancelInfoBar(size_t index) {
ConfirmInfoBarDelegate* infobar = GetInfoBarDelegate(index);
ASSERT_TRUE(infobar);
infobar->Cancel();
}
void CrashExtension(size_t index) {
ASSERT_LT(index, GetExtensionService()->extensions()->size());
const Extension* extension =
GetExtensionService()->extensions()->at(index);
ASSERT_TRUE(extension);
std::string extension_id(extension->id());
ExtensionHost* extension_host =
GetExtensionProcessManager()->GetBackgroundHostForExtension(extension);
ASSERT_TRUE(extension_host);
RenderProcessHost* extension_rph =
extension_host->render_view_host()->process();
base::KillProcess(extension_rph->GetHandle(), ResultCodes::KILLED, false);
ASSERT_TRUE(WaitForExtensionCrash(extension_id));
ASSERT_FALSE(
GetExtensionProcessManager()->GetBackgroundHostForExtension(extension));
}
void CheckExtensionConsistency(size_t index) {
ASSERT_LT(index, GetExtensionService()->extensions()->size());
const Extension* extension =
GetExtensionService()->extensions()->at(index);
ASSERT_TRUE(extension);
ExtensionHost* extension_host =
GetExtensionProcessManager()->GetBackgroundHostForExtension(extension);
ASSERT_TRUE(extension_host);
ASSERT_TRUE(GetExtensionProcessManager()->HasExtensionHost(extension_host));
ASSERT_TRUE(extension_host->IsRenderViewLive());
ASSERT_EQ(extension_host->render_view_host()->process(),
GetExtensionProcessManager()->GetExtensionProcess(extension->id()));
}
void LoadTestExtension() {
ExtensionBrowserTest::SetUpInProcessBrowserTestFixture();
const size_t size_before = GetExtensionService()->extensions()->size();
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
const Extension* extension = GetExtensionService()->extensions()->back();
ASSERT_TRUE(extension);
first_extension_id_ = extension->id();
CheckExtensionConsistency(size_before);
}
void LoadSecondExtension() {
int offset = GetExtensionService()->extensions()->size();
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("install").AppendASCII("install")));
const Extension* extension =
GetExtensionService()->extensions()->at(offset);
ASSERT_TRUE(extension);
second_extension_id_ = extension->id();
CheckExtensionConsistency(offset);
}
std::string first_extension_id_;
std::string second_extension_id_;
};
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest, Basic) {
const size_t size_before = GetExtensionService()->extensions()->size();
const size_t crash_size_before =
GetExtensionService()->terminated_extensions()->size();
LoadTestExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
ASSERT_EQ(crash_size_before + 1,
GetExtensionService()->terminated_extensions()->size());
AcceptInfoBar(0);
SCOPED_TRACE("after clicking the infobar");
CheckExtensionConsistency(size_before);
ASSERT_EQ(crash_size_before,
GetExtensionService()->terminated_extensions()->size());
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest, CloseAndReload) {
const size_t size_before = GetExtensionService()->extensions()->size();
const size_t crash_size_before =
GetExtensionService()->terminated_extensions()->size();
LoadTestExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
ASSERT_EQ(crash_size_before + 1,
GetExtensionService()->terminated_extensions()->size());
CancelInfoBar(0);
ReloadExtension(first_extension_id_);
SCOPED_TRACE("after reloading");
CheckExtensionConsistency(size_before);
ASSERT_EQ(crash_size_before,
GetExtensionService()->terminated_extensions()->size());
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest, ReloadIndependently) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
ReloadExtension(first_extension_id_);
SCOPED_TRACE("after reloading");
CheckExtensionConsistency(size_before);
TabContents* current_tab = browser()->GetSelectedTabContents();
ASSERT_TRUE(current_tab);
// The infobar should automatically hide after the extension is successfully
// reloaded.
ASSERT_EQ(0U, current_tab->infobar_count());
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest,
ReloadIndependentlyChangeTabs) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
TabContents* original_tab = browser()->GetSelectedTabContents();
ASSERT_TRUE(original_tab);
ASSERT_EQ(1U, original_tab->infobar_count());
// Open a new tab so the info bar will not be in the current tab.
browser()->NewTab();
TabContents* new_current_tab = browser()->GetSelectedTabContents();
ASSERT_TRUE(new_current_tab);
ASSERT_NE(new_current_tab, original_tab);
ASSERT_EQ(0U, new_current_tab->infobar_count());
ReloadExtension(first_extension_id_);
SCOPED_TRACE("after reloading");
CheckExtensionConsistency(size_before);
// The infobar should automatically hide after the extension is successfully
// reloaded.
ASSERT_EQ(0U, original_tab->infobar_count());
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest,
ReloadIndependentlyNavigatePage) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
TabContents* current_tab = browser()->GetSelectedTabContents();
ASSERT_TRUE(current_tab);
ASSERT_EQ(1U, current_tab->infobar_count());
// Navigate to another page.
ui_test_utils::NavigateToURL(browser(),
ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),
FilePath(FILE_PATH_LITERAL("title1.html"))));
ASSERT_EQ(1U, current_tab->infobar_count());
ReloadExtension(first_extension_id_);
SCOPED_TRACE("after reloading");
CheckExtensionConsistency(size_before);
// The infobar should automatically hide after the extension is successfully
// reloaded.
ASSERT_EQ(0U, current_tab->infobar_count());
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest,
ReloadIndependentlyTwoInfoBars) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
// Open a new window so that there will be an info bar in each.
Browser* browser2 = CreateBrowser(browser()->profile());
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
TabContents* current_tab = browser()->GetSelectedTabContents();
ASSERT_TRUE(current_tab);
ASSERT_EQ(1U, current_tab->infobar_count());
TabContents* current_tab2 = browser2->GetSelectedTabContents();
ASSERT_TRUE(current_tab2);
ASSERT_EQ(1U, current_tab2->infobar_count());
ReloadExtension(first_extension_id_);
SCOPED_TRACE("after reloading");
CheckExtensionConsistency(size_before);
// Both infobars should automatically hide after the extension is successfully
// reloaded.
ASSERT_EQ(0U, current_tab->infobar_count());
ASSERT_EQ(0U, current_tab2->infobar_count());
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest,
ReloadIndependentlyTwoInfoBarsSameBrowser) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
// Open a new window so that there will be an info bar in each.
Browser* browser2 = CreateBrowser(browser()->profile());
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
TabContents* current_tab = browser()->GetSelectedTabContents();
ASSERT_TRUE(current_tab);
ASSERT_EQ(1U, current_tab->infobar_count());
TabContents* current_tab2 = browser2->GetSelectedTabContents();
ASSERT_TRUE(current_tab2);
ASSERT_EQ(1U, current_tab2->infobar_count());
// Move second window into first browser so there will be multiple tabs
// with the info bar for the same extension in one browser.
TabContentsWrapper* contents =
browser2->tabstrip_model()->DetachTabContentsAt(0);
browser()->tabstrip_model()->AppendTabContents(contents, true);
current_tab2 = browser()->GetSelectedTabContents();
ASSERT_EQ(1U, current_tab2->infobar_count());
ASSERT_NE(current_tab2, current_tab);
ReloadExtension(first_extension_id_);
SCOPED_TRACE("after reloading");
CheckExtensionConsistency(size_before);
// Both infobars should automatically hide after the extension is successfully
// reloaded.
ASSERT_EQ(0U, current_tab2->infobar_count());
browser()->SelectPreviousTab();
ASSERT_EQ(current_tab, browser()->GetSelectedTabContents());
ASSERT_EQ(0U, current_tab->infobar_count());
}
// Make sure that when we don't do anything about the crashed extension
// and close the browser, it doesn't crash. The browser is closed implicitly
// at the end of each browser test.
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest, ShutdownWhileCrashed) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest, TwoExtensionsCrashFirst) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
LoadSecondExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before + 1, GetExtensionService()->extensions()->size());
AcceptInfoBar(0);
SCOPED_TRACE("after clicking the infobar");
CheckExtensionConsistency(size_before);
CheckExtensionConsistency(size_before + 1);
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest, TwoExtensionsCrashSecond) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
LoadSecondExtension();
CrashExtension(size_before + 1);
ASSERT_EQ(size_before + 1, GetExtensionService()->extensions()->size());
AcceptInfoBar(0);
SCOPED_TRACE("after clicking the infobar");
CheckExtensionConsistency(size_before);
CheckExtensionConsistency(size_before + 1);
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest,
TwoExtensionsCrashBothAtOnce) {
const size_t size_before = GetExtensionService()->extensions()->size();
const size_t crash_size_before =
GetExtensionService()->terminated_extensions()->size();
LoadTestExtension();
LoadSecondExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before + 1, GetExtensionService()->extensions()->size());
ASSERT_EQ(crash_size_before + 1,
GetExtensionService()->terminated_extensions()->size());
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
ASSERT_EQ(crash_size_before + 2,
GetExtensionService()->terminated_extensions()->size());
{
SCOPED_TRACE("first infobar");
AcceptInfoBar(0);
CheckExtensionConsistency(size_before);
}
{
SCOPED_TRACE("second infobar");
AcceptInfoBar(0);
CheckExtensionConsistency(size_before);
CheckExtensionConsistency(size_before + 1);
}
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest, TwoExtensionsOneByOne) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
LoadSecondExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
{
SCOPED_TRACE("first infobar");
AcceptInfoBar(0);
CheckExtensionConsistency(size_before);
}
{
SCOPED_TRACE("second infobar");
AcceptInfoBar(0);
CheckExtensionConsistency(size_before);
CheckExtensionConsistency(size_before + 1);
}
}
// Make sure that when we don't do anything about the crashed extensions
// and close the browser, it doesn't crash. The browser is closed implicitly
// at the end of each browser test.
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest,
TwoExtensionsShutdownWhileCrashed) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
LoadSecondExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest,
TwoExtensionsIgnoreFirst) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
LoadSecondExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before + 1, GetExtensionService()->extensions()->size());
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
CancelInfoBar(0);
AcceptInfoBar(1);
SCOPED_TRACE("infobars done");
ASSERT_EQ(size_before + 1, GetExtensionService()->extensions()->size());
CheckExtensionConsistency(size_before);
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest,
TwoExtensionsReloadIndependently) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
LoadSecondExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before + 1, GetExtensionService()->extensions()->size());
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
{
SCOPED_TRACE("first: reload");
TabContents* current_tab = browser()->GetSelectedTabContents();
ASSERT_TRUE(current_tab);
// At the beginning we should have one infobar displayed for each extension.
ASSERT_EQ(2U, current_tab->infobar_count());
ReloadExtension(first_extension_id_);
// One of the infobars should hide after the extension is reloaded.
ASSERT_EQ(1U, current_tab->infobar_count());
CheckExtensionConsistency(size_before);
}
{
SCOPED_TRACE("second: infobar");
AcceptInfoBar(0);
CheckExtensionConsistency(size_before);
CheckExtensionConsistency(size_before + 1);
}
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest, CrashAndUninstall) {
const size_t size_before = GetExtensionService()->extensions()->size();
const size_t crash_size_before =
GetExtensionService()->terminated_extensions()->size();
LoadTestExtension();
LoadSecondExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before + 1, GetExtensionService()->extensions()->size());
ASSERT_EQ(crash_size_before + 1,
GetExtensionService()->terminated_extensions()->size());
UninstallExtension(first_extension_id_);
SCOPED_TRACE("after uninstalling");
ASSERT_EQ(size_before + 1, GetExtensionService()->extensions()->size());
ASSERT_EQ(crash_size_before,
GetExtensionService()->terminated_extensions()->size());
ASSERT_EQ(0U, browser()->GetSelectedTabContents()->infobar_count());
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest, CrashAndUnloadAll) {
const size_t size_before = GetExtensionService()->extensions()->size();
const size_t crash_size_before =
GetExtensionService()->terminated_extensions()->size();
LoadTestExtension();
LoadSecondExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before + 1, GetExtensionService()->extensions()->size());
ASSERT_EQ(crash_size_before + 1,
GetExtensionService()->terminated_extensions()->size());
GetExtensionService()->UnloadAllExtensions();
ASSERT_EQ(crash_size_before,
GetExtensionService()->terminated_extensions()->size());
}
Mark ExtensionCrashRecoveryTest.TwoExtensionsReloadIndependently as FLAKY.
TBR=phajdan.jr@chromium.org
BUG=75134
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@77131 0039d316-1c4b-4281-b951-d872f2087c98
// Copyright (c) 2011 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 "base/process_util.h"
#include "chrome/browser/extensions/crashed_extension_infobar.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/confirm_infobar_delegate.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/result_codes.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/renderer_host/render_process_host.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
class ExtensionCrashRecoveryTest : public ExtensionBrowserTest {
protected:
ExtensionService* GetExtensionService() {
return browser()->profile()->GetExtensionService();
}
ExtensionProcessManager* GetExtensionProcessManager() {
return browser()->profile()->GetExtensionProcessManager();
}
ConfirmInfoBarDelegate* GetInfoBarDelegate(size_t index) {
TabContents* current_tab = browser()->GetSelectedTabContents();
EXPECT_LT(index, current_tab->infobar_count());
return current_tab->GetInfoBarDelegateAt(index)->AsConfirmInfoBarDelegate();
}
void AcceptInfoBar(size_t index) {
ConfirmInfoBarDelegate* infobar = GetInfoBarDelegate(index);
ASSERT_TRUE(infobar);
infobar->Accept();
WaitForExtensionLoad();
}
void CancelInfoBar(size_t index) {
ConfirmInfoBarDelegate* infobar = GetInfoBarDelegate(index);
ASSERT_TRUE(infobar);
infobar->Cancel();
}
void CrashExtension(size_t index) {
ASSERT_LT(index, GetExtensionService()->extensions()->size());
const Extension* extension =
GetExtensionService()->extensions()->at(index);
ASSERT_TRUE(extension);
std::string extension_id(extension->id());
ExtensionHost* extension_host =
GetExtensionProcessManager()->GetBackgroundHostForExtension(extension);
ASSERT_TRUE(extension_host);
RenderProcessHost* extension_rph =
extension_host->render_view_host()->process();
base::KillProcess(extension_rph->GetHandle(), ResultCodes::KILLED, false);
ASSERT_TRUE(WaitForExtensionCrash(extension_id));
ASSERT_FALSE(
GetExtensionProcessManager()->GetBackgroundHostForExtension(extension));
}
void CheckExtensionConsistency(size_t index) {
ASSERT_LT(index, GetExtensionService()->extensions()->size());
const Extension* extension =
GetExtensionService()->extensions()->at(index);
ASSERT_TRUE(extension);
ExtensionHost* extension_host =
GetExtensionProcessManager()->GetBackgroundHostForExtension(extension);
ASSERT_TRUE(extension_host);
ASSERT_TRUE(GetExtensionProcessManager()->HasExtensionHost(extension_host));
ASSERT_TRUE(extension_host->IsRenderViewLive());
ASSERT_EQ(extension_host->render_view_host()->process(),
GetExtensionProcessManager()->GetExtensionProcess(extension->id()));
}
void LoadTestExtension() {
ExtensionBrowserTest::SetUpInProcessBrowserTestFixture();
const size_t size_before = GetExtensionService()->extensions()->size();
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
const Extension* extension = GetExtensionService()->extensions()->back();
ASSERT_TRUE(extension);
first_extension_id_ = extension->id();
CheckExtensionConsistency(size_before);
}
void LoadSecondExtension() {
int offset = GetExtensionService()->extensions()->size();
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("install").AppendASCII("install")));
const Extension* extension =
GetExtensionService()->extensions()->at(offset);
ASSERT_TRUE(extension);
second_extension_id_ = extension->id();
CheckExtensionConsistency(offset);
}
std::string first_extension_id_;
std::string second_extension_id_;
};
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest, Basic) {
const size_t size_before = GetExtensionService()->extensions()->size();
const size_t crash_size_before =
GetExtensionService()->terminated_extensions()->size();
LoadTestExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
ASSERT_EQ(crash_size_before + 1,
GetExtensionService()->terminated_extensions()->size());
AcceptInfoBar(0);
SCOPED_TRACE("after clicking the infobar");
CheckExtensionConsistency(size_before);
ASSERT_EQ(crash_size_before,
GetExtensionService()->terminated_extensions()->size());
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest, CloseAndReload) {
const size_t size_before = GetExtensionService()->extensions()->size();
const size_t crash_size_before =
GetExtensionService()->terminated_extensions()->size();
LoadTestExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
ASSERT_EQ(crash_size_before + 1,
GetExtensionService()->terminated_extensions()->size());
CancelInfoBar(0);
ReloadExtension(first_extension_id_);
SCOPED_TRACE("after reloading");
CheckExtensionConsistency(size_before);
ASSERT_EQ(crash_size_before,
GetExtensionService()->terminated_extensions()->size());
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest, ReloadIndependently) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
ReloadExtension(first_extension_id_);
SCOPED_TRACE("after reloading");
CheckExtensionConsistency(size_before);
TabContents* current_tab = browser()->GetSelectedTabContents();
ASSERT_TRUE(current_tab);
// The infobar should automatically hide after the extension is successfully
// reloaded.
ASSERT_EQ(0U, current_tab->infobar_count());
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest,
ReloadIndependentlyChangeTabs) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
TabContents* original_tab = browser()->GetSelectedTabContents();
ASSERT_TRUE(original_tab);
ASSERT_EQ(1U, original_tab->infobar_count());
// Open a new tab so the info bar will not be in the current tab.
browser()->NewTab();
TabContents* new_current_tab = browser()->GetSelectedTabContents();
ASSERT_TRUE(new_current_tab);
ASSERT_NE(new_current_tab, original_tab);
ASSERT_EQ(0U, new_current_tab->infobar_count());
ReloadExtension(first_extension_id_);
SCOPED_TRACE("after reloading");
CheckExtensionConsistency(size_before);
// The infobar should automatically hide after the extension is successfully
// reloaded.
ASSERT_EQ(0U, original_tab->infobar_count());
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest,
ReloadIndependentlyNavigatePage) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
TabContents* current_tab = browser()->GetSelectedTabContents();
ASSERT_TRUE(current_tab);
ASSERT_EQ(1U, current_tab->infobar_count());
// Navigate to another page.
ui_test_utils::NavigateToURL(browser(),
ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),
FilePath(FILE_PATH_LITERAL("title1.html"))));
ASSERT_EQ(1U, current_tab->infobar_count());
ReloadExtension(first_extension_id_);
SCOPED_TRACE("after reloading");
CheckExtensionConsistency(size_before);
// The infobar should automatically hide after the extension is successfully
// reloaded.
ASSERT_EQ(0U, current_tab->infobar_count());
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest,
ReloadIndependentlyTwoInfoBars) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
// Open a new window so that there will be an info bar in each.
Browser* browser2 = CreateBrowser(browser()->profile());
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
TabContents* current_tab = browser()->GetSelectedTabContents();
ASSERT_TRUE(current_tab);
ASSERT_EQ(1U, current_tab->infobar_count());
TabContents* current_tab2 = browser2->GetSelectedTabContents();
ASSERT_TRUE(current_tab2);
ASSERT_EQ(1U, current_tab2->infobar_count());
ReloadExtension(first_extension_id_);
SCOPED_TRACE("after reloading");
CheckExtensionConsistency(size_before);
// Both infobars should automatically hide after the extension is successfully
// reloaded.
ASSERT_EQ(0U, current_tab->infobar_count());
ASSERT_EQ(0U, current_tab2->infobar_count());
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest,
ReloadIndependentlyTwoInfoBarsSameBrowser) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
// Open a new window so that there will be an info bar in each.
Browser* browser2 = CreateBrowser(browser()->profile());
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
TabContents* current_tab = browser()->GetSelectedTabContents();
ASSERT_TRUE(current_tab);
ASSERT_EQ(1U, current_tab->infobar_count());
TabContents* current_tab2 = browser2->GetSelectedTabContents();
ASSERT_TRUE(current_tab2);
ASSERT_EQ(1U, current_tab2->infobar_count());
// Move second window into first browser so there will be multiple tabs
// with the info bar for the same extension in one browser.
TabContentsWrapper* contents =
browser2->tabstrip_model()->DetachTabContentsAt(0);
browser()->tabstrip_model()->AppendTabContents(contents, true);
current_tab2 = browser()->GetSelectedTabContents();
ASSERT_EQ(1U, current_tab2->infobar_count());
ASSERT_NE(current_tab2, current_tab);
ReloadExtension(first_extension_id_);
SCOPED_TRACE("after reloading");
CheckExtensionConsistency(size_before);
// Both infobars should automatically hide after the extension is successfully
// reloaded.
ASSERT_EQ(0U, current_tab2->infobar_count());
browser()->SelectPreviousTab();
ASSERT_EQ(current_tab, browser()->GetSelectedTabContents());
ASSERT_EQ(0U, current_tab->infobar_count());
}
// Make sure that when we don't do anything about the crashed extension
// and close the browser, it doesn't crash. The browser is closed implicitly
// at the end of each browser test.
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest, ShutdownWhileCrashed) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest, TwoExtensionsCrashFirst) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
LoadSecondExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before + 1, GetExtensionService()->extensions()->size());
AcceptInfoBar(0);
SCOPED_TRACE("after clicking the infobar");
CheckExtensionConsistency(size_before);
CheckExtensionConsistency(size_before + 1);
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest, TwoExtensionsCrashSecond) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
LoadSecondExtension();
CrashExtension(size_before + 1);
ASSERT_EQ(size_before + 1, GetExtensionService()->extensions()->size());
AcceptInfoBar(0);
SCOPED_TRACE("after clicking the infobar");
CheckExtensionConsistency(size_before);
CheckExtensionConsistency(size_before + 1);
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest,
TwoExtensionsCrashBothAtOnce) {
const size_t size_before = GetExtensionService()->extensions()->size();
const size_t crash_size_before =
GetExtensionService()->terminated_extensions()->size();
LoadTestExtension();
LoadSecondExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before + 1, GetExtensionService()->extensions()->size());
ASSERT_EQ(crash_size_before + 1,
GetExtensionService()->terminated_extensions()->size());
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
ASSERT_EQ(crash_size_before + 2,
GetExtensionService()->terminated_extensions()->size());
{
SCOPED_TRACE("first infobar");
AcceptInfoBar(0);
CheckExtensionConsistency(size_before);
}
{
SCOPED_TRACE("second infobar");
AcceptInfoBar(0);
CheckExtensionConsistency(size_before);
CheckExtensionConsistency(size_before + 1);
}
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest, TwoExtensionsOneByOne) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
LoadSecondExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
{
SCOPED_TRACE("first infobar");
AcceptInfoBar(0);
CheckExtensionConsistency(size_before);
}
{
SCOPED_TRACE("second infobar");
AcceptInfoBar(0);
CheckExtensionConsistency(size_before);
CheckExtensionConsistency(size_before + 1);
}
}
// Make sure that when we don't do anything about the crashed extensions
// and close the browser, it doesn't crash. The browser is closed implicitly
// at the end of each browser test.
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest,
TwoExtensionsShutdownWhileCrashed) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
LoadSecondExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest,
TwoExtensionsIgnoreFirst) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
LoadSecondExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before + 1, GetExtensionService()->extensions()->size());
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
CancelInfoBar(0);
AcceptInfoBar(1);
SCOPED_TRACE("infobars done");
ASSERT_EQ(size_before + 1, GetExtensionService()->extensions()->size());
CheckExtensionConsistency(size_before);
}
// Marked as flaky due to http://crbug.com/75134
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest,
FLAKY_TwoExtensionsReloadIndependently) {
const size_t size_before = GetExtensionService()->extensions()->size();
LoadTestExtension();
LoadSecondExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before + 1, GetExtensionService()->extensions()->size());
CrashExtension(size_before);
ASSERT_EQ(size_before, GetExtensionService()->extensions()->size());
{
SCOPED_TRACE("first: reload");
TabContents* current_tab = browser()->GetSelectedTabContents();
ASSERT_TRUE(current_tab);
// At the beginning we should have one infobar displayed for each extension.
ASSERT_EQ(2U, current_tab->infobar_count());
ReloadExtension(first_extension_id_);
// One of the infobars should hide after the extension is reloaded.
ASSERT_EQ(1U, current_tab->infobar_count());
CheckExtensionConsistency(size_before);
}
{
SCOPED_TRACE("second: infobar");
AcceptInfoBar(0);
CheckExtensionConsistency(size_before);
CheckExtensionConsistency(size_before + 1);
}
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest, CrashAndUninstall) {
const size_t size_before = GetExtensionService()->extensions()->size();
const size_t crash_size_before =
GetExtensionService()->terminated_extensions()->size();
LoadTestExtension();
LoadSecondExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before + 1, GetExtensionService()->extensions()->size());
ASSERT_EQ(crash_size_before + 1,
GetExtensionService()->terminated_extensions()->size());
UninstallExtension(first_extension_id_);
SCOPED_TRACE("after uninstalling");
ASSERT_EQ(size_before + 1, GetExtensionService()->extensions()->size());
ASSERT_EQ(crash_size_before,
GetExtensionService()->terminated_extensions()->size());
ASSERT_EQ(0U, browser()->GetSelectedTabContents()->infobar_count());
}
IN_PROC_BROWSER_TEST_F(ExtensionCrashRecoveryTest, CrashAndUnloadAll) {
const size_t size_before = GetExtensionService()->extensions()->size();
const size_t crash_size_before =
GetExtensionService()->terminated_extensions()->size();
LoadTestExtension();
LoadSecondExtension();
CrashExtension(size_before);
ASSERT_EQ(size_before + 1, GetExtensionService()->extensions()->size());
ASSERT_EQ(crash_size_before + 1,
GetExtensionService()->terminated_extensions()->size());
GetExtensionService()->UnloadAllExtensions();
ASSERT_EQ(crash_size_before,
GetExtensionService()->terminated_extensions()->size());
}
|
/**
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
*/
#include "file_utils.h"
#ifdef OS_OSX
#include <Cocoa/Cocoa.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/network/IOEthernetInterface.h>
#include <IOKit/network/IONetworkInterface.h>
#include <IOKit/network/IOEthernetController.h>
#include <sys/utsname.h>
#elif defined(OS_WIN32)
#include <windows.h>
#include <shlobj.h>
#include <Iphlpapi.h>
#include <process.h>
#elif defined(OS_LINUX)
#include <cstdarg>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <linux/if.h>
#include <sys/utsname.h>
#endif
#include <iostream>
#include <sstream>
#include <cstring>
const std::string ILLEGAL = "<>{}|\\\"^`";
static std::string safe_encode(std::string &str)
{
std::string encodedStr;
for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
{
char c = *it;
if (isalnum(c) ||
c == '-' || c == '_' ||
c == '.' || c == '~' ||
c == '/' || c == '\\' ||
c == ' ')
{
encodedStr += c;
}
else if (c == ' ')
{
encodedStr += c;
}
else if (c <= 0x20 || c >= 0x7F || ILLEGAL.find(c) != std::string::npos)
{
// skip these bad out of range characters ....
}
else encodedStr += c;
}
return encodedStr;
}
namespace kroll
{
const char HEX2DEC[256] =
{
/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
/* 0 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 1 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 2 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 3 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1, -1,-1,-1,-1,
/* 4 */ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 5 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 6 */ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 7 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 8 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 9 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* A */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* B */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* C */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* D */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* E */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* F */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1
};
// Only alphanum is safe.
const char SAFE[256] =
{
/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
/* 0 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* 1 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* 2 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* 3 */ 1,1,1,1, 1,1,1,1, 1,1,0,0, 0,0,0,0,
/* 4 */ 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1,
/* 5 */ 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,0,
/* 6 */ 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1,
/* 7 */ 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,0,
/* 8 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* 9 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* A */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* B */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* C */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* D */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* E */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* F */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0
};
static bool CompareVersions(std::string a, std::string b)
{
int a1 = FileUtils::MakeVersion(a);
int b1 = FileUtils::MakeVersion(b);
return b1 > a1;
}
std::string FileUtils::GetApplicationDirectory()
{
#ifdef OS_OSX
NSString* bundlePath = [[NSBundle mainBundle] bundlePath];
NSString* contents = [NSString stringWithFormat:@"%@/Contents",bundlePath];
return std::string([contents UTF8String]);
#elif OS_WIN32
char path[MAX_PATH];
GetModuleFileName(NULL,path,MAX_PATH);
std::string p(path);
std::string::size_type pos = p.rfind("\\");
if (pos!=std::string::npos)
{
return p.substr(0,pos);
}
return p;
#elif OS_LINUX
char tmp[100];
sprintf(tmp,"/proc/%d/exe",getpid());
char pbuf[255];
int c = readlink(tmp,pbuf,255);
pbuf[c]='\0';
std::string str(pbuf);
size_t pos = str.rfind("/");
if (pos==std::string::npos) return str;
return str.substr(0,pos);
#endif
}
std::string FileUtils::GetApplicationDataDirectory(std::string &appid)
{
#ifdef OS_WIN32
char path[MAX_PATH];
int size = GetEnvironmentVariable("KR_RUNTIME_HOME",(char*)path,MAX_PATH);
path[size]='\0';
std::string dir = path;
#else
std::string dir = getenv("KR_RUNTIME_HOME");
#endif
dir+=KR_PATH_SEP;
dir+="appdata";
if (!IsDirectory(dir))
{
CreateDirectory(dir);
}
dir+=KR_PATH_SEP;
dir+=appid;
if (!IsDirectory(dir))
{
CreateDirectory(dir);
}
return dir;
}
std::string FileUtils::GetTempDirectory()
{
#ifdef OS_OSX
NSString * tempDir = NSTemporaryDirectory();
if (tempDir == nil)
tempDir = @"/tmp";
NSString *tmp = [tempDir stringByAppendingPathComponent:@"kXXXXX"];
const char * fsTemplate = [tmp fileSystemRepresentation];
NSMutableData * bufferData = [NSMutableData dataWithBytes: fsTemplate
length: strlen(fsTemplate)+1];
char * buffer = (char*)[bufferData mutableBytes];
mkdtemp(buffer);
NSString * temporaryDirectory = [[NSFileManager defaultManager]
stringWithFileSystemRepresentation: buffer
length: strlen(buffer)];
return std::string([temporaryDirectory UTF8String]);
#elif defined(OS_WIN32)
#define BUFSIZE 512
TCHAR szTempName[BUFSIZE];
GetTempPath(BUFSIZE,szTempName);
std::ostringstream s;
srand(GetTickCount()); // initialize seed
std::string dir(szTempName);
s << dir;
s << "\\k";
s << (double)rand();
return s.str();
#else
std::ostringstream dir;
const char* tmp = getenv("TMPDIR");
const char* tmp2 = getenv("TEMP");
if (tmp)
dir << std::string(tmp);
else if (tmp2)
dir << std::string(tmp2);
else
dir << std::string("/tmp");
std::string tmp_str = dir.str();
if (tmp_str.at(tmp_str.length()-1) != '/')
dir << "/";
dir << "kXXXXXX";
char* tempdir = strdup(dir.str().c_str());
tempdir = mkdtemp(tempdir);
tmp_str = std::string(tempdir);
free(tempdir);
return tmp_str;
#endif
}
std::string FileUtils::GetResourcesDirectory()
{
#ifdef OS_OSX
NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
std::string dir = std::string([resourcePath UTF8String]);
#elif OS_WIN32
std::string dir = FileUtils::GetApplicationDirectory();
dir.append("\\Resources");
#elif OS_LINUX
// TODO test this
std::string dir = FileUtils::GetApplicationDirectory();
dir.append("/Resources");
#endif
return dir;
}
bool FileUtils::IsFile(std::string &file)
{
#ifdef OS_OSX
BOOL isDir = NO;
NSString *f = [NSString stringWithCString:file.c_str()];
NSString *p = [f stringByStandardizingPath];
BOOL found = [[NSFileManager defaultManager] fileExistsAtPath:p isDirectory:&isDir];
return found && !isDir;
#elif OS_WIN32
WIN32_FIND_DATA findFileData;
HANDLE hFind = FindFirstFile(file.c_str(), &findFileData);
if (hFind != INVALID_HANDLE_VALUE)
{
bool yesno = (findFileData.dwFileAttributes & 0x00000000) == 0x00000000;
FindClose(hFind);
return yesno;
}
return false;
#elif OS_LINUX
struct stat st;
return (stat(file.c_str(),&st)==0) && S_ISREG(st.st_mode);
#endif
}
bool FileUtils::CreateDirectory(std::string &dir)
{
#ifdef OS_OSX
return [[NSFileManager defaultManager] createDirectoryAtPath:[NSString stringWithCString:dir.c_str()] attributes:nil];
#elif OS_WIN32
return ::CreateDirectory(dir.c_str(),NULL);
#elif OS_LINUX
return mkdir(dir.c_str(),0755) == 0;
#endif
return false;
}
bool FileUtils::DeleteDirectory(std::string &dir)
{
#ifdef OS_OSX
[[NSFileManager defaultManager] removeFileAtPath:[NSString stringWithCString:dir.c_str()] handler:nil];
#elif OS_WIN32
SHFILEOPSTRUCT op;
op.hwnd = NULL;
op.wFunc = FO_DELETE;
op.pFrom = dir.c_str();
op.pTo = NULL;
op.fFlags = FOF_NOCONFIRMATION | FOF_SILENT | FOF_NOERRORUI;
int rc = SHFileOperation(&op);
return (rc == 0);
#elif OS_LINUX
return unlink(dir.c_str()) == 0;
#endif
return false;
}
bool FileUtils::IsDirectory(std::string &dir)
{
#ifdef OS_OSX
BOOL isDir = NO;
BOOL found = [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithCString:dir.c_str()] isDirectory:&isDir];
return found && isDir;
#elif OS_WIN32
WIN32_FIND_DATA findFileData;
HANDLE hFind = FindFirstFile(dir.c_str(), &findFileData);
if (hFind != INVALID_HANDLE_VALUE)
{
bool yesno = (findFileData.dwFileAttributes & 0x00000010) == 0x00000010;
FindClose(hFind);
return yesno;
}
return false;
#elif OS_LINUX
struct stat st;
return (stat(dir.c_str(),&st)==0) && S_ISDIR(st.st_mode);
#endif
}
std::string FileUtils::GetDirectory(std::string &file)
{
size_t pos = file.find_last_of(KR_PATH_SEP);
if (pos == std::string::npos)
{
pos = file.find_last_of(KR_PATH_SEP_OTHER);
if (pos == std::string::npos)
{
return "."KR_PATH_SEP; //??
}
}
#ifdef OS_OSX
NSString *s = [[NSString stringWithCString:file.substr(0,pos).c_str()] stringByExpandingTildeInPath];
return [s fileSystemRepresentation];
#else
return file.substr(0, pos);
#endif
}
std::string FileUtils::Join(const char* path, ...)
{
va_list ap;
va_start(ap, path);
std::vector<std::string> parts;
parts.push_back(std::string(path));
while (true)
{
const char *i = va_arg(ap,const char*);
if (i == NULL) break;
parts.push_back(Trim(i));
}
va_end(ap);
std::string filepath;
std::vector<std::string>::iterator iter = parts.begin();
while (iter!=parts.end())
{
std::string p = (*iter++);
filepath+=p;
if (filepath.length() != 0 && iter!=parts.end())
{
filepath+=KR_PATH_SEP;
}
}
#ifdef OS_OSX
NSString *s = [[NSString stringWithCString:filepath.c_str()] stringByExpandingTildeInPath];
NSString *p = [s stringByStandardizingPath];
return std::string([p fileSystemRepresentation]);
#else
return filepath;
#endif
}
bool FileUtils::IsHidden(std::string &file)
{
#ifdef OS_OSX
// TODO finish this
return false;
#elif OS_WIN32
WIN32_FIND_DATA findFileData;
HANDLE hFind = FindFirstFile(file.c_str(), &findFileData);
if (hFind != INVALID_HANDLE_VALUE)
{
bool yesno = (findFileData.dwFileAttributes & 0x00000002) == 0x00000002;
FindClose(hFind);
return yesno;
}
return false;
#elif OS_LINUX
return (file.size() > 0 && file.at(0) == '.');
#endif
}
bool FileUtils::IsRuntimeInstalled()
{
std::string dir = GetRuntimeBaseDirectory();
return IsDirectory(dir);
}
std::string FileUtils::GetRuntimeBaseDirectory()
{
#ifdef OS_WIN32
char path[MAX_PATH];
std::string dir;
if (SHGetSpecialFolderPath(NULL,path,CSIDL_COMMON_APPDATA,FALSE))
{
dir.append(path);
dir.append("\\");
dir.append(PRODUCT_NAME);
}
else if (SHGetSpecialFolderPath(NULL,path,CSIDL_APPDATA,FALSE))
{
dir.append(path);
dir.append("\\");
dir.append(PRODUCT_NAME);
}
return dir;
#elif OS_OSX
// check to see if we already have a local one
NSString *localDir = [[NSString stringWithFormat:@"~/Library/Application Support/%s",PRODUCT_NAME] stringByExpandingTildeInPath];
std::string ls = std::string([localDir UTF8String]);
if (IsDirectory(ls))
{
return std::string([localDir UTF8String]);
}
// first check to see if we can install in system directory by checking
// if we can write to it
NSString *systemPath = @"/Library/Application Support";
if ([[NSFileManager defaultManager] isWritableFileAtPath:systemPath])
{
return std::string([[systemPath stringByAppendingString:@"/"PRODUCT_NAME] UTF8String]);
}
// if not, we fall back to installing into user directory
return std::string([localDir UTF8String]);
#elif OS_LINUX
std::string uid = std::string(getenv("USER"));
std::string p(INSTALL_PREFIX);
p.append("/");
p.append(PRODUCT_NAME);
bool writable = (access(p.c_str(),W_OK)) == 0;
if (uid.find("root")!=std::string::npos || writable)
{
return p;
}
passwd *user = getpwnam(uid.c_str());
std::string dir = std::string(user->pw_dir) + "/" + PRODUCT_NAME + "App";
return dir;
#endif
}
void FileUtils::ExtractVersion(std::string& spec, int *op, std::string &version)
{
if (spec.find(">=")!=std::string::npos)
{
*op = GreaterThanEqualTo;
version = spec.substr(2,spec.length());
}
else if (spec.find("<=")!=std::string::npos)
{
*op = LessThanEqualTo;
version = spec.substr(2,spec.length());
}
else if (spec.find("<")!=std::string::npos)
{
*op = LessThan;
version = spec.substr(1,spec.length());
}
else if (spec.find(">")!=std::string::npos)
{
*op = GreaterThan;
version = spec.substr(1,spec.length());
}
else if (spec.find("=")!=std::string::npos)
{
*op = EqualTo;
version = spec.substr(1,spec.length());
}
else
{
*op = EqualTo;
version = spec;
}
}
int FileUtils::MakeVersion(std::string& ver)
{
std::string v;
size_t pos = 0;
while(1)
{
size_t newpos = ver.find(".",pos);
if (newpos==std::string::npos)
{
v.append(ver.substr(pos,ver.length()));
break;
}
v.append(ver.substr(pos,newpos));
pos = newpos+1;
}
return atoi(v.c_str());
}
std::string FileUtils::FindVersioned(std::string& path, int op, std::string& version)
{
printf("\n1a: %s\n", path.c_str());
std::vector<std::string> files;
std::vector<std::string> found;
ListDir(path,files);
std::vector<std::string>::iterator iter = files.begin();
int findVersion = MakeVersion(version);
while (iter!=files.end())
{
std::string str = (*iter++);
std::string fullpath = std::string(path);
fullpath.append(KR_PATH_SEP);
fullpath.append(str);
printf("2: %s\n", fullpath.c_str());
if (IsDirectory(fullpath))
{
int theVersion = MakeVersion(str);
bool matched = false;
switch(op)
{
case EqualTo:
{
matched = (theVersion == findVersion);
break;
}
case GreaterThanEqualTo:
{
matched = (theVersion >= findVersion);
break;
}
case LessThanEqualTo:
{
matched = (theVersion <= findVersion);
break;
}
case GreaterThan:
{
matched = (theVersion > findVersion);
break;
}
case LessThan:
{
matched = (theVersion < findVersion);
break;
}
}
if (matched)
{
found.push_back(std::string(str));
}
}
}
if (found.size() > 0)
{
std::sort(found.begin(),found.end(),CompareVersions);
std::string file = found.at(0);
std::string f = std::string(path);
f.append(KR_PATH_SEP);
f.append(file);
return f;
}
return std::string();
}
std::string FileUtils::GetMachineId()
{
std::string path = FileUtils::Join(FileUtils::GetRuntimeBaseDirectory().c_str(),".titanium",NULL);
if (FileUtils::IsFile(path))
{
std::ifstream file(path.c_str());
if (file.bad() || file.fail())
{
return "-";
}
while (!file.eof())
{
std::string line;
std::getline(file,line);
FileUtils::Trim(line);
return line;
}
}
return "-";
}
std::string FileUtils::GetOSVersion()
{
#ifdef OS_WIN32
OSVERSIONINFO vi;
vi.dwOSVersionInfoSize = sizeof(vi);
if (GetVersionEx(&vi) == 0) return "?";
std::ostringstream str;
str << vi.dwMajorVersion << "." << vi.dwMinorVersion << " (Build " << (vi.dwBuildNumber & 0xFFFF);
if (vi.szCSDVersion[0]) str << ": " << vi.szCSDVersion;
str << ")";
return str.str();
#elif OS_OSX || OS_LINUX
struct utsname uts;
uname(&uts);
return uts.release;
#endif
}
std::string FileUtils::GetOSArchitecture()
{
#ifdef OS_WIN32
return std::string("win32");
#elif OS_OSX || OS_LINUX
struct utsname uts;
uname(&uts);
return uts.machine;
#endif
}
std::string FileUtils::EncodeURIComponent(std::string src)
{
const char DEC2HEX[16 + 1] = "0123456789ABCDEF";
const unsigned char *pSrc = (const unsigned char *)src.c_str();
const int SRC_LEN = src.length();
unsigned char * const pStart = new unsigned char[SRC_LEN * 3];
unsigned char * pEnd = pStart;
const unsigned char * const SRC_END = pSrc + SRC_LEN;
for (; pSrc < SRC_END; ++pSrc)
{
if (SAFE[*pSrc])
*pEnd++ = *pSrc;
else
{
// escape this char
*pEnd++ = '%';
*pEnd++ = DEC2HEX[*pSrc >> 4];
*pEnd++ = DEC2HEX[*pSrc & 0x0F];
}
}
std::string sResult((char *)pStart, (char *)pEnd);
delete [] pStart;
return sResult;
}
std::string FileUtils::DecodeURIComponent(std::string src)
{
// Note from RFC1630: "Sequences which start with a percent
// sign but are not followed by two hexadecimal characters
// (0-9, A-F) are reserved for future extension"
const unsigned char * pSrc = (const unsigned char *)src.c_str();
const int SRC_LEN = src.length();
const unsigned char * const SRC_END = pSrc + SRC_LEN;
// last decodable '%'
const unsigned char * const SRC_LAST_DEC = SRC_END - 2;
char * const pStart = new char[SRC_LEN];
char * pEnd = pStart;
while (pSrc < SRC_LAST_DEC)
{
if (*pSrc == '%')
{
char dec1, dec2;
if (-1 != (dec1 = HEX2DEC[*(pSrc + 1)])
&& -1 != (dec2 = HEX2DEC[*(pSrc + 2)]))
{
*pEnd++ = (dec1 << 4) + dec2;
pSrc += 3;
continue;
}
}
*pEnd++ = *pSrc++;
}
// the last 2- chars
while (pSrc < SRC_END)
*pEnd++ = *pSrc++;
std::string sResult(pStart, pEnd);
delete [] pStart;
return sResult;
}
void FileUtils::Tokenize(const std::string& str, std::vector<std::string>& tokens, const std::string &delimeters)
{
std::string::size_type lastPos = str.find_first_not_of(delimeters,0);
std::string::size_type pos = str.find_first_of(delimeters,lastPos);
while (std::string::npos!=pos || std::string::npos!=lastPos)
{
tokens.push_back(str.substr(lastPos,pos-lastPos));
lastPos = str.find_first_not_of(delimeters,pos);
pos = str.find_first_of(delimeters,lastPos);
}
}
std::string FileUtils::Trim(std::string str)
{
std::string c(safe_encode(str));
while (1)
{
size_t pos = c.rfind(" ");
if (pos == std::string::npos || pos!=c.length()-1)
{
break;
}
c = c.substr(0,pos);
}
while(1)
{
size_t pos = c.find(" ");
if (pos != 0)
{
break;
}
c = c.substr(1);
}
return c;
}
bool FileUtils::ReadManifest(std::string& path, std::string &runtimePath, std::vector< std::pair< std::pair<std::string,std::string>, bool> >& modules, std::vector<std::string> &moduleDirs, std::string &appname, std::string &appid, std::string &runtimeOverride, std::string &guid)
{
std::ifstream file(path.c_str());
if (file.bad() || file.fail())
{
return false;
}
bool foundRuntime = false;
const char *rt = runtimeOverride.c_str();
#ifdef DEBUG
std::cout << "Read Manifest: " << rt << std::endl;
#endif
while (!file.eof())
{
std::string line;
std::getline(file,line);
if (line.find(" ")==0)
{
continue;
}
size_t pos = line.find(":");
if (pos!=std::string::npos)
{
std::string key = Trim(line.substr(0,pos));
std::string value = Trim(line.substr(pos+1,line.length()));
if (key == "#appname")
{
appname = value;
continue;
}
else if (key == "#appid")
{
appid = value;
continue;
}
else if (key == "#guid")
{
guid = value;
continue;
}
else if (key.c_str()[0]=='#')
{
continue;
}
int op;
std::string version;
ExtractVersion(value,&op,version);
#ifdef DEBUG
std::cout << "Component: " << key << ":" << version << ", operation: " << op << std::endl;
#endif
std::pair<std::string,std::string> p(key,version);
if (key == "runtime")
{
// check to see if our runtime is found in our override directory
if (!runtimeOverride.empty())
{
std::string potentialRuntime = Join(rt,"runtime",NULL);
if (IsDirectory(potentialRuntime))
{
// extra special check for Win32 since we have to place the WebKit.dll
// inside the same relative path as .exe because of the COM embedded manifest crap-o-la
// so if we can't find kroll.dll in the resources folder we don't override
#ifdef OS_WIN32
std::string krolldll = kroll::FileUtils::Join(potentialRuntime.c_str(),"kroll.dll",NULL);
if (kroll::FileUtils::IsFile(krolldll))
{
#endif
runtimePath = potentialRuntime;
#ifdef DEBUG
std::cout << "found override runtime at: " << runtimePath << std::endl;
#endif
foundRuntime = true;
continue;
#ifdef OS_WIN32
}
#endif
}
}
runtimePath = FindRuntime(op,version);
modules.push_back(std::pair< std::pair<std::string,std::string>, bool>(p,false));
foundRuntime = true; // so we don't add again
}
else
{
// check to see if our module is contained within our runtime override
// directory and if it is, use it...
std::string potentialModule = kroll::FileUtils::Join(rt,"modules",key.c_str(),NULL);
#ifdef DEBUG
std::cout << "looking for bundled module at " << potentialModule << std::endl;
#endif
if (IsDirectory(potentialModule))
{
modules.push_back(std::pair< std::pair<std::string,std::string>, bool>(p,true));
moduleDirs.push_back(potentialModule);
#ifdef DEBUG
std::cout << "found override module at: " << potentialModule << std::endl;
#endif
continue;
}
std::string dir = FindModule(key,op,version);
bool found = dir!="";
modules.push_back(std::pair< std::pair<std::string,std::string>, bool>(p,found));
if (found)
{
#ifdef DEBUG
std::cout << "found module at: " << dir << std::endl;
#endif
moduleDirs.push_back(dir);
}
#ifdef DEBUG
else
{
std::cerr << "couldn't find module module: " << key << "/" << version << std::endl;
}
#endif
}
}
}
// we gotta always have a runtime
if (!foundRuntime)
{
std::pair<std::string,std::string> p("runtime",STRING(PRODUCT_VERSION)); //TODO: huh, what do we use?
modules.push_back(std::pair< std::pair<std::string,std::string>, bool>(p,false));
}
file.close();
return true;
}
std::string FileUtils::FindRuntime(int op, std::string& version)
{
std::string runtime = GetRuntimeBaseDirectory();
std::string path(runtime);
#ifdef OS_WIN32
path += "\\runtime\\win32";
#elif OS_LINUX
path += "/runtime/linux";
#elif OS_OSX
path += "/runtime/osx";
#endif
return FindVersioned(path,op,version);
}
std::string FileUtils::FindModule(std::string& name, int op, std::string& version)
{
std::string runtime = GetRuntimeBaseDirectory();
std::string path(runtime);
#ifdef OS_WIN32
path += "\\modules\\win32\\";
#elif OS_LINUX
path += "/modules/linux/";
#elif OS_OSX
path += "/modules/osx/";
#endif
path += name;
return FindVersioned(path,op,version);
}
void FileUtils::ListDir(std::string& path, std::vector<std::string> &files)
{
#if defined(OS_WIN32)
WIN32_FIND_DATA findFileData;
std::string q(path+"\\*");
HANDLE hFind = FindFirstFile(q.c_str(), &findFileData);
if (hFind != INVALID_HANDLE_VALUE)
{
do
{
files.push_back(std::string(findFileData.cFileName));
} while (FindNextFile(hFind, &findFileData));
FindClose(hFind);
}
#else
DIR *dp;
struct dirent *dirp;
if ((dp = opendir(path.c_str()))!=NULL)
{
while ((dirp = readdir(dp))!=NULL)
{
std::string fn = std::string(dirp->d_name);
if (fn.substr(0,1)=="." || fn.substr(0,2)=="..")
{
continue;
}
files.push_back(fn);
}
closedir(dp);
}
#endif
}
int FileUtils::RunAndWait(std::string &path, std::vector<std::string> &args)
{
#ifndef OS_WIN32
std::string p;
p+="\"";
p+=path;
p+="\" ";
std::vector<std::string>::iterator i = args.begin();
while (i!=args.end())
{
p+="\"";
p+=(*i++);
p+="\" ";
}
#ifdef DEBUG
std::cout << "running: " << p << std::endl;
#endif
return system(p.c_str());
#elif defined(OS_WIN32)
std::ostringstream ostr;
ostr << path.c_str();
if (args.size() > 0 )
{
std::vector<std::string>::iterator i = args.begin();
int idx = 0;
while (i!=args.end())
{
// we need to quote each argument
ostr << " \"" << (*i++).c_str() << "\"";
}
}
DWORD rc=0;
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
char buf[MAX_PATH];
DWORD size = GetCurrentDirectory(MAX_PATH,(char*)buf);
buf[size]='\0';
if (!CreateProcess( NULL, // No module name (use command line)
(char*)ostr.str().c_str(), // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
(char*)buf, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi ) // Pointer to PROCESS_INFORMATION structure
)
{
rc = -1;
}
else
{
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
// set the exit code
GetExitCodeProcess(pi.hProcess,&rc);
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
return rc;
#endif
}
std::string FileUtils::GetUsername()
{
#ifdef OS_OSX
return std::string([NSUserName() UTF8String]);
#elif OS_WIN32
char buf[MAX_PATH];
DWORD size = MAX_PATH;
if (::GetUserName(buf,&size))
{
buf[size]='\0';
}
else
{
sprintf(buf,"Unknown");
}
return std::string(buf);
#elif OS_LINUX
return std::string(getlogin());
#endif
}
#ifndef NO_UNZIP
void FileUtils::Unzip(std::string& source, std::string& destination)
{
#ifdef OS_OSX
//
// we don't include gzip since we're on OSX
// we just let the built-in OS handle extraction for us
//
std::vector<std::string> args;
args.push_back("--noqtn");
args.push_back("-x");
args.push_back("-k");
args.push_back("--rsrc");
args.push_back(source);
args.push_back(destination);
std::string cmdline = "/usr/bin/ditto";
RunAndWait(cmdline,args);
#elif OS_LINUX
std::vector<std::string> args;
args.push_back("-qq");
args.push_back("-o");
args.push_back(source);
args.push_back("-d");
args.push_back(destination);
std::string cmdline("/usr/bin/unzip");
RunAndWait(cmdline,args);
#elif OS_WIN32
HZIP hz = OpenZip(source.c_str(),0);
SetUnzipBaseDir(hz,destination.c_str());
ZIPENTRY ze;
GetZipItem(hz,-1,&ze);
int numitems=ze.index;
for (int zi=0; zi < numitems; zi++)
{
GetZipItem(hz,zi,&ze);
UnzipItem(hz,zi,ze.name);
}
CloseZip(hz);
#endif
}
#endif
}
more bugfixes for win32
/**
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
*/
#include "file_utils.h"
#ifdef OS_OSX
#include <Cocoa/Cocoa.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/network/IOEthernetInterface.h>
#include <IOKit/network/IONetworkInterface.h>
#include <IOKit/network/IOEthernetController.h>
#include <sys/utsname.h>
#elif defined(OS_WIN32)
#include <windows.h>
#include <shlobj.h>
#include <Iphlpapi.h>
#include <process.h>
#elif defined(OS_LINUX)
#include <cstdarg>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <linux/if.h>
#include <sys/utsname.h>
#endif
#include <iostream>
#include <sstream>
#include <cstring>
const std::string ILLEGAL = "<>{}|\\\"^`";
static std::string safe_encode(std::string &str)
{
std::string encodedStr;
for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
{
char c = *it;
if (isalnum(c) ||
c == '-' || c == '_' ||
c == '.' || c == '~' ||
c == '/' || c == '\\' ||
c == ' ')
{
encodedStr += c;
}
else if (c == ' ')
{
encodedStr += c;
}
else if (c <= 0x20 || c >= 0x7F || ILLEGAL.find(c) != std::string::npos)
{
// skip these bad out of range characters ....
}
else encodedStr += c;
}
return encodedStr;
}
namespace kroll
{
const char HEX2DEC[256] =
{
/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
/* 0 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 1 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 2 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 3 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1, -1,-1,-1,-1,
/* 4 */ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 5 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 6 */ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 7 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 8 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 9 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* A */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* B */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* C */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* D */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* E */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* F */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1
};
// Only alphanum is safe.
const char SAFE[256] =
{
/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
/* 0 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* 1 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* 2 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* 3 */ 1,1,1,1, 1,1,1,1, 1,1,0,0, 0,0,0,0,
/* 4 */ 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1,
/* 5 */ 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,0,
/* 6 */ 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1,
/* 7 */ 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,0,
/* 8 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* 9 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* A */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* B */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* C */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* D */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* E */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* F */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0
};
static bool CompareVersions(std::string a, std::string b)
{
int a1 = FileUtils::MakeVersion(a);
int b1 = FileUtils::MakeVersion(b);
return b1 > a1;
}
std::string FileUtils::GetApplicationDirectory()
{
#ifdef OS_OSX
NSString* bundlePath = [[NSBundle mainBundle] bundlePath];
NSString* contents = [NSString stringWithFormat:@"%@/Contents",bundlePath];
return std::string([contents UTF8String]);
#elif OS_WIN32
char path[MAX_PATH];
GetModuleFileName(NULL,path,MAX_PATH);
std::string p(path);
std::string::size_type pos = p.rfind("\\");
if (pos!=std::string::npos)
{
return p.substr(0,pos);
}
return p;
#elif OS_LINUX
char tmp[100];
sprintf(tmp,"/proc/%d/exe",getpid());
char pbuf[255];
int c = readlink(tmp,pbuf,255);
pbuf[c]='\0';
std::string str(pbuf);
size_t pos = str.rfind("/");
if (pos==std::string::npos) return str;
return str.substr(0,pos);
#endif
}
std::string FileUtils::GetApplicationDataDirectory(std::string &appid)
{
#ifdef OS_WIN32
char path[MAX_PATH];
int size = GetEnvironmentVariable("KR_RUNTIME_HOME",(char*)path,MAX_PATH);
path[size]='\0';
std::string dir = path;
#else
std::string dir = getenv("KR_RUNTIME_HOME");
#endif
dir+=KR_PATH_SEP;
dir+="appdata";
if (!IsDirectory(dir))
{
CreateDirectory(dir);
}
dir+=KR_PATH_SEP;
dir+=appid;
if (!IsDirectory(dir))
{
CreateDirectory(dir);
}
return dir;
}
std::string FileUtils::GetTempDirectory()
{
#ifdef OS_OSX
NSString * tempDir = NSTemporaryDirectory();
if (tempDir == nil)
tempDir = @"/tmp";
NSString *tmp = [tempDir stringByAppendingPathComponent:@"kXXXXX"];
const char * fsTemplate = [tmp fileSystemRepresentation];
NSMutableData * bufferData = [NSMutableData dataWithBytes: fsTemplate
length: strlen(fsTemplate)+1];
char * buffer = (char*)[bufferData mutableBytes];
mkdtemp(buffer);
NSString * temporaryDirectory = [[NSFileManager defaultManager]
stringWithFileSystemRepresentation: buffer
length: strlen(buffer)];
return std::string([temporaryDirectory UTF8String]);
#elif defined(OS_WIN32)
#define BUFSIZE 512
TCHAR szTempName[BUFSIZE];
GetTempPath(BUFSIZE,szTempName);
std::ostringstream s;
srand(GetTickCount()); // initialize seed
std::string dir(szTempName);
s << dir;
s << "\\k";
s << (double)rand();
return s.str();
#else
std::ostringstream dir;
const char* tmp = getenv("TMPDIR");
const char* tmp2 = getenv("TEMP");
if (tmp)
dir << std::string(tmp);
else if (tmp2)
dir << std::string(tmp2);
else
dir << std::string("/tmp");
std::string tmp_str = dir.str();
if (tmp_str.at(tmp_str.length()-1) != '/')
dir << "/";
dir << "kXXXXXX";
char* tempdir = strdup(dir.str().c_str());
tempdir = mkdtemp(tempdir);
tmp_str = std::string(tempdir);
free(tempdir);
return tmp_str;
#endif
}
std::string FileUtils::GetResourcesDirectory()
{
#ifdef OS_OSX
NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
std::string dir = std::string([resourcePath UTF8String]);
#elif OS_WIN32
std::string dir = FileUtils::GetApplicationDirectory();
dir.append("\\Resources");
#elif OS_LINUX
// TODO test this
std::string dir = FileUtils::GetApplicationDirectory();
dir.append("/Resources");
#endif
return dir;
}
bool FileUtils::IsFile(std::string &file)
{
#ifdef OS_OSX
BOOL isDir = NO;
NSString *f = [NSString stringWithCString:file.c_str()];
NSString *p = [f stringByStandardizingPath];
BOOL found = [[NSFileManager defaultManager] fileExistsAtPath:p isDirectory:&isDir];
return found && !isDir;
#elif OS_WIN32
WIN32_FIND_DATA findFileData;
HANDLE hFind = FindFirstFile(file.c_str(), &findFileData);
if (hFind != INVALID_HANDLE_VALUE)
{
bool yesno = (findFileData.dwFileAttributes & 0x00000000) == 0x00000000;
FindClose(hFind);
return yesno;
}
return false;
#elif OS_LINUX
struct stat st;
return (stat(file.c_str(),&st)==0) && S_ISREG(st.st_mode);
#endif
}
bool FileUtils::CreateDirectory(std::string &dir)
{
#ifdef OS_OSX
return [[NSFileManager defaultManager] createDirectoryAtPath:[NSString stringWithCString:dir.c_str()] attributes:nil];
#elif OS_WIN32
return ::CreateDirectory(dir.c_str(),NULL);
#elif OS_LINUX
return mkdir(dir.c_str(),0755) == 0;
#endif
return false;
}
bool FileUtils::DeleteDirectory(std::string &dir)
{
#ifdef OS_OSX
[[NSFileManager defaultManager] removeFileAtPath:[NSString stringWithCString:dir.c_str()] handler:nil];
#elif OS_WIN32
SHFILEOPSTRUCT op;
op.hwnd = NULL;
op.wFunc = FO_DELETE;
op.pFrom = dir.c_str();
op.pTo = NULL;
op.fFlags = FOF_NOCONFIRMATION | FOF_SILENT | FOF_NOERRORUI;
int rc = SHFileOperation(&op);
return (rc == 0);
#elif OS_LINUX
return unlink(dir.c_str()) == 0;
#endif
return false;
}
bool FileUtils::IsDirectory(std::string &dir)
{
#ifdef OS_OSX
BOOL isDir = NO;
BOOL found = [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithCString:dir.c_str()] isDirectory:&isDir];
return found && isDir;
#elif OS_WIN32
WIN32_FIND_DATA findFileData;
HANDLE hFind = FindFirstFile(dir.c_str(), &findFileData);
if (hFind != INVALID_HANDLE_VALUE)
{
bool yesno = (findFileData.dwFileAttributes & 0x00000010) == 0x00000010;
FindClose(hFind);
return yesno;
}
return false;
#elif OS_LINUX
struct stat st;
return (stat(dir.c_str(),&st)==0) && S_ISDIR(st.st_mode);
#endif
}
std::string FileUtils::GetDirectory(std::string &file)
{
size_t pos = file.find_last_of(KR_PATH_SEP);
if (pos == std::string::npos)
{
pos = file.find_last_of(KR_PATH_SEP_OTHER);
if (pos == std::string::npos)
{
return "."KR_PATH_SEP; //??
}
}
#ifdef OS_OSX
NSString *s = [[NSString stringWithCString:file.substr(0,pos).c_str()] stringByExpandingTildeInPath];
return [s fileSystemRepresentation];
#else
return file.substr(0, pos);
#endif
}
std::string FileUtils::Join(const char* path, ...)
{
va_list ap;
va_start(ap, path);
std::vector<std::string> parts;
parts.push_back(std::string(path));
while (true)
{
const char *i = va_arg(ap,const char*);
if (i == NULL) break;
parts.push_back(Trim(i));
}
va_end(ap);
std::string filepath;
std::vector<std::string>::iterator iter = parts.begin();
while (iter!=parts.end())
{
std::string p = (*iter++);
filepath+=p;
if (filepath.length() != 0 && iter!=parts.end())
{
filepath+=KR_PATH_SEP;
}
}
#ifdef OS_OSX
NSString *s = [[NSString stringWithCString:filepath.c_str()] stringByExpandingTildeInPath];
NSString *p = [s stringByStandardizingPath];
return std::string([p fileSystemRepresentation]);
#else
return filepath;
#endif
}
bool FileUtils::IsHidden(std::string &file)
{
#ifdef OS_OSX
// TODO finish this
return false;
#elif OS_WIN32
WIN32_FIND_DATA findFileData;
HANDLE hFind = FindFirstFile(file.c_str(), &findFileData);
if (hFind != INVALID_HANDLE_VALUE)
{
bool yesno = (findFileData.dwFileAttributes & 0x00000002) == 0x00000002;
FindClose(hFind);
return yesno;
}
return false;
#elif OS_LINUX
return (file.size() > 0 && file.at(0) == '.');
#endif
}
bool FileUtils::IsRuntimeInstalled()
{
std::string dir = GetRuntimeBaseDirectory();
return IsDirectory(dir);
}
std::string FileUtils::GetRuntimeBaseDirectory()
{
#ifdef OS_WIN32
char path[MAX_PATH];
std::string dir;
if (SHGetSpecialFolderPath(NULL,path,CSIDL_COMMON_APPDATA,FALSE))
{
dir.append(path);
dir.append("\\");
dir.append(PRODUCT_NAME);
}
else if (SHGetSpecialFolderPath(NULL,path,CSIDL_APPDATA,FALSE))
{
dir.append(path);
dir.append("\\");
dir.append(PRODUCT_NAME);
}
return dir;
#elif OS_OSX
// check to see if we already have a local one
NSString *localDir = [[NSString stringWithFormat:@"~/Library/Application Support/%s",PRODUCT_NAME] stringByExpandingTildeInPath];
std::string ls = std::string([localDir UTF8String]);
if (IsDirectory(ls))
{
return std::string([localDir UTF8String]);
}
// first check to see if we can install in system directory by checking
// if we can write to it
NSString *systemPath = @"/Library/Application Support";
if ([[NSFileManager defaultManager] isWritableFileAtPath:systemPath])
{
return std::string([[systemPath stringByAppendingString:@"/"PRODUCT_NAME] UTF8String]);
}
// if not, we fall back to installing into user directory
return std::string([localDir UTF8String]);
#elif OS_LINUX
std::string uid = std::string(getenv("USER"));
std::string p(INSTALL_PREFIX);
p.append("/");
p.append(PRODUCT_NAME);
bool writable = (access(p.c_str(),W_OK)) == 0;
if (uid.find("root")!=std::string::npos || writable)
{
return p;
}
passwd *user = getpwnam(uid.c_str());
std::string dir = std::string(user->pw_dir) + "/" + PRODUCT_NAME + "App";
return dir;
#endif
}
void FileUtils::ExtractVersion(std::string& spec, int *op, std::string &version)
{
if (spec.find(">=")!=std::string::npos)
{
*op = GreaterThanEqualTo;
version = spec.substr(2,spec.length());
}
else if (spec.find("<=")!=std::string::npos)
{
*op = LessThanEqualTo;
version = spec.substr(2,spec.length());
}
else if (spec.find("<")!=std::string::npos)
{
*op = LessThan;
version = spec.substr(1,spec.length());
}
else if (spec.find(">")!=std::string::npos)
{
*op = GreaterThan;
version = spec.substr(1,spec.length());
}
else if (spec.find("=")!=std::string::npos)
{
*op = EqualTo;
version = spec.substr(1,spec.length());
}
else
{
*op = EqualTo;
version = spec;
}
}
int FileUtils::MakeVersion(std::string& ver)
{
std::string v;
size_t pos = 0;
while(1)
{
size_t newpos = ver.find(".",pos);
if (newpos==std::string::npos)
{
v.append(ver.substr(pos,ver.length()));
break;
}
v.append(ver.substr(pos,newpos));
pos = newpos+1;
}
return atoi(v.c_str());
}
std::string FileUtils::FindVersioned(std::string& path, int op, std::string& version)
{
printf("\n1a: %s\n", path.c_str());
std::vector<std::string> files;
std::vector<std::string> found;
ListDir(path,files);
std::vector<std::string>::iterator iter = files.begin();
int findVersion = MakeVersion(version);
while (iter!=files.end())
{
std::string str = (*iter++);
std::string fullpath = std::string(path);
fullpath.append(KR_PATH_SEP);
fullpath.append(str);
printf("2: %s\n", fullpath.c_str());
if (IsDirectory(fullpath))
{
int theVersion = MakeVersion(str);
bool matched = false;
switch(op)
{
case EqualTo:
{
matched = (theVersion == findVersion);
break;
}
case GreaterThanEqualTo:
{
matched = (theVersion >= findVersion);
break;
}
case LessThanEqualTo:
{
matched = (theVersion <= findVersion);
break;
}
case GreaterThan:
{
matched = (theVersion > findVersion);
break;
}
case LessThan:
{
matched = (theVersion < findVersion);
break;
}
}
if (matched)
{
found.push_back(std::string(str));
}
}
}
if (found.size() > 0)
{
std::sort(found.begin(),found.end(),CompareVersions);
std::string file = found.at(0);
std::string f = std::string(path);
f.append(KR_PATH_SEP);
f.append(file);
return f;
}
return std::string();
}
std::string FileUtils::GetMachineId()
{
std::string path = FileUtils::Join(FileUtils::GetRuntimeBaseDirectory().c_str(),".titanium",NULL);
if (FileUtils::IsFile(path))
{
std::ifstream file(path.c_str());
if (file.bad() || file.fail())
{
return "-";
}
while (!file.eof())
{
std::string line;
std::getline(file,line);
FileUtils::Trim(line);
return line;
}
}
return "-";
}
std::string FileUtils::GetOSVersion()
{
#ifdef OS_WIN32
OSVERSIONINFO vi;
vi.dwOSVersionInfoSize = sizeof(vi);
if (GetVersionEx(&vi) == 0) return "?";
std::ostringstream str;
str << vi.dwMajorVersion << "." << vi.dwMinorVersion << " (Build " << (vi.dwBuildNumber & 0xFFFF);
if (vi.szCSDVersion[0]) str << ": " << vi.szCSDVersion;
str << ")";
return str.str();
#elif OS_OSX || OS_LINUX
struct utsname uts;
uname(&uts);
return uts.release;
#endif
}
std::string FileUtils::GetOSArchitecture()
{
#ifdef OS_WIN32
return std::string("win32");
#elif OS_OSX || OS_LINUX
struct utsname uts;
uname(&uts);
return uts.machine;
#endif
}
std::string FileUtils::EncodeURIComponent(std::string src)
{
const char DEC2HEX[16 + 1] = "0123456789ABCDEF";
const unsigned char *pSrc = (const unsigned char *)src.c_str();
const int SRC_LEN = src.length();
unsigned char * const pStart = new unsigned char[SRC_LEN * 3];
unsigned char * pEnd = pStart;
const unsigned char * const SRC_END = pSrc + SRC_LEN;
for (; pSrc < SRC_END; ++pSrc)
{
if (SAFE[*pSrc])
*pEnd++ = *pSrc;
else
{
// escape this char
*pEnd++ = '%';
*pEnd++ = DEC2HEX[*pSrc >> 4];
*pEnd++ = DEC2HEX[*pSrc & 0x0F];
}
}
std::string sResult((char *)pStart, (char *)pEnd);
delete [] pStart;
return sResult;
}
std::string FileUtils::DecodeURIComponent(std::string src)
{
// Note from RFC1630: "Sequences which start with a percent
// sign but are not followed by two hexadecimal characters
// (0-9, A-F) are reserved for future extension"
const unsigned char * pSrc = (const unsigned char *)src.c_str();
const int SRC_LEN = src.length();
const unsigned char * const SRC_END = pSrc + SRC_LEN;
// last decodable '%'
const unsigned char * const SRC_LAST_DEC = SRC_END - 2;
char * const pStart = new char[SRC_LEN];
char * pEnd = pStart;
while (pSrc < SRC_LAST_DEC)
{
if (*pSrc == '%')
{
char dec1, dec2;
if (-1 != (dec1 = HEX2DEC[*(pSrc + 1)])
&& -1 != (dec2 = HEX2DEC[*(pSrc + 2)]))
{
*pEnd++ = (dec1 << 4) + dec2;
pSrc += 3;
continue;
}
}
*pEnd++ = *pSrc++;
}
// the last 2- chars
while (pSrc < SRC_END)
*pEnd++ = *pSrc++;
std::string sResult(pStart, pEnd);
delete [] pStart;
return sResult;
}
void FileUtils::Tokenize(const std::string& str, std::vector<std::string>& tokens, const std::string &delimeters)
{
std::string::size_type lastPos = str.find_first_not_of(delimeters,0);
std::string::size_type pos = str.find_first_of(delimeters,lastPos);
while (std::string::npos!=pos || std::string::npos!=lastPos)
{
tokens.push_back(str.substr(lastPos,pos-lastPos));
lastPos = str.find_first_not_of(delimeters,pos);
pos = str.find_first_of(delimeters,lastPos);
}
}
std::string FileUtils::Trim(std::string str)
{
std::string c(safe_encode(str));
while (1)
{
size_t pos = c.rfind(" ");
if (pos == std::string::npos || pos!=c.length()-1)
{
break;
}
c = c.substr(0,pos);
}
while(1)
{
size_t pos = c.find(" ");
if (pos != 0)
{
break;
}
c = c.substr(1);
}
return c;
}
bool FileUtils::ReadManifest(std::string& path, std::string &runtimePath, std::vector< std::pair< std::pair<std::string,std::string>, bool> >& modules, std::vector<std::string> &moduleDirs, std::string &appname, std::string &appid, std::string &runtimeOverride, std::string &guid)
{
std::ifstream file(path.c_str());
if (file.bad() || file.fail())
{
return false;
}
bool foundRuntime = false;
const char *rt = runtimeOverride.c_str();
#ifdef DEBUG
std::cout << "Read Manifest: " << rt << std::endl;
#endif
while (!file.eof())
{
std::string line;
std::getline(file,line);
if (line.find(" ")==0)
{
continue;
}
size_t pos = line.find(":");
if (pos!=std::string::npos)
{
std::string key = Trim(line.substr(0,pos));
std::string value = Trim(line.substr(pos+1,line.length()));
if (key == "#appname")
{
appname = value;
continue;
}
else if (key == "#appid")
{
appid = value;
continue;
}
else if (key == "#guid")
{
guid = value;
continue;
}
else if (key.c_str()[0]=='#')
{
continue;
}
int op;
std::string version;
ExtractVersion(value,&op,version);
#ifdef DEBUG
std::cout << "Component: " << key << ":" << version << ", operation: " << op << std::endl;
#endif
std::pair<std::string,std::string> p(key,version);
if (key == "runtime")
{
// check to see if our runtime is found in our override directory
if (!runtimeOverride.empty())
{
std::string potentialRuntime = Join(rt,"runtime",NULL);
if (IsDirectory(potentialRuntime))
{
// extra special check for Win32 since we have to place the WebKit.dll
// inside the same relative path as .exe because of the COM embedded manifest crap-o-la
// so if we can't find kroll.dll in the resources folder we don't override
#ifdef OS_WIN32
std::string krolldll = kroll::FileUtils::Join(potentialRuntime.c_str(),"kroll.dll",NULL);
if (kroll::FileUtils::IsFile(krolldll))
{
#endif
runtimePath = potentialRuntime;
#ifdef DEBUG
std::cout << "found override runtime at: " << runtimePath << std::endl;
#endif
foundRuntime = true;
continue;
#ifdef OS_WIN32
}
#endif
}
}
runtimePath = FindRuntime(op,version);
if (runtimePath == "") {
modules.push_back(std::pair< std::pair<std::string,std::string>, bool>(p,false));
}
foundRuntime = true; // so we don't add again
}
else
{
// check to see if our module is contained within our runtime override
// directory and if it is, use it...
std::string potentialModule = kroll::FileUtils::Join(rt,"modules",key.c_str(),NULL);
#ifdef DEBUG
std::cout << "looking for bundled module at " << potentialModule << std::endl;
#endif
if (IsDirectory(potentialModule))
{
modules.push_back(std::pair< std::pair<std::string,std::string>, bool>(p,true));
moduleDirs.push_back(potentialModule);
#ifdef DEBUG
std::cout << "found override module at: " << potentialModule << std::endl;
#endif
continue;
}
std::string dir = FindModule(key,op,version);
bool found = dir!="";
modules.push_back(std::pair< std::pair<std::string,std::string>, bool>(p,found));
if (found)
{
#ifdef DEBUG
std::cout << "found module at: " << dir << std::endl;
#endif
moduleDirs.push_back(dir);
}
#ifdef DEBUG
else
{
std::cerr << "couldn't find module module: " << key << "/" << version << std::endl;
}
#endif
}
}
}
// we gotta always have a runtime
if (!foundRuntime)
{
std::pair<std::string,std::string> p("runtime",STRING(PRODUCT_VERSION)); //TODO: huh, what do we use?
modules.push_back(std::pair< std::pair<std::string,std::string>, bool>(p,false));
}
file.close();
return true;
}
std::string FileUtils::FindRuntime(int op, std::string& version)
{
std::string runtime = GetRuntimeBaseDirectory();
std::string path(runtime);
#ifdef OS_WIN32
path += "\\runtime\\win32";
#elif OS_LINUX
path += "/runtime/linux";
#elif OS_OSX
path += "/runtime/osx";
#endif
return FindVersioned(path,op,version);
}
std::string FileUtils::FindModule(std::string& name, int op, std::string& version)
{
std::string runtime = GetRuntimeBaseDirectory();
std::string path(runtime);
#ifdef OS_WIN32
path += "\\modules\\win32\\";
#elif OS_LINUX
path += "/modules/linux/";
#elif OS_OSX
path += "/modules/osx/";
#endif
path += name;
return FindVersioned(path,op,version);
}
void FileUtils::ListDir(std::string& path, std::vector<std::string> &files)
{
#if defined(OS_WIN32)
WIN32_FIND_DATA findFileData;
std::string q(path+"\\*");
HANDLE hFind = FindFirstFile(q.c_str(), &findFileData);
if (hFind != INVALID_HANDLE_VALUE)
{
do
{
files.push_back(std::string(findFileData.cFileName));
} while (FindNextFile(hFind, &findFileData));
FindClose(hFind);
}
#else
DIR *dp;
struct dirent *dirp;
if ((dp = opendir(path.c_str()))!=NULL)
{
while ((dirp = readdir(dp))!=NULL)
{
std::string fn = std::string(dirp->d_name);
if (fn.substr(0,1)=="." || fn.substr(0,2)=="..")
{
continue;
}
files.push_back(fn);
}
closedir(dp);
}
#endif
}
int FileUtils::RunAndWait(std::string &path, std::vector<std::string> &args)
{
#ifndef OS_WIN32
std::string p;
p+="\"";
p+=path;
p+="\" ";
std::vector<std::string>::iterator i = args.begin();
while (i!=args.end())
{
p+="\"";
p+=(*i++);
p+="\" ";
}
#ifdef DEBUG
std::cout << "running: " << p << std::endl;
#endif
return system(p.c_str());
#elif defined(OS_WIN32)
std::ostringstream ostr;
ostr << path.c_str();
if (args.size() > 0 )
{
std::vector<std::string>::iterator i = args.begin();
int idx = 0;
while (i!=args.end())
{
// we need to quote each argument
ostr << " \"" << (*i++).c_str() << "\"";
}
}
DWORD rc=0;
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
char buf[MAX_PATH];
DWORD size = GetCurrentDirectory(MAX_PATH,(char*)buf);
buf[size]='\0';
if (!CreateProcess( NULL, // No module name (use command line)
(char*)ostr.str().c_str(), // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
(char*)buf, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi ) // Pointer to PROCESS_INFORMATION structure
)
{
rc = -1;
}
else
{
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
// set the exit code
GetExitCodeProcess(pi.hProcess,&rc);
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
return rc;
#endif
}
std::string FileUtils::GetUsername()
{
#ifdef OS_OSX
return std::string([NSUserName() UTF8String]);
#elif OS_WIN32
char buf[MAX_PATH];
DWORD size = MAX_PATH;
if (::GetUserName(buf,&size))
{
buf[size]='\0';
}
else
{
sprintf(buf,"Unknown");
}
return std::string(buf);
#elif OS_LINUX
return std::string(getlogin());
#endif
}
#ifndef NO_UNZIP
void FileUtils::Unzip(std::string& source, std::string& destination)
{
#ifdef OS_OSX
//
// we don't include gzip since we're on OSX
// we just let the built-in OS handle extraction for us
//
std::vector<std::string> args;
args.push_back("--noqtn");
args.push_back("-x");
args.push_back("-k");
args.push_back("--rsrc");
args.push_back(source);
args.push_back(destination);
std::string cmdline = "/usr/bin/ditto";
RunAndWait(cmdline,args);
#elif OS_LINUX
std::vector<std::string> args;
args.push_back("-qq");
args.push_back("-o");
args.push_back(source);
args.push_back("-d");
args.push_back(destination);
std::string cmdline("/usr/bin/unzip");
RunAndWait(cmdline,args);
#elif OS_WIN32
HZIP hz = OpenZip(source.c_str(),0);
SetUnzipBaseDir(hz,destination.c_str());
ZIPENTRY ze;
GetZipItem(hz,-1,&ze);
int numitems=ze.index;
for (int zi=0; zi < numitems; zi++)
{
GetZipItem(hz,zi,&ze);
UnzipItem(hz,zi,ze.name);
}
CloseZip(hz);
#endif
}
#endif
}
|
#include <gtest/gtest.h>
#include <string>
#include <thread>
#include <unordered_set>
#include <utility>
#include <asio/io_service.hpp>
#include <beam/message/capnproto.hpp>
#include <beam/message/capnproto.hxx>
#include <beam/duplex/unordered_mixed.hpp>
#include <beam/duplex/unordered_mixed.hxx>
#include <beam/duplex/unordered_mixed_test.capnp.h>
#include <turbo/container/spsc_ring_queue.hpp>
#include <turbo/container/spsc_ring_queue.hxx>
namespace bii4 = beam::internet::ipv4;
namespace bme = beam::message;
namespace bdc = beam::duplex::common;
namespace bdu = beam::duplex::unordered_mixed;
namespace {
static const uint32_t localhost = 16777343U;
class initiator_slave
{
public:
typedef bdu::in_connection<bdu::UnreliableMsg, bdu::ReliableMsg> in_connection_type;
typedef bdu::out_connection<bdu::UnreliableMsg, bdu::ReliableMsg> out_connection_type;
typedef bdu::initiator<in_connection_type, out_connection_type> initiator_type;
initiator_slave(bdc::endpoint_id id, bdu::perf_params&& params);
~initiator_slave();
inline bool is_running() const { return thread_ != nullptr; }
inline const bdc::endpoint_id& get_endpoint_id() const { return id_; }
void start();
void stop();
void send_unreliable(std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>> message);
void send_reliable(std::unique_ptr<bme::capnproto<bdu::ReliableMsg>> message);
private:
typedef turbo::container::spsc_ring_queue<std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>>> unreliable_queue_type;
typedef turbo::container::spsc_ring_queue<std::unique_ptr<bme::capnproto<bdu::ReliableMsg>>> reliable_queue_type;
initiator_slave() = delete;
initiator_slave(const initiator_slave& other) = delete;
initiator_slave& operator=(const initiator_slave& other) = delete;
void run();
void brake();
void on_send_unreliable(out_connection_type& connection);
void on_send_reliable(out_connection_type& connection);
void on_disconnect(const bii4::address&, const beam::duplex::common::port&);
bdc::endpoint_id id_;
std::thread* thread_;
asio::io_service service_;
asio::io_service::strand strand_;
initiator_type initiator_;
unreliable_queue_type unreliable_queue_;
reliable_queue_type reliable_queue_;
in_connection_type::event_handlers handlers_;
};
initiator_slave::initiator_slave(bdc::endpoint_id id, bdu::perf_params&& params) :
id_(id),
thread_(nullptr),
service_(),
strand_(service_),
initiator_(strand_, std::move(params)),
unreliable_queue_(128),
reliable_queue_(128),
handlers_(
{
[&](const in_connection_type::event_handlers&)
{
initiator_.async_receive(handlers_);
},
[&](const in_connection_type&)
{
initiator_.async_receive(handlers_);
},
[&](const in_connection_type&)
{
GTEST_FATAL_FAILURE_("Unexpected disconnect");
},
[&](const in_connection_type&, std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>>)
{
initiator_.async_receive(handlers_);
},
[&](const in_connection_type&, std::unique_ptr<bme::capnproto<bdu::ReliableMsg>>)
{
initiator_.async_receive(handlers_);
}
})
{ }
initiator_slave::~initiator_slave()
{
if (initiator_.is_connected() || !service_.stopped())
{
stop();
}
if (is_running())
{
thread_->join();
delete thread_;
thread_ = nullptr;
}
}
void initiator_slave::start()
{
if (!is_running())
{
std::function<void ()> entry(std::bind(&initiator_slave::run, this));
thread_ = new std::thread(entry);
}
}
void initiator_slave::stop()
{
service_.post(std::bind(&initiator_slave::brake, this));
}
void initiator_slave::send_unreliable(std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>> message)
{
ASSERT_EQ(unreliable_queue_type::producer::result::success, unreliable_queue_.get_producer().try_enqueue_move(std::move(message))) << "Unreliable message enqueue failed";
initiator_.async_send(std::bind(&initiator_slave::on_send_unreliable, this, std::placeholders::_1));
}
void initiator_slave::send_reliable(std::unique_ptr<bme::capnproto<bdu::ReliableMsg>> message)
{
ASSERT_EQ(reliable_queue_type::producer::result::success, reliable_queue_.get_producer().try_enqueue_move(std::move(message))) << "Reliable message enqueue failed";
initiator_.async_send(std::bind(&initiator_slave::on_send_reliable, this, std::placeholders::_1));
}
void initiator_slave::run()
{
ASSERT_EQ(bdu::connection_result::success, initiator_.connect({id_.address}, id_.port)) << "Connection failed";
initiator_.async_receive(handlers_);
service_.run();
}
void initiator_slave::brake()
{
if (initiator_.is_connected())
{
initiator_.disconnect();
}
service_.stop();
}
void initiator_slave::on_send_unreliable(out_connection_type& connection)
{
std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>> message;
ASSERT_EQ(unreliable_queue_type::consumer::result::success, unreliable_queue_.get_consumer().try_dequeue_move(message)) << "Unreliable message dequeue failed";
connection.send_unreliable(*message);
}
void initiator_slave::on_send_reliable(out_connection_type& connection)
{
std::unique_ptr<bme::capnproto<bdu::ReliableMsg>> message;
ASSERT_EQ(reliable_queue_type::consumer::result::success, reliable_queue_.get_consumer().try_dequeue_move(message)) << "Reliable message dequeue failed";
connection.send_reliable(*message);
}
void initiator_slave::on_disconnect(const bii4::address&, const beam::duplex::common::port&)
{
GTEST_FATAL_FAILURE_("Unexpected disconnect");
}
struct responder_master
{
typedef bdu::in_connection<bdu::UnreliableMsg, bdu::ReliableMsg> in_connection_type;
typedef bdu::out_connection<bdu::UnreliableMsg, bdu::ReliableMsg> out_connection_type;
typedef bdu::responder<in_connection_type, out_connection_type> responder_type;
responder_master(bdc::endpoint_id&& point, bdu::perf_params&& params);
~responder_master();
void bind(bdc::endpoint_id&& point);
asio::io_service service;
asio::io_service::strand strand;
responder_type responder;
};
responder_master::responder_master(bdc::endpoint_id&& point, bdu::perf_params&& params) :
service(),
strand(service),
responder(strand, std::move(params))
{
bind(std::move(point));
}
responder_master::~responder_master()
{
if (!service.stopped())
{
service.stop();
}
}
void responder_master::bind(bdc::endpoint_id&& point)
{
ASSERT_EQ(bdu::bind_result::success, responder.bind(point)) << "Bind failed";
}
void setupConnection(::responder_master& master, ::initiator_slave& slave)
{
std::size_t connection_count = 0;
while (connection_count == 0)
{
master.responder.async_receive(
{
[&](const ::responder_master::in_connection_type::event_handlers& current)
{
slave.start();
master.responder.async_receive(current);
},
[&](const ::responder_master::in_connection_type&)
{
++connection_count;
},
[&](const ::responder_master::in_connection_type&)
{
GTEST_FATAL_FAILURE_("Unexpected disconnect");
},
[&](const ::responder_master::in_connection_type&, std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>>)
{
GTEST_FATAL_FAILURE_("Unexpected unreliable message");
},
[&](const ::responder_master::in_connection_type&, std::unique_ptr<bme::capnproto<bdu::ReliableMsg>>)
{
GTEST_FATAL_FAILURE_("Unexpected reliable message");
}
});
master.service.run();
}
master.service.reset();
}
} // anonymous namespace
TEST(unordered_mixed_test, basic_unreliable)
{
::responder_master master({0U, 8888U}, {24U});
::initiator_slave slave({::localhost, 8888U}, {24U});
setupConnection(master, slave);
std::size_t unreliable_count = 0;
while (unreliable_count == 0)
{
master.responder.async_receive(
{
[&](const ::responder_master::in_connection_type::event_handlers& current)
{
std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>> message(new bme::capnproto<bdu::UnreliableMsg>());
bdu::UnreliableMsg::Builder builder = message->get_builder();
builder.setValue(123U);
slave.send_unreliable(std::move(message));
master.responder.async_receive(current);
},
[&](const ::responder_master::in_connection_type&)
{
GTEST_FATAL_FAILURE_("Unexpected connect");
},
[&](const ::responder_master::in_connection_type&)
{
GTEST_FATAL_FAILURE_("Unexpected disconnect");
},
[&](const ::responder_master::in_connection_type&, std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>> message)
{
ASSERT_EQ(123U, message->get_reader().getValue()) << "Incorrect message value";
++unreliable_count;
},
[&](const ::responder_master::in_connection_type&, std::unique_ptr<bme::capnproto<bdu::ReliableMsg>>)
{
GTEST_FATAL_FAILURE_("Unexpected reliable message");
}
});
master.service.run();
};
slave.stop();
}
TEST(unordered_mixed_test, basic_reliable)
{
::responder_master master({0U, 8888U}, {24U});
::initiator_slave slave({::localhost, 8888U}, {24U});
setupConnection(master, slave);
std::unique_ptr<bme::capnproto<bdu::ReliableMsg>> message(new bme::capnproto<bdu::ReliableMsg>());
bdu::ReliableMsg::Builder builder = message->get_builder();
builder.setValue("foo");
slave.send_reliable(std::move(message));
std::size_t reliable_count = 0;
while (reliable_count == 0)
{
master.responder.async_receive(
{
[&](const ::responder_master::in_connection_type::event_handlers& current)
{
master.responder.async_receive(current);
},
[&](const ::responder_master::in_connection_type&)
{
GTEST_FATAL_FAILURE_("Unexpected connect");
},
[&](const ::responder_master::in_connection_type&)
{
GTEST_FATAL_FAILURE_("Unexpected disconnect");
},
[&](const ::responder_master::in_connection_type&, std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>>)
{
GTEST_FATAL_FAILURE_("Unexpected unreliable message");
},
[&](const ::responder_master::in_connection_type&, std::unique_ptr<bme::capnproto<bdu::ReliableMsg>> message)
{
ASSERT_STREQ("foo", message->get_reader().getValue().cStr()) << "Incorrect message value";
++reliable_count;
}
});
master.service.run();
master.service.reset();
};
slave.stop();
}
adding basic_initiated_mixed and basic_responded_mixed test cases
#include <gtest/gtest.h>
#include <string>
#include <thread>
#include <unordered_set>
#include <utility>
#include <asio/io_service.hpp>
#include <beam/message/capnproto.hpp>
#include <beam/message/capnproto.hxx>
#include <beam/duplex/unordered_mixed.hpp>
#include <beam/duplex/unordered_mixed.hxx>
#include <beam/duplex/unordered_mixed_test.capnp.h>
#include <turbo/container/spsc_ring_queue.hpp>
#include <turbo/container/spsc_ring_queue.hxx>
namespace bii4 = beam::internet::ipv4;
namespace bme = beam::message;
namespace bdc = beam::duplex::common;
namespace bdu = beam::duplex::unordered_mixed;
namespace {
static const uint32_t localhost = 16777343U;
class initiator_slave
{
public:
typedef bdu::in_connection<bdu::UnreliableMsg, bdu::ReliableMsg> in_connection_type;
typedef bdu::out_connection<bdu::UnreliableMsg, bdu::ReliableMsg> out_connection_type;
typedef bdu::initiator<in_connection_type, out_connection_type> initiator_type;
initiator_slave(bdc::endpoint_id id, bdu::perf_params&& params);
~initiator_slave();
inline bool is_running() const { return thread_ != nullptr; }
void start();
void stop();
void send_unreliable(std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>> message);
void send_reliable(std::unique_ptr<bme::capnproto<bdu::ReliableMsg>> message);
private:
typedef turbo::container::spsc_ring_queue<std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>>> unreliable_queue_type;
typedef turbo::container::spsc_ring_queue<std::unique_ptr<bme::capnproto<bdu::ReliableMsg>>> reliable_queue_type;
initiator_slave() = delete;
initiator_slave(const initiator_slave& other) = delete;
initiator_slave& operator=(const initiator_slave& other) = delete;
void run();
void brake();
void on_send_unreliable(out_connection_type& connection);
void on_send_reliable(out_connection_type& connection);
void on_disconnect(const bii4::address&, const beam::duplex::common::port&);
bdc::endpoint_id id_;
std::thread* thread_;
asio::io_service service_;
asio::io_service::strand strand_;
initiator_type initiator_;
unreliable_queue_type unreliable_queue_;
reliable_queue_type reliable_queue_;
in_connection_type::event_handlers handlers_;
};
initiator_slave::initiator_slave(bdc::endpoint_id id, bdu::perf_params&& params) :
id_(id),
thread_(nullptr),
service_(),
strand_(service_),
initiator_(strand_, std::move(params)),
unreliable_queue_(128),
reliable_queue_(128),
handlers_(
{
[&](const in_connection_type::event_handlers&)
{
initiator_.async_receive(handlers_);
},
[&](const in_connection_type&)
{
initiator_.async_receive(handlers_);
},
[&](const in_connection_type&)
{
GTEST_FATAL_FAILURE_("Unexpected disconnect");
},
[&](const in_connection_type&, std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>>)
{
initiator_.async_receive(handlers_);
},
[&](const in_connection_type&, std::unique_ptr<bme::capnproto<bdu::ReliableMsg>>)
{
initiator_.async_receive(handlers_);
}
})
{ }
initiator_slave::~initiator_slave()
{
if (initiator_.is_connected() || !service_.stopped())
{
stop();
}
if (is_running())
{
thread_->join();
delete thread_;
thread_ = nullptr;
}
}
void initiator_slave::start()
{
if (!is_running())
{
std::function<void ()> entry(std::bind(&initiator_slave::run, this));
thread_ = new std::thread(entry);
}
}
void initiator_slave::stop()
{
service_.post(std::bind(&initiator_slave::brake, this));
}
void initiator_slave::send_unreliable(std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>> message)
{
ASSERT_EQ(unreliable_queue_type::producer::result::success, unreliable_queue_.get_producer().try_enqueue_move(std::move(message))) << "Unreliable message enqueue failed";
initiator_.async_send(std::bind(&initiator_slave::on_send_unreliable, this, std::placeholders::_1));
}
void initiator_slave::send_reliable(std::unique_ptr<bme::capnproto<bdu::ReliableMsg>> message)
{
ASSERT_EQ(reliable_queue_type::producer::result::success, reliable_queue_.get_producer().try_enqueue_move(std::move(message))) << "Reliable message enqueue failed";
initiator_.async_send(std::bind(&initiator_slave::on_send_reliable, this, std::placeholders::_1));
}
void initiator_slave::run()
{
ASSERT_EQ(bdu::connection_result::success, initiator_.connect({id_.address}, id_.port)) << "Connection failed";
initiator_.async_receive(handlers_);
service_.run();
}
void initiator_slave::brake()
{
if (initiator_.is_connected())
{
initiator_.disconnect();
}
service_.stop();
}
void initiator_slave::on_send_unreliable(out_connection_type& connection)
{
std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>> message;
ASSERT_EQ(unreliable_queue_type::consumer::result::success, unreliable_queue_.get_consumer().try_dequeue_move(message)) << "Unreliable message dequeue failed";
connection.send_unreliable(*message);
}
void initiator_slave::on_send_reliable(out_connection_type& connection)
{
std::unique_ptr<bme::capnproto<bdu::ReliableMsg>> message;
ASSERT_EQ(reliable_queue_type::consumer::result::success, reliable_queue_.get_consumer().try_dequeue_move(message)) << "Reliable message dequeue failed";
connection.send_reliable(*message);
}
void initiator_slave::on_disconnect(const bii4::address&, const beam::duplex::common::port&)
{
GTEST_FATAL_FAILURE_("Unexpected disconnect");
}
struct responder_master
{
typedef bdu::in_connection<bdu::UnreliableMsg, bdu::ReliableMsg> in_connection_type;
typedef bdu::out_connection<bdu::UnreliableMsg, bdu::ReliableMsg> out_connection_type;
typedef bdu::responder<in_connection_type, out_connection_type> responder_type;
responder_master(bdc::endpoint_id&& point, bdu::perf_params&& params);
~responder_master();
void bind(bdc::endpoint_id&& point);
asio::io_service service;
asio::io_service::strand strand;
responder_type responder;
};
responder_master::responder_master(bdc::endpoint_id&& point, bdu::perf_params&& params) :
service(),
strand(service),
responder(strand, std::move(params))
{
bind(std::move(point));
}
responder_master::~responder_master()
{
if (!service.stopped())
{
service.stop();
}
}
void responder_master::bind(bdc::endpoint_id&& point)
{
ASSERT_EQ(bdu::bind_result::success, responder.bind(point)) << "Bind failed";
}
void setupConnection(::responder_master& master, ::initiator_slave& slave)
{
std::size_t connection_count = 0;
while (connection_count == 0)
{
master.responder.async_receive(
{
[&](const ::responder_master::in_connection_type::event_handlers& current)
{
slave.start();
master.responder.async_receive(current);
},
[&](const ::responder_master::in_connection_type&)
{
++connection_count;
},
[&](const ::responder_master::in_connection_type&)
{
GTEST_FATAL_FAILURE_("Unexpected disconnect");
},
[&](const ::responder_master::in_connection_type&, std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>>)
{
GTEST_FATAL_FAILURE_("Unexpected unreliable message");
},
[&](const ::responder_master::in_connection_type&, std::unique_ptr<bme::capnproto<bdu::ReliableMsg>>)
{
GTEST_FATAL_FAILURE_("Unexpected reliable message");
}
});
master.service.run();
}
master.service.reset();
}
} // anonymous namespace
TEST(unordered_mixed_test, basic_initiated_unreliable)
{
::responder_master master({0U, 8888U}, {24U});
::initiator_slave slave({::localhost, 8888U}, {24U});
setupConnection(master, slave);
std::size_t unreliable_count = 0;
while (unreliable_count == 0)
{
master.responder.async_receive(
{
[&](const ::responder_master::in_connection_type::event_handlers& current)
{
std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>> message(new bme::capnproto<bdu::UnreliableMsg>());
bdu::UnreliableMsg::Builder builder = message->get_builder();
builder.setValue(123U);
slave.send_unreliable(std::move(message));
master.responder.async_receive(current);
},
[&](const ::responder_master::in_connection_type&)
{
GTEST_FATAL_FAILURE_("Unexpected connect");
},
[&](const ::responder_master::in_connection_type&)
{
GTEST_FATAL_FAILURE_("Unexpected disconnect");
},
[&](const ::responder_master::in_connection_type&, std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>> message)
{
ASSERT_EQ(123U, message->get_reader().getValue()) << "Incorrect message value";
++unreliable_count;
},
[&](const ::responder_master::in_connection_type&, std::unique_ptr<bme::capnproto<bdu::ReliableMsg>>)
{
GTEST_FATAL_FAILURE_("Unexpected reliable message");
}
});
master.service.run();
};
slave.stop();
}
TEST(unordered_mixed_test, basic_initiated_reliable)
{
::responder_master master({0U, 8888U}, {24U});
::initiator_slave slave({::localhost, 8888U}, {24U});
setupConnection(master, slave);
std::unique_ptr<bme::capnproto<bdu::ReliableMsg>> message(new bme::capnproto<bdu::ReliableMsg>());
bdu::ReliableMsg::Builder builder = message->get_builder();
builder.setValue("foo");
slave.send_reliable(std::move(message));
std::size_t reliable_count = 0;
while (reliable_count == 0)
{
master.responder.async_receive(
{
[&](const ::responder_master::in_connection_type::event_handlers& current)
{
master.responder.async_receive(current);
},
[&](const ::responder_master::in_connection_type&)
{
GTEST_FATAL_FAILURE_("Unexpected connect");
},
[&](const ::responder_master::in_connection_type&)
{
GTEST_FATAL_FAILURE_("Unexpected disconnect");
},
[&](const ::responder_master::in_connection_type&, std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>>)
{
GTEST_FATAL_FAILURE_("Unexpected unreliable message");
},
[&](const ::responder_master::in_connection_type&, std::unique_ptr<bme::capnproto<bdu::ReliableMsg>> message)
{
ASSERT_STREQ("foo", message->get_reader().getValue().cStr()) << "Incorrect message value";
++reliable_count;
}
});
master.service.run();
master.service.reset();
};
slave.stop();
}
TEST(unordered_mixed_test, basic_initiated_mixed)
{
::responder_master master({0U, 8888U}, {24U});
::initiator_slave slave({::localhost, 8888U}, {24U});
setupConnection(master, slave);
std::unique_ptr<bme::capnproto<bdu::ReliableMsg>> message1(new bme::capnproto<bdu::ReliableMsg>());
bdu::ReliableMsg::Builder builder1 = message1->get_builder();
builder1.setValue("bar");
slave.send_reliable(std::move(message1));
std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>> message2(new bme::capnproto<bdu::UnreliableMsg>());
bdu::UnreliableMsg::Builder builder2 = message2->get_builder();
builder2.setValue(999U);
slave.send_unreliable(std::move(message2));
std::size_t reliable_count = 0;
std::size_t unreliable_count = 0;
while (reliable_count == 0 || unreliable_count == 0)
{
master.responder.async_receive(
{
[&](const ::responder_master::in_connection_type::event_handlers& current)
{
master.responder.async_receive(current);
},
[&](const ::responder_master::in_connection_type&)
{
GTEST_FATAL_FAILURE_("Unexpected connect");
},
[&](const ::responder_master::in_connection_type&)
{
GTEST_FATAL_FAILURE_("Unexpected disconnect");
},
[&](const ::responder_master::in_connection_type&, std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>> message)
{
ASSERT_EQ(999U, message->get_reader().getValue()) << "Incorrect unreliable message value";
++unreliable_count;
},
[&](const ::responder_master::in_connection_type&, std::unique_ptr<bme::capnproto<bdu::ReliableMsg>> message)
{
ASSERT_STREQ("bar", message->get_reader().getValue().cStr()) << "Incorrect reliable message value";
++reliable_count;
}
});
master.service.run();
master.service.reset();
};
slave.stop();
}
namespace {
struct initiator_master
{
typedef turbo::container::spsc_ring_queue<std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>>> unreliable_queue_type;
typedef turbo::container::spsc_ring_queue<std::unique_ptr<bme::capnproto<bdu::ReliableMsg>>> reliable_queue_type;
typedef bdu::in_connection<bdu::UnreliableMsg, bdu::ReliableMsg> in_connection_type;
typedef bdu::out_connection<bdu::UnreliableMsg, bdu::ReliableMsg> out_connection_type;
typedef bdu::initiator<in_connection_type, out_connection_type> initiator_type;
initiator_master(bdc::endpoint_id&& point, bdu::perf_params&& params);
~initiator_master();
void connect();
void send_unreliable(std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>> message);
void send_reliable(std::unique_ptr<bme::capnproto<bdu::ReliableMsg>> message);
void on_send_unreliable(out_connection_type& connection);
void on_send_reliable(out_connection_type& connection);
asio::io_service service;
asio::io_service::strand strand;
initiator_type initiator;
unreliable_queue_type unreliable_queue_;
reliable_queue_type reliable_queue_;
bdc::endpoint_id id;
};
initiator_master::initiator_master(bdc::endpoint_id&& point, bdu::perf_params&& params) :
service(),
strand(service),
initiator(strand, std::move(params)),
unreliable_queue_(128),
reliable_queue_(128),
id(std::move(point))
{ }
initiator_master::~initiator_master()
{
if (!service.stopped())
{
service.stop();
}
}
void initiator_master::connect()
{
ASSERT_EQ(bdu::connection_result::success, initiator.connect({id.address}, id.port)) << "Connection failed";
}
void initiator_master::send_unreliable(std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>> message)
{
ASSERT_EQ(unreliable_queue_type::producer::result::success, unreliable_queue_.get_producer().try_enqueue_move(std::move(message))) << "Unreliable message enqueue failed";
initiator.async_send(std::bind(&initiator_master::on_send_unreliable, this, std::placeholders::_1));
}
void initiator_master::send_reliable(std::unique_ptr<bme::capnproto<bdu::ReliableMsg>> message)
{
ASSERT_EQ(reliable_queue_type::producer::result::success, reliable_queue_.get_producer().try_enqueue_move(std::move(message))) << "Reliable message enqueue failed";
initiator.async_send(std::bind(&initiator_master::on_send_reliable, this, std::placeholders::_1));
}
void initiator_master::on_send_unreliable(out_connection_type& connection)
{
std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>> message;
ASSERT_EQ(unreliable_queue_type::consumer::result::success, unreliable_queue_.get_consumer().try_dequeue_move(message)) << "Unreliable message dequeue failed";
connection.send_unreliable(*message);
}
void initiator_master::on_send_reliable(out_connection_type& connection)
{
std::unique_ptr<bme::capnproto<bdu::ReliableMsg>> message;
ASSERT_EQ(reliable_queue_type::consumer::result::success, reliable_queue_.get_consumer().try_dequeue_move(message)) << "Reliable message dequeue failed";
connection.send_reliable(*message);
}
class responder_slave
{
public:
typedef turbo::container::spsc_ring_queue<std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>>> unreliable_queue_type;
typedef turbo::container::spsc_ring_queue<std::unique_ptr<bme::capnproto<bdu::ReliableMsg>>> reliable_queue_type;
typedef bdu::in_connection<bdu::UnreliableMsg, bdu::ReliableMsg> in_connection_type;
typedef bdu::out_connection<bdu::UnreliableMsg, bdu::ReliableMsg> out_connection_type;
typedef bdu::responder<in_connection_type, out_connection_type> responder_type;
responder_slave(bdc::endpoint_id id, bdu::perf_params&& params);
~responder_slave();
inline bool is_running() const { return thread_ != nullptr; }
void start();
void stop();
void send_unreliable(const bdc::endpoint_id& id, std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>> message);
void send_reliable(const bdc::endpoint_id& id, std::unique_ptr<bme::capnproto<bdu::ReliableMsg>> message);
private:
responder_slave() = delete;
responder_slave(const responder_slave& other) = delete;
responder_slave& operator=(const responder_slave& other) = delete;
void run();
void brake();
void on_send_unreliable(out_connection_type& connection);
void on_send_reliable(out_connection_type& connection);
bdc::endpoint_id id_;
std::thread* thread_;
asio::io_service service_;
asio::io_service::strand strand_;
responder_type responder_;
unreliable_queue_type unreliable_queue_;
reliable_queue_type reliable_queue_;
in_connection_type::event_handlers handlers_;
};
responder_slave::responder_slave(bdc::endpoint_id id, bdu::perf_params&& params) :
id_(id),
thread_(nullptr),
service_(),
strand_(service_),
responder_(strand_, std::move(params)),
unreliable_queue_(128),
reliable_queue_(128),
handlers_(
{
[&](const ::responder_slave::in_connection_type::event_handlers&)
{
responder_.async_receive(handlers_);
},
[&](const ::responder_slave::in_connection_type&)
{
responder_.async_receive(handlers_);
},
[&](const ::responder_slave::in_connection_type&)
{
responder_.async_receive(handlers_);
},
[&](const ::responder_slave::in_connection_type& in, std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>> request)
{
std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>> reply(new bme::capnproto<bdu::UnreliableMsg>());
bdu::UnreliableMsg::Builder builder = reply->get_builder();
builder.setValue(request->get_reader().getValue() + 10U);
send_unreliable(in.get_endpoint_id(), std::move(reply));
responder_.async_receive(handlers_);
},
[&](const ::responder_slave::in_connection_type& in, std::unique_ptr<bme::capnproto<bdu::ReliableMsg>> request)
{
std::unique_ptr<bme::capnproto<bdu::ReliableMsg>> reply(new bme::capnproto<bdu::ReliableMsg>());
bdu::ReliableMsg::Builder builder = reply->get_builder();
std::string tmp(request->get_reader().getValue());
builder.setValue(tmp.append("bar").c_str());
send_reliable(in.get_endpoint_id(), std::move(reply));
responder_.async_receive(handlers_);
}
})
{ }
responder_slave::~responder_slave()
{
if (responder_.is_bound() || !service_.stopped())
{
stop();
}
if (is_running())
{
thread_->join();
delete thread_;
thread_ = nullptr;
}
}
void responder_slave::start()
{
if (!is_running())
{
std::function<void ()> entry(std::bind(&responder_slave::run, this));
thread_ = new std::thread(entry);
}
}
void responder_slave::stop()
{
service_.post(std::bind(&responder_slave::brake, this));
}
void responder_slave::send_unreliable(const bdc::endpoint_id& id, std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>> message)
{
ASSERT_EQ(unreliable_queue_type::producer::result::success, unreliable_queue_.get_producer().try_enqueue_move(std::move(message))) << "Unreliable message enqueue failed";
responder_.async_send(id, std::bind(&responder_slave::on_send_unreliable, this, std::placeholders::_1));
}
void responder_slave::send_reliable(const bdc::endpoint_id& id, std::unique_ptr<bme::capnproto<bdu::ReliableMsg>> message)
{
ASSERT_EQ(reliable_queue_type::producer::result::success, reliable_queue_.get_producer().try_enqueue_move(std::move(message))) << "Reliable message enqueue failed";
responder_.async_send(id, std::bind(&responder_slave::on_send_reliable, this, std::placeholders::_1));
}
void responder_slave::run()
{
ASSERT_EQ(bdu::bind_result::success, responder_.bind(id_)) << "Bind failed";
responder_.async_receive(handlers_);
service_.run();
}
void responder_slave::brake()
{
if (responder_.is_bound())
{
responder_.unbind();
}
service_.stop();
}
void responder_slave::on_send_unreliable(out_connection_type& connection)
{
std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>> message;
ASSERT_EQ(unreliable_queue_type::consumer::result::success, unreliable_queue_.get_consumer().try_dequeue_move(message)) << "Unreliable message dequeue failed";
connection.send_unreliable(*message);
}
void responder_slave::on_send_reliable(out_connection_type& connection)
{
std::unique_ptr<bme::capnproto<bdu::ReliableMsg>> message;
ASSERT_EQ(reliable_queue_type::consumer::result::success, reliable_queue_.get_consumer().try_dequeue_move(message)) << "Reliable message dequeue failed";
connection.send_reliable(*message);
}
void setupConnection(::initiator_master& master, ::responder_slave& slave)
{
slave.start();
master.initiator.async_receive(
{
[&](const ::initiator_master::in_connection_type::event_handlers& current)
{
if (!master.initiator.is_connected())
{
master.initiator.connect({master.id.address}, master.id.port);
master.initiator.async_receive(current);
}
},
[&](const ::initiator_master::in_connection_type&)
{
},
[&](const ::initiator_master::in_connection_type&)
{
GTEST_FATAL_FAILURE_("Unexpected disconnect");
},
[&](const ::initiator_master::in_connection_type&, std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>>)
{
GTEST_FATAL_FAILURE_("Unexpected unreliable message");
},
[&](const ::initiator_master::in_connection_type&, std::unique_ptr<bme::capnproto<bdu::ReliableMsg>>)
{
GTEST_FATAL_FAILURE_("Unexpected reliable message");
}
});
master.service.run();
master.service.reset();
}
} // anonymous namespace
TEST(unordered_mixed_test, basic_responded_mixed)
{
::initiator_master master({::localhost, 8888U}, {24U, std::chrono::milliseconds(5)});
::responder_slave slave({0U, 8888U}, {24U});
setupConnection(master, slave);
std::size_t reliable_count = 0;
std::size_t unreliable_count = 0;
while (reliable_count == 0 || unreliable_count == 0)
{
master.initiator.async_receive(
{
[&](const ::initiator_master::in_connection_type::event_handlers& current)
{
std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>> message1(new bme::capnproto<bdu::UnreliableMsg>());
bdu::UnreliableMsg::Builder builder1 = message1->get_builder();
builder1.setValue(27U);
master.send_unreliable(std::move(message1));
std::unique_ptr<bme::capnproto<bdu::ReliableMsg>> message2(new bme::capnproto<bdu::ReliableMsg>());
bdu::ReliableMsg::Builder builder2 = message2->get_builder();
builder2.setValue("foo");
master.send_reliable(std::move(message2));
master.initiator.async_receive(current);
},
[&](const ::initiator_master::in_connection_type&)
{
GTEST_FATAL_FAILURE_("Unexpected connect");
},
[&](const ::initiator_master::in_connection_type&)
{
GTEST_FATAL_FAILURE_("Unexpected disconnect");
},
[&](const ::responder_master::in_connection_type&, std::unique_ptr<bme::capnproto<bdu::UnreliableMsg>> message)
{
ASSERT_EQ(37U, message->get_reader().getValue()) << "Incorrect unreliable message value";
++unreliable_count;
},
[&](const ::responder_master::in_connection_type&, std::unique_ptr<bme::capnproto<bdu::ReliableMsg>> message)
{
ASSERT_STREQ("foobar", message->get_reader().getValue().cStr()) << "Incorrect reliable message value";
++reliable_count;
}
});
master.service.run();
master.service.reset();
};
slave.stop();
}
|
/* This file is part of Zanshin
Copyright 2014 Kevin Ottens <ervin@kde.org>
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) version 3 or any later version
accepted by the membership of KDE e.V. (or its successor approved
by the membership of KDE e.V.), which shall act as a proxy
defined in Section 14 of version 3 of the license.
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 "akonadidatasourcerepository.h"
#include "akonadiserializer.h"
#include "akonadistorage.h"
#include <QMenu>
#include <Akonadi/Calendar/StandardCalendarActionManager>
#include <Akonadi/EntityTreeModel>
#include <KActionCollection>
#include <KAction>
#include <KLocalizedString>
#include <QWidget>
#include <QStandardItemModel>
#include <QItemSelectionModel>
#include <KCalCore/Todo>
#include <akonadi/notes/noteutils.h>
#include <akonadi/collectionpropertiesdialog.h>
#include <akonadi/attributefactory.h>
#include <pimcommon/acl/collectionaclpage.h>
#include <pimcommon/acl/imapaclattribute.h>
using namespace Akonadi;
DataSourceRepository::DataSourceRepository(QObject *parent)
: QObject(parent),
m_storage(new Storage),
m_serializer(new Serializer),
m_ownInterfaces(true)
{
}
DataSourceRepository::DataSourceRepository(StorageInterface *storage, SerializerInterface *serializer)
: m_storage(storage),
m_serializer(serializer),
m_ownInterfaces(false)
{
}
DataSourceRepository::~DataSourceRepository()
{
if (m_ownInterfaces) {
delete m_storage;
delete m_serializer;
}
}
KJob *DataSourceRepository::update(Domain::DataSource::Ptr source)
{
auto collection = m_serializer->createCollectionFromDataSource(source);
Q_ASSERT(collection.isValid());
return m_storage->updateCollection(collection);
}
void DataSourceRepository::configure(QMenu *menu , Domain::DataSource::Ptr selectedSource)
{
{
static bool pageRegistered = false;
if (!pageRegistered) {
kDebug() << "registering pages";
Akonadi::AttributeFactory::registerAttribute<PimCommon::ImapAclAttribute>();
// Akonadi::CollectionPropertiesDialog::registerPage(new CalendarSupport::CollectionGeneralPageFactory);
Akonadi::CollectionPropertiesDialog::registerPage(new PimCommon::CollectionAclPageFactory);
pageRegistered = true;
}
}
if (menu->isEmpty()) {
//We bind the lifetime of all actions to the menu and simply recreate the menu everytime.
QObject *parent = menu;
//This can could be used to provide a parent widget for the created dialogs
QWidget *parentWidget = 0;
static auto actionCollection = new KActionCollection(0, KComponentData());
//We can't delete the actionmanager because it's the parent of running jobs
static Akonadi::StandardCalendarActionManager *mActionManager = 0;
if (!mActionManager) {
mActionManager = new Akonadi::StandardCalendarActionManager(actionCollection, parentWidget);
QList<Akonadi::StandardActionManager::Type> standardActions;
standardActions << Akonadi::StandardActionManager::CreateCollection
<< Akonadi::StandardActionManager::DeleteCollections
<< Akonadi::StandardActionManager::SynchronizeCollections
<< Akonadi::StandardActionManager::CollectionProperties;
Q_FOREACH(Akonadi::StandardActionManager::Type standardAction, standardActions) {
mActionManager->createAction(standardAction);
}
const QStringList pages = QStringList() << QLatin1String("CalendarSupport::CollectionGeneralPage")
<< QLatin1String("Akonadi::CachePolicyPage")
<< QLatin1String("PimCommon::CollectionAclPage");
mActionManager->setCollectionPropertiesPageNames(pages);
}
const auto collection = m_serializer->createCollectionFromDataSource(selectedSource);
//FIXME set appropriate mimetypes based on selected source
if (m_serializer->isTaskCollection(collection)) {
mActionManager->setActionText(Akonadi::StandardActionManager::CreateCollection, ki18n("Add Task Folder"));
mActionManager->setActionText(Akonadi::StandardActionManager::DeleteCollections, ki18n("Delete Task Folder"));
mActionManager->setActionText(Akonadi::StandardActionManager::SynchronizeCollections, ki18n("Update Folder"));
mActionManager->setContextText(Akonadi::StandardActionManager::CollectionProperties,
Akonadi::StandardActionManager::DialogTitle,
tr("@title:window", "Properties of Task Folder %1"));
mActionManager->action(Akonadi::StandardActionManager::CreateCollection )->setProperty("ContentMimeTypes",
QStringList() << Akonadi::Collection::mimeType() << KCalCore::Todo::todoMimeType());
} else if (m_serializer->isNoteCollection(collection)) {
mActionManager->setActionText(Akonadi::StandardActionManager::CreateCollection, ki18n("Add Note Folder"));
mActionManager->setActionText(Akonadi::StandardActionManager::DeleteCollections, ki18n("Delete Note Folder"));
mActionManager->setActionText(Akonadi::StandardActionManager::SynchronizeCollections, ki18n("Update Folder"));
mActionManager->setContextText(Akonadi::StandardActionManager::CollectionProperties,
Akonadi::StandardActionManager::DialogTitle,
tr("@title:window", "Properties of Note Folder %1"));
mActionManager->action(Akonadi::StandardActionManager::CreateCollection )->setProperty("ContentMimeTypes",
QStringList() << Akonadi::Collection::mimeType() << Akonadi::NoteUtils::noteMimeType());
}
menu->addActions(actionCollection->actions());
//Since we have no ETM based selection model we simply emulate one to tell the actionmanager about the current collection
auto itemModel = new QStandardItemModel(parent);
auto selectionModel = new QItemSelectionModel(itemModel);
auto item = new QStandardItem();
item->setData(QVariant::fromValue(collection), Akonadi::EntityTreeModel::CollectionRole);
itemModel->setItem(0, 0, item);
mActionManager->setCollectionSelectionModel(selectionModel);
selectionModel->setCurrentIndex(itemModel->index(0, 0, QModelIndex()), QItemSelectionModel::SelectCurrent);
} else {
//update actions according to selected datasource
//TODO currently we always recreate all actions and menues
}
}
Set collectionmodel before updating actions.
This fixes a crash when calling the context-menu the second time.
/* This file is part of Zanshin
Copyright 2014 Kevin Ottens <ervin@kde.org>
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) version 3 or any later version
accepted by the membership of KDE e.V. (or its successor approved
by the membership of KDE e.V.), which shall act as a proxy
defined in Section 14 of version 3 of the license.
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 "akonadidatasourcerepository.h"
#include "akonadiserializer.h"
#include "akonadistorage.h"
#include <QMenu>
#include <Akonadi/Calendar/StandardCalendarActionManager>
#include <Akonadi/EntityTreeModel>
#include <KActionCollection>
#include <KAction>
#include <KLocalizedString>
#include <QWidget>
#include <QStandardItemModel>
#include <QItemSelectionModel>
#include <KCalCore/Todo>
#include <akonadi/notes/noteutils.h>
#include <akonadi/collectionpropertiesdialog.h>
#include <akonadi/attributefactory.h>
#include <pimcommon/acl/collectionaclpage.h>
#include <pimcommon/acl/imapaclattribute.h>
using namespace Akonadi;
DataSourceRepository::DataSourceRepository(QObject *parent)
: QObject(parent),
m_storage(new Storage),
m_serializer(new Serializer),
m_ownInterfaces(true)
{
}
DataSourceRepository::DataSourceRepository(StorageInterface *storage, SerializerInterface *serializer)
: m_storage(storage),
m_serializer(serializer),
m_ownInterfaces(false)
{
}
DataSourceRepository::~DataSourceRepository()
{
if (m_ownInterfaces) {
delete m_storage;
delete m_serializer;
}
}
KJob *DataSourceRepository::update(Domain::DataSource::Ptr source)
{
auto collection = m_serializer->createCollectionFromDataSource(source);
Q_ASSERT(collection.isValid());
return m_storage->updateCollection(collection);
}
void DataSourceRepository::configure(QMenu *menu , Domain::DataSource::Ptr selectedSource)
{
{
static bool pageRegistered = false;
if (!pageRegistered) {
kDebug() << "registering pages";
// Akonadi::CollectionPropertiesDialog::registerPage(new CalendarSupport::CollectionGeneralPageFactory);
Akonadi::CollectionPropertiesDialog::registerPage(new PimCommon::CollectionAclPageFactory);
pageRegistered = true;
}
}
if (menu->isEmpty()) {
//We bind the lifetime of all actions to the menu and simply recreate the menu everytime.
QObject *parent = menu;
//This can could be used to provide a parent widget for the created dialogs
QWidget *parentWidget = 0;
static auto actionCollection = new KActionCollection(0, KComponentData());
//We can't delete the actionmanager because it's the parent of running jobs
static Akonadi::StandardCalendarActionManager *mActionManager = 0;
if (!mActionManager) {
mActionManager = new Akonadi::StandardCalendarActionManager(actionCollection, parentWidget);
QList<Akonadi::StandardActionManager::Type> standardActions;
standardActions << Akonadi::StandardActionManager::CreateCollection
<< Akonadi::StandardActionManager::DeleteCollections
<< Akonadi::StandardActionManager::SynchronizeCollections
<< Akonadi::StandardActionManager::CollectionProperties;
Q_FOREACH(Akonadi::StandardActionManager::Type standardAction, standardActions) {
mActionManager->createAction(standardAction);
}
const QStringList pages = QStringList() << QLatin1String("CalendarSupport::CollectionGeneralPage")
<< QLatin1String("Akonadi::CachePolicyPage")
<< QLatin1String("PimCommon::CollectionAclPage");
mActionManager->setCollectionPropertiesPageNames(pages);
}
const auto collection = m_serializer->createCollectionFromDataSource(selectedSource);
//Since we have no ETM based selection model we simply emulate one to tell the actionmanager about the current collection
auto itemModel = new QStandardItemModel(parent);
auto selectionModel = new QItemSelectionModel(itemModel);
auto item = new QStandardItem();
item->setData(QVariant::fromValue(collection), Akonadi::EntityTreeModel::CollectionRole);
itemModel->setItem(0, 0, item);
mActionManager->setCollectionSelectionModel(selectionModel);
selectionModel->setCurrentIndex(itemModel->index(0, 0, QModelIndex()), QItemSelectionModel::SelectCurrent);
//FIXME set appropriate mimetypes based on selected source
if (m_serializer->isTaskCollection(collection)) {
mActionManager->setActionText(Akonadi::StandardActionManager::CreateCollection, ki18n("Add Task Folder"));
mActionManager->setActionText(Akonadi::StandardActionManager::DeleteCollections, ki18n("Delete Task Folder"));
mActionManager->setActionText(Akonadi::StandardActionManager::SynchronizeCollections, ki18n("Update Folder"));
mActionManager->setContextText(Akonadi::StandardActionManager::CollectionProperties,
Akonadi::StandardActionManager::DialogTitle,
tr("@title:window", "Properties of Task Folder %1"));
mActionManager->action(Akonadi::StandardActionManager::CreateCollection )->setProperty("ContentMimeTypes",
QStringList() << Akonadi::Collection::mimeType() << KCalCore::Todo::todoMimeType());
} else if (m_serializer->isNoteCollection(collection)) {
mActionManager->setActionText(Akonadi::StandardActionManager::CreateCollection, ki18n("Add Note Folder"));
mActionManager->setActionText(Akonadi::StandardActionManager::DeleteCollections, ki18n("Delete Note Folder"));
mActionManager->setActionText(Akonadi::StandardActionManager::SynchronizeCollections, ki18n("Update Folder"));
mActionManager->setContextText(Akonadi::StandardActionManager::CollectionProperties,
Akonadi::StandardActionManager::DialogTitle,
tr("@title:window", "Properties of Note Folder %1"));
mActionManager->action(Akonadi::StandardActionManager::CreateCollection )->setProperty("ContentMimeTypes",
QStringList() << Akonadi::Collection::mimeType() << Akonadi::NoteUtils::noteMimeType());
}
menu->addActions(actionCollection->actions());
} else {
//update actions according to selected datasource
//TODO currently we always recreate all actions and menues
}
}
|
/*
* Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation (FSF), 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 Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "autocorrelation.h"
#include "essentiamath.h"
using namespace std;
using namespace essentia;
using namespace standard;
const char* AutoCorrelation::name = "AutoCorrelation";
const char* AutoCorrelation::category = "Standard";
const char* AutoCorrelation::description = DOC(
"This algorithm computes the autocorrelation vector of a signal.\n"
"It uses the version most commonly used in signal processing, which doesn't remove "
"the mean from the observations.\n"
"Using the 'generalized' option this algorithm computes autocorrelation as described in [3].\n"
"\n"
"References:\n"
" [1] Autocorrelation -- from Wolfram MathWorld,\n"
" http://mathworld.wolfram.com/Autocorrelation.html\n\n"
" [2] Autocorrelation - Wikipedia, the free encyclopedia,\n"
" http://en.wikipedia.org/wiki/Autocorrelation\n\n"
" [3] Tolonen T., and Karjalainen, M. (2000). A computationally efficient multipitch analysis model.\n"
" IEEE Transactions on Audio, Speech, and Language Processing, 8(6), 708-716.\n\n"
);
void AutoCorrelation::configure() {
string ntype = parameter("normalization").toString();
if (ntype == "standard") {
_unbiasedNormalization = false;
}
else if (ntype == "unbiased") {
_unbiasedNormalization = true;
}
_generalized = parameter("generalized").toBool();
_frequencyDomainCompression = parameter("frequencyDomainCompression").toReal();
_fft->output("fft").set(_fftBuffer);
_ifft->input("fft").set(_fftBuffer);
}
void AutoCorrelation::compute() {
const std::vector<Real>& signal = _signal.get();
vector<Real>& correlation = _correlation.get();
if (signal.size() == 0) {
correlation.resize(0);
return;
}
_fft->input("frame").set(_paddedSignal);
_ifft->output("frame").set(_corr);
int size = int(signal.size());
int sizeFFT = int(nextPowerTwo(2*size));
// formula to get the auto-correlation (in matlab) is:
// [M,N] = size(x)
// X = fft(x,2^nextpow2(2*M-1));
// c = ifft(abs(X).^2);
// copy signal, and zero-pad it; use _corr as temporary array
_paddedSignal.resize(sizeFFT);
for (int i=0; i<size; i++) _paddedSignal[i] = signal[i];
for (int i=size; i<sizeFFT; i++) _paddedSignal[i] = 0.0;
// first compute fft
_fft->compute();
// take squared amplitude of the spectrum
// (using magnitude would compute sqrt*sqrt)
for (int i=0; i<int(_fftBuffer.size()); i++) {
if (!_generalized){
_fftBuffer[i] = complex<Real>(_fftBuffer[i].real() * _fftBuffer[i].real() +
_fftBuffer[i].imag() * _fftBuffer[i].imag(), // Generalized, todo 0.5 -> c
0.0); // squared amplitude -> complex part = 0
} else {
// Apply magnitude compression
_fftBuffer[i] = complex<Real>(
pow(sqrt(pow(_fftBuffer[i].real() / sizeFFT, 2) + pow(_fftBuffer[i].imag() / sizeFFT, 2)), _frequencyDomainCompression),
0.0); // squared amplitude -> complex part = 0
}
}
// step 3
_ifft->compute();
// copy results in output array, scaling on the go (normalizing the output of the IFFT)
Real scale = 1.0 / sizeFFT;
if (_generalized) {
scale = sizeFFT * scale;
}
correlation.resize(size);
if (_unbiasedNormalization) {
for (int i=0; i<size; i++) {
correlation[i] = _corr[i] * scale / (size - i);
}
}
else {
for (int i=0; i<size; i++) {
correlation[i] = _corr[i] * scale;
}
}
}
Simplify Autocorrelation code
/*
* Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation (FSF), 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 Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "autocorrelation.h"
#include "essentiamath.h"
using namespace std;
using namespace essentia;
using namespace standard;
const char* AutoCorrelation::name = "AutoCorrelation";
const char* AutoCorrelation::category = "Standard";
const char* AutoCorrelation::description = DOC(
"This algorithm computes the autocorrelation vector of a signal.\n"
"It uses the version most commonly used in signal processing, which doesn't remove "
"the mean from the observations.\n"
"Using the 'generalized' option this algorithm computes autocorrelation as described in [3].\n"
"\n"
"References:\n"
" [1] Autocorrelation -- from Wolfram MathWorld,\n"
" http://mathworld.wolfram.com/Autocorrelation.html\n\n"
" [2] Autocorrelation - Wikipedia, the free encyclopedia,\n"
" http://en.wikipedia.org/wiki/Autocorrelation\n\n"
" [3] Tolonen T., and Karjalainen, M. (2000). A computationally efficient multipitch analysis model.\n"
" IEEE Transactions on Audio, Speech, and Language Processing, 8(6), 708-716.\n\n"
);
void AutoCorrelation::configure() {
string ntype = parameter("normalization").toString();
if (ntype == "standard") {
_unbiasedNormalization = false;
}
else if (ntype == "unbiased") {
_unbiasedNormalization = true;
}
_generalized = parameter("generalized").toBool();
_frequencyDomainCompression = parameter("frequencyDomainCompression").toReal();
_ifft->configure("normalize", !_generalized);
_fft->output("fft").set(_fftBuffer);
_ifft->input("fft").set(_fftBuffer);
}
void AutoCorrelation::compute() {
const std::vector<Real>& signal = _signal.get();
vector<Real>& correlation = _correlation.get();
if (signal.size() == 0) {
correlation.resize(0);
return;
}
_fft->input("frame").set(_paddedSignal);
_ifft->output("frame").set(_corr);
int size = int(signal.size());
int sizeFFT = int(nextPowerTwo(2*size));
// formula to get the auto-correlation (in matlab) is:
// [M,N] = size(x)
// X = fft(x,2^nextpow2(2*M-1));
// c = ifft(abs(X).^2);
// copy signal, and zero-pad it; use _corr as temporary array
_paddedSignal.resize(sizeFFT);
for (int i=0; i<size; i++) _paddedSignal[i] = signal[i];
for (int i=size; i<sizeFFT; i++) _paddedSignal[i] = 0.0;
// first compute fft
_fft->compute();
// take squared amplitude of the spectrum
// (using magnitude would compute sqrt*sqrt)
for (int i=0; i<int(_fftBuffer.size()); i++) {
if (!_generalized){
_fftBuffer[i] = complex<Real>(_fftBuffer[i].real() * _fftBuffer[i].real() +
_fftBuffer[i].imag() * _fftBuffer[i].imag(), // Generalized, todo 0.5 -> c
0.0); // squared amplitude -> complex part = 0
} else {
// Apply magnitude compression
_fftBuffer[i] = complex<Real>(
pow(sqrt(pow(_fftBuffer[i].real() / sizeFFT, 2) + pow(_fftBuffer[i].imag() / sizeFFT, 2)), _frequencyDomainCompression),
0.0); // squared amplitude -> complex part = 0
}
}
// step 3
_ifft->compute();
// copy results in output array, scaling on the go (normalizing the output of the IFFT)
correlation.resize(size);
if (_unbiasedNormalization) {
for (int i=0; i<size; i++) {
correlation[i] = _corr[i] / (size - i);
}
}
else {
for (int i=0; i<size; i++) {
correlation[i] = _corr[i];
}
}
}
|
/*
* ProgramTest.cxx
*
* Author
* Andrew Brown <adb1413@rit.edu>
*/
#include "config.h"
#include <cassert>
#include <fstream>
#include <sstream>
#include <boost/filesystem.hpp>
#include <GL/glfw.h>
#include "glycerin/common.h"
#include "glycerin/shader/Program.hpp"
using namespace std;
using namespace Glycerin;
namespace bfs = boost::filesystem;
const char* VERTEX_SHADER =
"#version 140\n"
"uniform mat4 MVPMatrix = mat4(1);\n"
"in vec4 MCVertex;\n"
"void main() {\n"
" gl_Position = MVPMatrix * MCVertex;\n"
"}\n";
const char* FRAGMENT_SHADER =
"#version 140\n"
"uniform vec4 Color = vec4(1);\n"
"out vec4 FragColor;\n"
"void main() {\n"
" FragColor = Color;\n"
"}\n";
/**
* Unit test for Program.
*/
class ProgramTest {
public:
/**
* Ensures Program links with a vertex and fragment shader.
*/
void testLinkWithVertexAndFragmentShader() {
// Create a program
Program program = Program::create();
assert (program.handle() > 0);
// Create shaders
Shader vs = Shader::create(GL_VERTEX_SHADER);
vs.source(VERTEX_SHADER);
vs.compile();
Shader fs = Shader::create(GL_FRAGMENT_SHADER);
fs.source(FRAGMENT_SHADER);
fs.compile();
// Add the shaders to the program
program.attachShader(vs);
program.attachShader(fs);
// Delete the shaders
vs.dispose();
fs.dispose();
// Link the program
program.link();
if (!program.linked()) {
cerr << program.log() << endl;
throw runtime_error("Could not link program!");
}
// Validate it
program.validate();
if (!program.valid()) {
cerr << program.log() << endl;
throw runtime_error("Could not validate program!");
}
// Delete it
program.dispose();
}
};
int main(int argc, char *argv[]) {
// Capture the initial working directory before GLFW changes it
bfs::path dir = bfs::initial_path();
// Initialize GLFW
if (!glfwInit()) {
cerr << "Could not initialize GLFW!" << endl;
return 1;
}
// Reset current directory
bfs::current_path(dir);
// Open a window
glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2);
glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwOpenWindow(512, 512, 0, 0, 0, 0, 0, 0, GLFW_WINDOW);
// Run the test
ProgramTest test;
try {
test.testLinkWithVertexAndFragmentShader();
} catch (exception& e) {
cerr << e.what() << endl;
throw;
}
// Exit
glfwTerminate();
return 0;
}
Program test case with bad shaders (ref #15)
/*
* ProgramTest.cxx
*
* Author
* Andrew Brown <adb1413@rit.edu>
*/
#include "config.h"
#include <cassert>
#include <fstream>
#include <sstream>
#include <boost/filesystem.hpp>
#include <GL/glfw.h>
#include "glycerin/common.h"
#include "glycerin/shader/Program.hpp"
using namespace std;
using namespace Glycerin;
namespace bfs = boost::filesystem;
const char* BAD_VERTEX_SHADER =
"#version 140\n"
"in vec4 MCVertex;\n"
"void main() {\n"
" gl_position = MCVertex;\n"
"}\n";
const char* BAD_FRAGMENT_SHADER =
"#version 140\n"
"out vec4 FragColor;\n"
"void main() {\n"
" fragColor = vec4(1);\n"
"}\n";
const char* GOOD_VERTEX_SHADER =
"#version 140\n"
"uniform mat4 MVPMatrix = mat4(1);\n"
"in vec4 MCVertex;\n"
"void main() {\n"
" gl_Position = MVPMatrix * MCVertex;\n"
"}\n";
const char* GOOD_FRAGMENT_SHADER =
"#version 140\n"
"uniform vec4 Color = vec4(1);\n"
"out vec4 FragColor;\n"
"void main() {\n"
" FragColor = Color;\n"
"}\n";
/**
* Unit test for Program.
*/
class ProgramTest {
public:
/**
* Ensures Program links with a vertex and fragment shader.
*/
void testLinkWithGoodVertexAndFragmentShader() {
// Create a program
Program program = Program::create();
assert (program.handle() > 0);
// Create shaders
Shader vs = Shader::create(GL_VERTEX_SHADER);
vs.source(GOOD_VERTEX_SHADER);
vs.compile();
Shader fs = Shader::create(GL_FRAGMENT_SHADER);
fs.source(GOOD_FRAGMENT_SHADER);
fs.compile();
// Add the shaders to the program
program.attachShader(vs);
program.attachShader(fs);
// Delete the shaders
vs.dispose();
fs.dispose();
// Link the program
program.link();
if (!program.linked()) {
cerr << program.log() << endl;
throw runtime_error("Could not link program!");
}
// Validate it
program.validate();
if (!program.valid()) {
cerr << program.log() << endl;
throw runtime_error("Could not validate program!");
}
// Delete it
program.dispose();
}
/**
* Ensures Program does not link and validate with a bad vertex and fragment shader.
*/
void testLinkWithBadVertexAndFragmentShader() {
// Create a program
Program program = Program::create();
assert (program.handle() > 0);
// Create shaders
Shader vs = Shader::create(GL_VERTEX_SHADER);
vs.source(BAD_VERTEX_SHADER);
vs.compile();
Shader fs = Shader::create(GL_FRAGMENT_SHADER);
fs.source(BAD_FRAGMENT_SHADER);
fs.compile();
// Add the shaders to the program
program.attachShader(vs);
program.attachShader(fs);
// Delete the shaders
vs.dispose();
fs.dispose();
// Link the program
program.link();
if (program.linked()) {
throw runtime_error("Linked bad program!");
}
// Delete it
program.dispose();
}
};
int main(int argc, char *argv[]) {
// Capture the initial working directory before GLFW changes it
bfs::path dir = bfs::initial_path();
// Initialize GLFW
if (!glfwInit()) {
cerr << "Could not initialize GLFW!" << endl;
return 1;
}
// Reset current directory
bfs::current_path(dir);
// Open a window
glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2);
glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwOpenWindow(512, 512, 0, 0, 0, 0, 0, 0, GLFW_WINDOW);
// Run the test
ProgramTest test;
try {
test.testLinkWithGoodVertexAndFragmentShader();
test.testLinkWithBadVertexAndFragmentShader();
} catch (exception& e) {
cerr << e.what() << endl;
throw;
}
// Exit
glfwTerminate();
return 0;
}
|
/*
* integer_check.c
*/
#include <iomanip>
#include <iostream>
#include <sstream>
#include <unistd.h>
#include <integer.h>
bool verbose = false;
/*
* Get the elapsed number of system ticks before we start a test running.
*/
auto get_start_time_ticks() -> uint64_t {
uint32_t lo;
uint32_t hi;
asm volatile(
"cpuid\n\t"
"rdtsc\n\t"
"mov %%edx, %1\n\t"
"mov %%eax, %0\n\t"
: "=r" (lo), "=r" (hi)
:
: "rax", "rbx", "rcx", "rdx", "memory"
);
return (static_cast<uint64_t>(hi) << 32) | static_cast<uint64_t>(lo);
}
/*
* Get the elapsed number of system ticks after we complete a test running.
*/
auto get_end_time_ticks() -> uint64_t {
uint32_t lo;
uint32_t hi;
asm volatile(
"rdtscp\n\t"
"mov %%edx, %1\n\t"
"mov %%eax, %0\n\t"
"cpuid\n\t"
: "=r" (lo), "=r" (hi)
:
: "rax", "rbx", "rcx", "rdx", "memory"
);
return (static_cast<uint64_t>(hi) << 32) | static_cast<uint64_t>(lo);
}
/*
* Test a string against a string stream that should contain the same text.
*
* Returns true if the string and string stream match, false if they don't.
* If the global "verbose" flag is set then also prints the results.
*/
auto test_check(const std::string &tag, uint64_t t, const std::string &s, const std::stringstream &ss) -> bool {
bool res = (s == ss.str());
if (verbose) {
std::cout << std::setw(10) << std::left << tag << " | ";
std::cout << std::setw(10) << std::right << t << " | " << (res ? "pass" : "FAIL") << " | " << ss.str();
if (!res) {
std::cout << " (" << s << ')';
}
std::cout << '\n';
}
return res;
}
/*
* Similar to test_check() but doesn't actually check anything; the result is already
* known.
*
* This function allows uniform handling of test outputs.
*/
auto test_nocheck(const std::string &tag, uint64_t t, const std::string &s, bool res) {
if (verbose) {
std::cout << std::setw(10) << std::left << tag << " | ";
std::cout << std::setw(10) << std::right << t << " | " << (res ? "pass" : "FAIL") << " | " << s << '\n';
}
return res;
}
/*
* Test Constructors.
*/
auto test_construct() -> bool {
bool res = true;
/*
* Construct with a long integer 0.
*/
auto t0 = get_start_time_ticks();
c8::integer v0(0);
auto p0 = get_end_time_ticks() - t0;
std::stringstream s0;
s0 << v0;
res &= test_check("cons 0", p0, "0", s0);
/*
* Construct with a long integer.
*/
auto t1 = get_start_time_ticks();
c8::integer v1(0x123456789abcLL);
auto p1 = get_end_time_ticks() - t1;
std::stringstream s1;
s1 << std::hex << v1;
res &= test_check("cons 1", p1, "123456789abc", s1);
/*
* Construct with a string 0.
*/
auto t2 = get_start_time_ticks();
c8::integer v2("0");
auto p2 = get_end_time_ticks() - t2;
std::stringstream s2;
s2 << v2;
res &= test_check("cons 2", p2, "0", s2);
/*
* Construct with a hexadecimal string.
*/
auto t3 = get_start_time_ticks();
c8::integer v3("0x3837439787487386792386728abcd88379dc");
auto p3 = get_end_time_ticks() - t3;
std::stringstream s3;
s3 << std::hex << v3;
res &= test_check("cons 3", p3, "3837439787487386792386728abcd88379dc", s3);
/*
* Construct with a decimal string.
*/
auto t4 = get_start_time_ticks();
c8::integer v4("3897894117580750151618270927682762897697428275427542907478758957487582700682675349287325097");
auto p4 = get_end_time_ticks() - t4;
std::stringstream s4;
s4 << v4;
res &= test_check("cons 4", p4, "3897894117580750151618270927682762897697428275427542907478758957487582700682675349287325097", s4);
/*
* Construct with an octal string.
*/
auto t5 = get_start_time_ticks();
c8::integer v5("0115415157637671751");
auto p5 = get_end_time_ticks() - t5;
std::stringstream s5;
s5 << std::oct << v5;
res &= test_check("cons 5", p5, "115415157637671751", s5);
/*
* Attempt to construct with an invalid octal string.
*/
auto t6 = get_start_time_ticks();
try {
c8::integer v6("01185415157637671751");
auto p6 = get_end_time_ticks() - t6;
res &= test_nocheck("cons 6", p6, "failed to throw exception", false);
} catch (const std::invalid_argument &e) {
auto p6 = get_end_time_ticks() - t6;
res &= test_nocheck("cons 6", p6, "exception thrown: " + std::string(e.what()), true);
} catch (...) {
auto p6 = get_end_time_ticks() - t6;
res &= test_nocheck("cons 6", p6, "unexpected exception thrown", false);
}
/*
* Construct with a long integer.
*/
auto t7 = get_start_time_ticks();
c8::integer v7(-0x123456789abcLL);
auto p7 = get_end_time_ticks() - t7;
std::stringstream s7;
s7 << std::hex << v7;
res &= test_check("cons 7", p7, "-123456789abc", s7);
/*
* Construct with a hexadecimal string.
*/
auto t8 = get_start_time_ticks();
c8::integer v8("-0x3837439787487386792386728abcd88379dc");
auto p8 = get_end_time_ticks() - t8;
std::stringstream s8;
s8 << std::hex << v8;
res &= test_check("cons 8", p8, "-3837439787487386792386728abcd88379dc", s8);
/*
* Construct with a decimal string.
*/
auto t9 = get_start_time_ticks();
c8::integer v9("-3897894117580750151618270927682762897697428275427542907478758957487582700682675349287325097");
auto p9 = get_end_time_ticks() - t9;
std::stringstream s9;
s9 << v9;
res &= test_check("cons 9", p9, "-3897894117580750151618270927682762897697428275427542907478758957487582700682675349287325097", s9);
/*
* Construct with an octal string.
*/
auto t10 = get_start_time_ticks();
c8::integer v10("-0115415157637671751");
auto p10 = get_end_time_ticks() - t10;
std::stringstream s10;
s10 << std::oct << v10;
res &= test_check("cons 10", p10, "-115415157637671751", s10);
/*
* Attempt to construct with an invalid octal string.
*/
auto t11 = get_start_time_ticks();
try {
c8::integer v11("-01185415157637671751");
auto p11 = get_end_time_ticks() - t11;
res &= test_nocheck("cons 11", p11, "failed to throw exception", false);
} catch (const std::invalid_argument &e) {
auto p11 = get_end_time_ticks() - t11;
res &= test_nocheck("cons 11", p11, "exception thrown: " + std::string(e.what()), true);
} catch (...) {
auto p11 = get_end_time_ticks() - t11;
res &= test_nocheck("cons 11", p11, "unexpected exception thrown", false);
}
return res;
}
/*
* Test addition.
*/
auto test_add() -> bool {
bool res = true;
/*
* Add two positive values.
*/
c8::integer a0_0("31");
c8::integer a1_0("42");
auto t0 = get_start_time_ticks();
auto a2_0 = a0_0 + a1_0;
auto p0 = get_end_time_ticks() - t0;
std::stringstream s0;
s0 << a2_0;
res &= test_check("add 0", p0, "73", s0);
/*
* Add a positive and a negative value.
*/
c8::integer a0_1("42");
c8::integer a1_1("-21");
auto t1 = get_start_time_ticks();
auto a2_1 = a0_1 + a1_1;
auto p1 = get_end_time_ticks() - t1;
std::stringstream s1;
s1 << a2_1;
res &= test_check("add 1", p1, "21", s1);
/*
* Add a positive and a negative value that gives a negative result
*/
c8::integer a0_2("12345678");
c8::integer a1_2("-34738957485741895748957485743809574812345678");
auto t2 = get_start_time_ticks();
auto a2_2 = a0_2 + a1_2;
auto p2 = get_end_time_ticks() - t2;
std::stringstream s2;
s2 << a2_2;
res &= test_check("add 2", p2, "-34738957485741895748957485743809574800000000", s2);
/*
* Add two very large negative values.
*/
c8::integer a0_3("-10000000000000000000000000000000000000000000000000000000000000000008789");
c8::integer a1_3("-88888880000000000000000000000000000000000000000000000000000000999992000");
auto t3 = get_start_time_ticks();
auto a2_3 = a0_3 + a1_3;
auto p3 = get_end_time_ticks() - t3;
std::stringstream s3;
s3 << a2_3;
res &= test_check("add 3", p3, "-98888880000000000000000000000000000000000000000000000000000001000000789", s3);
return res;
}
/*
* Test subtraction.
*/
auto test_subtract() -> bool {
bool res = true;
/*
* Subtract a 1 digit value from another 1 digit value.
*/
c8::integer s0_0(52);
c8::integer s1_0(2);
auto t0 = get_start_time_ticks();
auto s2_0 = s0_0 - s1_0;
auto p0 = get_end_time_ticks() - t0;
std::stringstream s0;
s0 << s2_0;
res &= test_check("sub 0", p0, "50", s0);
/*
* Subtract a large negative value from another large negative value.
*/
c8::integer s0_1("-5872489572457574027439274027348275342809754320711018574807407090990940275827586671651690897");
c8::integer s1_1("-842758978027689671615847509157087514875097509475029454785478748571507457514754190754");
auto t1 = get_start_time_ticks();
auto s2_1 = s0_1 - s1_1;
auto p1 = get_end_time_ticks() - t1;
std::stringstream s1;
s1 << s2_1;
res &= test_check("sub 1", p1, "-5872488729698595999749602411500766185722239445613509099777952305512191704320129156897500143", s1);
/*
* Subtract a large negative value from a large value.
*/
c8::integer s0_2("10000000000000000000000000000000000000000000000000000000000000000000000");
c8::integer s1_2("-10000000000000000000000000000000000000000000000000000000000000000000000");
auto t2 = get_start_time_ticks();
auto s2_2 = s0_2 - s1_2;
auto p2 = get_end_time_ticks() - t2;
std::stringstream s2;
s2 << s2_2;
res &= test_check("sub 2", p2, "20000000000000000000000000000000000000000000000000000000000000000000000", s2);
/*
* Subtract a large value from a smaller one.
*/
c8::integer s0_3(2);
c8::integer s1_3(52);
auto t3 = get_start_time_ticks();
auto s2_3 = s0_3 - s1_3;
auto p3 = get_end_time_ticks() - t3;
std::stringstream s3;
s3 << s2_3;
res &= test_check("sub 3", p3, "-50", s3);
return res;
}
/*
* Test value comparisons.
*/
auto test_compare() -> bool {
bool res = true;
/*
* Compare two positive values.
*/
c8::integer co0_0(2);
c8::integer co1_0(1);
auto t0a = get_start_time_ticks();
auto co2_0a = (co0_0 == co1_0);
auto p0a = get_end_time_ticks() - t0a;
std::stringstream s0a;
s0a << co2_0a;
res &= test_check("comp 0a", p0a, "0", s0a);
auto t0b = get_start_time_ticks();
auto co2_0b = (co0_0 != co1_0);
auto p0b = get_end_time_ticks() - t0b;
std::stringstream s0b;
s0b << co2_0b;
res &= test_check("comp 0b", p0b, "1", s0b);
auto t0c = get_start_time_ticks();
auto co2_0c = (co0_0 > co1_0);
auto p0c = get_end_time_ticks() - t0c;
std::stringstream s0c;
s0c << co2_0c;
res &= test_check("comp 0c", p0c, "1", s0c);
auto t0d = get_start_time_ticks();
auto co2_0d = (co0_0 >= co1_0);
auto p0d = get_end_time_ticks() - t0d;
std::stringstream s0d;
s0d << co2_0d;
res &= test_check("comp 0d", p0d, "1", s0d);
auto t0e = get_start_time_ticks();
auto co2_0e = (co0_0 < co1_0);
auto p0e = get_end_time_ticks() - t0e;
std::stringstream s0e;
s0e << co2_0e;
res &= test_check("comp 0e", p0e, "0", s0e);
auto t0f = get_start_time_ticks();
auto co2_0f = (co0_0 <= co1_0);
auto p0f = get_end_time_ticks() - t0f;
std::stringstream s0f;
s0f << co2_0f;
res &= test_check("comp 0f", p0f, "0", s0f);
/*
* Compare a negative value with a positive one.
*/
c8::integer co0_1(-0x987654321LL);
c8::integer co1_1(1);
auto t1a = get_start_time_ticks();
auto co2_1a = (co0_1 == co1_1);
auto p1a = get_end_time_ticks() - t1a;
std::stringstream s1a;
s1a << co2_1a;
res &= test_check("comp 1a", p1a, "0", s1a);
auto t1b = get_start_time_ticks();
auto co2_1b = (co0_1 != co1_1);
auto p1b = get_end_time_ticks() - t1b;
std::stringstream s1b;
s1b << co2_1b;
res &= test_check("comp 1b", p1b, "1", s1b);
auto t1c = get_start_time_ticks();
auto co2_1c = (co0_1 > co1_1);
auto p1c = get_end_time_ticks() - t1c;
std::stringstream s1c;
s1c << co2_1c;
res &= test_check("comp 1c", p1c, "0", s1c);
auto t1d = get_start_time_ticks();
auto co2_1d = (co0_1 >= co1_1);
auto p1d = get_end_time_ticks() - t1d;
std::stringstream s1d;
s1d << co2_1d;
res &= test_check("comp 1d", p1d, "0", s1d);
auto t1e = get_start_time_ticks();
auto co2_1e = (co0_1 < co1_1);
auto p1e = get_end_time_ticks() - t1e;
std::stringstream s1e;
s1e << co2_1e;
res &= test_check("comp 1e", p1e, "1", s1e);
auto t1f = get_start_time_ticks();
auto co2_1f = (co0_1 <= co1_1);
auto p1f = get_end_time_ticks() - t1f;
std::stringstream s1f;
s1f << co2_1f;
res &= test_check("comp 1f", p1f, "1", s1f);
/*
* Compare a positive value with a negative one.
*/
c8::integer co0_2(1);
c8::integer co1_2(-0x987654321LL);
auto t2a = get_start_time_ticks();
auto co2_2a = (co0_2 == co1_2);
auto p2a = get_end_time_ticks() - t2a;
std::stringstream s2a;
s2a << co2_2a;
res &= test_check("comp 2a", p2a, "0", s2a);
auto t2b = get_start_time_ticks();
auto co2_2b = (co0_2 != co1_2);
auto p2b = get_end_time_ticks() - t2b;
std::stringstream s2b;
s2b << co2_2b;
res &= test_check("comp 2b", p2b, "1", s2b);
auto t2c = get_start_time_ticks();
auto co2_2c = (co0_2 > co1_2);
auto p2c = get_end_time_ticks() - t2c;
std::stringstream s2c;
s2c << co2_2c;
res &= test_check("comp 2c", p2c, "1", s2c);
auto t2d = get_start_time_ticks();
auto co2_2d = (co0_2 >= co1_2);
auto p2d = get_end_time_ticks() - t2d;
std::stringstream s2d;
s2d << co2_2d;
res &= test_check("comp 2d", p2d, "1", s2d);
auto t2e = get_start_time_ticks();
auto co2_2e = (co0_2 < co1_2);
auto p2e = get_end_time_ticks() - t2e;
std::stringstream s2e;
s2e << co2_2e;
res &= test_check("comp 2e", p2e, "0", s2e);
auto t2f = get_start_time_ticks();
auto co2_2f = (co0_2 <= co1_2);
auto p2f = get_end_time_ticks() - t2f;
std::stringstream s2f;
s2f << co2_2f;
res &= test_check("comp 2f", p2f, "0", s2f);
/*
* Compare two negative values.
*/
c8::integer co0_3(-0x2f987654321LL);
c8::integer co1_3(-0x2f987654321LL);
auto t3a = get_start_time_ticks();
auto co2_3a = (co0_3 == co1_3);
auto p3a = get_end_time_ticks() - t3a;
std::stringstream s3a;
s3a << co2_3a;
res &= test_check("comp 3a", p3a, "1", s3a);
auto t3b = get_start_time_ticks();
auto co2_3b = (co0_3 != co1_3);
auto p3b = get_end_time_ticks() - t3b;
std::stringstream s3b;
s3b << co2_3b;
res &= test_check("comp 3b", p3b, "0", s3b);
auto t3c = get_start_time_ticks();
auto co2_3c = (co0_3 > co1_3);
auto p3c = get_end_time_ticks() - t3c;
std::stringstream s3c;
s3c << co2_3c;
res &= test_check("comp 3c", p3c, "0", s3c);
auto t3d = get_start_time_ticks();
auto co2_3d = (co0_3 >= co1_3);
auto p3d = get_end_time_ticks() - t3d;
std::stringstream s3d;
s3d << co2_3d;
res &= test_check("comp 3d", p3d, "1", s3d);
auto t3e = get_start_time_ticks();
auto co2_3e = (co0_3 < co1_3);
auto p3e = get_end_time_ticks() - t3e;
std::stringstream s3e;
s3e << co2_3e;
res &= test_check("comp 3e", p3e, "0", s3e);
auto t3f = get_start_time_ticks();
auto co2_3f = (co0_3 <= co1_3);
auto p3f = get_end_time_ticks() - t3f;
std::stringstream s3f;
s3f << co2_3f;
res &= test_check("comp 3f", p3f, "1", s3f);
return res;
}
/*
* Test left shifting.
*/
auto test_lshift() -> bool {
bool res = true;
c8::integer l0_0(0x349f);
auto t0a = get_start_time_ticks();
auto l1_0a = l0_0 << 0;
auto p0a = get_end_time_ticks() - t0a;
std::stringstream s0a;
s0a << std::hex << l1_0a;
res &= test_check("lsh 0a", p0a, "349f", s0a);
auto t0b = get_start_time_ticks();
auto l1_0b = l0_0 << 1;
auto p0b = get_end_time_ticks() - t0b;
std::stringstream s0b;
s0b << std::hex << l1_0b;
res &= test_check("lsh 0b", p0b, "693e", s0b);
auto t0c = get_start_time_ticks();
auto l1_0c = l0_0 << 18;
auto p0c = get_end_time_ticks() - t0c;
std::stringstream s0c;
s0c << std::hex << l1_0c;
res &= test_check("lsh 0c", p0c, "d27c0000", s0c);
auto t0d = get_start_time_ticks();
auto l1_0d = l0_0 << 187;
auto p0d = get_end_time_ticks() - t0d;
std::stringstream s0d;
s0d << std::hex << l1_0d;
res &= test_check("lsh 0d", p0d, "1a4f80000000000000000000000000000000000000000000000", s0d);
c8::integer l0_1("-0x349f298375323985afbce9837928798789dffeffee987678687678676756562");
auto t1a = get_start_time_ticks();
auto l1_1a = l0_1 << 69;
auto p1a = get_end_time_ticks() - t1a;
std::stringstream s1a;
s1a << std::hex << l1_1a;
res &= test_check("lsh 1a", p1a, "-693e5306ea64730b5f79d306f250f30f13bffdffdd30ecf0d0ecf0ceceacac400000000000000000", s1a);
return res;
}
/*
* Test right shifting.
*/
auto test_rshift() -> bool {
bool res = true;
c8::integer r0_0("0x23490000000000000000000000000000000000000000000000000000");
auto t0a = get_start_time_ticks();
auto r1_0a = r0_0 >> 0;
auto p0a = get_end_time_ticks() - t0a;
std::stringstream s0a;
s0a << std::hex << r1_0a;
res &= test_check("rsh 0a", p0a, "23490000000000000000000000000000000000000000000000000000", s0a);
auto t0b = get_start_time_ticks();
auto r1_0b = r0_0 >> 1;
auto p0b = get_end_time_ticks() - t0b;
std::stringstream s0b;
s0b << std::hex << r1_0b;
res &= test_check("rsh 0b", p0b, "11a48000000000000000000000000000000000000000000000000000", s0b);
auto t0c = get_start_time_ticks();
auto r1_0c = r0_0 >> 19;
auto p0c = get_end_time_ticks() - t0c;
std::stringstream s0c;
s0c << std::hex << r1_0c;
res &= test_check("rsh 0c", p0c, "469200000000000000000000000000000000000000000000000", s0c);
auto t0d = get_start_time_ticks();
auto r1_0d = r0_0 >> 197;
auto p0d = get_end_time_ticks() - t0d;
std::stringstream s0d;
s0d << std::hex << r1_0d;
res &= test_check("rsh 0d", p0d, "11a4800", s0d);
c8::integer r0_1("-0x693e5306ea64730b5f79d306f250f30f13bffdffdd30ecf0d0ecf0ceceacac400000000000000000");
auto t1a = get_start_time_ticks();
auto r1_1a = r0_1 >> 123;
auto p1a = get_end_time_ticks() - t1a;
std::stringstream s1a;
s1a << std::hex << r1_1a;
res &= test_check("rsh 1a", p1a, "-d27ca60dd4c8e616bef3a60de4a1e61e277ffbffba61d9e1a", s1a);
return res;
}
/*
* Test multiplication.
*/
auto test_multiply() -> bool {
bool res = true;
c8::integer mu0_0(3);
c8::integer mu1_0(22);
auto t0 = get_start_time_ticks();
auto mu2_0 = mu0_0 * mu1_0;
auto p0 = get_end_time_ticks() - t0;
std::stringstream s0;
s0 << mu2_0;
res &= test_check("mul 0", p0, "66", s0);
c8::integer mu0_1(1000000000000000000LL);
c8::integer mu1_1("-9999999999999999999");
auto t1 = get_start_time_ticks();
auto mu2_1 = mu0_1 * mu1_1;
auto p1 = get_end_time_ticks() - t1;
std::stringstream s1;
s1 << mu2_1;
res &= test_check("mul 1", p1, "-9999999999999999999000000000000000000", s1);
c8::integer mu0_2(-0x2000000000000000LL);
c8::integer mu1_2(0x4000000000000000LL);
auto t2 = get_start_time_ticks();
auto mu2_2 = mu0_2 * mu1_2;
auto p2 = get_end_time_ticks() - t2;
std::stringstream s2;
s2 << std::hex << mu2_2;
res &= test_check("mul 2", p2, "-8000000000000000000000000000000", s2);
c8::integer mu0_3("-12345678901234567890123456789012345678901234567890123456789012345678901234567890");
c8::integer mu1_3("-1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890");
auto t3 = get_start_time_ticks();
auto mu2_3 = mu0_3 * mu1_3;
auto p3 = get_end_time_ticks() - t3;
std::stringstream s3;
s3 << mu2_3;
res &= test_check("mul 3", p3, "15241578753238836750495351562566681945008382873376009755225118122311263526910001371743100137174310012193273126047859425087639153757049236500533455762536198787501905199875019052100", s3);
return res;
}
/*
* Test division.
*/
auto test_divide() -> bool {
bool res = true;
c8::integer d0_0(1000000000000000000LL);
c8::integer d1_0(99999999999999999LL);
auto t0 = get_start_time_ticks();
auto d2_0 = d0_0 / d1_0;
auto mo2_0 = d0_0 % d1_0;
auto p0 = get_end_time_ticks() - t0;
std::stringstream s0a;
s0a << d2_0;
res &= test_check("div 0a", p0, "10", s0a);
std::stringstream s0b;
s0b << mo2_0;
res &= test_check("div 0b", p0, "10", s0b);
c8::integer d0_1("7829238792751875818917817519758789749174743847389742871867617465710657162");
c8::integer d1_1(-99999999999999999LL);
auto t1 = get_start_time_ticks();
auto d2_1 = d0_1 / d1_1;
auto mo2_1 = d0_1 % d1_1;
auto p1 = get_end_time_ticks() - t1;
std::stringstream s1a;
s1a << d2_1;
res &= test_check("div 1a", p1, "-78292387927518758972102054472775487212767983201652300846", s1a);
std::stringstream s1b;
s1b << mo2_1;
res &= test_check("div 1b", p1, "35600667362958008", s1b);
c8::integer d0_2("-0x100000000000000000000000000000000000000000000000000000000000000000000000");
c8::integer d1_2("0x10000000000000001000000000000000100000000");
auto t2 = get_start_time_ticks();
auto d2_2 = d0_2 / d1_2;
auto mo2_2 = d0_2 % d1_2;
auto p2 = get_end_time_ticks() - t2;
std::stringstream s2a;
s2a << std::hex << d2_2;
res &= test_check("div 2a", p2, "-ffffffffffffffff000000000000000", s2a);
std::stringstream s2b;
s2b << std::hex << mo2_2;
res &= test_check("div 2b", p2, "100000000000000000000000", s2b);
/*
* Divide by zero. This will throw an exception!
*/
c8::integer d0_3(2000);
c8::integer d1_3(0);
auto t3 = get_start_time_ticks();
try {
auto d2_3 = d0_3 / d1_3;
auto p3 = get_end_time_ticks() - t3;
std::stringstream s3;
s3 << d2_3;
res &= test_nocheck("div 3", p3, "failed to throw exception", false);
} catch (const std::logic_error &e) {
auto p3 = get_end_time_ticks() - t3;
res &= test_nocheck("div 3", p3, "exception thrown: " + std::string(e.what()), true);
} catch (...) {
auto p3 = get_end_time_ticks() - t3;
res &= test_nocheck("div 3", p3, "unexpected exception thrown", false);
}
return res;
c8::integer d0_4(1000000000000000000LL);
c8::integer d1_4(99999999999999999LL);
auto t4 = get_start_time_ticks();
auto d2_4 = d0_4 / d1_4;
auto mo2_4 = d0_4 % d1_4;
auto p4 = get_end_time_ticks() - t4;
std::stringstream s4a;
s4a << d2_4;
res &= test_check("div 4a", p4, "10", s4a);
std::stringstream s4b;
s0b << mo2_4;
res &= test_check("div 4b", p4, "10", s4b);
}
/*
* Test printing.
*/
auto test_print() -> bool {
bool res = true;
c8::integer v("-0xfedcfedc0123456789");
std::stringstream s0;
auto t0 = get_start_time_ticks();
s0 << v;
auto p0 = get_end_time_ticks() - t0;
res &= test_check("prn 0", p0, "-4701397401952099592073", s0);
std::stringstream s1;
auto t1 = get_start_time_ticks();
s1 << std::hex << v;
auto p1 = get_end_time_ticks() - t1;
res &= test_check("prn 1", p1, "-fedcfedc0123456789", s1);
std::stringstream s2;
auto t2 = get_start_time_ticks();
s2 << std::uppercase << std::hex << v;
auto p2 = get_end_time_ticks() - t2;
res &= test_check("prn 2", p2, "-FEDCFEDC0123456789", s2);
std::stringstream s3;
auto t3 = get_start_time_ticks();
s3 << std::oct << v;
auto p3 = get_end_time_ticks() - t3;
res &= test_check("prn 3", p3, "-775563766700044321263611", s3);
std::stringstream s4;
auto t4 = get_start_time_ticks();
s4 << std::showbase << v;
auto p4 = get_end_time_ticks() - t4;
res &= test_check("prn 4", p4, "-4701397401952099592073", s4);
std::stringstream s5;
auto t5 = get_start_time_ticks();
s5 << std::showbase << std::hex << v;
auto p5 = get_end_time_ticks() - t5;
res &= test_check("prn 5", p5, "-0xfedcfedc0123456789", s5);
std::stringstream s6;
auto t6 = get_start_time_ticks();
s6 << std::showbase << std::uppercase << std::hex << v;
auto p6 = get_end_time_ticks() - t6;
res &= test_check("prn 6", p6, "-0XFEDCFEDC0123456789", s6);
std::stringstream s7;
auto t7 = get_start_time_ticks();
s7 << std::showbase << std::oct << v;
auto p7 = get_end_time_ticks() - t7;
res &= test_check("prn 7", p7, "-0775563766700044321263611", s7);
return res;
}
/*
* Report the usage for this test program.
*/
static auto usage(const char *name) -> void {
std::cerr << "usage: " << name << " [OPTIONS]\n\n";
std::cerr << "Options\n";
std::cerr << " -v Verbose reporting (optional)\n\n";
}
/*
* Entry point.
*/
auto main(int argc, char **argv) -> int {
/*
* Parse the command line options.
*/
int ch;
while ((ch = getopt(argc, argv, "v?")) != -1) {
switch (ch) {
case 'v':
verbose = true;
break;
case '?':
usage(argv[0]);
exit(-1);
}
}
bool res = true;
res &= test_construct();
res &= test_add();
res &= test_subtract();
res &= test_compare();
res &= test_lshift();
res &= test_rshift();
res &= test_multiply();
res &= test_divide();
res &= test_print();
if (!res) {
std::cout << "TESTS FAILED!\n";
exit(-1);
}
std::cout << "All tests passed\n";
return 0;
}
Fix problem with unit test
/*
* integer_check.c
*/
#include <iomanip>
#include <iostream>
#include <sstream>
#include <unistd.h>
#include <integer.h>
bool verbose = false;
/*
* Get the elapsed number of system ticks before we start a test running.
*/
auto get_start_time_ticks() -> uint64_t {
uint32_t lo;
uint32_t hi;
asm volatile(
"cpuid\n\t"
"rdtsc\n\t"
"mov %%edx, %1\n\t"
"mov %%eax, %0\n\t"
: "=r" (lo), "=r" (hi)
:
: "rax", "rbx", "rcx", "rdx", "memory"
);
return (static_cast<uint64_t>(hi) << 32) | static_cast<uint64_t>(lo);
}
/*
* Get the elapsed number of system ticks after we complete a test running.
*/
auto get_end_time_ticks() -> uint64_t {
uint32_t lo;
uint32_t hi;
asm volatile(
"rdtscp\n\t"
"mov %%edx, %1\n\t"
"mov %%eax, %0\n\t"
"cpuid\n\t"
: "=r" (lo), "=r" (hi)
:
: "rax", "rbx", "rcx", "rdx", "memory"
);
return (static_cast<uint64_t>(hi) << 32) | static_cast<uint64_t>(lo);
}
/*
* Test a string against a string stream that should contain the same text.
*
* Returns true if the string and string stream match, false if they don't.
* If the global "verbose" flag is set then also prints the results.
*/
auto test_check(const std::string &tag, uint64_t t, const std::string &s, const std::stringstream &ss) -> bool {
bool res = (s == ss.str());
if (verbose) {
std::cout << std::setw(10) << std::left << tag << " | ";
std::cout << std::setw(10) << std::right << t << " | " << (res ? "pass" : "FAIL") << " | " << ss.str();
if (!res) {
std::cout << " (" << s << ')';
}
std::cout << '\n';
}
return res;
}
/*
* Similar to test_check() but doesn't actually check anything; the result is already
* known.
*
* This function allows uniform handling of test outputs.
*/
auto test_nocheck(const std::string &tag, uint64_t t, const std::string &s, bool res) {
if (verbose) {
std::cout << std::setw(10) << std::left << tag << " | ";
std::cout << std::setw(10) << std::right << t << " | " << (res ? "pass" : "FAIL") << " | " << s << '\n';
}
return res;
}
/*
* Test Constructors.
*/
auto test_construct() -> bool {
bool res = true;
/*
* Construct with a long integer 0.
*/
auto t0 = get_start_time_ticks();
c8::integer v0(0);
auto p0 = get_end_time_ticks() - t0;
std::stringstream s0;
s0 << v0;
res &= test_check("cons 0", p0, "0", s0);
/*
* Construct with a long integer.
*/
auto t1 = get_start_time_ticks();
c8::integer v1(0x123456789abcLL);
auto p1 = get_end_time_ticks() - t1;
std::stringstream s1;
s1 << std::hex << v1;
res &= test_check("cons 1", p1, "123456789abc", s1);
/*
* Construct with a string 0.
*/
auto t2 = get_start_time_ticks();
c8::integer v2("0");
auto p2 = get_end_time_ticks() - t2;
std::stringstream s2;
s2 << v2;
res &= test_check("cons 2", p2, "0", s2);
/*
* Construct with a hexadecimal string.
*/
auto t3 = get_start_time_ticks();
c8::integer v3("0x3837439787487386792386728abcd88379dc");
auto p3 = get_end_time_ticks() - t3;
std::stringstream s3;
s3 << std::hex << v3;
res &= test_check("cons 3", p3, "3837439787487386792386728abcd88379dc", s3);
/*
* Construct with a decimal string.
*/
auto t4 = get_start_time_ticks();
c8::integer v4("3897894117580750151618270927682762897697428275427542907478758957487582700682675349287325097");
auto p4 = get_end_time_ticks() - t4;
std::stringstream s4;
s4 << v4;
res &= test_check("cons 4", p4, "3897894117580750151618270927682762897697428275427542907478758957487582700682675349287325097", s4);
/*
* Construct with an octal string.
*/
auto t5 = get_start_time_ticks();
c8::integer v5("0115415157637671751");
auto p5 = get_end_time_ticks() - t5;
std::stringstream s5;
s5 << std::oct << v5;
res &= test_check("cons 5", p5, "115415157637671751", s5);
/*
* Attempt to construct with an invalid octal string.
*/
auto t6 = get_start_time_ticks();
try {
c8::integer v6("01185415157637671751");
auto p6 = get_end_time_ticks() - t6;
res &= test_nocheck("cons 6", p6, "failed to throw exception", false);
} catch (const std::invalid_argument &e) {
auto p6 = get_end_time_ticks() - t6;
res &= test_nocheck("cons 6", p6, "exception thrown: " + std::string(e.what()), true);
} catch (...) {
auto p6 = get_end_time_ticks() - t6;
res &= test_nocheck("cons 6", p6, "unexpected exception thrown", false);
}
/*
* Construct with a long integer.
*/
auto t7 = get_start_time_ticks();
c8::integer v7(-0x123456789abcLL);
auto p7 = get_end_time_ticks() - t7;
std::stringstream s7;
s7 << std::hex << v7;
res &= test_check("cons 7", p7, "-123456789abc", s7);
/*
* Construct with a hexadecimal string.
*/
auto t8 = get_start_time_ticks();
c8::integer v8("-0x3837439787487386792386728abcd88379dc");
auto p8 = get_end_time_ticks() - t8;
std::stringstream s8;
s8 << std::hex << v8;
res &= test_check("cons 8", p8, "-3837439787487386792386728abcd88379dc", s8);
/*
* Construct with a decimal string.
*/
auto t9 = get_start_time_ticks();
c8::integer v9("-3897894117580750151618270927682762897697428275427542907478758957487582700682675349287325097");
auto p9 = get_end_time_ticks() - t9;
std::stringstream s9;
s9 << v9;
res &= test_check("cons 9", p9, "-3897894117580750151618270927682762897697428275427542907478758957487582700682675349287325097", s9);
/*
* Construct with an octal string.
*/
auto t10 = get_start_time_ticks();
c8::integer v10("-0115415157637671751");
auto p10 = get_end_time_ticks() - t10;
std::stringstream s10;
s10 << std::oct << v10;
res &= test_check("cons 10", p10, "-115415157637671751", s10);
/*
* Attempt to construct with an invalid octal string.
*/
auto t11 = get_start_time_ticks();
try {
c8::integer v11("-01185415157637671751");
auto p11 = get_end_time_ticks() - t11;
res &= test_nocheck("cons 11", p11, "failed to throw exception", false);
} catch (const std::invalid_argument &e) {
auto p11 = get_end_time_ticks() - t11;
res &= test_nocheck("cons 11", p11, "exception thrown: " + std::string(e.what()), true);
} catch (...) {
auto p11 = get_end_time_ticks() - t11;
res &= test_nocheck("cons 11", p11, "unexpected exception thrown", false);
}
return res;
}
/*
* Test addition.
*/
auto test_add() -> bool {
bool res = true;
/*
* Add two positive values.
*/
c8::integer a0_0("31");
c8::integer a1_0("42");
auto t0 = get_start_time_ticks();
auto a2_0 = a0_0 + a1_0;
auto p0 = get_end_time_ticks() - t0;
std::stringstream s0;
s0 << a2_0;
res &= test_check("add 0", p0, "73", s0);
/*
* Add a positive and a negative value.
*/
c8::integer a0_1("42");
c8::integer a1_1("-21");
auto t1 = get_start_time_ticks();
auto a2_1 = a0_1 + a1_1;
auto p1 = get_end_time_ticks() - t1;
std::stringstream s1;
s1 << a2_1;
res &= test_check("add 1", p1, "21", s1);
/*
* Add a positive and a negative value that gives a negative result
*/
c8::integer a0_2("12345678");
c8::integer a1_2("-34738957485741895748957485743809574812345678");
auto t2 = get_start_time_ticks();
auto a2_2 = a0_2 + a1_2;
auto p2 = get_end_time_ticks() - t2;
std::stringstream s2;
s2 << a2_2;
res &= test_check("add 2", p2, "-34738957485741895748957485743809574800000000", s2);
/*
* Add two very large negative values.
*/
c8::integer a0_3("-10000000000000000000000000000000000000000000000000000000000000000008789");
c8::integer a1_3("-88888880000000000000000000000000000000000000000000000000000000999992000");
auto t3 = get_start_time_ticks();
auto a2_3 = a0_3 + a1_3;
auto p3 = get_end_time_ticks() - t3;
std::stringstream s3;
s3 << a2_3;
res &= test_check("add 3", p3, "-98888880000000000000000000000000000000000000000000000000000001000000789", s3);
return res;
}
/*
* Test subtraction.
*/
auto test_subtract() -> bool {
bool res = true;
/*
* Subtract a 1 digit value from another 1 digit value.
*/
c8::integer s0_0(52);
c8::integer s1_0(2);
auto t0 = get_start_time_ticks();
auto s2_0 = s0_0 - s1_0;
auto p0 = get_end_time_ticks() - t0;
std::stringstream s0;
s0 << s2_0;
res &= test_check("sub 0", p0, "50", s0);
/*
* Subtract a large negative value from another large negative value.
*/
c8::integer s0_1("-5872489572457574027439274027348275342809754320711018574807407090990940275827586671651690897");
c8::integer s1_1("-842758978027689671615847509157087514875097509475029454785478748571507457514754190754");
auto t1 = get_start_time_ticks();
auto s2_1 = s0_1 - s1_1;
auto p1 = get_end_time_ticks() - t1;
std::stringstream s1;
s1 << s2_1;
res &= test_check("sub 1", p1, "-5872488729698595999749602411500766185722239445613509099777952305512191704320129156897500143", s1);
/*
* Subtract a large negative value from a large value.
*/
c8::integer s0_2("10000000000000000000000000000000000000000000000000000000000000000000000");
c8::integer s1_2("-10000000000000000000000000000000000000000000000000000000000000000000000");
auto t2 = get_start_time_ticks();
auto s2_2 = s0_2 - s1_2;
auto p2 = get_end_time_ticks() - t2;
std::stringstream s2;
s2 << s2_2;
res &= test_check("sub 2", p2, "20000000000000000000000000000000000000000000000000000000000000000000000", s2);
/*
* Subtract a large value from a smaller one.
*/
c8::integer s0_3(2);
c8::integer s1_3(52);
auto t3 = get_start_time_ticks();
auto s2_3 = s0_3 - s1_3;
auto p3 = get_end_time_ticks() - t3;
std::stringstream s3;
s3 << s2_3;
res &= test_check("sub 3", p3, "-50", s3);
return res;
}
/*
* Test value comparisons.
*/
auto test_compare() -> bool {
bool res = true;
/*
* Compare two positive values.
*/
c8::integer co0_0(2);
c8::integer co1_0(1);
auto t0a = get_start_time_ticks();
auto co2_0a = (co0_0 == co1_0);
auto p0a = get_end_time_ticks() - t0a;
std::stringstream s0a;
s0a << co2_0a;
res &= test_check("comp 0a", p0a, "0", s0a);
auto t0b = get_start_time_ticks();
auto co2_0b = (co0_0 != co1_0);
auto p0b = get_end_time_ticks() - t0b;
std::stringstream s0b;
s0b << co2_0b;
res &= test_check("comp 0b", p0b, "1", s0b);
auto t0c = get_start_time_ticks();
auto co2_0c = (co0_0 > co1_0);
auto p0c = get_end_time_ticks() - t0c;
std::stringstream s0c;
s0c << co2_0c;
res &= test_check("comp 0c", p0c, "1", s0c);
auto t0d = get_start_time_ticks();
auto co2_0d = (co0_0 >= co1_0);
auto p0d = get_end_time_ticks() - t0d;
std::stringstream s0d;
s0d << co2_0d;
res &= test_check("comp 0d", p0d, "1", s0d);
auto t0e = get_start_time_ticks();
auto co2_0e = (co0_0 < co1_0);
auto p0e = get_end_time_ticks() - t0e;
std::stringstream s0e;
s0e << co2_0e;
res &= test_check("comp 0e", p0e, "0", s0e);
auto t0f = get_start_time_ticks();
auto co2_0f = (co0_0 <= co1_0);
auto p0f = get_end_time_ticks() - t0f;
std::stringstream s0f;
s0f << co2_0f;
res &= test_check("comp 0f", p0f, "0", s0f);
/*
* Compare a negative value with a positive one.
*/
c8::integer co0_1(-0x987654321LL);
c8::integer co1_1(1);
auto t1a = get_start_time_ticks();
auto co2_1a = (co0_1 == co1_1);
auto p1a = get_end_time_ticks() - t1a;
std::stringstream s1a;
s1a << co2_1a;
res &= test_check("comp 1a", p1a, "0", s1a);
auto t1b = get_start_time_ticks();
auto co2_1b = (co0_1 != co1_1);
auto p1b = get_end_time_ticks() - t1b;
std::stringstream s1b;
s1b << co2_1b;
res &= test_check("comp 1b", p1b, "1", s1b);
auto t1c = get_start_time_ticks();
auto co2_1c = (co0_1 > co1_1);
auto p1c = get_end_time_ticks() - t1c;
std::stringstream s1c;
s1c << co2_1c;
res &= test_check("comp 1c", p1c, "0", s1c);
auto t1d = get_start_time_ticks();
auto co2_1d = (co0_1 >= co1_1);
auto p1d = get_end_time_ticks() - t1d;
std::stringstream s1d;
s1d << co2_1d;
res &= test_check("comp 1d", p1d, "0", s1d);
auto t1e = get_start_time_ticks();
auto co2_1e = (co0_1 < co1_1);
auto p1e = get_end_time_ticks() - t1e;
std::stringstream s1e;
s1e << co2_1e;
res &= test_check("comp 1e", p1e, "1", s1e);
auto t1f = get_start_time_ticks();
auto co2_1f = (co0_1 <= co1_1);
auto p1f = get_end_time_ticks() - t1f;
std::stringstream s1f;
s1f << co2_1f;
res &= test_check("comp 1f", p1f, "1", s1f);
/*
* Compare a positive value with a negative one.
*/
c8::integer co0_2(1);
c8::integer co1_2(-0x987654321LL);
auto t2a = get_start_time_ticks();
auto co2_2a = (co0_2 == co1_2);
auto p2a = get_end_time_ticks() - t2a;
std::stringstream s2a;
s2a << co2_2a;
res &= test_check("comp 2a", p2a, "0", s2a);
auto t2b = get_start_time_ticks();
auto co2_2b = (co0_2 != co1_2);
auto p2b = get_end_time_ticks() - t2b;
std::stringstream s2b;
s2b << co2_2b;
res &= test_check("comp 2b", p2b, "1", s2b);
auto t2c = get_start_time_ticks();
auto co2_2c = (co0_2 > co1_2);
auto p2c = get_end_time_ticks() - t2c;
std::stringstream s2c;
s2c << co2_2c;
res &= test_check("comp 2c", p2c, "1", s2c);
auto t2d = get_start_time_ticks();
auto co2_2d = (co0_2 >= co1_2);
auto p2d = get_end_time_ticks() - t2d;
std::stringstream s2d;
s2d << co2_2d;
res &= test_check("comp 2d", p2d, "1", s2d);
auto t2e = get_start_time_ticks();
auto co2_2e = (co0_2 < co1_2);
auto p2e = get_end_time_ticks() - t2e;
std::stringstream s2e;
s2e << co2_2e;
res &= test_check("comp 2e", p2e, "0", s2e);
auto t2f = get_start_time_ticks();
auto co2_2f = (co0_2 <= co1_2);
auto p2f = get_end_time_ticks() - t2f;
std::stringstream s2f;
s2f << co2_2f;
res &= test_check("comp 2f", p2f, "0", s2f);
/*
* Compare two negative values.
*/
c8::integer co0_3(-0x2f987654321LL);
c8::integer co1_3(-0x2f987654321LL);
auto t3a = get_start_time_ticks();
auto co2_3a = (co0_3 == co1_3);
auto p3a = get_end_time_ticks() - t3a;
std::stringstream s3a;
s3a << co2_3a;
res &= test_check("comp 3a", p3a, "1", s3a);
auto t3b = get_start_time_ticks();
auto co2_3b = (co0_3 != co1_3);
auto p3b = get_end_time_ticks() - t3b;
std::stringstream s3b;
s3b << co2_3b;
res &= test_check("comp 3b", p3b, "0", s3b);
auto t3c = get_start_time_ticks();
auto co2_3c = (co0_3 > co1_3);
auto p3c = get_end_time_ticks() - t3c;
std::stringstream s3c;
s3c << co2_3c;
res &= test_check("comp 3c", p3c, "0", s3c);
auto t3d = get_start_time_ticks();
auto co2_3d = (co0_3 >= co1_3);
auto p3d = get_end_time_ticks() - t3d;
std::stringstream s3d;
s3d << co2_3d;
res &= test_check("comp 3d", p3d, "1", s3d);
auto t3e = get_start_time_ticks();
auto co2_3e = (co0_3 < co1_3);
auto p3e = get_end_time_ticks() - t3e;
std::stringstream s3e;
s3e << co2_3e;
res &= test_check("comp 3e", p3e, "0", s3e);
auto t3f = get_start_time_ticks();
auto co2_3f = (co0_3 <= co1_3);
auto p3f = get_end_time_ticks() - t3f;
std::stringstream s3f;
s3f << co2_3f;
res &= test_check("comp 3f", p3f, "1", s3f);
return res;
}
/*
* Test left shifting.
*/
auto test_lshift() -> bool {
bool res = true;
c8::integer l0_0(0x349f);
auto t0a = get_start_time_ticks();
auto l1_0a = l0_0 << 0;
auto p0a = get_end_time_ticks() - t0a;
std::stringstream s0a;
s0a << std::hex << l1_0a;
res &= test_check("lsh 0a", p0a, "349f", s0a);
auto t0b = get_start_time_ticks();
auto l1_0b = l0_0 << 1;
auto p0b = get_end_time_ticks() - t0b;
std::stringstream s0b;
s0b << std::hex << l1_0b;
res &= test_check("lsh 0b", p0b, "693e", s0b);
auto t0c = get_start_time_ticks();
auto l1_0c = l0_0 << 18;
auto p0c = get_end_time_ticks() - t0c;
std::stringstream s0c;
s0c << std::hex << l1_0c;
res &= test_check("lsh 0c", p0c, "d27c0000", s0c);
auto t0d = get_start_time_ticks();
auto l1_0d = l0_0 << 187;
auto p0d = get_end_time_ticks() - t0d;
std::stringstream s0d;
s0d << std::hex << l1_0d;
res &= test_check("lsh 0d", p0d, "1a4f80000000000000000000000000000000000000000000000", s0d);
c8::integer l0_1("-0x349f298375323985afbce9837928798789dffeffee987678687678676756562");
auto t1a = get_start_time_ticks();
auto l1_1a = l0_1 << 69;
auto p1a = get_end_time_ticks() - t1a;
std::stringstream s1a;
s1a << std::hex << l1_1a;
res &= test_check("lsh 1a", p1a, "-693e5306ea64730b5f79d306f250f30f13bffdffdd30ecf0d0ecf0ceceacac400000000000000000", s1a);
return res;
}
/*
* Test right shifting.
*/
auto test_rshift() -> bool {
bool res = true;
c8::integer r0_0("0x23490000000000000000000000000000000000000000000000000000");
auto t0a = get_start_time_ticks();
auto r1_0a = r0_0 >> 0;
auto p0a = get_end_time_ticks() - t0a;
std::stringstream s0a;
s0a << std::hex << r1_0a;
res &= test_check("rsh 0a", p0a, "23490000000000000000000000000000000000000000000000000000", s0a);
auto t0b = get_start_time_ticks();
auto r1_0b = r0_0 >> 1;
auto p0b = get_end_time_ticks() - t0b;
std::stringstream s0b;
s0b << std::hex << r1_0b;
res &= test_check("rsh 0b", p0b, "11a48000000000000000000000000000000000000000000000000000", s0b);
auto t0c = get_start_time_ticks();
auto r1_0c = r0_0 >> 19;
auto p0c = get_end_time_ticks() - t0c;
std::stringstream s0c;
s0c << std::hex << r1_0c;
res &= test_check("rsh 0c", p0c, "469200000000000000000000000000000000000000000000000", s0c);
auto t0d = get_start_time_ticks();
auto r1_0d = r0_0 >> 197;
auto p0d = get_end_time_ticks() - t0d;
std::stringstream s0d;
s0d << std::hex << r1_0d;
res &= test_check("rsh 0d", p0d, "11a4800", s0d);
c8::integer r0_1("-0x693e5306ea64730b5f79d306f250f30f13bffdffdd30ecf0d0ecf0ceceacac400000000000000000");
auto t1a = get_start_time_ticks();
auto r1_1a = r0_1 >> 123;
auto p1a = get_end_time_ticks() - t1a;
std::stringstream s1a;
s1a << std::hex << r1_1a;
res &= test_check("rsh 1a", p1a, "-d27ca60dd4c8e616bef3a60de4a1e61e277ffbffba61d9e1a", s1a);
return res;
}
/*
* Test multiplication.
*/
auto test_multiply() -> bool {
bool res = true;
c8::integer mu0_0(3);
c8::integer mu1_0(22);
auto t0 = get_start_time_ticks();
auto mu2_0 = mu0_0 * mu1_0;
auto p0 = get_end_time_ticks() - t0;
std::stringstream s0;
s0 << mu2_0;
res &= test_check("mul 0", p0, "66", s0);
c8::integer mu0_1(1000000000000000000LL);
c8::integer mu1_1("-9999999999999999999");
auto t1 = get_start_time_ticks();
auto mu2_1 = mu0_1 * mu1_1;
auto p1 = get_end_time_ticks() - t1;
std::stringstream s1;
s1 << mu2_1;
res &= test_check("mul 1", p1, "-9999999999999999999000000000000000000", s1);
c8::integer mu0_2(-0x2000000000000000LL);
c8::integer mu1_2(0x4000000000000000LL);
auto t2 = get_start_time_ticks();
auto mu2_2 = mu0_2 * mu1_2;
auto p2 = get_end_time_ticks() - t2;
std::stringstream s2;
s2 << std::hex << mu2_2;
res &= test_check("mul 2", p2, "-8000000000000000000000000000000", s2);
c8::integer mu0_3("-12345678901234567890123456789012345678901234567890123456789012345678901234567890");
c8::integer mu1_3("-1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890");
auto t3 = get_start_time_ticks();
auto mu2_3 = mu0_3 * mu1_3;
auto p3 = get_end_time_ticks() - t3;
std::stringstream s3;
s3 << mu2_3;
res &= test_check("mul 3", p3, "15241578753238836750495351562566681945008382873376009755225118122311263526910001371743100137174310012193273126047859425087639153757049236500533455762536198787501905199875019052100", s3);
return res;
}
/*
* Test division.
*/
auto test_divide() -> bool {
bool res = true;
c8::integer d0_0(1000000000000000000LL);
c8::integer d1_0(99999999999999999LL);
auto t0 = get_start_time_ticks();
auto d2_0 = d0_0 / d1_0;
auto mo2_0 = d0_0 % d1_0;
auto p0 = get_end_time_ticks() - t0;
std::stringstream s0a;
s0a << d2_0;
res &= test_check("div 0a", p0, "10", s0a);
std::stringstream s0b;
s0b << mo2_0;
res &= test_check("div 0b", p0, "10", s0b);
c8::integer d0_1("7829238792751875818917817519758789749174743847389742871867617465710657162");
c8::integer d1_1(-99999999999999999LL);
auto t1 = get_start_time_ticks();
auto d2_1 = d0_1 / d1_1;
auto mo2_1 = d0_1 % d1_1;
auto p1 = get_end_time_ticks() - t1;
std::stringstream s1a;
s1a << d2_1;
res &= test_check("div 1a", p1, "-78292387927518758972102054472775487212767983201652300846", s1a);
std::stringstream s1b;
s1b << mo2_1;
res &= test_check("div 1b", p1, "35600667362958008", s1b);
c8::integer d0_2("-0x100000000000000000000000000000000000000000000000000000000000000000000000");
c8::integer d1_2("0x10000000000000001000000000000000100000000");
auto t2 = get_start_time_ticks();
auto d2_2 = d0_2 / d1_2;
auto mo2_2 = d0_2 % d1_2;
auto p2 = get_end_time_ticks() - t2;
std::stringstream s2a;
s2a << std::hex << d2_2;
res &= test_check("div 2a", p2, "-ffffffffffffffff000000000000000", s2a);
std::stringstream s2b;
s2b << std::hex << mo2_2;
res &= test_check("div 2b", p2, "100000000000000000000000", s2b);
/*
* Divide by zero. This will throw an exception!
*/
c8::integer d0_3(2000);
c8::integer d1_3(0);
auto t3 = get_start_time_ticks();
try {
auto d2_3 = d0_3 / d1_3;
auto p3 = get_end_time_ticks() - t3;
std::stringstream s3;
s3 << d2_3;
res &= test_nocheck("div 3", p3, "failed to throw exception", false);
} catch (const std::logic_error &e) {
auto p3 = get_end_time_ticks() - t3;
res &= test_nocheck("div 3", p3, "exception thrown: " + std::string(e.what()), true);
} catch (...) {
auto p3 = get_end_time_ticks() - t3;
res &= test_nocheck("div 3", p3, "unexpected exception thrown", false);
}
c8::integer d0_4(-1000000000000000000LL);
c8::integer d1_4(-99999999999999999LL);
auto t4 = get_start_time_ticks();
auto d2_4 = d0_4 / d1_4;
auto mo2_4 = d0_4 % d1_4;
auto p4 = get_end_time_ticks() - t4;
std::stringstream s4a;
s4a << d2_4;
res &= test_check("div 4a", p4, "10", s4a);
std::stringstream s4b;
s4b << mo2_4;
res &= test_check("div 4b", p4, "10", s4b);
return res;
}
/*
* Test printing.
*/
auto test_print() -> bool {
bool res = true;
c8::integer v("-0xfedcfedc0123456789");
std::stringstream s0;
auto t0 = get_start_time_ticks();
s0 << v;
auto p0 = get_end_time_ticks() - t0;
res &= test_check("prn 0", p0, "-4701397401952099592073", s0);
std::stringstream s1;
auto t1 = get_start_time_ticks();
s1 << std::hex << v;
auto p1 = get_end_time_ticks() - t1;
res &= test_check("prn 1", p1, "-fedcfedc0123456789", s1);
std::stringstream s2;
auto t2 = get_start_time_ticks();
s2 << std::uppercase << std::hex << v;
auto p2 = get_end_time_ticks() - t2;
res &= test_check("prn 2", p2, "-FEDCFEDC0123456789", s2);
std::stringstream s3;
auto t3 = get_start_time_ticks();
s3 << std::oct << v;
auto p3 = get_end_time_ticks() - t3;
res &= test_check("prn 3", p3, "-775563766700044321263611", s3);
std::stringstream s4;
auto t4 = get_start_time_ticks();
s4 << std::showbase << v;
auto p4 = get_end_time_ticks() - t4;
res &= test_check("prn 4", p4, "-4701397401952099592073", s4);
std::stringstream s5;
auto t5 = get_start_time_ticks();
s5 << std::showbase << std::hex << v;
auto p5 = get_end_time_ticks() - t5;
res &= test_check("prn 5", p5, "-0xfedcfedc0123456789", s5);
std::stringstream s6;
auto t6 = get_start_time_ticks();
s6 << std::showbase << std::uppercase << std::hex << v;
auto p6 = get_end_time_ticks() - t6;
res &= test_check("prn 6", p6, "-0XFEDCFEDC0123456789", s6);
std::stringstream s7;
auto t7 = get_start_time_ticks();
s7 << std::showbase << std::oct << v;
auto p7 = get_end_time_ticks() - t7;
res &= test_check("prn 7", p7, "-0775563766700044321263611", s7);
return res;
}
/*
* Report the usage for this test program.
*/
static auto usage(const char *name) -> void {
std::cerr << "usage: " << name << " [OPTIONS]\n\n";
std::cerr << "Options\n";
std::cerr << " -v Verbose reporting (optional)\n\n";
}
/*
* Entry point.
*/
auto main(int argc, char **argv) -> int {
/*
* Parse the command line options.
*/
int ch;
while ((ch = getopt(argc, argv, "v?")) != -1) {
switch (ch) {
case 'v':
verbose = true;
break;
case '?':
usage(argv[0]);
exit(-1);
}
}
bool res = true;
res &= test_construct();
res &= test_add();
res &= test_subtract();
res &= test_compare();
res &= test_lshift();
res &= test_rshift();
res &= test_multiply();
res &= test_divide();
res &= test_print();
if (!res) {
std::cout << "TESTS FAILED!\n";
exit(-1);
}
std::cout << "All tests passed\n";
return 0;
}
|
#include "test/integration/integration_test.h"
#include <string>
#include "envoy/config/accesslog/v2/file.pb.h"
#include "common/filesystem/filesystem_impl.h"
#include "common/http/header_map_impl.h"
#include "common/http/headers.h"
#include "common/protobuf/utility.h"
#include "test/integration/utility.h"
#include "test/mocks/http/mocks.h"
#include "test/test_common/network_utility.h"
#include "test/test_common/printers.h"
#include "test/test_common/utility.h"
#include "gtest/gtest.h"
using Envoy::Http::Headers;
using Envoy::Http::HeaderValueOf;
using Envoy::Http::HttpStatusIs;
using testing::EndsWith;
using testing::HasSubstr;
using testing::MatchesRegex;
using testing::Not;
namespace Envoy {
INSTANTIATE_TEST_CASE_P(IpVersions, IntegrationTest,
testing::ValuesIn(TestEnvironment::getIpVersionsForTest()),
TestUtility::ipTestParamsToString);
TEST_P(IntegrationTest, RouterNotFound) { testRouterNotFound(); }
TEST_P(IntegrationTest, RouterNotFoundBodyNoBuffer) { testRouterNotFoundWithBody(); }
TEST_P(IntegrationTest, RouterClusterNotFound404) { testRouterClusterNotFound404(); }
TEST_P(IntegrationTest, RouterClusterNotFound503) { testRouterClusterNotFound503(); }
TEST_P(IntegrationTest, RouterRedirect) { testRouterRedirect(); }
TEST_P(IntegrationTest, RouterDirectResponse) { testRouterDirectResponse(); }
TEST_P(IntegrationTest, ComputedHealthCheck) { testComputedHealthCheck(); }
TEST_P(IntegrationTest, AddEncodedTrailers) { testAddEncodedTrailers(); }
TEST_P(IntegrationTest, DrainClose) { testDrainClose(); }
TEST_P(IntegrationTest, ConnectionClose) {
config_helper_.addFilter(ConfigHelper::DEFAULT_HEALTH_CHECK_FILTER);
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response =
codec_client_->makeHeaderOnlyRequest(Http::TestHeaderMapImpl{{":method", "GET"},
{":path", "/healthcheck"},
{":authority", "host"},
{"connection", "close"}});
response->waitForEndStream();
codec_client_->waitForDisconnect();
EXPECT_TRUE(response->complete());
EXPECT_THAT(response->headers(), HttpStatusIs("200"));
}
TEST_P(IntegrationTest, RouterRequestAndResponseWithBodyNoBuffer) {
testRouterRequestAndResponseWithBody(1024, 512, false);
}
TEST_P(IntegrationTest, FlowControlOnAndGiantBody) {
config_helper_.setBufferLimits(1024, 1024);
testRouterRequestAndResponseWithBody(1024 * 1024, 1024 * 1024, false);
}
TEST_P(IntegrationTest, RouterRequestAndResponseLargeHeaderNoBuffer) {
testRouterRequestAndResponseWithBody(1024, 512, true);
}
TEST_P(IntegrationTest, RouterHeaderOnlyRequestAndResponseNoBuffer) {
testRouterHeaderOnlyRequestAndResponse(true);
}
TEST_P(IntegrationTest, ShutdownWithActiveConnPoolConnections) {
testRouterHeaderOnlyRequestAndResponse(false);
}
TEST_P(IntegrationTest, RouterUpstreamDisconnectBeforeRequestcomplete) {
testRouterUpstreamDisconnectBeforeRequestComplete();
}
TEST_P(IntegrationTest, RouterUpstreamDisconnectBeforeResponseComplete) {
testRouterUpstreamDisconnectBeforeResponseComplete();
}
TEST_P(IntegrationTest, RouterDownstreamDisconnectBeforeRequestComplete) {
testRouterDownstreamDisconnectBeforeRequestComplete();
}
TEST_P(IntegrationTest, RouterDownstreamDisconnectBeforeResponseComplete) {
testRouterDownstreamDisconnectBeforeResponseComplete();
}
TEST_P(IntegrationTest, RouterUpstreamResponseBeforeRequestComplete) {
testRouterUpstreamResponseBeforeRequestComplete();
}
TEST_P(IntegrationTest, Retry) { testRetry(); }
TEST_P(IntegrationTest, RetryAttemptCount) { testRetryAttemptCountHeader(); }
TEST_P(IntegrationTest, RetryHostPredicateFilter) { testRetryHostPredicateFilter(); }
TEST_P(IntegrationTest, RetryPriority) { testRetryPriority(); }
TEST_P(IntegrationTest, EnvoyHandling100Continue) { testEnvoyHandling100Continue(); }
TEST_P(IntegrationTest, EnvoyHandlingDuplicate100Continues) { testEnvoyHandling100Continue(true); }
TEST_P(IntegrationTest, EnvoyProxyingEarly100Continue) { testEnvoyProxying100Continue(true); }
TEST_P(IntegrationTest, EnvoyProxyingLate100Continue) { testEnvoyProxying100Continue(false); }
TEST_P(IntegrationTest, EnvoyProxyingEarly100ContinueWithEncoderFilter) {
testEnvoyProxying100Continue(true, true);
}
TEST_P(IntegrationTest, EnvoyProxyingLate100ContinueWithEncoderFilter) {
testEnvoyProxying100Continue(false, true);
}
TEST_P(IntegrationTest, TwoRequests) { testTwoRequests(); }
TEST_P(IntegrationTest, TwoRequestsWithForcedBackup) { testTwoRequests(true); }
TEST_P(IntegrationTest, UpstreamDisconnectWithTwoRequests) {
testUpstreamDisconnectWithTwoRequests();
}
TEST_P(IntegrationTest, EncodingHeaderOnlyResponse) { testHeadersOnlyFilterEncoding(); }
TEST_P(IntegrationTest, DecodingHeaderOnlyResponse) { testHeadersOnlyFilterDecoding(); }
TEST_P(IntegrationTest, EncodingHeaderOnlyResponseIntermediateFilters) {
testHeadersOnlyFilterEncodingIntermediateFilters();
}
TEST_P(IntegrationTest, DecodingHeaderOnlyResponseIntermediateFilters) {
testHeadersOnlyFilterDecodingIntermediateFilters();
}
TEST_P(IntegrationTest, DecodingHeaderOnlyInterleaved) { testHeadersOnlyFilterInterleaved(); }
TEST_P(IntegrationTest, RetryHittingBufferLimit) { testRetryHittingBufferLimit(); }
TEST_P(IntegrationTest, HittingDecoderFilterLimit) { testHittingDecoderFilterLimit(); }
// Tests idle timeout behaviour with single request and validates that idle timer kicks in
// after given timeout.
TEST_P(IntegrationTest, IdleTimoutBasic) { testIdleTimeoutBasic(); }
// Tests idle timeout behaviour with multiple requests and validates that idle timer kicks in
// after both the requests are done.
TEST_P(IntegrationTest, IdleTimeoutWithTwoRequests) { testIdleTimeoutWithTwoRequests(); }
// Test hitting the bridge filter with too many response bytes to buffer. Given
// the headers are not proxied, the connection manager will send a local error reply.
TEST_P(IntegrationTest, HittingGrpcFilterLimitBufferingHeaders) {
config_helper_.addFilter("{ name: envoy.grpc_http1_bridge, config: {} }");
config_helper_.setBufferLimits(1024, 1024);
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response = codec_client_->makeHeaderOnlyRequest(
Http::TestHeaderMapImpl{{":method", "POST"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"},
{"content-type", "application/grpc"},
{"x-envoy-retry-grpc-on", "cancelled"}});
waitForNextUpstreamRequest();
// Send the overly large response. Because the grpc_http1_bridge filter buffers and buffer
// limits are exceeded, this will be translated into an unknown gRPC error.
upstream_request_->encodeHeaders(Http::TestHeaderMapImpl{{":status", "200"}}, false);
fake_upstreams_[0]->set_allow_unexpected_disconnects(true);
upstream_request_->encodeData(1024 * 65, false);
ASSERT_TRUE(fake_upstream_connection_->waitForDisconnect());
response->waitForEndStream();
EXPECT_TRUE(response->complete());
EXPECT_THAT(response->headers(), HttpStatusIs("200"));
EXPECT_THAT(response->headers(),
HeaderValueOf(Headers::get().GrpcStatus, "2")); // Unknown gRPC error
}
TEST_P(IntegrationTest, HittingEncoderFilterLimit) { testHittingEncoderFilterLimit(); }
TEST_P(IntegrationTest, BadFirstline) { testBadFirstline(); }
TEST_P(IntegrationTest, MissingDelimiter) { testMissingDelimiter(); }
TEST_P(IntegrationTest, InvalidCharacterInFirstline) { testInvalidCharacterInFirstline(); }
TEST_P(IntegrationTest, InvalidVersion) { testInvalidVersion(); }
TEST_P(IntegrationTest, Http10Disabled) { testHttp10Disabled(); }
TEST_P(IntegrationTest, Http09Enabled) { testHttp09Enabled(); }
TEST_P(IntegrationTest, Http10Enabled) { testHttp10Enabled(); }
TEST_P(IntegrationTest, TestInlineHeaders) { testInlineHeaders(); }
TEST_P(IntegrationTest, Http10WithHostandKeepAlive) { testHttp10WithHostAndKeepAlive(); }
TEST_P(IntegrationTest, NoHost) { testNoHost(); }
TEST_P(IntegrationTest, BadPath) { testBadPath(); }
TEST_P(IntegrationTest, AbsolutePath) { testAbsolutePath(); }
TEST_P(IntegrationTest, AbsolutePathWithPort) { testAbsolutePathWithPort(); }
TEST_P(IntegrationTest, AbsolutePathWithoutPort) { testAbsolutePathWithoutPort(); }
TEST_P(IntegrationTest, Connect) { testConnect(); }
TEST_P(IntegrationTest, ValidZeroLengthContent) { testValidZeroLengthContent(); }
TEST_P(IntegrationTest, InvalidContentLength) { testInvalidContentLength(); }
TEST_P(IntegrationTest, MultipleContentLengths) { testMultipleContentLengths(); }
TEST_P(IntegrationTest, OverlyLongHeaders) { testOverlyLongHeaders(); }
TEST_P(IntegrationTest, UpstreamProtocolError) { testUpstreamProtocolError(); }
TEST_P(IntegrationTest, TestHead) {
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
Http::TestHeaderMapImpl head_request{{":method", "HEAD"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"}};
// Without an explicit content length, assume we chunk for HTTP/1.1
auto response = sendRequestAndWaitForResponse(head_request, 0, default_response_headers_, 0);
ASSERT_TRUE(response->complete());
EXPECT_THAT(response->headers(), HttpStatusIs("200"));
EXPECT_EQ(response->headers().ContentLength(), nullptr);
EXPECT_THAT(response->headers(),
HeaderValueOf(Headers::get().TransferEncoding,
Http::Headers::get().TransferEncodingValues.Chunked));
EXPECT_EQ(0, response->body().size());
// Preserve explicit content length.
Http::TestHeaderMapImpl content_length_response{{":status", "200"}, {"content-length", "12"}};
response = sendRequestAndWaitForResponse(head_request, 0, content_length_response, 0);
ASSERT_TRUE(response->complete());
EXPECT_THAT(response->headers(), HttpStatusIs("200"));
EXPECT_THAT(response->headers(), HeaderValueOf(Headers::get().ContentLength, "12"));
EXPECT_EQ(response->headers().TransferEncoding(), nullptr);
EXPECT_EQ(0, response->body().size());
cleanupUpstreamAndDownstream();
}
// The Envoy HTTP/1.1 codec ASSERTs that T-E headers are cleared in
// encodeHeaders, so to test upstreams explicitly sending T-E: chunked we have
// to send raw HTTP.
TEST_P(IntegrationTest, TestHeadWithExplicitTE) {
initialize();
auto tcp_client = makeTcpConnection(lookupPort("http"));
tcp_client->write("HEAD / HTTP/1.1\r\nHost: host\r\n\r\n");
FakeRawConnectionPtr fake_upstream_connection;
ASSERT_TRUE(fake_upstreams_[0]->waitForRawConnection(fake_upstream_connection));
std::string data;
ASSERT_TRUE(fake_upstream_connection->waitForData(
FakeRawConnection::waitForInexactMatch("\r\n\r\n"), &data));
ASSERT_TRUE(
fake_upstream_connection->write("HTTP/1.1 200 OK\r\nTransfer-encoding: chunked\r\n\r\n"));
tcp_client->waitForData("\r\n\r\n", false);
std::string response = tcp_client->data();
EXPECT_THAT(response, HasSubstr("HTTP/1.1 200 OK\r\n"));
EXPECT_THAT(response, Not(HasSubstr("content-length")));
EXPECT_THAT(response, HasSubstr("transfer-encoding: chunked\r\n"));
EXPECT_THAT(response, EndsWith("\r\n\r\n"));
ASSERT_TRUE(fake_upstream_connection->close());
ASSERT_TRUE(fake_upstream_connection->waitForDisconnect());
tcp_client->close();
}
TEST_P(IntegrationTest, TestBind) {
std::string address_string;
if (GetParam() == Network::Address::IpVersion::v4) {
address_string = TestUtility::getIpv4Loopback();
} else {
address_string = "::1";
}
config_helper_.setSourceAddress(address_string);
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response =
codec_client_->makeRequestWithBody(Http::TestHeaderMapImpl{{":method", "GET"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"}},
1024);
ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_));
ASSERT_NE(fake_upstream_connection_, nullptr);
std::string address =
fake_upstream_connection_->connection().remoteAddress()->ip()->addressAsString();
EXPECT_EQ(address, address_string);
ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_));
ASSERT_NE(upstream_request_, nullptr);
ASSERT_TRUE(upstream_request_->waitForEndStream(*dispatcher_));
cleanupUpstreamAndDownstream();
}
TEST_P(IntegrationTest, TestFailedBind) {
config_helper_.setSourceAddress("8.8.8.8");
initialize();
// Envoy will create and close some number of connections when trying to bind.
// Make sure they don't cause assertion failures when we ignore them.
fake_upstreams_[0]->set_allow_unexpected_disconnects(true);
codec_client_ = makeHttpConnection(lookupPort("http"));
// With no ability to successfully bind on an upstream connection Envoy should
// send a 500.
auto response = codec_client_->makeHeaderOnlyRequest(
Http::TestHeaderMapImpl{{":method", "GET"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"},
{"x-forwarded-for", "10.0.0.1"},
{"x-envoy-upstream-rq-timeout-ms", "1000"}});
response->waitForEndStream();
EXPECT_TRUE(response->complete());
EXPECT_THAT(response->headers(), HttpStatusIs("503"));
EXPECT_LT(0, test_server_->counter("cluster.cluster_0.bind_errors")->value());
}
ConfigHelper::HttpModifierFunction setVia(const std::string& via) {
return
[via](
envoy::config::filter::network::http_connection_manager::v2::HttpConnectionManager& hcm) {
hcm.set_via(via);
};
}
// Validate in a basic header-only request we get via header insertion.
TEST_P(IntegrationTest, ViaAppendHeaderOnly) {
config_helper_.addConfigModifier(setVia("bar"));
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response =
codec_client_->makeHeaderOnlyRequest(Http::TestHeaderMapImpl{{":method", "GET"},
{":path", "/test/long/url"},
{":authority", "host"},
{"via", "foo"},
{"connection", "close"}});
waitForNextUpstreamRequest();
EXPECT_THAT(upstream_request_->headers(), HeaderValueOf(Headers::get().Via, "foo, bar"));
upstream_request_->encodeHeaders(Http::TestHeaderMapImpl{{":status", "200"}}, true);
response->waitForEndStream();
codec_client_->waitForDisconnect();
EXPECT_TRUE(response->complete());
EXPECT_THAT(response->headers(), HttpStatusIs("200"));
EXPECT_THAT(response->headers(), HeaderValueOf(Headers::get().Via, "bar"));
}
// Validate that 100-continue works as expected with via header addition on both request and
// response path.
TEST_P(IntegrationTest, ViaAppendWith100Continue) {
config_helper_.addConfigModifier(setVia("foo"));
}
// Test delayed close semantics for downstream HTTP/1.1 connections. When an early response is
// sent by Envoy, it will wait for response acknowledgment (via FIN/RST) from the client before
// closing the socket (with a timeout for ensuring cleanup).
TEST_P(IntegrationTest, TestDelayedConnectionTeardownOnGracefulClose) {
// This test will trigger an early 413 Payload Too Large response due to buffer limits being
// exceeded. The following filter is needed since the router filter will never trigger a 413.
config_helper_.addFilter("{ name: envoy.http_dynamo_filter, config: {} }");
config_helper_.setBufferLimits(1024, 1024);
initialize();
fake_upstreams_[0]->set_allow_unexpected_disconnects(true);
codec_client_ = makeHttpConnection(lookupPort("http"));
auto encoder_decoder =
codec_client_->startRequest(Http::TestHeaderMapImpl{{":method", "POST"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"}});
request_encoder_ = &encoder_decoder.first;
auto response = std::move(encoder_decoder.second);
codec_client_->sendData(*request_encoder_, 1024 * 65, false);
response->waitForEndStream();
EXPECT_TRUE(response->complete());
EXPECT_STREQ("413", response->headers().Status()->value().c_str());
// With no delayed close processing, Envoy will close the connection immediately after flushing
// and this should instead return true.
EXPECT_FALSE(codec_client_->waitForDisconnect(std::chrono::milliseconds(500)));
// Issue a local close and check that the client did not pick up a remote close which can happen
// when delayed close semantics are disabled.
codec_client_->connection()->close(Network::ConnectionCloseType::NoFlush);
EXPECT_EQ(codec_client_->last_connection_event(), Network::ConnectionEvent::LocalClose);
}
// Test configuration of the delayed close timeout on downstream HTTP/1.1 connections. A value of 0
// disables delayed close processing.
TEST_P(IntegrationTest, TestDelayedConnectionTeardownConfig) {
config_helper_.addFilter("{ name: envoy.http_dynamo_filter, config: {} }");
config_helper_.setBufferLimits(1024, 1024);
config_helper_.addConfigModifier(
[](envoy::config::filter::network::http_connection_manager::v2::HttpConnectionManager& hcm) {
hcm.mutable_delayed_close_timeout()->set_seconds(0);
});
initialize();
fake_upstreams_[0]->set_allow_unexpected_disconnects(true);
codec_client_ = makeHttpConnection(lookupPort("http"));
auto encoder_decoder =
codec_client_->startRequest(Http::TestHeaderMapImpl{{":method", "POST"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"}});
request_encoder_ = &encoder_decoder.first;
auto response = std::move(encoder_decoder.second);
codec_client_->sendData(*request_encoder_, 1024 * 65, false);
response->waitForEndStream();
// There is a potential race in the client's response processing when delayed close logic is
// disabled in Envoy (see https://github.com/envoyproxy/envoy/issues/2929). Depending on timing,
// a client may receive an RST prior to reading the response data from the socket, which may clear
// the receive buffers. Also, clients which don't flush the receive buffer upon receiving a remote
// close may also lose data (Envoy is susceptible to this).
// Therefore, avoid checking response code/payload here and instead simply look for the remote
// close.
EXPECT_TRUE(codec_client_->waitForDisconnect(std::chrono::milliseconds(500)));
EXPECT_EQ(codec_client_->last_connection_event(), Network::ConnectionEvent::RemoteClose);
}
// Test that delay closed connections are eventually force closed when the timeout triggers.
TEST_P(IntegrationTest, TestDelayedConnectionTeardownTimeoutTrigger) {
config_helper_.addFilter("{ name: envoy.http_dynamo_filter, config: {} }");
config_helper_.setBufferLimits(1024, 1024);
config_helper_.addConfigModifier(
[](envoy::config::filter::network::http_connection_manager::v2::HttpConnectionManager& hcm) {
// 200ms.
hcm.mutable_delayed_close_timeout()->set_nanos(200000000);
});
initialize();
fake_upstreams_[0]->set_allow_unexpected_disconnects(true);
codec_client_ = makeHttpConnection(lookupPort("http"));
auto encoder_decoder =
codec_client_->startRequest(Http::TestHeaderMapImpl{{":method", "POST"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"}});
request_encoder_ = &encoder_decoder.first;
auto response = std::move(encoder_decoder.second);
codec_client_->sendData(*request_encoder_, 1024 * 65, false);
response->waitForEndStream();
// The delayed close timeout should trigger since client is not closing the connection.
EXPECT_TRUE(codec_client_->waitForDisconnect(std::chrono::milliseconds(2000)));
EXPECT_EQ(codec_client_->last_connection_event(), Network::ConnectionEvent::RemoteClose);
EXPECT_EQ(test_server_->counter("http.config_test.downstream_cx_delayed_close_timeout")->value(),
1);
}
} // namespace Envoy
test: fixing a test bug (#5118)
Risk Level: n/a (test only)
Testing: now testing 100 continue with via
Docs Changes: n/a
Release Notes: n/a
Signed-off-by: Alyssa Wilk <b9253d1ec9cc3e9d2aab68d288ba3dab3452adf6@chromium.org>
#include "test/integration/integration_test.h"
#include <string>
#include "envoy/config/accesslog/v2/file.pb.h"
#include "common/filesystem/filesystem_impl.h"
#include "common/http/header_map_impl.h"
#include "common/http/headers.h"
#include "common/protobuf/utility.h"
#include "test/integration/utility.h"
#include "test/mocks/http/mocks.h"
#include "test/test_common/network_utility.h"
#include "test/test_common/printers.h"
#include "test/test_common/utility.h"
#include "gtest/gtest.h"
using Envoy::Http::Headers;
using Envoy::Http::HeaderValueOf;
using Envoy::Http::HttpStatusIs;
using testing::EndsWith;
using testing::HasSubstr;
using testing::MatchesRegex;
using testing::Not;
namespace Envoy {
INSTANTIATE_TEST_CASE_P(IpVersions, IntegrationTest,
testing::ValuesIn(TestEnvironment::getIpVersionsForTest()),
TestUtility::ipTestParamsToString);
TEST_P(IntegrationTest, RouterNotFound) { testRouterNotFound(); }
TEST_P(IntegrationTest, RouterNotFoundBodyNoBuffer) { testRouterNotFoundWithBody(); }
TEST_P(IntegrationTest, RouterClusterNotFound404) { testRouterClusterNotFound404(); }
TEST_P(IntegrationTest, RouterClusterNotFound503) { testRouterClusterNotFound503(); }
TEST_P(IntegrationTest, RouterRedirect) { testRouterRedirect(); }
TEST_P(IntegrationTest, RouterDirectResponse) { testRouterDirectResponse(); }
TEST_P(IntegrationTest, ComputedHealthCheck) { testComputedHealthCheck(); }
TEST_P(IntegrationTest, AddEncodedTrailers) { testAddEncodedTrailers(); }
TEST_P(IntegrationTest, DrainClose) { testDrainClose(); }
TEST_P(IntegrationTest, ConnectionClose) {
config_helper_.addFilter(ConfigHelper::DEFAULT_HEALTH_CHECK_FILTER);
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response =
codec_client_->makeHeaderOnlyRequest(Http::TestHeaderMapImpl{{":method", "GET"},
{":path", "/healthcheck"},
{":authority", "host"},
{"connection", "close"}});
response->waitForEndStream();
codec_client_->waitForDisconnect();
EXPECT_TRUE(response->complete());
EXPECT_THAT(response->headers(), HttpStatusIs("200"));
}
TEST_P(IntegrationTest, RouterRequestAndResponseWithBodyNoBuffer) {
testRouterRequestAndResponseWithBody(1024, 512, false);
}
TEST_P(IntegrationTest, FlowControlOnAndGiantBody) {
config_helper_.setBufferLimits(1024, 1024);
testRouterRequestAndResponseWithBody(1024 * 1024, 1024 * 1024, false);
}
TEST_P(IntegrationTest, RouterRequestAndResponseLargeHeaderNoBuffer) {
testRouterRequestAndResponseWithBody(1024, 512, true);
}
TEST_P(IntegrationTest, RouterHeaderOnlyRequestAndResponseNoBuffer) {
testRouterHeaderOnlyRequestAndResponse(true);
}
TEST_P(IntegrationTest, ShutdownWithActiveConnPoolConnections) {
testRouterHeaderOnlyRequestAndResponse(false);
}
TEST_P(IntegrationTest, RouterUpstreamDisconnectBeforeRequestcomplete) {
testRouterUpstreamDisconnectBeforeRequestComplete();
}
TEST_P(IntegrationTest, RouterUpstreamDisconnectBeforeResponseComplete) {
testRouterUpstreamDisconnectBeforeResponseComplete();
}
TEST_P(IntegrationTest, RouterDownstreamDisconnectBeforeRequestComplete) {
testRouterDownstreamDisconnectBeforeRequestComplete();
}
TEST_P(IntegrationTest, RouterDownstreamDisconnectBeforeResponseComplete) {
testRouterDownstreamDisconnectBeforeResponseComplete();
}
TEST_P(IntegrationTest, RouterUpstreamResponseBeforeRequestComplete) {
testRouterUpstreamResponseBeforeRequestComplete();
}
TEST_P(IntegrationTest, Retry) { testRetry(); }
TEST_P(IntegrationTest, RetryAttemptCount) { testRetryAttemptCountHeader(); }
TEST_P(IntegrationTest, RetryHostPredicateFilter) { testRetryHostPredicateFilter(); }
TEST_P(IntegrationTest, RetryPriority) { testRetryPriority(); }
TEST_P(IntegrationTest, EnvoyHandling100Continue) { testEnvoyHandling100Continue(); }
TEST_P(IntegrationTest, EnvoyHandlingDuplicate100Continues) { testEnvoyHandling100Continue(true); }
TEST_P(IntegrationTest, EnvoyProxyingEarly100Continue) { testEnvoyProxying100Continue(true); }
TEST_P(IntegrationTest, EnvoyProxyingLate100Continue) { testEnvoyProxying100Continue(false); }
TEST_P(IntegrationTest, EnvoyProxyingEarly100ContinueWithEncoderFilter) {
testEnvoyProxying100Continue(true, true);
}
TEST_P(IntegrationTest, EnvoyProxyingLate100ContinueWithEncoderFilter) {
testEnvoyProxying100Continue(false, true);
}
TEST_P(IntegrationTest, TwoRequests) { testTwoRequests(); }
TEST_P(IntegrationTest, TwoRequestsWithForcedBackup) { testTwoRequests(true); }
TEST_P(IntegrationTest, UpstreamDisconnectWithTwoRequests) {
testUpstreamDisconnectWithTwoRequests();
}
TEST_P(IntegrationTest, EncodingHeaderOnlyResponse) { testHeadersOnlyFilterEncoding(); }
TEST_P(IntegrationTest, DecodingHeaderOnlyResponse) { testHeadersOnlyFilterDecoding(); }
TEST_P(IntegrationTest, EncodingHeaderOnlyResponseIntermediateFilters) {
testHeadersOnlyFilterEncodingIntermediateFilters();
}
TEST_P(IntegrationTest, DecodingHeaderOnlyResponseIntermediateFilters) {
testHeadersOnlyFilterDecodingIntermediateFilters();
}
TEST_P(IntegrationTest, DecodingHeaderOnlyInterleaved) { testHeadersOnlyFilterInterleaved(); }
TEST_P(IntegrationTest, RetryHittingBufferLimit) { testRetryHittingBufferLimit(); }
TEST_P(IntegrationTest, HittingDecoderFilterLimit) { testHittingDecoderFilterLimit(); }
// Tests idle timeout behaviour with single request and validates that idle timer kicks in
// after given timeout.
TEST_P(IntegrationTest, IdleTimoutBasic) { testIdleTimeoutBasic(); }
// Tests idle timeout behaviour with multiple requests and validates that idle timer kicks in
// after both the requests are done.
TEST_P(IntegrationTest, IdleTimeoutWithTwoRequests) { testIdleTimeoutWithTwoRequests(); }
// Test hitting the bridge filter with too many response bytes to buffer. Given
// the headers are not proxied, the connection manager will send a local error reply.
TEST_P(IntegrationTest, HittingGrpcFilterLimitBufferingHeaders) {
config_helper_.addFilter("{ name: envoy.grpc_http1_bridge, config: {} }");
config_helper_.setBufferLimits(1024, 1024);
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response = codec_client_->makeHeaderOnlyRequest(
Http::TestHeaderMapImpl{{":method", "POST"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"},
{"content-type", "application/grpc"},
{"x-envoy-retry-grpc-on", "cancelled"}});
waitForNextUpstreamRequest();
// Send the overly large response. Because the grpc_http1_bridge filter buffers and buffer
// limits are exceeded, this will be translated into an unknown gRPC error.
upstream_request_->encodeHeaders(Http::TestHeaderMapImpl{{":status", "200"}}, false);
fake_upstreams_[0]->set_allow_unexpected_disconnects(true);
upstream_request_->encodeData(1024 * 65, false);
ASSERT_TRUE(fake_upstream_connection_->waitForDisconnect());
response->waitForEndStream();
EXPECT_TRUE(response->complete());
EXPECT_THAT(response->headers(), HttpStatusIs("200"));
EXPECT_THAT(response->headers(),
HeaderValueOf(Headers::get().GrpcStatus, "2")); // Unknown gRPC error
}
TEST_P(IntegrationTest, HittingEncoderFilterLimit) { testHittingEncoderFilterLimit(); }
TEST_P(IntegrationTest, BadFirstline) { testBadFirstline(); }
TEST_P(IntegrationTest, MissingDelimiter) { testMissingDelimiter(); }
TEST_P(IntegrationTest, InvalidCharacterInFirstline) { testInvalidCharacterInFirstline(); }
TEST_P(IntegrationTest, InvalidVersion) { testInvalidVersion(); }
TEST_P(IntegrationTest, Http10Disabled) { testHttp10Disabled(); }
TEST_P(IntegrationTest, Http09Enabled) { testHttp09Enabled(); }
TEST_P(IntegrationTest, Http10Enabled) { testHttp10Enabled(); }
TEST_P(IntegrationTest, TestInlineHeaders) { testInlineHeaders(); }
TEST_P(IntegrationTest, Http10WithHostandKeepAlive) { testHttp10WithHostAndKeepAlive(); }
TEST_P(IntegrationTest, NoHost) { testNoHost(); }
TEST_P(IntegrationTest, BadPath) { testBadPath(); }
TEST_P(IntegrationTest, AbsolutePath) { testAbsolutePath(); }
TEST_P(IntegrationTest, AbsolutePathWithPort) { testAbsolutePathWithPort(); }
TEST_P(IntegrationTest, AbsolutePathWithoutPort) { testAbsolutePathWithoutPort(); }
TEST_P(IntegrationTest, Connect) { testConnect(); }
TEST_P(IntegrationTest, ValidZeroLengthContent) { testValidZeroLengthContent(); }
TEST_P(IntegrationTest, InvalidContentLength) { testInvalidContentLength(); }
TEST_P(IntegrationTest, MultipleContentLengths) { testMultipleContentLengths(); }
TEST_P(IntegrationTest, OverlyLongHeaders) { testOverlyLongHeaders(); }
TEST_P(IntegrationTest, UpstreamProtocolError) { testUpstreamProtocolError(); }
TEST_P(IntegrationTest, TestHead) {
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
Http::TestHeaderMapImpl head_request{{":method", "HEAD"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"}};
// Without an explicit content length, assume we chunk for HTTP/1.1
auto response = sendRequestAndWaitForResponse(head_request, 0, default_response_headers_, 0);
ASSERT_TRUE(response->complete());
EXPECT_THAT(response->headers(), HttpStatusIs("200"));
EXPECT_EQ(response->headers().ContentLength(), nullptr);
EXPECT_THAT(response->headers(),
HeaderValueOf(Headers::get().TransferEncoding,
Http::Headers::get().TransferEncodingValues.Chunked));
EXPECT_EQ(0, response->body().size());
// Preserve explicit content length.
Http::TestHeaderMapImpl content_length_response{{":status", "200"}, {"content-length", "12"}};
response = sendRequestAndWaitForResponse(head_request, 0, content_length_response, 0);
ASSERT_TRUE(response->complete());
EXPECT_THAT(response->headers(), HttpStatusIs("200"));
EXPECT_THAT(response->headers(), HeaderValueOf(Headers::get().ContentLength, "12"));
EXPECT_EQ(response->headers().TransferEncoding(), nullptr);
EXPECT_EQ(0, response->body().size());
cleanupUpstreamAndDownstream();
}
// The Envoy HTTP/1.1 codec ASSERTs that T-E headers are cleared in
// encodeHeaders, so to test upstreams explicitly sending T-E: chunked we have
// to send raw HTTP.
TEST_P(IntegrationTest, TestHeadWithExplicitTE) {
initialize();
auto tcp_client = makeTcpConnection(lookupPort("http"));
tcp_client->write("HEAD / HTTP/1.1\r\nHost: host\r\n\r\n");
FakeRawConnectionPtr fake_upstream_connection;
ASSERT_TRUE(fake_upstreams_[0]->waitForRawConnection(fake_upstream_connection));
std::string data;
ASSERT_TRUE(fake_upstream_connection->waitForData(
FakeRawConnection::waitForInexactMatch("\r\n\r\n"), &data));
ASSERT_TRUE(
fake_upstream_connection->write("HTTP/1.1 200 OK\r\nTransfer-encoding: chunked\r\n\r\n"));
tcp_client->waitForData("\r\n\r\n", false);
std::string response = tcp_client->data();
EXPECT_THAT(response, HasSubstr("HTTP/1.1 200 OK\r\n"));
EXPECT_THAT(response, Not(HasSubstr("content-length")));
EXPECT_THAT(response, HasSubstr("transfer-encoding: chunked\r\n"));
EXPECT_THAT(response, EndsWith("\r\n\r\n"));
ASSERT_TRUE(fake_upstream_connection->close());
ASSERT_TRUE(fake_upstream_connection->waitForDisconnect());
tcp_client->close();
}
TEST_P(IntegrationTest, TestBind) {
std::string address_string;
if (GetParam() == Network::Address::IpVersion::v4) {
address_string = TestUtility::getIpv4Loopback();
} else {
address_string = "::1";
}
config_helper_.setSourceAddress(address_string);
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response =
codec_client_->makeRequestWithBody(Http::TestHeaderMapImpl{{":method", "GET"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"}},
1024);
ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_));
ASSERT_NE(fake_upstream_connection_, nullptr);
std::string address =
fake_upstream_connection_->connection().remoteAddress()->ip()->addressAsString();
EXPECT_EQ(address, address_string);
ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_));
ASSERT_NE(upstream_request_, nullptr);
ASSERT_TRUE(upstream_request_->waitForEndStream(*dispatcher_));
cleanupUpstreamAndDownstream();
}
TEST_P(IntegrationTest, TestFailedBind) {
config_helper_.setSourceAddress("8.8.8.8");
initialize();
// Envoy will create and close some number of connections when trying to bind.
// Make sure they don't cause assertion failures when we ignore them.
fake_upstreams_[0]->set_allow_unexpected_disconnects(true);
codec_client_ = makeHttpConnection(lookupPort("http"));
// With no ability to successfully bind on an upstream connection Envoy should
// send a 500.
auto response = codec_client_->makeHeaderOnlyRequest(
Http::TestHeaderMapImpl{{":method", "GET"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"},
{"x-forwarded-for", "10.0.0.1"},
{"x-envoy-upstream-rq-timeout-ms", "1000"}});
response->waitForEndStream();
EXPECT_TRUE(response->complete());
EXPECT_THAT(response->headers(), HttpStatusIs("503"));
EXPECT_LT(0, test_server_->counter("cluster.cluster_0.bind_errors")->value());
}
ConfigHelper::HttpModifierFunction setVia(const std::string& via) {
return
[via](
envoy::config::filter::network::http_connection_manager::v2::HttpConnectionManager& hcm) {
hcm.set_via(via);
};
}
// Validate in a basic header-only request we get via header insertion.
TEST_P(IntegrationTest, ViaAppendHeaderOnly) {
config_helper_.addConfigModifier(setVia("bar"));
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response =
codec_client_->makeHeaderOnlyRequest(Http::TestHeaderMapImpl{{":method", "GET"},
{":path", "/test/long/url"},
{":authority", "host"},
{"via", "foo"},
{"connection", "close"}});
waitForNextUpstreamRequest();
EXPECT_THAT(upstream_request_->headers(), HeaderValueOf(Headers::get().Via, "foo, bar"));
upstream_request_->encodeHeaders(Http::TestHeaderMapImpl{{":status", "200"}}, true);
response->waitForEndStream();
codec_client_->waitForDisconnect();
EXPECT_TRUE(response->complete());
EXPECT_THAT(response->headers(), HttpStatusIs("200"));
EXPECT_THAT(response->headers(), HeaderValueOf(Headers::get().Via, "bar"));
}
// Validate that 100-continue works as expected with via header addition on both request and
// response path.
TEST_P(IntegrationTest, ViaAppendWith100Continue) {
config_helper_.addConfigModifier(setVia("foo"));
testEnvoyHandling100Continue(false, "foo");
}
// Test delayed close semantics for downstream HTTP/1.1 connections. When an early response is
// sent by Envoy, it will wait for response acknowledgment (via FIN/RST) from the client before
// closing the socket (with a timeout for ensuring cleanup).
TEST_P(IntegrationTest, TestDelayedConnectionTeardownOnGracefulClose) {
// This test will trigger an early 413 Payload Too Large response due to buffer limits being
// exceeded. The following filter is needed since the router filter will never trigger a 413.
config_helper_.addFilter("{ name: envoy.http_dynamo_filter, config: {} }");
config_helper_.setBufferLimits(1024, 1024);
initialize();
fake_upstreams_[0]->set_allow_unexpected_disconnects(true);
codec_client_ = makeHttpConnection(lookupPort("http"));
auto encoder_decoder =
codec_client_->startRequest(Http::TestHeaderMapImpl{{":method", "POST"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"}});
request_encoder_ = &encoder_decoder.first;
auto response = std::move(encoder_decoder.second);
codec_client_->sendData(*request_encoder_, 1024 * 65, false);
response->waitForEndStream();
EXPECT_TRUE(response->complete());
EXPECT_STREQ("413", response->headers().Status()->value().c_str());
// With no delayed close processing, Envoy will close the connection immediately after flushing
// and this should instead return true.
EXPECT_FALSE(codec_client_->waitForDisconnect(std::chrono::milliseconds(500)));
// Issue a local close and check that the client did not pick up a remote close which can happen
// when delayed close semantics are disabled.
codec_client_->connection()->close(Network::ConnectionCloseType::NoFlush);
EXPECT_EQ(codec_client_->last_connection_event(), Network::ConnectionEvent::LocalClose);
}
// Test configuration of the delayed close timeout on downstream HTTP/1.1 connections. A value of 0
// disables delayed close processing.
TEST_P(IntegrationTest, TestDelayedConnectionTeardownConfig) {
config_helper_.addFilter("{ name: envoy.http_dynamo_filter, config: {} }");
config_helper_.setBufferLimits(1024, 1024);
config_helper_.addConfigModifier(
[](envoy::config::filter::network::http_connection_manager::v2::HttpConnectionManager& hcm) {
hcm.mutable_delayed_close_timeout()->set_seconds(0);
});
initialize();
fake_upstreams_[0]->set_allow_unexpected_disconnects(true);
codec_client_ = makeHttpConnection(lookupPort("http"));
auto encoder_decoder =
codec_client_->startRequest(Http::TestHeaderMapImpl{{":method", "POST"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"}});
request_encoder_ = &encoder_decoder.first;
auto response = std::move(encoder_decoder.second);
codec_client_->sendData(*request_encoder_, 1024 * 65, false);
response->waitForEndStream();
// There is a potential race in the client's response processing when delayed close logic is
// disabled in Envoy (see https://github.com/envoyproxy/envoy/issues/2929). Depending on timing,
// a client may receive an RST prior to reading the response data from the socket, which may clear
// the receive buffers. Also, clients which don't flush the receive buffer upon receiving a remote
// close may also lose data (Envoy is susceptible to this).
// Therefore, avoid checking response code/payload here and instead simply look for the remote
// close.
EXPECT_TRUE(codec_client_->waitForDisconnect(std::chrono::milliseconds(500)));
EXPECT_EQ(codec_client_->last_connection_event(), Network::ConnectionEvent::RemoteClose);
}
// Test that delay closed connections are eventually force closed when the timeout triggers.
TEST_P(IntegrationTest, TestDelayedConnectionTeardownTimeoutTrigger) {
config_helper_.addFilter("{ name: envoy.http_dynamo_filter, config: {} }");
config_helper_.setBufferLimits(1024, 1024);
config_helper_.addConfigModifier(
[](envoy::config::filter::network::http_connection_manager::v2::HttpConnectionManager& hcm) {
// 200ms.
hcm.mutable_delayed_close_timeout()->set_nanos(200000000);
});
initialize();
fake_upstreams_[0]->set_allow_unexpected_disconnects(true);
codec_client_ = makeHttpConnection(lookupPort("http"));
auto encoder_decoder =
codec_client_->startRequest(Http::TestHeaderMapImpl{{":method", "POST"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"}});
request_encoder_ = &encoder_decoder.first;
auto response = std::move(encoder_decoder.second);
codec_client_->sendData(*request_encoder_, 1024 * 65, false);
response->waitForEndStream();
// The delayed close timeout should trigger since client is not closing the connection.
EXPECT_TRUE(codec_client_->waitForDisconnect(std::chrono::milliseconds(2000)));
EXPECT_EQ(codec_client_->last_connection_event(), Network::ConnectionEvent::RemoteClose);
EXPECT_EQ(test_server_->counter("http.config_test.downstream_cx_delayed_close_timeout")->value(),
1);
}
} // namespace Envoy
|
#include "pch.hpp"
#include "MainScene.hpp"
#include <EasyDx/Systems/SimpleRender.hpp>
#include <DirectXColors.h>
#include <numeric>
using gsl::span;
std::unique_ptr<dx::Object> MainScene::MakeFloor() const
{
using namespace DirectX;
const dx::PositionType positions[] = {{-3.5f, 0.0f, -10.0f}, {-3.5f, 0.0f, 0.0f},
{7.5f, 0.0f, 0.0f}, {-3.5f, 0.0f, -10.0f},
{7.5f, 0.0f, 0.0f}, {7.5f, 0.0f, -10.0f}};
const dx::VectorType normals[] = {
{0.0f, 1.0f, 0.0f}, {0.0f, 1.0f, 0.0f}, {0.0f, 1.0f, 0.0f},
{0.0f, 1.0f, 0.0f}, {0.0f, 1.0f, 0.0f}, {0.0f, 1.0f, 0.0f},
};
const dx::TexCoordType texCoords[] = {{0.0f, 4.0f}, {0.0f, 0.0f}, {4.0f, 0.0f},
{0.0f, 4.0f}, {4.0f, 0.0f}, {4.0f, 4.0f}};
const dx::ShortIndex indices[] = {0, 1, 2, 3, 4, 5};
const dx::Smoothness smoothness = {
XMFLOAT4{0.5f, 0.5f, 0.5f, 1.0f}, XMFLOAT4{1.0f, 1.0f, 1.0f, 1.0f},
XMFLOAT4{0.4f, 0.4f, 0.4f, 1.0f}, XMFLOAT4{1.0f, 1.0f, 1.0f, 1.0f}, 16.0f};
return dx::MakeObjectWithDefaultRendering(
m_device3D, m_predefined,
dx::PosNormTexVertexInput{span{positions}, span{normals}, span{texCoords}, span{indices}},
smoothness, dx::Get2DTexView(m_device3D, dx::Ref(m_checkBoardTex)), m_predefined.GetRepeatSampler());
}
std::unique_ptr<dx::Object> MainScene::MakeWall() const
{
const dx::PositionType positions[] = {
{-3.5f, 0.0f, 0.0f}, {-3.5f, 4.0f, 0.0f}, {-2.5f, 4.0f, 0.0f}, {-3.5f, 0.0f, 0.0f},
{-2.5f, 4.0f, 0.0f}, {-2.5f, 0.0f, 0.0f}, {2.5f, 0.0f, 0.0f}, {2.5f, 4.0f, 0.0f},
{7.5f, 4.0f, 0.0f}, {2.5f, 0.0f, 0.0f}, {7.5f, 4.0f, 0.0f}, {7.5f, 0.0f, 0.0f},
{-3.5f, 4.0f, 0.0f}, {-3.5f, 6.0f, 0.0f}, {7.5f, 6.0f, 0.0f}, {-3.5f, 4.0f, 0.0f},
{7.5f, 6.0f, 0.0f}, {7.5f, 4.0f, 0.0f}};
const dx::VectorType normals[] = {
{0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f},
{0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f},
{0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f},
{0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f},
{0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f}};
const dx::TexCoordType texCoords[] = {
{0.0f, 2.0f}, {0.0f, 0.0f}, {0.5f, 0.0f}, {0.0f, 2.0f}, {0.5f, 0.0f}, {0.5f, 2.0f},
{0.0f, 2.0f}, {0.0f, 0.0f}, {2.0f, 0.0f}, {0.0f, 2.0f}, {2.0f, 0.0f}, {2.0f, 2.0f},
{0.0f, 1.0f}, {0.0f, 0.0f}, {6.0f, 0.0f}, {0.0f, 1.0f}, {6.0f, 0.0f}, {6.0f, 1.0f},
};
std::uint16_t indices[18];
std::iota(std::begin(indices), std::end(indices), 0);
using namespace DirectX;
const auto smoothness =
dx::Smoothness{XMFLOAT4{0.5f, 0.5f, 0.5f, 1.0f}, XMFLOAT4{1.0f, 1.0f, 1.0f, 1.0f},
XMFLOAT4{0.4f, 0.4f, 0.4f, 1.0f}, XMFLOAT4{1.0f, 1.0f, 1.0f, 1.0f}, 16.0f};
return dx::MakeObjectWithDefaultRendering(
m_device3D, m_predefined,
dx::PosNormTexVertexInput{span{positions}, span{normals}, span{texCoords}, span{indices}},
smoothness,
dx::Get2DTexView(m_device3D, dx::Ref(m_brick01Tex)), m_predefined.GetRepeatSampler());
}
std::unique_ptr<dx::Object> MainScene::MakeMirror() const
{
using namespace DirectX;
const dx::PositionType positions[] = {{-2.5f, 0.0f, 0.0f}, {-2.5f, 4.0f, 0.0f},
{2.5f, 4.0f, 0.0f}, {-2.5f, 0.0f, 0.0f},
{2.5f, 4.0f, 0.0f}, {2.5f, 0.0f, 0.0f}};
const dx::VectorType normals[] = {
{0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f},
{0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f},
};
const dx::TexCoordType texCoords[] = {{0.0f, 1.0f}, {0.0f, 0.0f}, {1.0f, 0.0f},
{0.0f, 1.0f}, {1.0f, 0.0f}, {1.0f, 1.0f}};
const std::uint16_t indices[] = {0, 1, 2, 3, 4, 5};
auto smoothness =
dx::Smoothness{XMFLOAT4{0.5f, 0.5f, 0.5f, 1.0f}, XMFLOAT4{1.0f, 1.0f, 1.0f, 0.5f},
XMFLOAT4{0.4f, 0.4f, 0.4f, 1.0f}, XMFLOAT4{}, 16.0f};
return dx::MakeObjectWithDefaultRendering(
m_device3D, m_predefined,
dx::PosNormTexVertexInput{span{positions}, span{normals}, span{texCoords}, span{indices}},
smoothness, dx::Get2DTexView(m_device3D, dx::Ref(m_iceTex)));
}
std::unique_ptr<dx::Object> MainScene::MakeBall() const
{
using namespace DirectX;
dx::ModelResultUnit sphereMesh;
dx::MakeUVSphere(1.0f, 30.0f, 30.0f, sphereMesh);
auto smoothness =
dx::Smoothness{XMFLOAT4{0.5f, 0.5f, 0.5f, 1.0f}, XMFLOAT4{1.0f, 1.0f, 1.0f, 0.5f},
XMFLOAT4{0.4f, 0.4f, 0.4f, 1.0f}, XMFLOAT4{}, 16.0f};
auto ball = dx::MakeObjectWithDefaultRendering(
m_device3D, m_predefined,
sphereMesh,
smoothness, m_predefined.GetWhite());
dx::Transform transform;
transform.SetPosition({0.0f, 2.0f, -2.5f});
ball->AddComponent<dx::TransformComponent>(std::move(transform));
return ball;
};
MainScene::MainScene(dx::Game& game)
: m_device3D{game.IndependentResources().Device3D()}, m_predefined{game.Predefined()}
{
auto& resources = game.IndependentResources();
auto& device = resources.Device3D();
BuildLights();
BuildCamera();
BuildObjects();
}
void MainScene::BuildObjects()
{
LoadTextures();
m_ball = MakeBall();
m_floor = MakeFloor();
m_wall = MakeWall();
m_mirror = MakeMirror();
InitReflectedMaterial();
}
void MainScene::InitReflectedMaterial()
{
using namespace DirectX;
m_reflectedMaterial = dx::MakeBasicLightingMaterial(
m_predefined,
// the same smoothness with sphere
dx::Smoothness{XMFLOAT4{0.5f, 0.5f, 0.5f, 1.0f}, XMFLOAT4{1.0f, 1.0f, 1.0f, 0.5f},
XMFLOAT4{0.4f, 0.4f, 0.4f, 1.0f}, XMFLOAT4{}, 16.0f},
m_predefined.GetWhite());
auto& [shaders, blending, depthStencil, rasterizerState] = m_reflectedMaterial->Passes[0];
rasterizerState = m_predefined.GetCullClockwise();
depthStencil.StencilState = m_predefined.GetDrawnOnly();
depthStencil.StencilRef = 1;
}
void MainScene::BuildCamera()
{
auto& camera = MainCamera();
const float theta = 1.24f * DirectX::XM_PI;
const float phi = 0.42f * DirectX::XM_PI;
const float radius = 12.0f;
float x = radius * sinf(phi) * cosf(theta);
float z = radius * sinf(phi) * sinf(theta);
float y = radius * cosf(phi);
camera.SetLookAt({x, y, z}, {}, {0.0f, 1.0f, 0.0f});
camera.SetNearZ(1.0f);
camera.SetFarZ(1000.0f);
camera.SetFov(DirectX::XM_PIDIV4);
camera.UseDefaultMoveEvents(true);
auto& vp = camera.Viewport();
vp.Right = 1.0f;
vp.Bottom = 1.0f;
}
void MainScene::BuildLights()
{
std::array<dx::DirectionalLight, 3> dirLights = {};
dirLights[0].Direction = {0.57735f, -0.57735f, 0.57735f};
dirLights[1].Direction = {-0.57735f, -0.57735f, 0.57735f};
dirLights[2].Direction = {0.0f, -0.707f, -0.707f};
for (auto& light : dirLights)
{
light.Color = {1.0f, 1.0f, 1.0f, 1.0f};
light.Enabled = true;
}
auto& lights = Lights();
for (auto& dirLight : dirLights)
{
lights.emplace_back(std::move(dirLight));
}
}
void MainScene::LoadTextures()
{
m_checkBoardTex =
dx::Load2DTexFromDdsFile(m_device3D, fs::current_path() / "Tex" / "checkboard.dds");
m_brick01Tex = dx::Load2DTexFromDdsFile(m_device3D, fs::current_path() / "Tex" / "brick01.dds");
m_iceTex = dx::Load2DTexFromDdsFile(m_device3D, fs::current_path() / "Tex" / "ice.dds");
}
void MainScene::Render(const dx::Game& game)
{
auto& dependentGraphics = game.DependentResources();
auto& [swapChain, depthStencilBuffer] = dependentGraphics;
auto& independent = game.IndependentResources();
auto& context3D = independent.Context3D();
dependentGraphics.Bind(context3D);
const auto& camera = MainCamera();
// const auto lights = gsl::make_span(dirLights_);
depthStencilBuffer.ClearBoth(context3D);
swapChain.Front().Clear(context3D, DirectX::Colors::White);
context3D.IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
const auto& predefined = game.Predefined();
using namespace dx::systems;
const auto render = [&](const dx::Object& object) {
SimpleRenderSystem(context3D, *this, object);
};
auto& mirrorMat = m_mirror->GetComponent<dx::MeshRenderer>()->GetMaterial();
// 1. render floor, wall, sphere normally.
{
render(*m_floor);
render(*m_wall);
render(*m_ball);
}
// 2. Render mirror. stencil buffer only
{
auto& [shaders, blending, depthStencil, rasterizerState] = mirrorMat.Passes[0];
blending.BlendState = predefined.GetNoWriteToRT();
blending.SampleMask = static_cast<UINT>(-1);
depthStencil.StencilState = predefined.GetStencilAlways();
depthStencil.StencilRef = 1;
render(*m_mirror);
}
// 3. Draw the reflected sphere.
// rendering without an object
{
const auto meshRenderer = m_ball->GetComponent<dx::MeshRenderer>();
auto sharedMesh = meshRenderer->SharedMesh();
auto& material = meshRenderer->GetMaterial();
auto lights = Lights();
auto reflectionMatrix =
DirectX::XMMatrixReflect(DirectX::XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f));
for (auto& light : lights)
{
auto& direction = std::get<dx::DirectionalLight>(light).Direction;
auto dirF4 = dx::MakeDirection4(direction);
auto reflected =
DirectX::XMVector4Transform(DirectX::XMLoadFloat4(&dirF4), reflectionMatrix);
DirectX::XMStoreFloat3(&direction, reflected);
}
auto& transform = m_ball->GetComponent<dx::TransformComponent>()->GetTransform();
auto& shaders = m_reflectedMaterial->Passes[0].Shaders;
dx::systems::PrepareVsCb(context3D, shaders.VertexShader_.Inputs,
transform.Matrix() * reflectionMatrix, gsl::make_span(lights), camera);
dx::systems::PreparePsCb(context3D, shaders.PixelShader_.Inputs, gsl::make_span(lights),
camera);
dx::DrawMesh(context3D, *sharedMesh, *m_reflectedMaterial);
}
// 4. Draw the mirror with alpha blending.
{
auto& blending = mirrorMat.Passes[0].Blending;
blending.BlendFactor = {0.5f, 0.5f, 0.5f, 1.0f};
blending.BlendState = predefined.GetTransparent();
blending.SampleMask = static_cast<UINT>(-1);
render(*m_mirror);
}
//// 5. Draw the shadow.
//{
// context3D.OMSetDepthStencilState(predefined.GetNoDoubleBlending().Get(), 0);
// dx::UpdateAndDraw(drawContext, sphereShadow_);
// context3D.OMSetBlendState({}, {}, static_cast<UINT>(-1));
// context3D.OMSetDepthStencilState({}, 0);
//}
// swapChain.Present();
}
Mirror 编译错误修正。
#include "pch.hpp"
#include "MainScene.hpp"
#include <EasyDx/Systems/SimpleRender.hpp>
#include <DirectXColors.h>
#include <numeric>
using gsl::span;
std::unique_ptr<dx::Object> MainScene::MakeFloor() const
{
using namespace DirectX;
const dx::PositionType positions[] = {{-3.5f, 0.0f, -10.0f}, {-3.5f, 0.0f, 0.0f},
{7.5f, 0.0f, 0.0f}, {-3.5f, 0.0f, -10.0f},
{7.5f, 0.0f, 0.0f}, {7.5f, 0.0f, -10.0f}};
const dx::VectorType normals[] = {
{0.0f, 1.0f, 0.0f}, {0.0f, 1.0f, 0.0f}, {0.0f, 1.0f, 0.0f},
{0.0f, 1.0f, 0.0f}, {0.0f, 1.0f, 0.0f}, {0.0f, 1.0f, 0.0f},
};
const dx::TexCoordType texCoords[] = {{0.0f, 4.0f}, {0.0f, 0.0f}, {4.0f, 0.0f},
{0.0f, 4.0f}, {4.0f, 0.0f}, {4.0f, 4.0f}};
const dx::ShortIndex indices[] = {0, 1, 2, 3, 4, 5};
const dx::Smoothness smoothness = {
XMFLOAT4{0.5f, 0.5f, 0.5f, 1.0f}, XMFLOAT4{1.0f, 1.0f, 1.0f, 1.0f},
XMFLOAT4{0.4f, 0.4f, 0.4f, 1.0f}, XMFLOAT4{1.0f, 1.0f, 1.0f, 1.0f}, 16.0f};
return dx::MakeObjectWithDefaultRendering(
m_device3D, m_predefined,
dx::PosNormTexVertexInput{span{positions}, span{normals}, span{texCoords}, span{indices}},
smoothness, dx::Get2DTexView(m_device3D, dx::Ref(m_checkBoardTex)), m_predefined.GetRepeatSampler());
}
std::unique_ptr<dx::Object> MainScene::MakeWall() const
{
const dx::PositionType positions[] = {
{-3.5f, 0.0f, 0.0f}, {-3.5f, 4.0f, 0.0f}, {-2.5f, 4.0f, 0.0f}, {-3.5f, 0.0f, 0.0f},
{-2.5f, 4.0f, 0.0f}, {-2.5f, 0.0f, 0.0f}, {2.5f, 0.0f, 0.0f}, {2.5f, 4.0f, 0.0f},
{7.5f, 4.0f, 0.0f}, {2.5f, 0.0f, 0.0f}, {7.5f, 4.0f, 0.0f}, {7.5f, 0.0f, 0.0f},
{-3.5f, 4.0f, 0.0f}, {-3.5f, 6.0f, 0.0f}, {7.5f, 6.0f, 0.0f}, {-3.5f, 4.0f, 0.0f},
{7.5f, 6.0f, 0.0f}, {7.5f, 4.0f, 0.0f}};
const dx::VectorType normals[] = {
{0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f},
{0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f},
{0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f},
{0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f},
{0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f}};
const dx::TexCoordType texCoords[] = {
{0.0f, 2.0f}, {0.0f, 0.0f}, {0.5f, 0.0f}, {0.0f, 2.0f}, {0.5f, 0.0f}, {0.5f, 2.0f},
{0.0f, 2.0f}, {0.0f, 0.0f}, {2.0f, 0.0f}, {0.0f, 2.0f}, {2.0f, 0.0f}, {2.0f, 2.0f},
{0.0f, 1.0f}, {0.0f, 0.0f}, {6.0f, 0.0f}, {0.0f, 1.0f}, {6.0f, 0.0f}, {6.0f, 1.0f},
};
std::uint16_t indices[18];
std::iota(std::begin(indices), std::end(indices), 0);
using namespace DirectX;
const auto smoothness =
dx::Smoothness{XMFLOAT4{0.5f, 0.5f, 0.5f, 1.0f}, XMFLOAT4{1.0f, 1.0f, 1.0f, 1.0f},
XMFLOAT4{0.4f, 0.4f, 0.4f, 1.0f}, XMFLOAT4{1.0f, 1.0f, 1.0f, 1.0f}, 16.0f};
return dx::MakeObjectWithDefaultRendering(
m_device3D, m_predefined,
dx::PosNormTexVertexInput{span{positions}, span{normals}, span{texCoords}, span{indices}},
smoothness,
dx::Get2DTexView(m_device3D, dx::Ref(m_brick01Tex)), m_predefined.GetRepeatSampler());
}
std::unique_ptr<dx::Object> MainScene::MakeMirror() const
{
using namespace DirectX;
const dx::PositionType positions[] = {{-2.5f, 0.0f, 0.0f}, {-2.5f, 4.0f, 0.0f},
{2.5f, 4.0f, 0.0f}, {-2.5f, 0.0f, 0.0f},
{2.5f, 4.0f, 0.0f}, {2.5f, 0.0f, 0.0f}};
const dx::VectorType normals[] = {
{0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f},
{0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, -1.0f},
};
const dx::TexCoordType texCoords[] = {{0.0f, 1.0f}, {0.0f, 0.0f}, {1.0f, 0.0f},
{0.0f, 1.0f}, {1.0f, 0.0f}, {1.0f, 1.0f}};
const std::uint16_t indices[] = {0, 1, 2, 3, 4, 5};
auto smoothness =
dx::Smoothness{XMFLOAT4{0.5f, 0.5f, 0.5f, 1.0f}, XMFLOAT4{1.0f, 1.0f, 1.0f, 0.5f},
XMFLOAT4{0.4f, 0.4f, 0.4f, 1.0f}, XMFLOAT4{}, 16.0f};
return dx::MakeObjectWithDefaultRendering(
m_device3D, m_predefined,
dx::PosNormTexVertexInput{span{positions}, span{normals}, span{texCoords}, span{indices}},
smoothness, dx::Get2DTexView(m_device3D, dx::Ref(m_iceTex)));
}
std::unique_ptr<dx::Object> MainScene::MakeBall() const
{
using namespace DirectX;
dx::ModelResultUnit sphereMesh;
dx::MakeUVSphere(1.0f, 30.0f, 30.0f, sphereMesh);
auto smoothness =
dx::Smoothness{XMFLOAT4{0.5f, 0.5f, 0.5f, 1.0f}, XMFLOAT4{1.0f, 1.0f, 1.0f, 0.5f},
XMFLOAT4{0.4f, 0.4f, 0.4f, 1.0f}, XMFLOAT4{}, 16.0f};
auto ball = dx::MakeObjectWithDefaultRendering(
m_device3D, m_predefined,
sphereMesh,
smoothness, m_predefined.GetWhite());
dx::Transform transform;
transform.SetPosition({0.0f, 2.0f, -2.5f});
ball->AddComponent<dx::TransformComponent>(std::move(transform));
return ball;
};
MainScene::MainScene(dx::Game& game)
: dx::SceneBase{game}, m_device3D{game.IndependentResources().Device3D()},
m_predefined{game.Predefined()}
{
auto& resources = game.IndependentResources();
auto& device = resources.Device3D();
BuildLights();
BuildCamera();
BuildObjects();
}
void MainScene::BuildObjects()
{
LoadTextures();
m_ball = MakeBall();
m_floor = MakeFloor();
m_wall = MakeWall();
m_mirror = MakeMirror();
InitReflectedMaterial();
}
void MainScene::InitReflectedMaterial()
{
using namespace DirectX;
m_reflectedMaterial = dx::MakeBasicLightingMaterial(
m_predefined,
// the same smoothness with sphere
dx::Smoothness{XMFLOAT4{0.5f, 0.5f, 0.5f, 1.0f}, XMFLOAT4{1.0f, 1.0f, 1.0f, 0.5f},
XMFLOAT4{0.4f, 0.4f, 0.4f, 1.0f}, XMFLOAT4{}, 16.0f},
m_predefined.GetWhite());
auto& [shaders, blending, depthStencil, rasterizerState] = m_reflectedMaterial->Passes[0];
rasterizerState = m_predefined.GetCullClockwise();
depthStencil.StencilState = m_predefined.GetDrawnOnly();
depthStencil.StencilRef = 1;
}
void MainScene::BuildCamera()
{
auto& camera = MainCamera();
const float theta = 1.24f * DirectX::XM_PI;
const float phi = 0.42f * DirectX::XM_PI;
const float radius = 12.0f;
float x = radius * sinf(phi) * cosf(theta);
float z = radius * sinf(phi) * sinf(theta);
float y = radius * cosf(phi);
camera.SetLookAt({x, y, z}, {}, {0.0f, 1.0f, 0.0f});
camera.SetNearZ(1.0f);
camera.SetFarZ(1000.0f);
camera.SetFov(DirectX::XM_PIDIV4);
camera.UseDefaultMoveEvents(true);
auto& vp = camera.Viewport();
vp.Right = 1.0f;
vp.Bottom = 1.0f;
}
void MainScene::BuildLights()
{
std::array<dx::DirectionalLight, 3> dirLights = {};
dirLights[0].Direction = {0.57735f, -0.57735f, 0.57735f};
dirLights[1].Direction = {-0.57735f, -0.57735f, 0.57735f};
dirLights[2].Direction = {0.0f, -0.707f, -0.707f};
for (auto& light : dirLights)
{
light.Color = {1.0f, 1.0f, 1.0f, 1.0f};
light.Enabled = true;
}
auto& lights = Lights();
for (auto& dirLight : dirLights)
{
lights.emplace_back(std::move(dirLight));
}
}
void MainScene::LoadTextures()
{
m_checkBoardTex =
dx::Load2DTexFromDdsFile(m_device3D, fs::current_path() / "Tex" / "checkboard.dds");
m_brick01Tex = dx::Load2DTexFromDdsFile(m_device3D, fs::current_path() / "Tex" / "brick01.dds");
m_iceTex = dx::Load2DTexFromDdsFile(m_device3D, fs::current_path() / "Tex" / "ice.dds");
}
void MainScene::Render(const dx::Game& game)
{
auto& dependentGraphics = game.DependentResources();
auto& [swapChain, depthStencilBuffer] = dependentGraphics;
auto& independent = game.IndependentResources();
auto& context3D = independent.Context3D();
dependentGraphics.Bind(context3D);
const auto& camera = MainCamera();
// const auto lights = gsl::make_span(dirLights_);
depthStencilBuffer.ClearBoth(context3D);
swapChain.Front().Clear(context3D, DirectX::Colors::White);
context3D.IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
const auto& predefined = game.Predefined();
using namespace dx::systems;
const auto render = [&](const dx::Object& object) {
SimpleRenderSystem(context3D, *this, object);
};
auto& mirrorMat = m_mirror->GetComponent<dx::MeshRenderer>()->GetMaterial();
// 1. render floor, wall, sphere normally.
{
render(*m_floor);
render(*m_wall);
render(*m_ball);
}
// 2. Render mirror. stencil buffer only
{
auto& [shaders, blending, depthStencil, rasterizerState] = mirrorMat.Passes[0];
blending.BlendState = predefined.GetNoWriteToRT();
blending.SampleMask = static_cast<UINT>(-1);
depthStencil.StencilState = predefined.GetStencilAlways();
depthStencil.StencilRef = 1;
render(*m_mirror);
}
// 3. Draw the reflected sphere.
// rendering without an object
{
const auto meshRenderer = m_ball->GetComponent<dx::MeshRenderer>();
auto sharedMesh = meshRenderer->SharedMesh();
auto& material = meshRenderer->GetMaterial();
auto lights = Lights();
auto reflectionMatrix =
DirectX::XMMatrixReflect(DirectX::XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f));
for (auto& light : lights)
{
auto& direction = std::get<dx::DirectionalLight>(light).Direction;
auto dirF4 = dx::MakeDirection4(direction);
auto reflected =
DirectX::XMVector4Transform(DirectX::XMLoadFloat4(&dirF4), reflectionMatrix);
DirectX::XMStoreFloat3(&direction, reflected);
}
auto& transform = m_ball->GetComponent<dx::TransformComponent>()->GetTransform();
auto& shaders = m_reflectedMaterial->Passes[0].Shaders;
dx::systems::PrepareVsCb(context3D, shaders.VertexShader_.Inputs,
transform.Matrix() * reflectionMatrix, gsl::make_span(lights), camera);
dx::systems::PreparePsCb(context3D, shaders.PixelShader_.Inputs, gsl::make_span(lights),
camera);
dx::DrawMesh(context3D, *sharedMesh, *m_reflectedMaterial);
}
// 4. Draw the mirror with alpha blending.
{
auto& blending = mirrorMat.Passes[0].Blending;
blending.BlendFactor = {0.5f, 0.5f, 0.5f, 1.0f};
blending.BlendState = predefined.GetTransparent();
blending.SampleMask = static_cast<UINT>(-1);
render(*m_mirror);
}
//// 5. Draw the shadow.
//{
// context3D.OMSetDepthStencilState(predefined.GetNoDoubleBlending().Get(), 0);
// dx::UpdateAndDraw(drawContext, sphereShadow_);
// context3D.OMSetBlendState({}, {}, static_cast<UINT>(-1));
// context3D.OMSetDepthStencilState({}, 0);
//}
// swapChain.Present();
} |
#include "ndis56common.h"
#include "kdebugprint.h"
#include "Trace.h"
#ifdef NETKVM_WPP_ENABLED
#include "ParaNdis6_RSS.tmh"
#endif
#if PARANDIS_SUPPORT_RSS
#define RSS_PRINT_LEVEL 0
static void PrintIndirectionTable(const NDIS_RECEIVE_SCALE_PARAMETERS* Params);
static void PrintIndirectionTable(const PARANDIS_SCALING_SETTINGS *RSSScalingSetting);
static void PrintRSSSettings(PPARANDIS_RSS_PARAMS RSSParameters);
static NDIS_STATUS ParaNdis_SetupRSSQueueMap(PARANDIS_ADAPTER *pContext);
static VOID ApplySettings(PPARANDIS_RSS_PARAMS RSSParameters,
PARANDIS_RSS_MODE NewRSSMode,
PARANDIS_HASHING_SETTINGS *ReceiveHashingSettings,
PARANDIS_SCALING_SETTINGS *ReceiveScalingSettings)
{
CNdisPassiveWriteAutoLock autoLock(RSSParameters->rwLock);
RSSParameters->RSSMode = NewRSSMode;
if(NewRSSMode != PARANDIS_RSS_DISABLED)
{
RSSParameters->ActiveHashingSettings = *ReceiveHashingSettings;
if(NewRSSMode == PARANDIS_RSS_FULL)
{
if(RSSParameters->ActiveRSSScalingSettings.CPUIndexMapping != NULL)
NdisFreeMemory(RSSParameters->ActiveRSSScalingSettings.CPUIndexMapping, 0, 0);
RSSParameters->ActiveRSSScalingSettings = *ReceiveScalingSettings;
ReceiveScalingSettings->CPUIndexMapping = NULL;
}
}
}
static VOID InitRSSParameters(PARANDIS_ADAPTER *pContext)
{
PARANDIS_RSS_PARAMS *RSSParameters = &pContext->RSSParameters;
RSSParameters->ReceiveQueuesNumber = pContext->RSSMaxQueuesNumber;
RSSParameters->RSSScalingSettings.DefaultQueue = PARANDIS_RECEIVE_UNCLASSIFIED_PACKET;
RSSParameters->ActiveRSSScalingSettings.DefaultQueue = PARANDIS_RECEIVE_UNCLASSIFIED_PACKET;
}
static VOID CleanupRSSParameters(PARANDIS_RSS_PARAMS *RSSParameters)
{
if(RSSParameters->ActiveRSSScalingSettings.CPUIndexMapping != NULL)
NdisFreeMemory(RSSParameters->ActiveRSSScalingSettings.CPUIndexMapping, 0, 0);
if(RSSParameters->RSSScalingSettings.CPUIndexMapping != NULL)
NdisFreeMemory(RSSParameters->RSSScalingSettings.CPUIndexMapping, 0, 0);
}
static VOID InitRSSCapabilities(PARANDIS_ADAPTER *pContext)
{
NDIS_RECEIVE_SCALE_CAPABILITIES *RSSCapabilities = &pContext->RSSCapabilities;
RSSCapabilities->Header.Type = NDIS_OBJECT_TYPE_RSS_CAPABILITIES;
RSSCapabilities->Header.Revision = NDIS_RECEIVE_SCALE_CAPABILITIES_REVISION_1;
RSSCapabilities->Header.Size = NDIS_SIZEOF_RECEIVE_SCALE_CAPABILITIES_REVISION_1;
RSSCapabilities->CapabilitiesFlags = NDIS_RSS_CAPS_MESSAGE_SIGNALED_INTERRUPTS |
NDIS_RSS_CAPS_CLASSIFICATION_AT_ISR |
NdisHashFunctionToeplitz;
if (pContext->bRSSSupportedByDevice)
{
ULONG flags = 0;
flags |= (pContext->DeviceRSSCapabilities.SupportedHashes & VIRTIO_NET_RSS_HASH_TYPE_TCPv4) ?
NDIS_RSS_CAPS_HASH_TYPE_TCP_IPV4 : 0;
flags |= (pContext->DeviceRSSCapabilities.SupportedHashes & VIRTIO_NET_RSS_HASH_TYPE_TCPv6) ?
NDIS_RSS_CAPS_HASH_TYPE_TCP_IPV6 : 0;
flags |= (pContext->DeviceRSSCapabilities.SupportedHashes & VIRTIO_NET_RSS_HASH_TYPE_TCP_EX) ?
NDIS_RSS_CAPS_HASH_TYPE_TCP_IPV6_EX : 0;
RSSCapabilities->CapabilitiesFlags |= flags;
}
else
{
RSSCapabilities->CapabilitiesFlags |= NDIS_RSS_CAPS_HASH_TYPE_TCP_IPV4 |
NDIS_RSS_CAPS_HASH_TYPE_TCP_IPV6 |
NDIS_RSS_CAPS_HASH_TYPE_TCP_IPV6_EX;
}
RSSCapabilities->NumberOfInterruptMessages = 1;
RSSCapabilities->NumberOfReceiveQueues = pContext->RSSMaxQueuesNumber;
#if (NDIS_SUPPORT_NDIS630)
RSSCapabilities->Header.Revision = NDIS_RECEIVE_SCALE_CAPABILITIES_REVISION_2;
RSSCapabilities->Header.Size = NDIS_SIZEOF_RECEIVE_SCALE_CAPABILITIES_REVISION_2;
RSSCapabilities->NumberOfIndirectionTableEntries = NDIS_RSS_INDIRECTION_TABLE_MAX_SIZE_REVISION_2 / sizeof(PROCESSOR_NUMBER);
#endif
#if (NDIS_SUPPORT_NDIS680)
if (CheckNdisVersion(6, 80))
{
RSSCapabilities->Header.Revision = NDIS_RECEIVE_SCALE_CAPABILITIES_REVISION_3;
RSSCapabilities->Header.Size = NDIS_SIZEOF_RECEIVE_SCALE_CAPABILITIES_REVISION_3;
if (pContext->bRSSSupportedByDevice)
{
ULONG flags = 0;
flags |= (pContext->DeviceRSSCapabilities.SupportedHashes & VIRTIO_NET_RSS_HASH_TYPE_UDPv4) ?
NDIS_RSS_CAPS_HASH_TYPE_UDP_IPV4 : 0;
flags |= (pContext->DeviceRSSCapabilities.SupportedHashes & VIRTIO_NET_RSS_HASH_TYPE_UDPv6) ?
NDIS_RSS_CAPS_HASH_TYPE_UDP_IPV6 : 0;
flags |= (pContext->DeviceRSSCapabilities.SupportedHashes & VIRTIO_NET_RSS_HASH_TYPE_UDP_EX) ?
NDIS_RSS_CAPS_HASH_TYPE_UDP_IPV6_EX : 0;
RSSCapabilities->CapabilitiesFlags |= flags;
}
else
{
RSSCapabilities->CapabilitiesFlags |= NDIS_RSS_CAPS_HASH_TYPE_UDP_IPV4 |
NDIS_RSS_CAPS_HASH_TYPE_UDP_IPV6 |
NDIS_RSS_CAPS_HASH_TYPE_UDP_IPV6_EX;
}
}
#endif
}
void ParaNdis6_CheckDeviceRSSCapabilities(PARANDIS_ADAPTER *pContext, bool& bRss, bool& bHash)
{
if (bHash || bRss)
{
DPrintf(0, "[%s] Device supports %s %s: key of %d, table of %d, hashes %X\n", __FUNCTION__,
bHash ? "Hash" : " ", bRss ? "RSS" : " ",
pContext->DeviceRSSCapabilities.MaxKeySize,
pContext->DeviceRSSCapabilities.MaxIndirectEntries,
pContext->DeviceRSSCapabilities.SupportedHashes);
}
BOOLEAN bResult = (pContext->DeviceRSSCapabilities.SupportedHashes & VIRTIO_NET_RSS_HASH_TYPE_IPv4) &&
pContext->DeviceRSSCapabilities.MaxKeySize >= NDIS_RSS_HASH_SECRET_KEY_MAX_SIZE_REVISION_2;
if (!bResult)
{
bRss = false;
bHash = false;
}
bResult = bResult && pContext->DeviceRSSCapabilities.MaxIndirectEntries >= NDIS_RSS_INDIRECTION_TABLE_MAX_SIZE_REVISION_2 / sizeof(PROCESSOR_NUMBER);
if (!bResult)
{
bRss = false;
}
DPrintf(0, "[%s] Driver will use: %s %s\n", __FUNCTION__, bHash ? "Hash" : " ", bRss ? "RSS" : " ");
}
NDIS_RECEIVE_SCALE_CAPABILITIES* ParaNdis6_RSSCreateConfiguration(PARANDIS_ADAPTER *pContext)
{
InitRSSParameters(pContext);
InitRSSCapabilities(pContext);
return &pContext->RSSCapabilities;
}
static ULONG TranslateHashTypes(ULONG hashSettings)
{
ULONG val = 0;
val |= (hashSettings & NDIS_HASH_IPV4) ? VIRTIO_NET_RSS_HASH_TYPE_IPv4 : 0;
val |= (hashSettings & NDIS_HASH_TCP_IPV4) ? VIRTIO_NET_RSS_HASH_TYPE_TCPv4 : 0;
val |= (hashSettings & NDIS_HASH_IPV6) ? VIRTIO_NET_RSS_HASH_TYPE_IPv6 : 0;
val |= (hashSettings & NDIS_HASH_IPV6_EX) ? VIRTIO_NET_RSS_HASH_TYPE_IP_EX : 0;
val |= (hashSettings & NDIS_HASH_TCP_IPV6) ? VIRTIO_NET_RSS_HASH_TYPE_TCPv6 : 0;
val |= (hashSettings & NDIS_HASH_TCP_IPV6_EX) ? VIRTIO_NET_RSS_HASH_TYPE_TCP_EX : 0;
#if (NDIS_SUPPORT_NDIS680)
val |= (hashSettings & NDIS_HASH_UDP_IPV4) ? VIRTIO_NET_RSS_HASH_TYPE_UDPv4 : 0;
val |= (hashSettings & NDIS_HASH_UDP_IPV6) ? VIRTIO_NET_RSS_HASH_TYPE_UDPv6 : 0;
val |= (hashSettings & NDIS_HASH_UDP_IPV6_EX) ? VIRTIO_NET_RSS_HASH_TYPE_UDP_EX : 0;
#endif
TraceNoPrefix(0, "[%s] 0x%X -> 0x%X", __FUNCTION__, hashSettings, val);
return val;
}
static USHORT ResolveQueue(PARANDIS_ADAPTER *pContext, PPROCESSOR_NUMBER proc, USHORT *fallback)
{
GROUP_AFFINITY a;
ParaNdis_ProcessorNumberToGroupAffinity(&a, proc);
USHORT n;
for (n = 0; n < pContext->nPathBundles; ++n)
{
const GROUP_AFFINITY& b = pContext->pPathBundles[n].rxPath.DPCAffinity;
if (a.Group == b.Group && a.Mask == b.Mask)
{
return n;
}
}
// the CPU is not used by any queue
n = (*fallback)++;
if (*fallback >= pContext->nPathBundles)
{
*fallback = 0;
}
TraceNoPrefix(0, "[%s] fallback CPU %d.%d -> Q%d", __FUNCTION__, proc->Group, proc->Number, n);
return n;
}
static void SetDeviceRSSSettings(PARANDIS_ADAPTER *pContext, bool bForceOff = false)
{
if (!pContext->bRSSSupportedByDevice && !pContext->bHashReportedByDevice)
{
return;
}
UCHAR command = pContext->bRSSSupportedByDevice ?
VIRTIO_NET_CTRL_MQ_RSS_CONFIG : VIRTIO_NET_CTRL_MQ_HASH_CONFIG;
if (pContext->RSSParameters.RSSMode == PARANDIS_RSS_DISABLED || bForceOff)
{
virtio_net_rss_config cfg = {};
cfg.max_tx_vq = (USHORT)pContext->nPathBundles;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_MQ, command, &cfg, sizeof(cfg), NULL, 0, 2);
}
else
{
virtio_net_rss_config *cfg;
USHORT fallbackQueue = 0;
USHORT indirection_table_len = pContext->RSSParameters.ActiveRSSScalingSettings.IndirectionTableSize / sizeof(PROCESSOR_NUMBER);
UCHAR hash_key_len = (UCHAR)pContext->RSSParameters.ActiveHashingSettings.HashSecretKeySize;
ULONG config_size;
if (!pContext->bRSSSupportedByDevice)
{
indirection_table_len = 1;
}
config_size = virtio_net_rss_config_size(indirection_table_len, hash_key_len);
cfg = (virtio_net_rss_config *)ParaNdis_AllocateMemory(pContext, config_size);
if (!cfg)
{
return;
}
cfg->indirection_table_mask = indirection_table_len - 1;
cfg->unclassified_queue = ResolveQueue(pContext, &pContext->RSSParameters.ActiveRSSScalingSettings.DefaultProcessor, &fallbackQueue);
for (USHORT i = 0; i < indirection_table_len; ++i)
{
cfg->indirection_table[i] = ResolveQueue(pContext,
pContext->RSSParameters.ActiveRSSScalingSettings.IndirectionTable + i,
&fallbackQueue);
}
TraceNoPrefix(0, "[%s] Translated indirections: (len = %d)\n", __FUNCTION__, indirection_table_len);
ParaNdis_PrintTable<80, 10>(0, cfg->indirection_table, indirection_table_len, "%d", [](const __u16 *p) { return *p; });
max_tx_vq(cfg) = (USHORT)pContext->nPathBundles;
hash_key_length(cfg) = hash_key_len;
for (USHORT i = 0; i < hash_key_len; ++i)
{
hash_key_data(cfg, i) = pContext->RSSParameters.ActiveHashingSettings.HashSecretKey[i];
}
TraceNoPrefix(0, "[%s] RSS key: (len = %d)\n", __FUNCTION__, hash_key_len);
ParaNdis_PrintTable<80, 10>(0, (hash_key_length_ptr(cfg) + 1), hash_key_len, "%X", [](const __u8 *p) { return *p; });
cfg->hash_types = TranslateHashTypes(pContext->RSSParameters.ActiveHashingSettings.HashInformation);
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_MQ, command, cfg, config_size, NULL, 0, 2);
NdisFreeMemory(cfg, NULL, 0);
}
}
static BOOLEAN IsValidHashInfo(ULONG HashInformation)
{
#define HASH_FLAGS_COMBINATION(Type, Flags) ( ((Type) & (Flags)) && !((Type) & ~(Flags)) )
ULONG ulHashType = NDIS_RSS_HASH_TYPE_FROM_HASH_INFO(HashInformation);
ULONG ulHashFunction = NDIS_RSS_HASH_FUNC_FROM_HASH_INFO(HashInformation);
ULONG ulAllowedHashTypes = NDIS_HASH_IPV4 | NDIS_HASH_TCP_IPV4 | NDIS_HASH_IPV6 | NDIS_HASH_TCP_IPV6 |
NDIS_HASH_IPV6_EX | NDIS_HASH_TCP_IPV6_EX;
#if (NDIS_SUPPORT_NDIS680)
ulAllowedHashTypes |= NDIS_HASH_UDP_IPV4 | NDIS_HASH_UDP_IPV6 | NDIS_HASH_UDP_IPV6_EX;
#endif
if (HashInformation == 0)
return TRUE;
if (HASH_FLAGS_COMBINATION(ulHashType, ulAllowedHashTypes))
return ulHashFunction == NdisHashFunctionToeplitz;
return FALSE;
}
static __inline
BOOLEAN IsPowerOfTwo(ULONG n)
{
return ((n != 0) && ((n & (~n + 1)) == n));
}
static __inline
BOOLEAN IsCompatibleAffinities(PGROUP_AFFINITY a1, PGROUP_AFFINITY a2)
{
return (a1->Group == a2->Group) && (a1->Mask & a2->Mask);
}
static
CCHAR FindReceiveQueueForCurrentCpu(PPARANDIS_SCALING_SETTINGS RSSScalingSettings)
{
ULONG CurrProcIdx;
CurrProcIdx = ParaNdis_GetCurrentCPUIndex();
if(CurrProcIdx >= RSSScalingSettings->CPUIndexMappingSize)
return PARANDIS_RECEIVE_NO_QUEUE;
return RSSScalingSettings->CPUIndexMapping[CurrProcIdx];
}
static
void SetDefaultQueue(PPARANDIS_SCALING_SETTINGS RSSScalingSettings, ULONG idx)
{
if (idx < RSSScalingSettings->CPUIndexMappingSize)
{
NTSTATUS status;
status = KeGetProcessorNumberFromIndex(idx, &RSSScalingSettings->DefaultProcessor);
if (NT_SUCCESS(status))
{
RSSScalingSettings->DefaultQueue = RSSScalingSettings->CPUIndexMapping[idx];
return;
}
}
RSSScalingSettings->DefaultQueue = PARANDIS_RECEIVE_UNCLASSIFIED_PACKET;
}
static
BOOLEAN AllocateCPUMappingArray(PARANDIS_ADAPTER *pContext, PPARANDIS_SCALING_SETTINGS RSSScalingSettings)
{
ULONG i;
ULONG CPUNumber = KeQueryActiveProcessorCountEx(ALL_PROCESSOR_GROUPS);
PCHAR NewCPUMappingArray = (PCHAR)ParaNdis_AllocateMemory(pContext, sizeof(CCHAR) * CPUNumber);
if(!NewCPUMappingArray)
return FALSE;
RSSScalingSettings->CPUIndexMapping = NewCPUMappingArray;
RSSScalingSettings->CPUIndexMappingSize = CPUNumber;
for(i = 0; i < CPUNumber; i++)
{
RSSScalingSettings->CPUIndexMapping[i] = PARANDIS_RECEIVE_NO_QUEUE;
}
return TRUE;
}
static
VOID FillCPUMappingArray(
PPARANDIS_SCALING_SETTINGS RSSScalingSettings,
CCHAR ReceiveQueuesNumber)
{
ULONG i;
CCHAR ReceiveQueue = PARANDIS_FIRST_RSS_RECEIVE_QUEUE;
auto IndirectionTableChanged = false;
RSSScalingSettings->FirstQueueIndirectionIndex = INVALID_INDIRECTION_INDEX;
for (i = 0; i < RSSScalingSettings->IndirectionTableSize/sizeof(PROCESSOR_NUMBER); i++)
{
PPROCESSOR_NUMBER ProcNum = &RSSScalingSettings->IndirectionTable[i];
ULONG CurrProcIdx = KeGetProcessorIndexFromNumber(ProcNum);
if(CurrProcIdx != INVALID_PROCESSOR_INDEX)
{
if (RSSScalingSettings->CPUIndexMapping[CurrProcIdx] == PARANDIS_RECEIVE_NO_QUEUE)
{
if (ReceiveQueue == PARANDIS_FIRST_RSS_RECEIVE_QUEUE)
RSSScalingSettings->FirstQueueIndirectionIndex = i;
if (ReceiveQueue != ReceiveQueuesNumber)
{
RSSScalingSettings->CPUIndexMapping[CurrProcIdx] = ReceiveQueue++;
}
}
RSSScalingSettings->QueueIndirectionTable[i] = RSSScalingSettings->CPUIndexMapping[CurrProcIdx];
}
else
{
RSSScalingSettings->QueueIndirectionTable[i] = PARANDIS_RECEIVE_NO_QUEUE;
}
}
if (RSSScalingSettings->FirstQueueIndirectionIndex == INVALID_INDIRECTION_INDEX)
{
DPrintf(0, "[%s] - CPU <-> queue assignment failed!", __FUNCTION__);
return;
}
for (i = 0; i < RSSScalingSettings->IndirectionTableSize / sizeof(PROCESSOR_NUMBER); i++)
{
if (RSSScalingSettings->QueueIndirectionTable[i] == PARANDIS_RECEIVE_NO_QUEUE)
{
/* If some hash values remains unassigned after the first pass, either because
mapping processor number to index failed or there are not enough queues,
reassign the hash values to the first queue*/
RSSScalingSettings->QueueIndirectionTable[i] = PARANDIS_FIRST_RSS_RECEIVE_QUEUE;
RSSScalingSettings->IndirectionTable[i] = RSSScalingSettings->IndirectionTable[RSSScalingSettings->FirstQueueIndirectionIndex];
IndirectionTableChanged = true;
}
}
if (IndirectionTableChanged)
{
DPrintf(0, "[%s] Indirection table changed\n", __FUNCTION__);
}
}
static ULONG MinimalRssParametersLength(const NDIS_RECEIVE_SCALE_PARAMETERS* Params)
{
if (Params->Header.Revision == NDIS_RECEIVE_SCALE_PARAMETERS_REVISION_2)
{
return NDIS_SIZEOF_RECEIVE_SCALE_PARAMETERS_REVISION_2;
}
#if (NDIS_SUPPORT_NDIS660)
// we can receive structure rev.3
if (Params->Header.Revision == NDIS_RECEIVE_SCALE_PARAMETERS_REVISION_3)
{
return NDIS_SIZEOF_RECEIVE_SCALE_PARAMETERS_REVISION_3;
}
#endif
return sizeof(*Params);
}
NDIS_STATUS ParaNdis6_RSSSetParameters( PARANDIS_ADAPTER *pContext,
const NDIS_RECEIVE_SCALE_PARAMETERS* Params,
UINT ParamsLength,
PUINT ParamsBytesRead)
{
PARANDIS_RSS_PARAMS *RSSParameters = &pContext->RSSParameters;
ULONG ProcessorMasksSize;
ULONG IndirectionTableEntries;
ULONG minimalLength;
*ParamsBytesRead = 0;
if (ParamsLength < sizeof(Params->Header))
{
DPrintf(0, "[%s] invalid length %d!\n", __FUNCTION__, ParamsLength);
return NDIS_STATUS_INVALID_LENGTH;
}
minimalLength = MinimalRssParametersLength(Params);
if (ParamsLength < minimalLength)
{
DPrintf(0, "[%s] invalid length (1) %d < %d!\n", __FUNCTION__, ParamsLength, minimalLength);
*ParamsBytesRead = sizeof(Params->Header);
return NDIS_STATUS_INVALID_LENGTH;
}
if ((RSSParameters->RSSMode == PARANDIS_RSS_HASHING) &&
!(Params->Flags & NDIS_RSS_PARAM_FLAG_DISABLE_RSS) &&
(Params->HashInformation != 0))
{
return NDIS_STATUS_NOT_SUPPORTED;
}
if (!(Params->Flags & (NDIS_RSS_PARAM_FLAG_HASH_INFO_UNCHANGED | NDIS_RSS_PARAM_FLAG_DISABLE_RSS)) &&
!IsValidHashInfo(Params->HashInformation))
{
DPrintf(0, "[%s] invalid: flags %X, hash info %X!\n", __FUNCTION__, Params->Flags, Params->HashInformation);
return NDIS_STATUS_INVALID_PARAMETER;
}
CNdisPassiveWriteAutoLock autoLock(RSSParameters->rwLock);
if(Params->Flags & NDIS_RSS_PARAM_FLAG_DISABLE_RSS || (Params->HashInformation == 0))
{
ApplySettings(RSSParameters, PARANDIS_RSS_DISABLED, NULL, NULL);
}
else
{
BOOLEAN bHasDefaultCPU = false;
ULONG defaultCPUIndex = INVALID_PROCESSOR_INDEX;
#if (NDIS_SUPPORT_NDIS660)
// we can receive structure rev.3
if (Params->Header.Revision >= NDIS_RECEIVE_SCALE_PARAMETERS_REVISION_3 &&
!(Params->Flags & NDIS_RSS_PARAM_FLAG_DEFAULT_PROCESSOR_UNCHANGED))
{
PROCESSOR_NUMBER num = Params->DefaultProcessorNumber;
// due to unknown reason the Reserved field might be not zero
// (we see it on Win10.18362), this causes KeGetProcessorIndexFromNumber
// to return INVALID_PROCESSOR_INDEX
num.Reserved = 0;
bHasDefaultCPU = true;
defaultCPUIndex = KeGetProcessorIndexFromNumber(&num);
TraceNoPrefix(0, "[%s] has default CPU idx %d\n", __FUNCTION__, defaultCPUIndex);
}
#endif
DPrintf(0, "[%s] RSS Params: flags 0x%4.4x, hash information 0x%4.4lx\n",
__FUNCTION__, Params->Flags, Params->HashInformation);
IndirectionTableEntries = Params->IndirectionTableSize / sizeof(PROCESSOR_NUMBER);
if (!(Params->Flags & NDIS_RSS_PARAM_FLAG_ITABLE_UNCHANGED) &&
((Params->IndirectionTableSize > sizeof(RSSParameters->RSSScalingSettings.IndirectionTable)) ||
(ParamsLength < (Params->IndirectionTableOffset + Params->IndirectionTableSize)) ||
!IsPowerOfTwo(IndirectionTableEntries))
)
{
DPrintf(0, "[%s] invalid length (2), flags %x\n", __FUNCTION__, Params->Flags);
return NDIS_STATUS_INVALID_LENGTH;
}
if (!(Params->Flags & NDIS_RSS_PARAM_FLAG_HASH_KEY_UNCHANGED) &&
((Params->HashSecretKeySize > sizeof(RSSParameters->RSSHashingSettings.HashSecretKey)) ||
(ParamsLength < (Params->HashSecretKeyOffset + Params->HashSecretKeySize)))
)
{
DPrintf(0, "[%s] invalid length (3), flags %x\n", __FUNCTION__, Params->Flags);
return NDIS_STATUS_INVALID_LENGTH;
}
ProcessorMasksSize = Params->NumberOfProcessorMasks * Params->ProcessorMasksEntrySize;
if (ParamsLength < Params->ProcessorMasksOffset + ProcessorMasksSize)
{
DPrintf(0, "[%s] invalid length (4), flags %x\n", __FUNCTION__, Params->Flags);
return NDIS_STATUS_INVALID_LENGTH;
}
if (!(Params->Flags & NDIS_RSS_PARAM_FLAG_ITABLE_UNCHANGED))
{
PrintIndirectionTable(Params);
if(!AllocateCPUMappingArray(pContext, &RSSParameters->RSSScalingSettings))
return NDIS_STATUS_RESOURCES;
RSSParameters->RSSScalingSettings.IndirectionTableSize = Params->IndirectionTableSize;
NdisMoveMemory(RSSParameters->RSSScalingSettings.IndirectionTable,
(char*)Params + Params->IndirectionTableOffset, Params->IndirectionTableSize);
RSSParameters->RSSScalingSettings.RSSHashMask = IndirectionTableEntries - 1;
*ParamsBytesRead += Params->IndirectionTableSize;
*ParamsBytesRead += ProcessorMasksSize;
FillCPUMappingArray(&RSSParameters->RSSScalingSettings, RSSParameters->ReceiveQueuesNumber);
if (bHasDefaultCPU)
{
SetDefaultQueue(&RSSParameters->RSSScalingSettings, defaultCPUIndex);
}
PrintRSSSettings(RSSParameters);
}
else if (bHasDefaultCPU)
{
SetDefaultQueue(&RSSParameters->ActiveRSSScalingSettings, defaultCPUIndex);
RSSParameters->RSSScalingSettings.DefaultQueue = RSSParameters->ActiveRSSScalingSettings.DefaultQueue;
RSSParameters->RSSScalingSettings.DefaultProcessor = RSSParameters->ActiveRSSScalingSettings.DefaultProcessor;
TraceNoPrefix(0, "[%s] default queue -> %d\n", __FUNCTION__, RSSParameters->ActiveRSSScalingSettings.DefaultQueue);
}
if (!(Params->Flags & NDIS_RSS_PARAM_FLAG_HASH_INFO_UNCHANGED))
RSSParameters->RSSHashingSettings.HashInformation = Params->HashInformation;
if (!(Params->Flags & NDIS_RSS_PARAM_FLAG_HASH_KEY_UNCHANGED))
{
RSSParameters->RSSHashingSettings.HashSecretKeySize = Params->HashSecretKeySize;
NdisMoveMemory(RSSParameters->RSSHashingSettings.HashSecretKey,
(char*)Params + Params->HashSecretKeyOffset, Params->HashSecretKeySize);
*ParamsBytesRead += Params->HashSecretKeySize;
}
ApplySettings(RSSParameters,
PARANDIS_RSS_FULL,
&RSSParameters->RSSHashingSettings,
&RSSParameters->RSSScalingSettings);
}
*ParamsBytesRead += minimalLength;
#if (NDIS_SUPPORT_NDIS680)
if (CheckNdisVersion(6, 80))
{
// simplify this on Win10
*ParamsBytesRead = ParamsLength;
}
#endif
ParaNdis_ResetRxClassification(pContext);
NDIS_STATUS status = ParaNdis_SetupRSSQueueMap(pContext);
if (NT_SUCCESS(status))
{
SetDeviceRSSSettings(pContext);
}
return status;
}
ULONG ParaNdis6_QueryReceiveHash(const PARANDIS_RSS_PARAMS *RSSParameters,
RSS_HASH_KEY_PARAMETERS *RSSHashKeyParameters)
{
CNdisPassiveReadAutoLock autoLock(RSSParameters->rwLock);
NdisZeroMemory(RSSHashKeyParameters, sizeof(*RSSHashKeyParameters));
RSSHashKeyParameters->ReceiveHashParameters.Header.Type = NDIS_OBJECT_TYPE_DEFAULT;
RSSHashKeyParameters->ReceiveHashParameters.Header.Revision = NDIS_RECEIVE_HASH_PARAMETERS_REVISION_1;
RSSHashKeyParameters->ReceiveHashParameters.Header.Size = NDIS_SIZEOF_RECEIVE_HASH_PARAMETERS_REVISION_1;
RSSHashKeyParameters->ReceiveHashParameters.HashInformation = RSSParameters->ReceiveHashingSettings.HashInformation;
if(RSSParameters->RSSMode == PARANDIS_RSS_HASHING)
RSSHashKeyParameters->ReceiveHashParameters.Flags = NDIS_RECEIVE_HASH_FLAG_ENABLE_HASH;
RSSHashKeyParameters->ReceiveHashParameters.HashSecretKeySize = RSSParameters->ReceiveHashingSettings.HashSecretKeySize;
NdisMoveMemory(RSSHashKeyParameters->HashSecretKey,
RSSParameters->ReceiveHashingSettings.HashSecretKey,
RSSHashKeyParameters->ReceiveHashParameters.HashSecretKeySize);
RSSHashKeyParameters->ReceiveHashParameters.HashSecretKeyOffset = FIELD_OFFSET(RSS_HASH_KEY_PARAMETERS, HashSecretKey);
return sizeof(RSSHashKeyParameters->ReceiveHashParameters) + RSSHashKeyParameters->ReceiveHashParameters.HashSecretKeySize;
}
NDIS_STATUS ParaNdis6_RSSSetReceiveHash(PARANDIS_ADAPTER *pContext,
const NDIS_RECEIVE_HASH_PARAMETERS* Params,
UINT ParamsLength,
PUINT ParamsBytesRead)
{
PARANDIS_RSS_PARAMS *RSSParameters = &pContext->RSSParameters;
CNdisPassiveWriteAutoLock autoLock(RSSParameters->rwLock);
if (ParamsLength < sizeof(NDIS_RECEIVE_HASH_PARAMETERS))
return NDIS_STATUS_INVALID_LENGTH;
*ParamsBytesRead += sizeof(NDIS_RECEIVE_HASH_PARAMETERS);
if (RSSParameters->RSSMode == PARANDIS_RSS_FULL)
{
//Here we check that originator doesn't try to enable hashing while full RSS is on.
//Disable hashing abd clear parameters is legitimate operation hovewer
if(Params->Flags & NDIS_RECEIVE_HASH_FLAG_ENABLE_HASH)
{
if(!(Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_INFO_UNCHANGED) && (Params->HashInformation != 0))
return NDIS_STATUS_NOT_SUPPORTED;
if((Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_INFO_UNCHANGED) &&
(RSSParameters->ReceiveHashingSettings.HashInformation != 0))
return NDIS_STATUS_NOT_SUPPORTED;
}
}
if (!(Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_INFO_UNCHANGED) &&
(!IsValidHashInfo(Params->HashInformation)))
return NDIS_STATUS_INVALID_PARAMETER;
if ( (!(Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_KEY_UNCHANGED)) &&
( (Params->HashSecretKeySize > NDIS_RSS_HASH_SECRET_KEY_MAX_SIZE_REVISION_2) ||
(ParamsLength < (Params->HashSecretKeyOffset + Params->HashSecretKeySize)) )
)
return NDIS_STATUS_INVALID_LENGTH;
if (!(Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_INFO_UNCHANGED))
{
RSSParameters->ReceiveHashingSettings.HashInformation = Params->HashInformation;
}
if (!(Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_KEY_UNCHANGED))
{
RSSParameters->ReceiveHashingSettings.HashSecretKeySize = Params->HashSecretKeySize;
NdisMoveMemory(RSSParameters->ReceiveHashingSettings.HashSecretKey,
(char*)Params + Params->HashSecretKeyOffset, Params->HashSecretKeySize);
*ParamsBytesRead += Params->HashSecretKeySize;
}
if(RSSParameters->RSSMode != PARANDIS_RSS_FULL)
{
ApplySettings(RSSParameters,
((Params->Flags & NDIS_RECEIVE_HASH_FLAG_ENABLE_HASH) && (Params->HashInformation != 0))
? PARANDIS_RSS_HASHING : PARANDIS_RSS_DISABLED,
&RSSParameters->ReceiveHashingSettings, NULL);
}
ParaNdis_ResetRxClassification(pContext);
SetDeviceRSSSettings(pContext);
return NDIS_STATUS_SUCCESS;
}
typedef struct _tagHASH_CALC_SG_BUF_ENTRY
{
PCHAR chunkPtr;
ULONG chunkLen;
} HASH_CALC_SG_BUF_ENTRY, *PHASH_CALC_SG_BUF_ENTRY;
// Little Endian version ONLY
static
UINT32 ToeplitzHash(const PHASH_CALC_SG_BUF_ENTRY sgBuff, int sgEntriesNum, PCCHAR fullKey)
{
#define TOEPLITZ_MAX_BIT_NUM (7)
#define TOEPLITZ_BYTE_HAS_BIT(byte, bit) ((byte) & (1 << (TOEPLITZ_MAX_BIT_NUM - (bit))))
#define TOEPLITZ_BYTE_BIT_STATE(byte, bit) (((byte) >> (TOEPLITZ_MAX_BIT_NUM - (bit))) & 1)
UINT32 firstKeyWord, res = 0;
UINT byte, bit;
PHASH_CALC_SG_BUF_ENTRY sgEntry;
PCCHAR next_key_byte = fullKey + sizeof(firstKeyWord);
firstKeyWord = RtlUlongByteSwap(*(UINT32*)fullKey);
for(sgEntry = sgBuff; sgEntry < sgBuff + sgEntriesNum; ++sgEntry)
{
for (byte = 0; byte < sgEntry->chunkLen; ++byte)
{
for (bit = 0; bit <= TOEPLITZ_MAX_BIT_NUM; ++bit)
{
if (TOEPLITZ_BYTE_HAS_BIT(sgEntry->chunkPtr[byte], bit))
{
res ^= firstKeyWord;
}
firstKeyWord = (firstKeyWord << 1) | TOEPLITZ_BYTE_BIT_STATE(*next_key_byte, bit);
}
++next_key_byte;
}
}
return res;
#undef TOEPLITZ_BYTE_HAS_BIT
#undef TOEPLITZ_BYTE_BIT_STATE
#undef TOEPLITZ_MAX_BIT_NUM
}
static __inline
IPV6_ADDRESS* GetIP6SrcAddrForHash(
PVOID dataBuffer,
PNET_PACKET_INFO packetInfo,
bool xEnabled)
{
return (xEnabled && packetInfo->ip6HomeAddrOffset)
? (IPV6_ADDRESS*) RtlOffsetToPointer(dataBuffer, packetInfo->ip6HomeAddrOffset)
: (IPV6_ADDRESS*) RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen + FIELD_OFFSET(IPv6Header, ip6_src_address));
}
static __inline
IPV6_ADDRESS* GetIP6DstAddrForHash(
PVOID dataBuffer,
PNET_PACKET_INFO packetInfo,
bool xEnabled)
{
return (xEnabled && packetInfo->ip6DestAddrOffset)
? (IPV6_ADDRESS*) RtlOffsetToPointer(dataBuffer, packetInfo->ip6DestAddrOffset)
: (IPV6_ADDRESS*) RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen + FIELD_OFFSET(IPv6Header, ip6_dst_address));
}
static
VOID RSSCalcHash_Unsafe(
PARANDIS_RSS_PARAMS *RSSParameters,
PVOID dataBuffer,
PNET_PACKET_INFO packetInfo)
{
HASH_CALC_SG_BUF_ENTRY sgBuff[3];
ULONG hashTypes = NDIS_RSS_HASH_TYPE_FROM_HASH_INFO(RSSParameters->ActiveHashingSettings.HashInformation);
if(packetInfo->isIP4)
{
if(packetInfo->isTCP && (hashTypes & NDIS_HASH_TCP_IPV4))
{
IPv4Header *pIpHeader = (IPv4Header *) RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen);
TCPHeader *pTCPHeader = (TCPHeader *) RtlOffsetToPointer(pIpHeader, packetInfo->L3HdrLen);
sgBuff[0].chunkPtr = RtlOffsetToPointer(pIpHeader, FIELD_OFFSET(IPv4Header, ip_src));
sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv4Header, ip_src) + RTL_FIELD_SIZE(IPv4Header, ip_dest);
sgBuff[1].chunkPtr = RtlOffsetToPointer(pTCPHeader, FIELD_OFFSET(TCPHeader, tcp_src));
sgBuff[1].chunkLen = RTL_FIELD_SIZE(TCPHeader, tcp_src) + RTL_FIELD_SIZE(TCPHeader, tcp_dest);
packetInfo->RSSHash.Value = ToeplitzHash(sgBuff, 2, &RSSParameters->ActiveHashingSettings.HashSecretKey[0]);
packetInfo->RSSHash.Type = NDIS_HASH_TCP_IPV4;
packetInfo->RSSHash.Function = NdisHashFunctionToeplitz;
return;
}
#if (NDIS_SUPPORT_NDIS680)
if (packetInfo->isUDP && (hashTypes & NDIS_HASH_UDP_IPV4))
{
IPv4Header *pIpHeader = (IPv4Header *)RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen);
UDPHeader *pUDPHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, packetInfo->L3HdrLen);
sgBuff[0].chunkPtr = RtlOffsetToPointer(pIpHeader, FIELD_OFFSET(IPv4Header, ip_src));
sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv4Header, ip_src) + RTL_FIELD_SIZE(IPv4Header, ip_dest);
sgBuff[1].chunkPtr = RtlOffsetToPointer(pUDPHeader, FIELD_OFFSET(UDPHeader, udp_src));
sgBuff[1].chunkLen = RTL_FIELD_SIZE(UDPHeader, udp_src) + RTL_FIELD_SIZE(UDPHeader, udp_dest);
packetInfo->RSSHash.Value = ToeplitzHash(sgBuff, 2, RSSParameters->ActiveHashingSettings.HashSecretKey);
packetInfo->RSSHash.Type = NDIS_HASH_UDP_IPV4;
packetInfo->RSSHash.Function = NdisHashFunctionToeplitz;
return;
}
#endif
if(hashTypes & NDIS_HASH_IPV4)
{
sgBuff[0].chunkPtr = RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen + FIELD_OFFSET(IPv4Header, ip_src));
sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv4Header, ip_src) + RTL_FIELD_SIZE(IPv4Header, ip_dest);
packetInfo->RSSHash.Value = ToeplitzHash(sgBuff, 1, RSSParameters->ActiveHashingSettings.HashSecretKey);
packetInfo->RSSHash.Type = NDIS_HASH_IPV4;
packetInfo->RSSHash.Function = NdisHashFunctionToeplitz;
return;
}
}
else if(packetInfo->isIP6)
{
if(packetInfo->isTCP)
{
if(hashTypes & (NDIS_HASH_TCP_IPV6 | NDIS_HASH_TCP_IPV6_EX))
{
IPv6Header *pIpHeader = (IPv6Header *) RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen);
TCPHeader *pTCPHeader = (TCPHeader *) RtlOffsetToPointer(pIpHeader, packetInfo->L3HdrLen);
bool xEnabled = (hashTypes & NDIS_HASH_TCP_IPV6_EX) != 0;
sgBuff[0].chunkPtr = (PCHAR) GetIP6SrcAddrForHash(dataBuffer, packetInfo, xEnabled);
sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_src_address);
sgBuff[1].chunkPtr = (PCHAR) GetIP6DstAddrForHash(dataBuffer, packetInfo, xEnabled);
sgBuff[1].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_dst_address);
sgBuff[2].chunkPtr = RtlOffsetToPointer(pTCPHeader, FIELD_OFFSET(TCPHeader, tcp_src));
sgBuff[2].chunkLen = RTL_FIELD_SIZE(TCPHeader, tcp_src) + RTL_FIELD_SIZE(TCPHeader, tcp_dest);
packetInfo->RSSHash.Value = ToeplitzHash(sgBuff, 3, RSSParameters->ActiveHashingSettings.HashSecretKey);
packetInfo->RSSHash.Type = xEnabled ? NDIS_HASH_TCP_IPV6_EX : NDIS_HASH_TCP_IPV6;
packetInfo->RSSHash.Function = NdisHashFunctionToeplitz;
return;
}
}
#if (NDIS_SUPPORT_NDIS680)
if (packetInfo->isUDP && (hashTypes & (NDIS_HASH_UDP_IPV6 | NDIS_HASH_UDP_IPV6_EX)))
{
IPv6Header *pIpHeader = (IPv6Header *)RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen);
UDPHeader *pUDPHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, packetInfo->L3HdrLen);
bool xEnabled = (hashTypes & NDIS_HASH_UDP_IPV6_EX) != 0;
sgBuff[0].chunkPtr = (PCHAR)GetIP6SrcAddrForHash(dataBuffer, packetInfo, xEnabled);
sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_src_address);
sgBuff[1].chunkPtr = (PCHAR)GetIP6DstAddrForHash(dataBuffer, packetInfo, xEnabled);
sgBuff[1].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_dst_address);
sgBuff[2].chunkPtr = RtlOffsetToPointer(pUDPHeader, FIELD_OFFSET(UDPHeader, udp_src));
sgBuff[2].chunkLen = RTL_FIELD_SIZE(UDPHeader, udp_src) + RTL_FIELD_SIZE(UDPHeader, udp_dest);
packetInfo->RSSHash.Value = ToeplitzHash(sgBuff, 3, RSSParameters->ActiveHashingSettings.HashSecretKey);
packetInfo->RSSHash.Type = xEnabled ? NDIS_HASH_UDP_IPV6_EX : NDIS_HASH_UDP_IPV6;
packetInfo->RSSHash.Function = NdisHashFunctionToeplitz;
return;
}
#endif
if(hashTypes & (NDIS_HASH_IPV6 | NDIS_HASH_IPV6_EX))
{
bool xEnabled = (hashTypes & NDIS_HASH_IPV6_EX) != 0;
sgBuff[0].chunkPtr = (PCHAR) GetIP6SrcAddrForHash(dataBuffer, packetInfo, xEnabled);
sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_src_address);
sgBuff[1].chunkPtr = (PCHAR) GetIP6DstAddrForHash(dataBuffer, packetInfo, xEnabled);
sgBuff[1].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_dst_address);
packetInfo->RSSHash.Value = ToeplitzHash(sgBuff, 2, RSSParameters->ActiveHashingSettings.HashSecretKey);
packetInfo->RSSHash.Type = xEnabled ? NDIS_HASH_IPV6_EX : NDIS_HASH_IPV6;
packetInfo->RSSHash.Function = NdisHashFunctionToeplitz;
return;
}
if(hashTypes & NDIS_HASH_IPV6)
{
IPv6Header *pIpHeader = (IPv6Header *) RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen);
sgBuff[0].chunkPtr = RtlOffsetToPointer(pIpHeader, FIELD_OFFSET(IPv6Header, ip6_src_address));
sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_src_address) + RTL_FIELD_SIZE(IPv6Header, ip6_dst_address);
packetInfo->RSSHash.Value = ToeplitzHash(sgBuff, 2, RSSParameters->ActiveHashingSettings.HashSecretKey);
packetInfo->RSSHash.Type = NDIS_HASH_IPV6;
packetInfo->RSSHash.Function = NdisHashFunctionToeplitz;
return;
}
}
packetInfo->RSSHash.Value = 0;
packetInfo->RSSHash.Type = 0;
packetInfo->RSSHash.Function = 0;
}
VOID ParaNdis6_RSSAnalyzeReceivedPacket(
PARANDIS_RSS_PARAMS *RSSParameters,
PVOID dataBuffer,
PNET_PACKET_INFO packetInfo)
{
CNdisDispatchReadAutoLock autoLock(RSSParameters->rwLock);
if(RSSParameters->RSSMode != PARANDIS_RSS_DISABLED)
{
RSSCalcHash_Unsafe(RSSParameters, dataBuffer, packetInfo);
}
}
CCHAR ParaNdis6_RSSGetScalingDataForPacket(
PARANDIS_RSS_PARAMS *RSSParameters,
PNET_PACKET_INFO packetInfo,
PPROCESSOR_NUMBER targetProcessor)
{
CCHAR targetQueue;
CNdisDispatchReadAutoLock autoLock(RSSParameters->rwLock);
if (RSSParameters->RSSMode != PARANDIS_RSS_FULL ||
RSSParameters->ActiveRSSScalingSettings.FirstQueueIndirectionIndex == INVALID_INDIRECTION_INDEX)
{
targetQueue = PARANDIS_RECEIVE_UNCLASSIFIED_PACKET;
}
else if (packetInfo->RSSHash.Type == 0)
{
targetQueue = RSSParameters->ActiveRSSScalingSettings.DefaultQueue;
*targetProcessor = RSSParameters->ActiveRSSScalingSettings.DefaultProcessor;
}
else
{
ULONG indirectionIndex = packetInfo->RSSHash.Value & RSSParameters->ActiveRSSScalingSettings.RSSHashMask;
targetQueue = RSSParameters->ActiveRSSScalingSettings.QueueIndirectionTable[indirectionIndex];
if (targetQueue == PARANDIS_RECEIVE_NO_QUEUE)
{
targetQueue = PARANDIS_RECEIVE_UNCLASSIFIED_PACKET;
}
else
{
*targetProcessor = RSSParameters->ActiveRSSScalingSettings.IndirectionTable[indirectionIndex];
}
}
return targetQueue;
}
CCHAR ParaNdis6_RSSGetCurrentCpuReceiveQueue(PARANDIS_RSS_PARAMS *RSSParameters)
{
CCHAR res;
CNdisDispatchReadAutoLock autoLock(RSSParameters->rwLock);
if(RSSParameters->RSSMode != PARANDIS_RSS_FULL)
{
res = PARANDIS_RECEIVE_NO_QUEUE;
}
else
{
res = FindReceiveQueueForCurrentCpu(&RSSParameters->ActiveRSSScalingSettings);
}
return res;
}
static void PrintIndirectionTable(const NDIS_RECEIVE_SCALE_PARAMETERS* Params)
{
ULONG IndirectionTableEntries = Params->IndirectionTableSize / sizeof(PROCESSOR_NUMBER);
DPrintf(RSS_PRINT_LEVEL, "Params: flags 0x%4.4x, hash information 0x%4.4lx\n",
Params->Flags, Params->HashInformation);
DPrintf(RSS_PRINT_LEVEL, "NDIS IndirectionTable[%lu]\n", IndirectionTableEntries);
ParaNdis_PrintTable<80, 20>(RSS_PRINT_LEVEL, (const PROCESSOR_NUMBER *)((char *)Params + Params->IndirectionTableOffset), IndirectionTableEntries,
"%u/%u", [](const PROCESSOR_NUMBER *proc) { return proc->Group; }, [](const PROCESSOR_NUMBER *proc) { return proc->Number; });
}
static void PrintIndirectionTable(const PARANDIS_SCALING_SETTINGS *RSSScalingSetting)
{
ULONG IndirectionTableEntries = RSSScalingSetting->IndirectionTableSize/ sizeof(PROCESSOR_NUMBER);
DPrintf(RSS_PRINT_LEVEL, "Driver IndirectionTable[%lu]\n", IndirectionTableEntries);
ParaNdis_PrintTable<80, 20>(RSS_PRINT_LEVEL, RSSScalingSetting->IndirectionTable, IndirectionTableEntries,
"%u/%u", [](const PROCESSOR_NUMBER *proc) { return proc->Group; }, [](const PROCESSOR_NUMBER *proc) { return proc->Number; });
}
static void PrintRSSSettings(const PPARANDIS_RSS_PARAMS RSSParameters)
{
ULONG CPUNumber = KeQueryActiveProcessorCountEx(ALL_PROCESSOR_GROUPS);
DPrintf(RSS_PRINT_LEVEL, "%lu cpus, %d queues, first queue CPU index %ld, default queue %d\n",
CPUNumber, RSSParameters->ReceiveQueuesNumber,
RSSParameters->RSSScalingSettings.FirstQueueIndirectionIndex,
RSSParameters->RSSScalingSettings.DefaultQueue);
PrintIndirectionTable(&RSSParameters->ActiveRSSScalingSettings);
DPrintf(RSS_PRINT_LEVEL, "CPU mapping table[%u]:\n", RSSParameters->ActiveRSSScalingSettings.CPUIndexMappingSize);
ParaNdis_PrintCharArray(RSS_PRINT_LEVEL, RSSParameters->ActiveRSSScalingSettings.CPUIndexMapping, RSSParameters->ActiveRSSScalingSettings.CPUIndexMappingSize);
DPrintf(RSS_PRINT_LEVEL, "Queue indirection table[%u]:\n", RSSParameters->ReceiveQueuesNumber);
ParaNdis_PrintCharArray(RSS_PRINT_LEVEL, RSSParameters->ActiveRSSScalingSettings.QueueIndirectionTable, RSSParameters->ReceiveQueuesNumber);
}
NDIS_STATUS ParaNdis_SetupRSSQueueMap(PARANDIS_ADAPTER *pContext)
{
USHORT rssIndex, bundleIndex;
ULONG cpuIndex;
ULONG rssTableSize = pContext->RSSParameters.RSSScalingSettings.IndirectionTableSize / sizeof(PROCESSOR_NUMBER);
rssIndex = 0;
bundleIndex = 0;
USHORT *cpuIndexTable;
ULONG cpuNumbers;
cpuNumbers = KeQueryActiveProcessorCountEx(ALL_PROCESSOR_GROUPS);
cpuIndexTable = (USHORT *)NdisAllocateMemoryWithTagPriority(pContext->MiniportHandle, cpuNumbers * sizeof(*cpuIndexTable),
PARANDIS_MEMORY_TAG, NormalPoolPriority);
if (cpuIndexTable == nullptr)
{
DPrintf(0, "[%s] cpu index table allocation failed\n", __FUNCTION__);
return NDIS_STATUS_RESOURCES;
}
NdisZeroMemory(cpuIndexTable, sizeof(*cpuIndexTable) * cpuNumbers);
for (bundleIndex = 0; bundleIndex < pContext->nPathBundles; ++bundleIndex)
{
cpuIndex = pContext->pPathBundles[bundleIndex].rxPath.getCPUIndex();
if (cpuIndex == INVALID_PROCESSOR_INDEX)
{
DPrintf(0, "[%s] Invalid CPU index for path %u\n", __FUNCTION__, bundleIndex);
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_SOFT_ERRORS;
}
else if (cpuIndex >= cpuNumbers)
{
DPrintf(0, "[%s] CPU index %lu exceeds CPU range %lu\n", __FUNCTION__, cpuIndex, cpuNumbers);
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_SOFT_ERRORS;
}
else
{
cpuIndexTable[cpuIndex] = bundleIndex;
}
}
DPrintf(0, "[%s] Entering, RSS table size = %lu, # of path bundles = %u. RSS2QueueLength = %u, RSS2QueueMap =0x%p\n",
__FUNCTION__, rssTableSize, pContext->nPathBundles,
pContext->RSS2QueueLength, pContext->RSS2QueueMap);
if (pContext->RSS2QueueLength && pContext->RSS2QueueLength < rssTableSize)
{
DPrintf(0, "[%s] Freeing RSS2Queue Map\n", __FUNCTION__);
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, pContext->RSS2QueueMap, PARANDIS_MEMORY_TAG);
pContext->RSS2QueueLength = 0;
}
if (!pContext->RSS2QueueLength)
{
pContext->RSS2QueueLength = USHORT(rssTableSize);
pContext->RSS2QueueMap = (CPUPathBundle **)NdisAllocateMemoryWithTagPriority(pContext->MiniportHandle, rssTableSize * sizeof(*pContext->RSS2QueueMap),
PARANDIS_MEMORY_TAG, NormalPoolPriority);
if (pContext->RSS2QueueMap == nullptr)
{
DPrintf(0, "[%s] - Allocating RSS to queue mapping failed\n", __FUNCTION__);
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_RESOURCES;
}
NdisZeroMemory(pContext->RSS2QueueMap, sizeof(*pContext->RSS2QueueMap) * pContext->RSS2QueueLength);
}
for (rssIndex = 0; rssIndex < rssTableSize; rssIndex++)
{
pContext->RSS2QueueMap[rssIndex] = pContext->pPathBundles;
}
for (rssIndex = 0; rssIndex < rssTableSize; rssIndex++)
{
cpuIndex = NdisProcessorNumberToIndex(pContext->RSSParameters.RSSScalingSettings.IndirectionTable[rssIndex]);
bundleIndex = cpuIndexTable[cpuIndex];
DPrintf(3, "[%s] filling the relationship, rssIndex = %u, bundleIndex = %u\n", __FUNCTION__, rssIndex, bundleIndex);
DPrintf(3, "[%s] RSS proc number %u/%u, bundle affinity %u/%llu\n", __FUNCTION__,
pContext->RSSParameters.RSSScalingSettings.IndirectionTable[rssIndex].Group,
pContext->RSSParameters.RSSScalingSettings.IndirectionTable[rssIndex].Number,
pContext->pPathBundles[bundleIndex].txPath.DPCAffinity.Group,
pContext->pPathBundles[bundleIndex].txPath.DPCAffinity.Mask);
pContext->RSS2QueueMap[rssIndex] = pContext->pPathBundles + bundleIndex;
}
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_SUCCESS;
}
void ParaNdis6_EnableDeviceRssSupport(PARANDIS_ADAPTER *pContext, BOOLEAN b)
{
if (!b)
{
SetDeviceRSSSettings(pContext, true);
pContext->bRSSSupportedByDevice = false;
}
else
{
pContext->bRSSSupportedByDevice = pContext->bRSSSupportedByDevicePersistent;
SetDeviceRSSSettings(pContext);
}
}
PARANDIS_RSS_PARAMS::PARANDIS_RSS_PARAMS(PARANDIS_ADAPTER *pContext) : m_pContext(pContext)
{
FailedInitialization = !rwLock.Create(pContext->MiniportHandle);
}
PARANDIS_RSS_PARAMS::~PARANDIS_RSS_PARAMS()
{
CleanupRSSParameters(this);
}
#endif
netkvm: correct printouts to output data from proper structure
The printout should output the data from the structure that
up-to-date before printoing.
Signed-off-by: Yuri Benditovich <9668326cb042de5d91fd7679dac7ca5ea402812c@daynix.com>
#include "ndis56common.h"
#include "kdebugprint.h"
#include "Trace.h"
#ifdef NETKVM_WPP_ENABLED
#include "ParaNdis6_RSS.tmh"
#endif
#if PARANDIS_SUPPORT_RSS
#define RSS_PRINT_LEVEL 0
static void PrintIndirectionTable(const NDIS_RECEIVE_SCALE_PARAMETERS* Params);
static void PrintIndirectionTable(const PARANDIS_SCALING_SETTINGS *RSSScalingSetting);
static void PrintRSSSettings(PPARANDIS_RSS_PARAMS RSSParameters);
static NDIS_STATUS ParaNdis_SetupRSSQueueMap(PARANDIS_ADAPTER *pContext);
static VOID ApplySettings(PPARANDIS_RSS_PARAMS RSSParameters,
PARANDIS_RSS_MODE NewRSSMode,
PARANDIS_HASHING_SETTINGS *ReceiveHashingSettings,
PARANDIS_SCALING_SETTINGS *ReceiveScalingSettings)
{
CNdisPassiveWriteAutoLock autoLock(RSSParameters->rwLock);
RSSParameters->RSSMode = NewRSSMode;
if(NewRSSMode != PARANDIS_RSS_DISABLED)
{
RSSParameters->ActiveHashingSettings = *ReceiveHashingSettings;
if(NewRSSMode == PARANDIS_RSS_FULL)
{
if(RSSParameters->ActiveRSSScalingSettings.CPUIndexMapping != NULL)
NdisFreeMemory(RSSParameters->ActiveRSSScalingSettings.CPUIndexMapping, 0, 0);
RSSParameters->ActiveRSSScalingSettings = *ReceiveScalingSettings;
ReceiveScalingSettings->CPUIndexMapping = NULL;
}
}
}
static VOID InitRSSParameters(PARANDIS_ADAPTER *pContext)
{
PARANDIS_RSS_PARAMS *RSSParameters = &pContext->RSSParameters;
RSSParameters->ReceiveQueuesNumber = pContext->RSSMaxQueuesNumber;
RSSParameters->RSSScalingSettings.DefaultQueue = PARANDIS_RECEIVE_UNCLASSIFIED_PACKET;
RSSParameters->ActiveRSSScalingSettings.DefaultQueue = PARANDIS_RECEIVE_UNCLASSIFIED_PACKET;
}
static VOID CleanupRSSParameters(PARANDIS_RSS_PARAMS *RSSParameters)
{
if(RSSParameters->ActiveRSSScalingSettings.CPUIndexMapping != NULL)
NdisFreeMemory(RSSParameters->ActiveRSSScalingSettings.CPUIndexMapping, 0, 0);
if(RSSParameters->RSSScalingSettings.CPUIndexMapping != NULL)
NdisFreeMemory(RSSParameters->RSSScalingSettings.CPUIndexMapping, 0, 0);
}
static VOID InitRSSCapabilities(PARANDIS_ADAPTER *pContext)
{
NDIS_RECEIVE_SCALE_CAPABILITIES *RSSCapabilities = &pContext->RSSCapabilities;
RSSCapabilities->Header.Type = NDIS_OBJECT_TYPE_RSS_CAPABILITIES;
RSSCapabilities->Header.Revision = NDIS_RECEIVE_SCALE_CAPABILITIES_REVISION_1;
RSSCapabilities->Header.Size = NDIS_SIZEOF_RECEIVE_SCALE_CAPABILITIES_REVISION_1;
RSSCapabilities->CapabilitiesFlags = NDIS_RSS_CAPS_MESSAGE_SIGNALED_INTERRUPTS |
NDIS_RSS_CAPS_CLASSIFICATION_AT_ISR |
NdisHashFunctionToeplitz;
if (pContext->bRSSSupportedByDevice)
{
ULONG flags = 0;
flags |= (pContext->DeviceRSSCapabilities.SupportedHashes & VIRTIO_NET_RSS_HASH_TYPE_TCPv4) ?
NDIS_RSS_CAPS_HASH_TYPE_TCP_IPV4 : 0;
flags |= (pContext->DeviceRSSCapabilities.SupportedHashes & VIRTIO_NET_RSS_HASH_TYPE_TCPv6) ?
NDIS_RSS_CAPS_HASH_TYPE_TCP_IPV6 : 0;
flags |= (pContext->DeviceRSSCapabilities.SupportedHashes & VIRTIO_NET_RSS_HASH_TYPE_TCP_EX) ?
NDIS_RSS_CAPS_HASH_TYPE_TCP_IPV6_EX : 0;
RSSCapabilities->CapabilitiesFlags |= flags;
}
else
{
RSSCapabilities->CapabilitiesFlags |= NDIS_RSS_CAPS_HASH_TYPE_TCP_IPV4 |
NDIS_RSS_CAPS_HASH_TYPE_TCP_IPV6 |
NDIS_RSS_CAPS_HASH_TYPE_TCP_IPV6_EX;
}
RSSCapabilities->NumberOfInterruptMessages = 1;
RSSCapabilities->NumberOfReceiveQueues = pContext->RSSMaxQueuesNumber;
#if (NDIS_SUPPORT_NDIS630)
RSSCapabilities->Header.Revision = NDIS_RECEIVE_SCALE_CAPABILITIES_REVISION_2;
RSSCapabilities->Header.Size = NDIS_SIZEOF_RECEIVE_SCALE_CAPABILITIES_REVISION_2;
RSSCapabilities->NumberOfIndirectionTableEntries = NDIS_RSS_INDIRECTION_TABLE_MAX_SIZE_REVISION_2 / sizeof(PROCESSOR_NUMBER);
#endif
#if (NDIS_SUPPORT_NDIS680)
if (CheckNdisVersion(6, 80))
{
RSSCapabilities->Header.Revision = NDIS_RECEIVE_SCALE_CAPABILITIES_REVISION_3;
RSSCapabilities->Header.Size = NDIS_SIZEOF_RECEIVE_SCALE_CAPABILITIES_REVISION_3;
if (pContext->bRSSSupportedByDevice)
{
ULONG flags = 0;
flags |= (pContext->DeviceRSSCapabilities.SupportedHashes & VIRTIO_NET_RSS_HASH_TYPE_UDPv4) ?
NDIS_RSS_CAPS_HASH_TYPE_UDP_IPV4 : 0;
flags |= (pContext->DeviceRSSCapabilities.SupportedHashes & VIRTIO_NET_RSS_HASH_TYPE_UDPv6) ?
NDIS_RSS_CAPS_HASH_TYPE_UDP_IPV6 : 0;
flags |= (pContext->DeviceRSSCapabilities.SupportedHashes & VIRTIO_NET_RSS_HASH_TYPE_UDP_EX) ?
NDIS_RSS_CAPS_HASH_TYPE_UDP_IPV6_EX : 0;
RSSCapabilities->CapabilitiesFlags |= flags;
}
else
{
RSSCapabilities->CapabilitiesFlags |= NDIS_RSS_CAPS_HASH_TYPE_UDP_IPV4 |
NDIS_RSS_CAPS_HASH_TYPE_UDP_IPV6 |
NDIS_RSS_CAPS_HASH_TYPE_UDP_IPV6_EX;
}
}
#endif
}
void ParaNdis6_CheckDeviceRSSCapabilities(PARANDIS_ADAPTER *pContext, bool& bRss, bool& bHash)
{
if (bHash || bRss)
{
DPrintf(0, "[%s] Device supports %s %s: key of %d, table of %d, hashes %X\n", __FUNCTION__,
bHash ? "Hash" : " ", bRss ? "RSS" : " ",
pContext->DeviceRSSCapabilities.MaxKeySize,
pContext->DeviceRSSCapabilities.MaxIndirectEntries,
pContext->DeviceRSSCapabilities.SupportedHashes);
}
BOOLEAN bResult = (pContext->DeviceRSSCapabilities.SupportedHashes & VIRTIO_NET_RSS_HASH_TYPE_IPv4) &&
pContext->DeviceRSSCapabilities.MaxKeySize >= NDIS_RSS_HASH_SECRET_KEY_MAX_SIZE_REVISION_2;
if (!bResult)
{
bRss = false;
bHash = false;
}
bResult = bResult && pContext->DeviceRSSCapabilities.MaxIndirectEntries >= NDIS_RSS_INDIRECTION_TABLE_MAX_SIZE_REVISION_2 / sizeof(PROCESSOR_NUMBER);
if (!bResult)
{
bRss = false;
}
DPrintf(0, "[%s] Driver will use: %s %s\n", __FUNCTION__, bHash ? "Hash" : " ", bRss ? "RSS" : " ");
}
NDIS_RECEIVE_SCALE_CAPABILITIES* ParaNdis6_RSSCreateConfiguration(PARANDIS_ADAPTER *pContext)
{
InitRSSParameters(pContext);
InitRSSCapabilities(pContext);
return &pContext->RSSCapabilities;
}
static ULONG TranslateHashTypes(ULONG hashSettings)
{
ULONG val = 0;
val |= (hashSettings & NDIS_HASH_IPV4) ? VIRTIO_NET_RSS_HASH_TYPE_IPv4 : 0;
val |= (hashSettings & NDIS_HASH_TCP_IPV4) ? VIRTIO_NET_RSS_HASH_TYPE_TCPv4 : 0;
val |= (hashSettings & NDIS_HASH_IPV6) ? VIRTIO_NET_RSS_HASH_TYPE_IPv6 : 0;
val |= (hashSettings & NDIS_HASH_IPV6_EX) ? VIRTIO_NET_RSS_HASH_TYPE_IP_EX : 0;
val |= (hashSettings & NDIS_HASH_TCP_IPV6) ? VIRTIO_NET_RSS_HASH_TYPE_TCPv6 : 0;
val |= (hashSettings & NDIS_HASH_TCP_IPV6_EX) ? VIRTIO_NET_RSS_HASH_TYPE_TCP_EX : 0;
#if (NDIS_SUPPORT_NDIS680)
val |= (hashSettings & NDIS_HASH_UDP_IPV4) ? VIRTIO_NET_RSS_HASH_TYPE_UDPv4 : 0;
val |= (hashSettings & NDIS_HASH_UDP_IPV6) ? VIRTIO_NET_RSS_HASH_TYPE_UDPv6 : 0;
val |= (hashSettings & NDIS_HASH_UDP_IPV6_EX) ? VIRTIO_NET_RSS_HASH_TYPE_UDP_EX : 0;
#endif
TraceNoPrefix(0, "[%s] 0x%X -> 0x%X", __FUNCTION__, hashSettings, val);
return val;
}
static USHORT ResolveQueue(PARANDIS_ADAPTER *pContext, PPROCESSOR_NUMBER proc, USHORT *fallback)
{
GROUP_AFFINITY a;
ParaNdis_ProcessorNumberToGroupAffinity(&a, proc);
USHORT n;
for (n = 0; n < pContext->nPathBundles; ++n)
{
const GROUP_AFFINITY& b = pContext->pPathBundles[n].rxPath.DPCAffinity;
if (a.Group == b.Group && a.Mask == b.Mask)
{
return n;
}
}
// the CPU is not used by any queue
n = (*fallback)++;
if (*fallback >= pContext->nPathBundles)
{
*fallback = 0;
}
TraceNoPrefix(0, "[%s] fallback CPU %d.%d -> Q%d", __FUNCTION__, proc->Group, proc->Number, n);
return n;
}
static void SetDeviceRSSSettings(PARANDIS_ADAPTER *pContext, bool bForceOff = false)
{
if (!pContext->bRSSSupportedByDevice && !pContext->bHashReportedByDevice)
{
return;
}
UCHAR command = pContext->bRSSSupportedByDevice ?
VIRTIO_NET_CTRL_MQ_RSS_CONFIG : VIRTIO_NET_CTRL_MQ_HASH_CONFIG;
if (pContext->RSSParameters.RSSMode == PARANDIS_RSS_DISABLED || bForceOff)
{
virtio_net_rss_config cfg = {};
cfg.max_tx_vq = (USHORT)pContext->nPathBundles;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_MQ, command, &cfg, sizeof(cfg), NULL, 0, 2);
}
else
{
virtio_net_rss_config *cfg;
USHORT fallbackQueue = 0;
USHORT indirection_table_len = pContext->RSSParameters.ActiveRSSScalingSettings.IndirectionTableSize / sizeof(PROCESSOR_NUMBER);
UCHAR hash_key_len = (UCHAR)pContext->RSSParameters.ActiveHashingSettings.HashSecretKeySize;
ULONG config_size;
if (!pContext->bRSSSupportedByDevice)
{
indirection_table_len = 1;
}
config_size = virtio_net_rss_config_size(indirection_table_len, hash_key_len);
cfg = (virtio_net_rss_config *)ParaNdis_AllocateMemory(pContext, config_size);
if (!cfg)
{
return;
}
cfg->indirection_table_mask = indirection_table_len - 1;
cfg->unclassified_queue = ResolveQueue(pContext, &pContext->RSSParameters.ActiveRSSScalingSettings.DefaultProcessor, &fallbackQueue);
for (USHORT i = 0; i < indirection_table_len; ++i)
{
cfg->indirection_table[i] = ResolveQueue(pContext,
pContext->RSSParameters.ActiveRSSScalingSettings.IndirectionTable + i,
&fallbackQueue);
}
TraceNoPrefix(0, "[%s] Translated indirections: (len = %d)\n", __FUNCTION__, indirection_table_len);
ParaNdis_PrintTable<80, 10>(0, cfg->indirection_table, indirection_table_len, "%d", [](const __u16 *p) { return *p; });
max_tx_vq(cfg) = (USHORT)pContext->nPathBundles;
hash_key_length(cfg) = hash_key_len;
for (USHORT i = 0; i < hash_key_len; ++i)
{
hash_key_data(cfg, i) = pContext->RSSParameters.ActiveHashingSettings.HashSecretKey[i];
}
TraceNoPrefix(0, "[%s] RSS key: (len = %d)\n", __FUNCTION__, hash_key_len);
ParaNdis_PrintTable<80, 10>(0, (hash_key_length_ptr(cfg) + 1), hash_key_len, "%X", [](const __u8 *p) { return *p; });
cfg->hash_types = TranslateHashTypes(pContext->RSSParameters.ActiveHashingSettings.HashInformation);
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_MQ, command, cfg, config_size, NULL, 0, 2);
NdisFreeMemory(cfg, NULL, 0);
}
}
static BOOLEAN IsValidHashInfo(ULONG HashInformation)
{
#define HASH_FLAGS_COMBINATION(Type, Flags) ( ((Type) & (Flags)) && !((Type) & ~(Flags)) )
ULONG ulHashType = NDIS_RSS_HASH_TYPE_FROM_HASH_INFO(HashInformation);
ULONG ulHashFunction = NDIS_RSS_HASH_FUNC_FROM_HASH_INFO(HashInformation);
ULONG ulAllowedHashTypes = NDIS_HASH_IPV4 | NDIS_HASH_TCP_IPV4 | NDIS_HASH_IPV6 | NDIS_HASH_TCP_IPV6 |
NDIS_HASH_IPV6_EX | NDIS_HASH_TCP_IPV6_EX;
#if (NDIS_SUPPORT_NDIS680)
ulAllowedHashTypes |= NDIS_HASH_UDP_IPV4 | NDIS_HASH_UDP_IPV6 | NDIS_HASH_UDP_IPV6_EX;
#endif
if (HashInformation == 0)
return TRUE;
if (HASH_FLAGS_COMBINATION(ulHashType, ulAllowedHashTypes))
return ulHashFunction == NdisHashFunctionToeplitz;
return FALSE;
}
static __inline
BOOLEAN IsPowerOfTwo(ULONG n)
{
return ((n != 0) && ((n & (~n + 1)) == n));
}
static __inline
BOOLEAN IsCompatibleAffinities(PGROUP_AFFINITY a1, PGROUP_AFFINITY a2)
{
return (a1->Group == a2->Group) && (a1->Mask & a2->Mask);
}
static
CCHAR FindReceiveQueueForCurrentCpu(PPARANDIS_SCALING_SETTINGS RSSScalingSettings)
{
ULONG CurrProcIdx;
CurrProcIdx = ParaNdis_GetCurrentCPUIndex();
if(CurrProcIdx >= RSSScalingSettings->CPUIndexMappingSize)
return PARANDIS_RECEIVE_NO_QUEUE;
return RSSScalingSettings->CPUIndexMapping[CurrProcIdx];
}
static
void SetDefaultQueue(PPARANDIS_SCALING_SETTINGS RSSScalingSettings, ULONG idx)
{
if (idx < RSSScalingSettings->CPUIndexMappingSize)
{
NTSTATUS status;
status = KeGetProcessorNumberFromIndex(idx, &RSSScalingSettings->DefaultProcessor);
if (NT_SUCCESS(status))
{
RSSScalingSettings->DefaultQueue = RSSScalingSettings->CPUIndexMapping[idx];
return;
}
}
RSSScalingSettings->DefaultQueue = PARANDIS_RECEIVE_UNCLASSIFIED_PACKET;
}
static
BOOLEAN AllocateCPUMappingArray(PARANDIS_ADAPTER *pContext, PPARANDIS_SCALING_SETTINGS RSSScalingSettings)
{
ULONG i;
ULONG CPUNumber = KeQueryActiveProcessorCountEx(ALL_PROCESSOR_GROUPS);
PCHAR NewCPUMappingArray = (PCHAR)ParaNdis_AllocateMemory(pContext, sizeof(CCHAR) * CPUNumber);
if(!NewCPUMappingArray)
return FALSE;
RSSScalingSettings->CPUIndexMapping = NewCPUMappingArray;
RSSScalingSettings->CPUIndexMappingSize = CPUNumber;
for(i = 0; i < CPUNumber; i++)
{
RSSScalingSettings->CPUIndexMapping[i] = PARANDIS_RECEIVE_NO_QUEUE;
}
return TRUE;
}
static
VOID FillCPUMappingArray(
PPARANDIS_SCALING_SETTINGS RSSScalingSettings,
CCHAR ReceiveQueuesNumber)
{
ULONG i;
CCHAR ReceiveQueue = PARANDIS_FIRST_RSS_RECEIVE_QUEUE;
auto IndirectionTableChanged = false;
RSSScalingSettings->FirstQueueIndirectionIndex = INVALID_INDIRECTION_INDEX;
for (i = 0; i < RSSScalingSettings->IndirectionTableSize/sizeof(PROCESSOR_NUMBER); i++)
{
PPROCESSOR_NUMBER ProcNum = &RSSScalingSettings->IndirectionTable[i];
ULONG CurrProcIdx = KeGetProcessorIndexFromNumber(ProcNum);
if(CurrProcIdx != INVALID_PROCESSOR_INDEX)
{
if (RSSScalingSettings->CPUIndexMapping[CurrProcIdx] == PARANDIS_RECEIVE_NO_QUEUE)
{
if (ReceiveQueue == PARANDIS_FIRST_RSS_RECEIVE_QUEUE)
RSSScalingSettings->FirstQueueIndirectionIndex = i;
if (ReceiveQueue != ReceiveQueuesNumber)
{
RSSScalingSettings->CPUIndexMapping[CurrProcIdx] = ReceiveQueue++;
}
}
RSSScalingSettings->QueueIndirectionTable[i] = RSSScalingSettings->CPUIndexMapping[CurrProcIdx];
}
else
{
RSSScalingSettings->QueueIndirectionTable[i] = PARANDIS_RECEIVE_NO_QUEUE;
}
}
if (RSSScalingSettings->FirstQueueIndirectionIndex == INVALID_INDIRECTION_INDEX)
{
DPrintf(0, "[%s] - CPU <-> queue assignment failed!", __FUNCTION__);
return;
}
for (i = 0; i < RSSScalingSettings->IndirectionTableSize / sizeof(PROCESSOR_NUMBER); i++)
{
if (RSSScalingSettings->QueueIndirectionTable[i] == PARANDIS_RECEIVE_NO_QUEUE)
{
/* If some hash values remains unassigned after the first pass, either because
mapping processor number to index failed or there are not enough queues,
reassign the hash values to the first queue*/
RSSScalingSettings->QueueIndirectionTable[i] = PARANDIS_FIRST_RSS_RECEIVE_QUEUE;
RSSScalingSettings->IndirectionTable[i] = RSSScalingSettings->IndirectionTable[RSSScalingSettings->FirstQueueIndirectionIndex];
IndirectionTableChanged = true;
}
}
if (IndirectionTableChanged)
{
DPrintf(0, "[%s] Indirection table changed\n", __FUNCTION__);
}
}
static ULONG MinimalRssParametersLength(const NDIS_RECEIVE_SCALE_PARAMETERS* Params)
{
if (Params->Header.Revision == NDIS_RECEIVE_SCALE_PARAMETERS_REVISION_2)
{
return NDIS_SIZEOF_RECEIVE_SCALE_PARAMETERS_REVISION_2;
}
#if (NDIS_SUPPORT_NDIS660)
// we can receive structure rev.3
if (Params->Header.Revision == NDIS_RECEIVE_SCALE_PARAMETERS_REVISION_3)
{
return NDIS_SIZEOF_RECEIVE_SCALE_PARAMETERS_REVISION_3;
}
#endif
return sizeof(*Params);
}
NDIS_STATUS ParaNdis6_RSSSetParameters( PARANDIS_ADAPTER *pContext,
const NDIS_RECEIVE_SCALE_PARAMETERS* Params,
UINT ParamsLength,
PUINT ParamsBytesRead)
{
PARANDIS_RSS_PARAMS *RSSParameters = &pContext->RSSParameters;
ULONG ProcessorMasksSize;
ULONG IndirectionTableEntries;
ULONG minimalLength;
*ParamsBytesRead = 0;
if (ParamsLength < sizeof(Params->Header))
{
DPrintf(0, "[%s] invalid length %d!\n", __FUNCTION__, ParamsLength);
return NDIS_STATUS_INVALID_LENGTH;
}
minimalLength = MinimalRssParametersLength(Params);
if (ParamsLength < minimalLength)
{
DPrintf(0, "[%s] invalid length (1) %d < %d!\n", __FUNCTION__, ParamsLength, minimalLength);
*ParamsBytesRead = sizeof(Params->Header);
return NDIS_STATUS_INVALID_LENGTH;
}
if ((RSSParameters->RSSMode == PARANDIS_RSS_HASHING) &&
!(Params->Flags & NDIS_RSS_PARAM_FLAG_DISABLE_RSS) &&
(Params->HashInformation != 0))
{
return NDIS_STATUS_NOT_SUPPORTED;
}
if (!(Params->Flags & (NDIS_RSS_PARAM_FLAG_HASH_INFO_UNCHANGED | NDIS_RSS_PARAM_FLAG_DISABLE_RSS)) &&
!IsValidHashInfo(Params->HashInformation))
{
DPrintf(0, "[%s] invalid: flags %X, hash info %X!\n", __FUNCTION__, Params->Flags, Params->HashInformation);
return NDIS_STATUS_INVALID_PARAMETER;
}
CNdisPassiveWriteAutoLock autoLock(RSSParameters->rwLock);
if(Params->Flags & NDIS_RSS_PARAM_FLAG_DISABLE_RSS || (Params->HashInformation == 0))
{
ApplySettings(RSSParameters, PARANDIS_RSS_DISABLED, NULL, NULL);
}
else
{
BOOLEAN bHasDefaultCPU = false;
ULONG defaultCPUIndex = INVALID_PROCESSOR_INDEX;
#if (NDIS_SUPPORT_NDIS660)
// we can receive structure rev.3
if (Params->Header.Revision >= NDIS_RECEIVE_SCALE_PARAMETERS_REVISION_3 &&
!(Params->Flags & NDIS_RSS_PARAM_FLAG_DEFAULT_PROCESSOR_UNCHANGED))
{
PROCESSOR_NUMBER num = Params->DefaultProcessorNumber;
// due to unknown reason the Reserved field might be not zero
// (we see it on Win10.18362), this causes KeGetProcessorIndexFromNumber
// to return INVALID_PROCESSOR_INDEX
num.Reserved = 0;
bHasDefaultCPU = true;
defaultCPUIndex = KeGetProcessorIndexFromNumber(&num);
TraceNoPrefix(0, "[%s] has default CPU idx %d\n", __FUNCTION__, defaultCPUIndex);
}
#endif
DPrintf(0, "[%s] RSS Params: flags 0x%4.4x, hash information 0x%4.4lx\n",
__FUNCTION__, Params->Flags, Params->HashInformation);
IndirectionTableEntries = Params->IndirectionTableSize / sizeof(PROCESSOR_NUMBER);
if (!(Params->Flags & NDIS_RSS_PARAM_FLAG_ITABLE_UNCHANGED) &&
((Params->IndirectionTableSize > sizeof(RSSParameters->RSSScalingSettings.IndirectionTable)) ||
(ParamsLength < (Params->IndirectionTableOffset + Params->IndirectionTableSize)) ||
!IsPowerOfTwo(IndirectionTableEntries))
)
{
DPrintf(0, "[%s] invalid length (2), flags %x\n", __FUNCTION__, Params->Flags);
return NDIS_STATUS_INVALID_LENGTH;
}
if (!(Params->Flags & NDIS_RSS_PARAM_FLAG_HASH_KEY_UNCHANGED) &&
((Params->HashSecretKeySize > sizeof(RSSParameters->RSSHashingSettings.HashSecretKey)) ||
(ParamsLength < (Params->HashSecretKeyOffset + Params->HashSecretKeySize)))
)
{
DPrintf(0, "[%s] invalid length (3), flags %x\n", __FUNCTION__, Params->Flags);
return NDIS_STATUS_INVALID_LENGTH;
}
ProcessorMasksSize = Params->NumberOfProcessorMasks * Params->ProcessorMasksEntrySize;
if (ParamsLength < Params->ProcessorMasksOffset + ProcessorMasksSize)
{
DPrintf(0, "[%s] invalid length (4), flags %x\n", __FUNCTION__, Params->Flags);
return NDIS_STATUS_INVALID_LENGTH;
}
if (!(Params->Flags & NDIS_RSS_PARAM_FLAG_ITABLE_UNCHANGED))
{
PrintIndirectionTable(Params);
if(!AllocateCPUMappingArray(pContext, &RSSParameters->RSSScalingSettings))
return NDIS_STATUS_RESOURCES;
RSSParameters->RSSScalingSettings.IndirectionTableSize = Params->IndirectionTableSize;
NdisMoveMemory(RSSParameters->RSSScalingSettings.IndirectionTable,
(char*)Params + Params->IndirectionTableOffset, Params->IndirectionTableSize);
RSSParameters->RSSScalingSettings.RSSHashMask = IndirectionTableEntries - 1;
*ParamsBytesRead += Params->IndirectionTableSize;
*ParamsBytesRead += ProcessorMasksSize;
FillCPUMappingArray(&RSSParameters->RSSScalingSettings, RSSParameters->ReceiveQueuesNumber);
if (bHasDefaultCPU)
{
SetDefaultQueue(&RSSParameters->RSSScalingSettings, defaultCPUIndex);
}
PrintRSSSettings(RSSParameters);
}
else if (bHasDefaultCPU)
{
SetDefaultQueue(&RSSParameters->ActiveRSSScalingSettings, defaultCPUIndex);
RSSParameters->RSSScalingSettings.DefaultQueue = RSSParameters->ActiveRSSScalingSettings.DefaultQueue;
RSSParameters->RSSScalingSettings.DefaultProcessor = RSSParameters->ActiveRSSScalingSettings.DefaultProcessor;
TraceNoPrefix(0, "[%s] default queue -> %d\n", __FUNCTION__, RSSParameters->ActiveRSSScalingSettings.DefaultQueue);
}
if (!(Params->Flags & NDIS_RSS_PARAM_FLAG_HASH_INFO_UNCHANGED))
RSSParameters->RSSHashingSettings.HashInformation = Params->HashInformation;
if (!(Params->Flags & NDIS_RSS_PARAM_FLAG_HASH_KEY_UNCHANGED))
{
RSSParameters->RSSHashingSettings.HashSecretKeySize = Params->HashSecretKeySize;
NdisMoveMemory(RSSParameters->RSSHashingSettings.HashSecretKey,
(char*)Params + Params->HashSecretKeyOffset, Params->HashSecretKeySize);
*ParamsBytesRead += Params->HashSecretKeySize;
}
ApplySettings(RSSParameters,
PARANDIS_RSS_FULL,
&RSSParameters->RSSHashingSettings,
&RSSParameters->RSSScalingSettings);
}
*ParamsBytesRead += minimalLength;
#if (NDIS_SUPPORT_NDIS680)
if (CheckNdisVersion(6, 80))
{
// simplify this on Win10
*ParamsBytesRead = ParamsLength;
}
#endif
ParaNdis_ResetRxClassification(pContext);
NDIS_STATUS status = ParaNdis_SetupRSSQueueMap(pContext);
if (NT_SUCCESS(status))
{
SetDeviceRSSSettings(pContext);
}
return status;
}
ULONG ParaNdis6_QueryReceiveHash(const PARANDIS_RSS_PARAMS *RSSParameters,
RSS_HASH_KEY_PARAMETERS *RSSHashKeyParameters)
{
CNdisPassiveReadAutoLock autoLock(RSSParameters->rwLock);
NdisZeroMemory(RSSHashKeyParameters, sizeof(*RSSHashKeyParameters));
RSSHashKeyParameters->ReceiveHashParameters.Header.Type = NDIS_OBJECT_TYPE_DEFAULT;
RSSHashKeyParameters->ReceiveHashParameters.Header.Revision = NDIS_RECEIVE_HASH_PARAMETERS_REVISION_1;
RSSHashKeyParameters->ReceiveHashParameters.Header.Size = NDIS_SIZEOF_RECEIVE_HASH_PARAMETERS_REVISION_1;
RSSHashKeyParameters->ReceiveHashParameters.HashInformation = RSSParameters->ReceiveHashingSettings.HashInformation;
if(RSSParameters->RSSMode == PARANDIS_RSS_HASHING)
RSSHashKeyParameters->ReceiveHashParameters.Flags = NDIS_RECEIVE_HASH_FLAG_ENABLE_HASH;
RSSHashKeyParameters->ReceiveHashParameters.HashSecretKeySize = RSSParameters->ReceiveHashingSettings.HashSecretKeySize;
NdisMoveMemory(RSSHashKeyParameters->HashSecretKey,
RSSParameters->ReceiveHashingSettings.HashSecretKey,
RSSHashKeyParameters->ReceiveHashParameters.HashSecretKeySize);
RSSHashKeyParameters->ReceiveHashParameters.HashSecretKeyOffset = FIELD_OFFSET(RSS_HASH_KEY_PARAMETERS, HashSecretKey);
return sizeof(RSSHashKeyParameters->ReceiveHashParameters) + RSSHashKeyParameters->ReceiveHashParameters.HashSecretKeySize;
}
NDIS_STATUS ParaNdis6_RSSSetReceiveHash(PARANDIS_ADAPTER *pContext,
const NDIS_RECEIVE_HASH_PARAMETERS* Params,
UINT ParamsLength,
PUINT ParamsBytesRead)
{
PARANDIS_RSS_PARAMS *RSSParameters = &pContext->RSSParameters;
CNdisPassiveWriteAutoLock autoLock(RSSParameters->rwLock);
if (ParamsLength < sizeof(NDIS_RECEIVE_HASH_PARAMETERS))
return NDIS_STATUS_INVALID_LENGTH;
*ParamsBytesRead += sizeof(NDIS_RECEIVE_HASH_PARAMETERS);
if (RSSParameters->RSSMode == PARANDIS_RSS_FULL)
{
//Here we check that originator doesn't try to enable hashing while full RSS is on.
//Disable hashing abd clear parameters is legitimate operation hovewer
if(Params->Flags & NDIS_RECEIVE_HASH_FLAG_ENABLE_HASH)
{
if(!(Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_INFO_UNCHANGED) && (Params->HashInformation != 0))
return NDIS_STATUS_NOT_SUPPORTED;
if((Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_INFO_UNCHANGED) &&
(RSSParameters->ReceiveHashingSettings.HashInformation != 0))
return NDIS_STATUS_NOT_SUPPORTED;
}
}
if (!(Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_INFO_UNCHANGED) &&
(!IsValidHashInfo(Params->HashInformation)))
return NDIS_STATUS_INVALID_PARAMETER;
if ( (!(Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_KEY_UNCHANGED)) &&
( (Params->HashSecretKeySize > NDIS_RSS_HASH_SECRET_KEY_MAX_SIZE_REVISION_2) ||
(ParamsLength < (Params->HashSecretKeyOffset + Params->HashSecretKeySize)) )
)
return NDIS_STATUS_INVALID_LENGTH;
if (!(Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_INFO_UNCHANGED))
{
RSSParameters->ReceiveHashingSettings.HashInformation = Params->HashInformation;
}
if (!(Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_KEY_UNCHANGED))
{
RSSParameters->ReceiveHashingSettings.HashSecretKeySize = Params->HashSecretKeySize;
NdisMoveMemory(RSSParameters->ReceiveHashingSettings.HashSecretKey,
(char*)Params + Params->HashSecretKeyOffset, Params->HashSecretKeySize);
*ParamsBytesRead += Params->HashSecretKeySize;
}
if(RSSParameters->RSSMode != PARANDIS_RSS_FULL)
{
ApplySettings(RSSParameters,
((Params->Flags & NDIS_RECEIVE_HASH_FLAG_ENABLE_HASH) && (Params->HashInformation != 0))
? PARANDIS_RSS_HASHING : PARANDIS_RSS_DISABLED,
&RSSParameters->ReceiveHashingSettings, NULL);
}
ParaNdis_ResetRxClassification(pContext);
SetDeviceRSSSettings(pContext);
return NDIS_STATUS_SUCCESS;
}
typedef struct _tagHASH_CALC_SG_BUF_ENTRY
{
PCHAR chunkPtr;
ULONG chunkLen;
} HASH_CALC_SG_BUF_ENTRY, *PHASH_CALC_SG_BUF_ENTRY;
// Little Endian version ONLY
static
UINT32 ToeplitzHash(const PHASH_CALC_SG_BUF_ENTRY sgBuff, int sgEntriesNum, PCCHAR fullKey)
{
#define TOEPLITZ_MAX_BIT_NUM (7)
#define TOEPLITZ_BYTE_HAS_BIT(byte, bit) ((byte) & (1 << (TOEPLITZ_MAX_BIT_NUM - (bit))))
#define TOEPLITZ_BYTE_BIT_STATE(byte, bit) (((byte) >> (TOEPLITZ_MAX_BIT_NUM - (bit))) & 1)
UINT32 firstKeyWord, res = 0;
UINT byte, bit;
PHASH_CALC_SG_BUF_ENTRY sgEntry;
PCCHAR next_key_byte = fullKey + sizeof(firstKeyWord);
firstKeyWord = RtlUlongByteSwap(*(UINT32*)fullKey);
for(sgEntry = sgBuff; sgEntry < sgBuff + sgEntriesNum; ++sgEntry)
{
for (byte = 0; byte < sgEntry->chunkLen; ++byte)
{
for (bit = 0; bit <= TOEPLITZ_MAX_BIT_NUM; ++bit)
{
if (TOEPLITZ_BYTE_HAS_BIT(sgEntry->chunkPtr[byte], bit))
{
res ^= firstKeyWord;
}
firstKeyWord = (firstKeyWord << 1) | TOEPLITZ_BYTE_BIT_STATE(*next_key_byte, bit);
}
++next_key_byte;
}
}
return res;
#undef TOEPLITZ_BYTE_HAS_BIT
#undef TOEPLITZ_BYTE_BIT_STATE
#undef TOEPLITZ_MAX_BIT_NUM
}
static __inline
IPV6_ADDRESS* GetIP6SrcAddrForHash(
PVOID dataBuffer,
PNET_PACKET_INFO packetInfo,
bool xEnabled)
{
return (xEnabled && packetInfo->ip6HomeAddrOffset)
? (IPV6_ADDRESS*) RtlOffsetToPointer(dataBuffer, packetInfo->ip6HomeAddrOffset)
: (IPV6_ADDRESS*) RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen + FIELD_OFFSET(IPv6Header, ip6_src_address));
}
static __inline
IPV6_ADDRESS* GetIP6DstAddrForHash(
PVOID dataBuffer,
PNET_PACKET_INFO packetInfo,
bool xEnabled)
{
return (xEnabled && packetInfo->ip6DestAddrOffset)
? (IPV6_ADDRESS*) RtlOffsetToPointer(dataBuffer, packetInfo->ip6DestAddrOffset)
: (IPV6_ADDRESS*) RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen + FIELD_OFFSET(IPv6Header, ip6_dst_address));
}
static
VOID RSSCalcHash_Unsafe(
PARANDIS_RSS_PARAMS *RSSParameters,
PVOID dataBuffer,
PNET_PACKET_INFO packetInfo)
{
HASH_CALC_SG_BUF_ENTRY sgBuff[3];
ULONG hashTypes = NDIS_RSS_HASH_TYPE_FROM_HASH_INFO(RSSParameters->ActiveHashingSettings.HashInformation);
if(packetInfo->isIP4)
{
if(packetInfo->isTCP && (hashTypes & NDIS_HASH_TCP_IPV4))
{
IPv4Header *pIpHeader = (IPv4Header *) RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen);
TCPHeader *pTCPHeader = (TCPHeader *) RtlOffsetToPointer(pIpHeader, packetInfo->L3HdrLen);
sgBuff[0].chunkPtr = RtlOffsetToPointer(pIpHeader, FIELD_OFFSET(IPv4Header, ip_src));
sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv4Header, ip_src) + RTL_FIELD_SIZE(IPv4Header, ip_dest);
sgBuff[1].chunkPtr = RtlOffsetToPointer(pTCPHeader, FIELD_OFFSET(TCPHeader, tcp_src));
sgBuff[1].chunkLen = RTL_FIELD_SIZE(TCPHeader, tcp_src) + RTL_FIELD_SIZE(TCPHeader, tcp_dest);
packetInfo->RSSHash.Value = ToeplitzHash(sgBuff, 2, &RSSParameters->ActiveHashingSettings.HashSecretKey[0]);
packetInfo->RSSHash.Type = NDIS_HASH_TCP_IPV4;
packetInfo->RSSHash.Function = NdisHashFunctionToeplitz;
return;
}
#if (NDIS_SUPPORT_NDIS680)
if (packetInfo->isUDP && (hashTypes & NDIS_HASH_UDP_IPV4))
{
IPv4Header *pIpHeader = (IPv4Header *)RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen);
UDPHeader *pUDPHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, packetInfo->L3HdrLen);
sgBuff[0].chunkPtr = RtlOffsetToPointer(pIpHeader, FIELD_OFFSET(IPv4Header, ip_src));
sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv4Header, ip_src) + RTL_FIELD_SIZE(IPv4Header, ip_dest);
sgBuff[1].chunkPtr = RtlOffsetToPointer(pUDPHeader, FIELD_OFFSET(UDPHeader, udp_src));
sgBuff[1].chunkLen = RTL_FIELD_SIZE(UDPHeader, udp_src) + RTL_FIELD_SIZE(UDPHeader, udp_dest);
packetInfo->RSSHash.Value = ToeplitzHash(sgBuff, 2, RSSParameters->ActiveHashingSettings.HashSecretKey);
packetInfo->RSSHash.Type = NDIS_HASH_UDP_IPV4;
packetInfo->RSSHash.Function = NdisHashFunctionToeplitz;
return;
}
#endif
if(hashTypes & NDIS_HASH_IPV4)
{
sgBuff[0].chunkPtr = RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen + FIELD_OFFSET(IPv4Header, ip_src));
sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv4Header, ip_src) + RTL_FIELD_SIZE(IPv4Header, ip_dest);
packetInfo->RSSHash.Value = ToeplitzHash(sgBuff, 1, RSSParameters->ActiveHashingSettings.HashSecretKey);
packetInfo->RSSHash.Type = NDIS_HASH_IPV4;
packetInfo->RSSHash.Function = NdisHashFunctionToeplitz;
return;
}
}
else if(packetInfo->isIP6)
{
if(packetInfo->isTCP)
{
if(hashTypes & (NDIS_HASH_TCP_IPV6 | NDIS_HASH_TCP_IPV6_EX))
{
IPv6Header *pIpHeader = (IPv6Header *) RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen);
TCPHeader *pTCPHeader = (TCPHeader *) RtlOffsetToPointer(pIpHeader, packetInfo->L3HdrLen);
bool xEnabled = (hashTypes & NDIS_HASH_TCP_IPV6_EX) != 0;
sgBuff[0].chunkPtr = (PCHAR) GetIP6SrcAddrForHash(dataBuffer, packetInfo, xEnabled);
sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_src_address);
sgBuff[1].chunkPtr = (PCHAR) GetIP6DstAddrForHash(dataBuffer, packetInfo, xEnabled);
sgBuff[1].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_dst_address);
sgBuff[2].chunkPtr = RtlOffsetToPointer(pTCPHeader, FIELD_OFFSET(TCPHeader, tcp_src));
sgBuff[2].chunkLen = RTL_FIELD_SIZE(TCPHeader, tcp_src) + RTL_FIELD_SIZE(TCPHeader, tcp_dest);
packetInfo->RSSHash.Value = ToeplitzHash(sgBuff, 3, RSSParameters->ActiveHashingSettings.HashSecretKey);
packetInfo->RSSHash.Type = xEnabled ? NDIS_HASH_TCP_IPV6_EX : NDIS_HASH_TCP_IPV6;
packetInfo->RSSHash.Function = NdisHashFunctionToeplitz;
return;
}
}
#if (NDIS_SUPPORT_NDIS680)
if (packetInfo->isUDP && (hashTypes & (NDIS_HASH_UDP_IPV6 | NDIS_HASH_UDP_IPV6_EX)))
{
IPv6Header *pIpHeader = (IPv6Header *)RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen);
UDPHeader *pUDPHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, packetInfo->L3HdrLen);
bool xEnabled = (hashTypes & NDIS_HASH_UDP_IPV6_EX) != 0;
sgBuff[0].chunkPtr = (PCHAR)GetIP6SrcAddrForHash(dataBuffer, packetInfo, xEnabled);
sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_src_address);
sgBuff[1].chunkPtr = (PCHAR)GetIP6DstAddrForHash(dataBuffer, packetInfo, xEnabled);
sgBuff[1].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_dst_address);
sgBuff[2].chunkPtr = RtlOffsetToPointer(pUDPHeader, FIELD_OFFSET(UDPHeader, udp_src));
sgBuff[2].chunkLen = RTL_FIELD_SIZE(UDPHeader, udp_src) + RTL_FIELD_SIZE(UDPHeader, udp_dest);
packetInfo->RSSHash.Value = ToeplitzHash(sgBuff, 3, RSSParameters->ActiveHashingSettings.HashSecretKey);
packetInfo->RSSHash.Type = xEnabled ? NDIS_HASH_UDP_IPV6_EX : NDIS_HASH_UDP_IPV6;
packetInfo->RSSHash.Function = NdisHashFunctionToeplitz;
return;
}
#endif
if(hashTypes & (NDIS_HASH_IPV6 | NDIS_HASH_IPV6_EX))
{
bool xEnabled = (hashTypes & NDIS_HASH_IPV6_EX) != 0;
sgBuff[0].chunkPtr = (PCHAR) GetIP6SrcAddrForHash(dataBuffer, packetInfo, xEnabled);
sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_src_address);
sgBuff[1].chunkPtr = (PCHAR) GetIP6DstAddrForHash(dataBuffer, packetInfo, xEnabled);
sgBuff[1].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_dst_address);
packetInfo->RSSHash.Value = ToeplitzHash(sgBuff, 2, RSSParameters->ActiveHashingSettings.HashSecretKey);
packetInfo->RSSHash.Type = xEnabled ? NDIS_HASH_IPV6_EX : NDIS_HASH_IPV6;
packetInfo->RSSHash.Function = NdisHashFunctionToeplitz;
return;
}
if(hashTypes & NDIS_HASH_IPV6)
{
IPv6Header *pIpHeader = (IPv6Header *) RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen);
sgBuff[0].chunkPtr = RtlOffsetToPointer(pIpHeader, FIELD_OFFSET(IPv6Header, ip6_src_address));
sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_src_address) + RTL_FIELD_SIZE(IPv6Header, ip6_dst_address);
packetInfo->RSSHash.Value = ToeplitzHash(sgBuff, 2, RSSParameters->ActiveHashingSettings.HashSecretKey);
packetInfo->RSSHash.Type = NDIS_HASH_IPV6;
packetInfo->RSSHash.Function = NdisHashFunctionToeplitz;
return;
}
}
packetInfo->RSSHash.Value = 0;
packetInfo->RSSHash.Type = 0;
packetInfo->RSSHash.Function = 0;
}
VOID ParaNdis6_RSSAnalyzeReceivedPacket(
PARANDIS_RSS_PARAMS *RSSParameters,
PVOID dataBuffer,
PNET_PACKET_INFO packetInfo)
{
CNdisDispatchReadAutoLock autoLock(RSSParameters->rwLock);
if(RSSParameters->RSSMode != PARANDIS_RSS_DISABLED)
{
RSSCalcHash_Unsafe(RSSParameters, dataBuffer, packetInfo);
}
}
CCHAR ParaNdis6_RSSGetScalingDataForPacket(
PARANDIS_RSS_PARAMS *RSSParameters,
PNET_PACKET_INFO packetInfo,
PPROCESSOR_NUMBER targetProcessor)
{
CCHAR targetQueue;
CNdisDispatchReadAutoLock autoLock(RSSParameters->rwLock);
if (RSSParameters->RSSMode != PARANDIS_RSS_FULL ||
RSSParameters->ActiveRSSScalingSettings.FirstQueueIndirectionIndex == INVALID_INDIRECTION_INDEX)
{
targetQueue = PARANDIS_RECEIVE_UNCLASSIFIED_PACKET;
}
else if (packetInfo->RSSHash.Type == 0)
{
targetQueue = RSSParameters->ActiveRSSScalingSettings.DefaultQueue;
*targetProcessor = RSSParameters->ActiveRSSScalingSettings.DefaultProcessor;
}
else
{
ULONG indirectionIndex = packetInfo->RSSHash.Value & RSSParameters->ActiveRSSScalingSettings.RSSHashMask;
targetQueue = RSSParameters->ActiveRSSScalingSettings.QueueIndirectionTable[indirectionIndex];
if (targetQueue == PARANDIS_RECEIVE_NO_QUEUE)
{
targetQueue = PARANDIS_RECEIVE_UNCLASSIFIED_PACKET;
}
else
{
*targetProcessor = RSSParameters->ActiveRSSScalingSettings.IndirectionTable[indirectionIndex];
}
}
return targetQueue;
}
CCHAR ParaNdis6_RSSGetCurrentCpuReceiveQueue(PARANDIS_RSS_PARAMS *RSSParameters)
{
CCHAR res;
CNdisDispatchReadAutoLock autoLock(RSSParameters->rwLock);
if(RSSParameters->RSSMode != PARANDIS_RSS_FULL)
{
res = PARANDIS_RECEIVE_NO_QUEUE;
}
else
{
res = FindReceiveQueueForCurrentCpu(&RSSParameters->ActiveRSSScalingSettings);
}
return res;
}
static void PrintIndirectionTable(const NDIS_RECEIVE_SCALE_PARAMETERS* Params)
{
ULONG IndirectionTableEntries = Params->IndirectionTableSize / sizeof(PROCESSOR_NUMBER);
DPrintf(RSS_PRINT_LEVEL, "Params: flags 0x%4.4x, hash information 0x%4.4lx\n",
Params->Flags, Params->HashInformation);
DPrintf(RSS_PRINT_LEVEL, "NDIS IndirectionTable[%lu]\n", IndirectionTableEntries);
ParaNdis_PrintTable<80, 20>(RSS_PRINT_LEVEL, (const PROCESSOR_NUMBER *)((char *)Params + Params->IndirectionTableOffset), IndirectionTableEntries,
"%u/%u", [](const PROCESSOR_NUMBER *proc) { return proc->Group; }, [](const PROCESSOR_NUMBER *proc) { return proc->Number; });
}
static void PrintIndirectionTable(const PARANDIS_SCALING_SETTINGS *RSSScalingSetting)
{
ULONG IndirectionTableEntries = RSSScalingSetting->IndirectionTableSize/ sizeof(PROCESSOR_NUMBER);
DPrintf(RSS_PRINT_LEVEL, "Driver IndirectionTable[%lu]\n", IndirectionTableEntries);
ParaNdis_PrintTable<80, 20>(RSS_PRINT_LEVEL, RSSScalingSetting->IndirectionTable, IndirectionTableEntries,
"%u/%u", [](const PROCESSOR_NUMBER *proc) { return proc->Group; }, [](const PROCESSOR_NUMBER *proc) { return proc->Number; });
}
static void PrintRSSSettings(const PPARANDIS_RSS_PARAMS RSSParameters)
{
ULONG CPUNumber = KeQueryActiveProcessorCountEx(ALL_PROCESSOR_GROUPS);
PARANDIS_SCALING_SETTINGS *scaling = &RSSParameters->RSSScalingSettings;
DPrintf(RSS_PRINT_LEVEL, "%lu cpus, %d queues, first queue CPU index %ld, default queue %d\n",
CPUNumber, RSSParameters->ReceiveQueuesNumber,
scaling->FirstQueueIndirectionIndex,
scaling->DefaultQueue);
PrintIndirectionTable(scaling);
DPrintf(RSS_PRINT_LEVEL, "CPU mapping table[%u]:\n", scaling->CPUIndexMappingSize);
ParaNdis_PrintCharArray(RSS_PRINT_LEVEL, scaling->CPUIndexMapping, scaling->CPUIndexMappingSize);
DPrintf(RSS_PRINT_LEVEL, "Queue indirection table[%u]:\n", RSSParameters->ReceiveQueuesNumber);
ParaNdis_PrintCharArray(RSS_PRINT_LEVEL, scaling->QueueIndirectionTable, RSSParameters->ReceiveQueuesNumber);
}
NDIS_STATUS ParaNdis_SetupRSSQueueMap(PARANDIS_ADAPTER *pContext)
{
USHORT rssIndex, bundleIndex;
ULONG cpuIndex;
ULONG rssTableSize = pContext->RSSParameters.RSSScalingSettings.IndirectionTableSize / sizeof(PROCESSOR_NUMBER);
rssIndex = 0;
bundleIndex = 0;
USHORT *cpuIndexTable;
ULONG cpuNumbers;
cpuNumbers = KeQueryActiveProcessorCountEx(ALL_PROCESSOR_GROUPS);
cpuIndexTable = (USHORT *)NdisAllocateMemoryWithTagPriority(pContext->MiniportHandle, cpuNumbers * sizeof(*cpuIndexTable),
PARANDIS_MEMORY_TAG, NormalPoolPriority);
if (cpuIndexTable == nullptr)
{
DPrintf(0, "[%s] cpu index table allocation failed\n", __FUNCTION__);
return NDIS_STATUS_RESOURCES;
}
NdisZeroMemory(cpuIndexTable, sizeof(*cpuIndexTable) * cpuNumbers);
for (bundleIndex = 0; bundleIndex < pContext->nPathBundles; ++bundleIndex)
{
cpuIndex = pContext->pPathBundles[bundleIndex].rxPath.getCPUIndex();
if (cpuIndex == INVALID_PROCESSOR_INDEX)
{
DPrintf(0, "[%s] Invalid CPU index for path %u\n", __FUNCTION__, bundleIndex);
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_SOFT_ERRORS;
}
else if (cpuIndex >= cpuNumbers)
{
DPrintf(0, "[%s] CPU index %lu exceeds CPU range %lu\n", __FUNCTION__, cpuIndex, cpuNumbers);
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_SOFT_ERRORS;
}
else
{
cpuIndexTable[cpuIndex] = bundleIndex;
}
}
DPrintf(0, "[%s] Entering, RSS table size = %lu, # of path bundles = %u. RSS2QueueLength = %u, RSS2QueueMap =0x%p\n",
__FUNCTION__, rssTableSize, pContext->nPathBundles,
pContext->RSS2QueueLength, pContext->RSS2QueueMap);
if (pContext->RSS2QueueLength && pContext->RSS2QueueLength < rssTableSize)
{
DPrintf(0, "[%s] Freeing RSS2Queue Map\n", __FUNCTION__);
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, pContext->RSS2QueueMap, PARANDIS_MEMORY_TAG);
pContext->RSS2QueueLength = 0;
}
if (!pContext->RSS2QueueLength)
{
pContext->RSS2QueueLength = USHORT(rssTableSize);
pContext->RSS2QueueMap = (CPUPathBundle **)NdisAllocateMemoryWithTagPriority(pContext->MiniportHandle, rssTableSize * sizeof(*pContext->RSS2QueueMap),
PARANDIS_MEMORY_TAG, NormalPoolPriority);
if (pContext->RSS2QueueMap == nullptr)
{
DPrintf(0, "[%s] - Allocating RSS to queue mapping failed\n", __FUNCTION__);
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_RESOURCES;
}
NdisZeroMemory(pContext->RSS2QueueMap, sizeof(*pContext->RSS2QueueMap) * pContext->RSS2QueueLength);
}
for (rssIndex = 0; rssIndex < rssTableSize; rssIndex++)
{
pContext->RSS2QueueMap[rssIndex] = pContext->pPathBundles;
}
for (rssIndex = 0; rssIndex < rssTableSize; rssIndex++)
{
cpuIndex = NdisProcessorNumberToIndex(pContext->RSSParameters.RSSScalingSettings.IndirectionTable[rssIndex]);
bundleIndex = cpuIndexTable[cpuIndex];
DPrintf(3, "[%s] filling the relationship, rssIndex = %u, bundleIndex = %u\n", __FUNCTION__, rssIndex, bundleIndex);
DPrintf(3, "[%s] RSS proc number %u/%u, bundle affinity %u/%llu\n", __FUNCTION__,
pContext->RSSParameters.RSSScalingSettings.IndirectionTable[rssIndex].Group,
pContext->RSSParameters.RSSScalingSettings.IndirectionTable[rssIndex].Number,
pContext->pPathBundles[bundleIndex].txPath.DPCAffinity.Group,
pContext->pPathBundles[bundleIndex].txPath.DPCAffinity.Mask);
pContext->RSS2QueueMap[rssIndex] = pContext->pPathBundles + bundleIndex;
}
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_SUCCESS;
}
void ParaNdis6_EnableDeviceRssSupport(PARANDIS_ADAPTER *pContext, BOOLEAN b)
{
if (!b)
{
SetDeviceRSSSettings(pContext, true);
pContext->bRSSSupportedByDevice = false;
}
else
{
pContext->bRSSSupportedByDevice = pContext->bRSSSupportedByDevicePersistent;
SetDeviceRSSSettings(pContext);
}
}
PARANDIS_RSS_PARAMS::PARANDIS_RSS_PARAMS(PARANDIS_ADAPTER *pContext) : m_pContext(pContext)
{
FailedInitialization = !rwLock.Create(pContext->MiniportHandle);
}
PARANDIS_RSS_PARAMS::~PARANDIS_RSS_PARAMS()
{
CleanupRSSParameters(this);
}
#endif
|
#include "graphic_system.hpp"
#include <core/units.hpp>
#include "../physics/physics_comp.hpp"
namespace mo {
namespace sys {
namespace graphic {
using namespace renderer;
using namespace unit_literals;
namespace {
bool is_lazy_particle(Effect_type t) {
switch(t) {
case Effect_type::none: return true;
case Effect_type::element_fire: return true;
case Effect_type::element_frost: return true;
case Effect_type::element_water: return true;
case Effect_type::element_stone: return true;
case Effect_type::element_gas: return true;
case Effect_type::element_lightning: return true;
case Effect_type::health: return true;
case Effect_type::flame_thrower: return false;
}
}
}
Graphic_system::Graphic_system(
ecs::Entity_manager& entity_manager,
sys::physics::Transform_system& ts,
asset::Asset_manager& asset_manager,
renderer::Particle_renderer& particle_renderer,
state::State_system& state_system) noexcept
: effects(&Graphic_system::add_effect, this),
_assets(asset_manager),
_particle_renderer(particle_renderer),
_transform(ts),
_sprite_batch(asset_manager),
_sprites(entity_manager.list<Sprite_comp>()),
_particles(entity_manager.list<Particle_emiter_comp>()),
_state_change_slot(&Graphic_system::_on_state_change, this)
{
_state_change_slot.connect(state_system.state_change_events);
entity_manager.register_component_type<Sprite_comp>();
entity_manager.register_component_type<Particle_emiter_comp>();
}
void Graphic_system::add_effect(ecs::Entity& entity, Effect_type type) {
auto emiter_m = entity.get<Particle_emiter_comp>();
auto& emiter = emiter_m.is_some() ? emiter_m.get_or_throw()
: entity.emplace<Particle_emiter_comp>();
for(auto i : util::range(Particle_emiter_comp::max_emiters)) {
auto& e = emiter._emiters[i];
if(e._type==type) {
emiter.particle_type(i, type, false);
emiter.enabled(i, true, true);
return;
}
}
for(auto i : util::range(Particle_emiter_comp::max_emiters)) {
auto& e = emiter._emiters[i];
if(!e._enabled) {
emiter.particle_type(i, type, false);
emiter.enabled(i, true, true);
return;
}
}
}
void Graphic_system::draw(const renderer::Camera& camera) noexcept{
glm::vec2 upper_left = camera.screen_to_world({camera.viewport().x, camera.viewport().y});
glm::vec2 lower_right = camera.screen_to_world({camera.viewport().z, camera.viewport().w});
_transform.foreach_in_rect(upper_left, lower_right, [&](ecs::Entity& entity) {
process(entity.get<physics::Transform_comp>(),
entity.get<Sprite_comp>())
>> [&](const auto& trans, const auto& sp) {
auto sprite = sp.sprite();
sprite.position = trans.position();
sprite.layer = trans.layer();
sprite.rotation = trans.rotation();
_sprite_batch.draw(camera, sprite);
};
});
_sprite_batch.drawAll(camera);
}
void Graphic_system::update(Time dt) noexcept{
for(auto& sprite : _sprites) {
sprite.current_frame(
sprite._animation->next_frame(
sprite.animation_type(), sprite.current_frame(), dt.value(), sprite._repeat_animation
)
);
}
for(auto& p : _particles) {
int i = -1;
for(auto& e : p._emiters) {
i++;
if(!e._enabled)
continue;
_create_emiter(e);
if(!e._emiter)
continue;
auto transform = p.owner().get<physics::Transform_comp>();
auto physics = p.owner().get<physics::Physics_comp>();
transform.process([&](auto& t) {
auto vel = Velocity{0,0};
if(!is_lazy_particle(e._type))
vel = physics.process(vel, [](auto& p){return p.velocity();});
e._emiter->update_center(t.position(), t.rotation(), vel);
});
if(e._scale) {
physics.process([&](auto& phys){
p.scale(i, phys.radius());
});
}
if(e._temporary) {
if(e._to_be_disabled)
p.enabled(i, false);
else
e._to_be_disabled = true;
}
}
}
}
namespace {
Particle_emiter_ptr create_orb_emiter(Texture_ptr tex,
Particle_renderer& particle_renderer) {
if(tex) {
return particle_renderer.create_emiter(
{0_m,0_m},
0_deg,
0.5_m,
0_m,
renderer::Collision_handler::none,
100,
200,
0.05_s, 0.1_s,
util::scerp<Angle>(0_deg, 0_deg),
util::scerp<Angle>(0_deg, 0_deg),
util::lerp<Speed_per_time>(8_m/second_2, 0_m/second_2),
util::lerp<Angle_acceleration>(3000_deg/second_2, 0_deg/second_2),
util::lerp<glm::vec4>({0.6,0.6,0.6,0}, {0,0,0,0.0}),
util::lerp<Position>({25_cm, 25_cm}, {60_cm, 60_cm}, {2_cm, 2_cm}),
util::scerp<int8_t>(0),
tex
);
}
return {};
}
Texture_ptr load_tex(asset::Asset_manager& a, std::string tex_name) {
return a.load<renderer::Texture>(asset::AID(
asset::Asset_type::tex, std::move(tex_name)));
}
}
void Graphic_system::_create_emiter(Particle_emiter_comp::Emiter& e) {
if(!e._emiter && e._enabled) {
switch(e._type) {
case Effect_type::none:
e._enabled = false;
return;
case Effect_type::element_fire:
e._emiter = create_orb_emiter(load_tex(_assets,"particle_fire"),
_particle_renderer);
break;
case Effect_type::element_frost:
e._emiter = create_orb_emiter(load_tex(_assets,"particle_frost"),
_particle_renderer);
break;
case Effect_type::element_water:
e._emiter = create_orb_emiter(load_tex(_assets,"particle_water"),
_particle_renderer);
break;
case Effect_type::element_stone:
e._emiter = create_orb_emiter(load_tex(_assets,"particle_stone"),
_particle_renderer);
break;
case Effect_type::element_gas:
e._emiter = create_orb_emiter(load_tex(_assets,"particle_gas"),
_particle_renderer);
break;
case Effect_type::element_lightning:
e._emiter = create_orb_emiter(load_tex(_assets,"particle_lightning"),
_particle_renderer);
break;
case Effect_type::health:
e._emiter = create_orb_emiter(load_tex(_assets,"particle_health"),
_particle_renderer);
break;
case Effect_type::flame_thrower:
e._emiter = _particle_renderer.create_emiter(
{0_m,0_m},
0_deg,
0.01_m,
0.55_m,
renderer::Collision_handler::bounce,
400,
500,
1.0_s, 1.2_s,
util::scerp<Angle>(0_deg, 15_deg),
util::scerp<Angle>(0_deg, 0_deg),
util::lerp<Speed_per_time>(10_m/second_2, 0_m/second_2),
util::scerp<Angle_acceleration>(0_deg/second_2, 5_deg/second_2),
util::lerp<glm::vec4>({1,0.5,0.5,0}, {0,0,0,0.5}),
util::lerp<Position>({20_cm, 20_cm}, {100_cm, 100_cm}, {10_cm, 10_cm}),
util::scerp<int8_t>(0),
load_tex(_assets,"particle_fire")
);
break;
// TODO
}
}
}
void Graphic_system::_on_state_change(ecs::Entity& entity, state::State_data& data){
entity.get<Sprite_comp>().process([&](Sprite_comp& sprite) {
bool toRepeat = false;
renderer::Animation_type type;
// Map Entity-State to Animation-Type
switch(data.s){
case state::Entity_state::idle:
type = renderer::Animation_type::idle;
toRepeat = true;
break;
case state::Entity_state::walking:
type = renderer::Animation_type::walking;
toRepeat = true;
break;
case state::Entity_state::attacking_melee:
type = renderer::Animation_type::attacking_melee;
toRepeat = false;
break;
case state::Entity_state::attacking_range:
type = renderer::Animation_type::attacking_range;
toRepeat = true;
break;
case state::Entity_state::change_weapon:
type = renderer::Animation_type::change_weapon;
toRepeat = false;
break;
case state::Entity_state::taking:
type = renderer::Animation_type::taking;
toRepeat = false;
break;
case state::Entity_state::interacting:
type = renderer::Animation_type::interacting;
toRepeat = false;
break;
case state::Entity_state::damaged:
type = renderer::Animation_type::damaged;
toRepeat = false;
break;
case state::Entity_state::healed:
type = renderer::Animation_type::healed;
toRepeat = false;
break;
case state::Entity_state::dead:
type = renderer::Animation_type::died;
toRepeat = true;
break;
case state::Entity_state::dying:
type = renderer::Animation_type::died; // TODO[seb]: dying? last frame from died?
toRepeat = false;
break;
case state::Entity_state::resurrected:
type = renderer::Animation_type::resurrected;
toRepeat = false;
break;
default:
type = renderer::Animation_type::idle;
toRepeat = false;
break;
}
// applying new animation type
sprite._repeat_animation = toRepeat;
sprite.animation_type(type);
// applying magnitude
sprite.animation()->modulation(type, data.magnitude);
// calculating remaining time for current animation and inform state_comp about it
data.min_time(sprite.animation()->remaining_time(sprite.animation_type(), sprite.current_frame()));
});
}
}
}
}
Fixes for Windows Environment
#include "graphic_system.hpp"
#include <core/units.hpp>
#include "../physics/physics_comp.hpp"
namespace mo {
namespace sys {
namespace graphic {
using namespace renderer;
using namespace unit_literals;
namespace {
bool is_lazy_particle(Effect_type t) {
switch(t) {
case Effect_type::none: return true;
case Effect_type::element_fire: return true;
case Effect_type::element_frost: return true;
case Effect_type::element_water: return true;
case Effect_type::element_stone: return true;
case Effect_type::element_gas: return true;
case Effect_type::element_lightning: return true;
case Effect_type::health: return true;
case Effect_type::flame_thrower: return false;
}
FAIL("UNREACHABLE, maybe");
}
}
Graphic_system::Graphic_system(
ecs::Entity_manager& entity_manager,
sys::physics::Transform_system& ts,
asset::Asset_manager& asset_manager,
renderer::Particle_renderer& particle_renderer,
state::State_system& state_system) noexcept
: effects(&Graphic_system::add_effect, this),
_assets(asset_manager),
_particle_renderer(particle_renderer),
_transform(ts),
_sprite_batch(asset_manager),
_sprites(entity_manager.list<Sprite_comp>()),
_particles(entity_manager.list<Particle_emiter_comp>()),
_state_change_slot(&Graphic_system::_on_state_change, this)
{
_state_change_slot.connect(state_system.state_change_events);
entity_manager.register_component_type<Sprite_comp>();
entity_manager.register_component_type<Particle_emiter_comp>();
}
void Graphic_system::add_effect(ecs::Entity& entity, Effect_type type) {
auto emiter_m = entity.get<Particle_emiter_comp>();
auto& emiter = emiter_m.is_some() ? emiter_m.get_or_throw()
: entity.emplace<Particle_emiter_comp>();
for(auto i : util::range(Particle_emiter_comp::max_emiters)) {
auto& e = emiter._emiters[i];
if(e._type==type) {
emiter.particle_type(i, type, false);
emiter.enabled(i, true, true);
return;
}
}
for(auto i : util::range(Particle_emiter_comp::max_emiters)) {
auto& e = emiter._emiters[i];
if(!e._enabled) {
emiter.particle_type(i, type, false);
emiter.enabled(i, true, true);
return;
}
}
}
void Graphic_system::draw(const renderer::Camera& camera) noexcept{
glm::vec2 upper_left = camera.screen_to_world({camera.viewport().x, camera.viewport().y});
glm::vec2 lower_right = camera.screen_to_world({camera.viewport().z, camera.viewport().w});
_transform.foreach_in_rect(upper_left, lower_right, [&](ecs::Entity& entity) {
process(entity.get<physics::Transform_comp>(),
entity.get<Sprite_comp>())
>> [&](const auto& trans, const auto& sp) {
auto sprite = sp.sprite();
sprite.position = trans.position();
sprite.layer = trans.layer();
sprite.rotation = trans.rotation();
_sprite_batch.draw(camera, sprite);
};
});
_sprite_batch.drawAll(camera);
}
void Graphic_system::update(Time dt) noexcept{
for(auto& sprite : _sprites) {
sprite.current_frame(
sprite._animation->next_frame(
sprite.animation_type(), sprite.current_frame(), dt.value(), sprite._repeat_animation
)
);
}
for(auto& p : _particles) {
int i = -1;
for(auto& e : p._emiters) {
i++;
if(!e._enabled)
continue;
_create_emiter(e);
if(!e._emiter)
continue;
auto transform = p.owner().get<physics::Transform_comp>();
auto physics = p.owner().get<physics::Physics_comp>();
transform.process([&](auto& t) {
auto vel = Velocity{0,0};
if(!is_lazy_particle(e._type))
vel = physics.process(vel, [](auto& p){return p.velocity();});
e._emiter->update_center(t.position(), t.rotation(), vel);
});
if(e._scale) {
physics.process([&](auto& phys){
p.scale(i, phys.radius());
});
}
if(e._temporary) {
if(e._to_be_disabled)
p.enabled(i, false);
else
e._to_be_disabled = true;
}
}
}
}
namespace {
Particle_emiter_ptr create_orb_emiter(Texture_ptr tex,
Particle_renderer& particle_renderer) {
if(tex) {
return particle_renderer.create_emiter(
{0_m,0_m},
0_deg,
0.5_m,
0_m,
renderer::Collision_handler::none,
100,
200,
0.05_s, 0.1_s,
util::scerp<Angle>(0_deg, 0_deg),
util::scerp<Angle>(0_deg, 0_deg),
util::lerp<Speed_per_time>(8_m/second_2, 0_m/second_2),
util::lerp<Angle_acceleration>(3000_deg/second_2, 0_deg/second_2),
util::lerp<glm::vec4>({0.6,0.6,0.6,0}, {0,0,0,0.0}),
util::lerp<Position>({25_cm, 25_cm}, {60_cm, 60_cm}, {2_cm, 2_cm}),
util::scerp<int8_t>(0),
tex
);
}
return {};
}
Texture_ptr load_tex(asset::Asset_manager& a, std::string tex_name) {
return a.load<renderer::Texture>(asset::AID(
asset::Asset_type::tex, std::move(tex_name)));
}
}
void Graphic_system::_create_emiter(Particle_emiter_comp::Emiter& e) {
if(!e._emiter && e._enabled) {
switch(e._type) {
case Effect_type::none:
e._enabled = false;
return;
case Effect_type::element_fire:
e._emiter = create_orb_emiter(load_tex(_assets,"particle_fire"),
_particle_renderer);
break;
case Effect_type::element_frost:
e._emiter = create_orb_emiter(load_tex(_assets,"particle_frost"),
_particle_renderer);
break;
case Effect_type::element_water:
e._emiter = create_orb_emiter(load_tex(_assets,"particle_water"),
_particle_renderer);
break;
case Effect_type::element_stone:
e._emiter = create_orb_emiter(load_tex(_assets,"particle_stone"),
_particle_renderer);
break;
case Effect_type::element_gas:
e._emiter = create_orb_emiter(load_tex(_assets,"particle_gas"),
_particle_renderer);
break;
case Effect_type::element_lightning:
e._emiter = create_orb_emiter(load_tex(_assets,"particle_lightning"),
_particle_renderer);
break;
case Effect_type::health:
e._emiter = create_orb_emiter(load_tex(_assets,"particle_health"),
_particle_renderer);
break;
case Effect_type::flame_thrower:
e._emiter = _particle_renderer.create_emiter(
{0_m,0_m},
0_deg,
0.01_m,
0.55_m,
renderer::Collision_handler::bounce,
400,
500,
1.0_s, 1.2_s,
util::scerp<Angle>(0_deg, 15_deg),
util::scerp<Angle>(0_deg, 0_deg),
util::lerp<Speed_per_time>(10_m/second_2, 0_m/second_2),
util::scerp<Angle_acceleration>(0_deg/second_2, 5_deg/second_2),
util::lerp<glm::vec4>({1,0.5,0.5,0}, {0,0,0,0.5}),
util::lerp<Position>({20_cm, 20_cm}, {100_cm, 100_cm}, {10_cm, 10_cm}),
util::scerp<int8_t>(0),
load_tex(_assets,"particle_fire")
);
break;
// TODO
}
}
}
void Graphic_system::_on_state_change(ecs::Entity& entity, state::State_data& data){
entity.get<Sprite_comp>().process([&](Sprite_comp& sprite) {
bool toRepeat = false;
renderer::Animation_type type;
// Map Entity-State to Animation-Type
switch(data.s){
case state::Entity_state::idle:
type = renderer::Animation_type::idle;
toRepeat = true;
break;
case state::Entity_state::walking:
type = renderer::Animation_type::walking;
toRepeat = true;
break;
case state::Entity_state::attacking_melee:
type = renderer::Animation_type::attacking_melee;
toRepeat = false;
break;
case state::Entity_state::attacking_range:
type = renderer::Animation_type::attacking_range;
toRepeat = true;
break;
case state::Entity_state::change_weapon:
type = renderer::Animation_type::change_weapon;
toRepeat = false;
break;
case state::Entity_state::taking:
type = renderer::Animation_type::taking;
toRepeat = false;
break;
case state::Entity_state::interacting:
type = renderer::Animation_type::interacting;
toRepeat = false;
break;
case state::Entity_state::damaged:
type = renderer::Animation_type::damaged;
toRepeat = false;
break;
case state::Entity_state::healed:
type = renderer::Animation_type::healed;
toRepeat = false;
break;
case state::Entity_state::dead:
type = renderer::Animation_type::died;
toRepeat = true;
break;
case state::Entity_state::dying:
type = renderer::Animation_type::died; // TODO[seb]: dying? last frame from died?
toRepeat = false;
break;
case state::Entity_state::resurrected:
type = renderer::Animation_type::resurrected;
toRepeat = false;
break;
default:
type = renderer::Animation_type::idle;
toRepeat = false;
break;
}
// applying new animation type
sprite._repeat_animation = toRepeat;
sprite.animation_type(type);
// applying magnitude
sprite.animation()->modulation(type, data.magnitude);
// calculating remaining time for current animation and inform state_comp about it
data.min_time(sprite.animation()->remaining_time(sprite.animation_type(), sprite.current_frame()));
});
}
}
}
}
|
/*
* Copyright (C) 2021-present ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <seastar/core/reactor.hh>
#include <seastar/testing/test_case.hh>
#include <seastar/core/timed_out_error.hh>
#include <seastar/core/coroutine.hh>
#include <seastar/coroutine/maybe_yield.hh>
#include <seastar/core/gate.hh>
#include <seastar/core/queue.hh>
#include <seastar/core/future-util.hh>
#include <seastar/core/weak_ptr.hh>
#include <seastar/util/defer.hh>
#include "raft/server.hh"
#include "raft/logical_clock.hh"
#include "serializer.hh"
#include "serializer_impl.hh"
#include "idl/uuid.dist.hh"
#include "idl/uuid.dist.impl.hh"
#include "test/lib/random_utils.hh"
#include "test/raft/logical_timer.hh"
#include "test/raft/ticker.hh"
#include "test/raft/generator.hh"
#include "to_string.hh"
using namespace seastar;
using namespace std::chrono_literals;
seastar::logger tlogger("randomized_nemesis_test");
// A direct translaction of a mathematical definition of a state machine
// (see e.g. Wikipedia) as a C++ concept. Implementations of this concept
// do not store the state, they only define the types, the transition function
// (which is a pure function), and the initial state (which is a constant).
template <typename M> concept PureStateMachine =
requires (typename M::state_t s, typename M::input_t i) {
// The type of all possible states.
typename M::state_t;
// The type of all possible inputs (commands).
typename M::input_t;
// The type of all possible outputs.
typename M::output_t;
// The transition function (a pure function - no side effects). It takes a state
// and an input, and returns the next state and the output produced
// by applying the input to the given state.
{ M::delta(s, i) } -> std::same_as<std::pair<typename M::state_t, typename M::output_t>>;
// The initial state, of type `state_t`.
M::init;
requires std::is_same_v<const typename M::state_t, decltype(M::init)>;
};
// Used to uniquely identify commands passed into `apply` in order to return
// the outputs of these commands. See `impure_state_machine` and `call`.
using cmd_id_t = utils::UUID;
// A set of in-memory snapshots maintained by a single Raft server.
// The different parts of the server (the state machine, persistence,
// rpc) will share a single `snapshots_t`.
template <typename State>
using snapshots_t = std::unordered_map<raft::snapshot_id, State>;
// To replicate a state machine, our Raft implementation requires it to
// be represented with the `raft::state_machine` interface.
//
// `impure_state_machine` is an implementation of `raft::state_machine`
// that wraps a `PureStateMachine`. It keeps a variable of type `state_t`
// representing the current state. In `apply` it deserializes the given
// command into `input_t`, uses the transition (`delta`) function to
// produce the next state and output, replaces its current state with the
// obtained state and returns the output (more on that below); it does so
// sequentially for every given command. We can think of `PureStateMachine`
// as the actual state machine - the business logic, and `impure_state_machine`
// as the ``boilerplate'' that allows the pure machine to be replicated
// by Raft and communicate with the external world.
//
// The interface also requires maintainance of snapshots. We use the
// `snapshots_t` introduced above; `impure_state_machine` keeps a reference to `snapshots_t`
// because it will share it with an implementation of `raft::persistence`.
template <PureStateMachine M>
class impure_state_machine : public raft::state_machine {
typename M::state_t _val;
snapshots_t<typename M::state_t>& _snapshots;
// Used to ensure that when `abort()` returns there are
// no more in-progress methods running on this object.
seastar::gate _gate;
// To obtain output from an applied command, the client (see `call`)
// first allocates a channel in this data structure by calling `with_output_channel`
// and makes the returned command ID a part of the command passed to Raft.
// When (if) we eventually apply the command, we use the ID to find the output channel
// here and push the output to the client waiting on the other end.
// The channel is allocated only on the local server where `with_output_channel`
// was called; other replicas of the state machine will therefore not find the ID
// in their instances of `_output_channels` so they just drop the output.
std::unordered_map<cmd_id_t, promise<typename M::output_t>> _output_channels;
public:
impure_state_machine(snapshots_t<typename M::state_t>& snapshots)
: _val(M::init), _snapshots(snapshots) {}
future<> apply(std::vector<raft::command_cref> cmds) override {
co_await with_gate(_gate, [this, cmds = std::move(cmds)] () mutable -> future<> {
for (auto& cref : cmds) {
_gate.check();
auto is = ser::as_input_stream(cref);
auto cmd_id = ser::deserialize(is, boost::type<cmd_id_t>{});
auto input = ser::deserialize(is, boost::type<typename M::input_t>{});
auto [new_state, output] = M::delta(std::move(_val), std::move(input));
_val = std::move(new_state);
auto it = _output_channels.find(cmd_id);
if (it != _output_channels.end()) {
// We are on the leader server where the client submitted the command
// and waits for the output. Send it to them.
it->second.set_value(std::move(output));
_output_channels.erase(it);
} else {
// This is not the leader on which the command was submitted,
// or it is but the client already gave up on us and deallocated the channel.
// In any case we simply drop the output.
}
co_await coroutine::maybe_yield();
}
});
}
future<raft::snapshot_id> take_snapshot() override {
auto id = raft::snapshot_id::create_random_id();
assert(_snapshots.emplace(id, _val).second);
co_return id;
}
void drop_snapshot(raft::snapshot_id id) override {
_snapshots.erase(id);
}
future<> load_snapshot(raft::snapshot_id id) override {
auto it = _snapshots.find(id);
assert(it != _snapshots.end()); // dunno if the snapshot can actually be missing
_val = it->second;
co_return;
}
future<> abort() override {
return _gate.close();
}
struct output_channel_dropped : public raft::error {
output_channel_dropped() : error("output channel dropped") {}
};
// Before sending a command to Raft, the client must obtain a command ID
// and an output channel using this function.
template <typename F>
future<typename M::output_t> with_output_channel(F f) {
return with_gate(_gate, [this, f = std::move(f)] () mutable -> future<typename M::output_t> {
promise<typename M::output_t> p;
auto fut = p.get_future();
auto cmd_id = utils::make_random_uuid();
assert(_output_channels.emplace(cmd_id, std::move(p)).second);
auto guard = defer([this, cmd_id] {
auto it = _output_channels.find(cmd_id);
if (it != _output_channels.end()) {
it->second.set_exception(output_channel_dropped{});
_output_channels.erase(it);
}
});
return f(cmd_id, std::move(fut)).finally([guard = std::move(guard)] {});
});
}
};
// TODO: serializable concept?
template <typename Input>
raft::command make_command(const cmd_id_t& cmd_id, const Input& input) {
raft::command cmd;
ser::serialize(cmd, cmd_id);
ser::serialize(cmd, input);
return cmd;
}
// TODO: handle other errors?
template <PureStateMachine M>
using call_result_t = std::variant<typename M::output_t, timed_out_error, raft::not_a_leader, raft::dropped_entry, raft::commit_status_unknown>;
// Sends a given `input` as a command to `server`, waits until the command gets replicated
// and applied on that server and returns the produced output.
//
// The wait time is limited using `timeout` which is a logical time point referring to the
// logical clock used by `timer`. Standard way to use is to pass `timer.now() + X_t`
// as the time point, where `X` is the maximum number of ticks that we wait for.
//
// `sm` must be a reference to the state machine owned by `server`.
//
// The `server` may currently be a follower, in which case it will return a `not_a_leader` error.
template <PureStateMachine M>
future<call_result_t<M>> call(
typename M::input_t input,
raft::logical_clock::time_point timeout,
logical_timer& timer,
raft::server& server,
impure_state_machine<M>& sm) {
using output_channel_dropped = typename impure_state_machine<M>::output_channel_dropped;
return sm.with_output_channel([&, input = std::move(input), timeout] (cmd_id_t cmd_id, future<typename M::output_t> f) {
return timer.with_timeout(timeout, [&] (typename M::input_t input, future<typename M::output_t> f) {
return server.add_entry(
make_command(std::move(cmd_id), std::move(input)),
raft::wait_type::applied
).then_wrapped([output_f = std::move(f)] (future<> add_entry_f) mutable {
if (add_entry_f.failed()) {
// We need to discard `output_f`; the only expected exception is:
(void)output_f.discard_result().handle_exception_type([] (const output_channel_dropped&) {});
std::rethrow_exception(add_entry_f.get_exception());
}
return std::move(output_f);
});
}(std::move(input), std::move(f)));
}).then([] (typename M::output_t output) {
return make_ready_future<call_result_t<M>>(std::move(output));
}).handle_exception([] (std::exception_ptr eptr) {
try {
std::rethrow_exception(eptr);
} catch (raft::not_a_leader e) {
return make_ready_future<call_result_t<M>>(e);
} catch (raft::dropped_entry e) {
return make_ready_future<call_result_t<M>>(e);
} catch (raft::commit_status_unknown e) {
return make_ready_future<call_result_t<M>>(e);
} catch (logical_timer::timed_out<typename M::output_t> e) {
(void)e.get_future().discard_result()
.handle_exception([] (std::exception_ptr eptr) {
try {
std::rethrow_exception(eptr);
} catch (const output_channel_dropped&) {
} catch (const raft::dropped_entry&) {
} catch (const raft::commit_status_unknown&) {
} catch (const raft::not_a_leader&) {
} catch (const raft::stopped_error&) {
}
});
return make_ready_future<call_result_t<M>>(timed_out_error{});
}
});
}
// Allows a Raft server to communicate with other servers.
// The implementation is mostly boilerplate. It assumes that there exists a method of message passing
// given by a `send_message_t` function (passed in the constructor) for sending and by the `receive`
// function for receiving messages.
//
// We also keep a reference to a `snapshots_t` set to be shared with the `impure_state_machine`
// on the same server. We access this set when we receive or send a snapshot message.
template <typename State>
class rpc : public raft::rpc {
using reply_id_t = uint32_t;
struct snapshot_message {
raft::install_snapshot ins;
State snapshot_payload;
reply_id_t reply_id;
};
struct snapshot_reply_message {
raft::snapshot_reply reply;
reply_id_t reply_id;
};
struct execute_barrier_on_leader {
reply_id_t reply_id;
};
struct execute_barrier_on_leader_reply {
raft::read_barrier_reply reply;
reply_id_t reply_id;
};
public:
using message_t = std::variant<
snapshot_message,
snapshot_reply_message,
raft::append_request,
raft::append_reply,
raft::vote_request,
raft::vote_reply,
raft::timeout_now,
raft::read_quorum,
raft::read_quorum_reply,
execute_barrier_on_leader,
execute_barrier_on_leader_reply>;
using send_message_t = std::function<void(raft::server_id dst, message_t)>;
private:
snapshots_t<State>& _snapshots;
logical_timer _timer;
send_message_t _send;
// Before we send a snapshot apply request we create a promise-future pair,
// allocate a new ID, and put the promise here under that ID. We then send the ID
// together with the request and wait on the future.
// When (if) a reply returns, we take the ID from the reply (which is the same
// as the ID in the corresponding request), take the promise under that ID
// and push the reply through that promise.
std::unordered_map<reply_id_t, std::variant<promise<raft::snapshot_reply>, promise<raft::read_barrier_reply>>> _reply_promises;
reply_id_t _counter = 0;
// Used to ensure that when `abort()` returns there are
// no more in-progress methods running on this object.
seastar::gate _gate;
public:
rpc(snapshots_t<State>& snaps, send_message_t send)
: _snapshots(snaps), _send(std::move(send)) {
}
// Message is delivered to us
future<> receive(raft::server_id src, message_t payload) {
assert(_client);
auto& c = *_client;
co_await std::visit(make_visitor(
[&] (snapshot_message m) -> future<> {
_snapshots.emplace(m.ins.snp.id, std::move(m.snapshot_payload));
co_await with_gate(_gate, [&] () -> future<> {
auto reply = co_await c.apply_snapshot(src, std::move(m.ins));
_send(src, snapshot_reply_message{
.reply = std::move(reply),
.reply_id = m.reply_id
});
});
},
[this] (snapshot_reply_message m) -> future<> {
auto it = _reply_promises.find(m.reply_id);
if (it != _reply_promises.end()) {
std::get<promise<raft::snapshot_reply>>(it->second).set_value(std::move(m.reply));
}
co_return;
},
[&] (raft::append_request m) -> future<> {
c.append_entries(src, std::move(m));
co_return;
},
[&] (raft::append_reply m) -> future<> {
c.append_entries_reply(src, std::move(m));
co_return;
},
[&] (raft::vote_request m) -> future<> {
c.request_vote(src, std::move(m));
co_return;
},
[&] (raft::vote_reply m) -> future<> {
c.request_vote_reply(src, std::move(m));
co_return;
},
[&] (raft::timeout_now m) -> future<> {
c.timeout_now_request(src, std::move(m));
co_return;
},
[&] (raft::read_quorum m) -> future<> {
c.read_quorum_request(src, std::move(m));
co_return;
},
[&] (raft::read_quorum_reply m) -> future<> {
c.read_quorum_reply(src, std::move(m));
co_return;
},
[&] (execute_barrier_on_leader m) -> future<> {
co_await with_gate(_gate, [&] () -> future<> {
auto reply = co_await c.execute_read_barrier(src);
_send(src, execute_barrier_on_leader_reply{
.reply = std::move(reply),
.reply_id = m.reply_id
});
});
},
[this] (execute_barrier_on_leader_reply m) -> future<> {
auto it = _reply_promises.find(m.reply_id);
if (it != _reply_promises.end()) {
std::get<promise<raft::read_barrier_reply>>(it->second).set_value(std::move(m.reply));
}
co_return;
}
), std::move(payload));
}
// This is the only function of `raft::rpc` which actually expects a response.
virtual future<raft::snapshot_reply> send_snapshot(raft::server_id dst, const raft::install_snapshot& ins, seastar::abort_source&) override {
auto it = _snapshots.find(ins.snp.id);
assert(it != _snapshots.end());
auto id = _counter++;
promise<raft::snapshot_reply> p;
auto f = p.get_future();
_reply_promises.emplace(id, std::move(p));
auto guard = defer([this, id] { _reply_promises.erase(id); });
_send(dst, snapshot_message{
.ins = ins,
.snapshot_payload = it->second,
.reply_id = id
});
// The message receival function on the other side, when it receives the snapshot message,
// will apply the snapshot and send `id` back to us in the snapshot reply message (see `receive`,
// `snapshot_message` case). When we receive the reply, we shall find `id` in `_reply_promises`
// and push the reply through the promise, which will resolve `f` (see `receive`, `snapshot_reply_message`
// case).
co_return co_await with_gate(_gate,
[&, guard = std::move(guard), f = std::move(f)] () mutable -> future<raft::snapshot_reply> {
// TODO configurable
static const raft::logical_clock::duration send_snapshot_timeout = 20_t;
// TODO: catch aborts from the abort_source as well
try {
co_return co_await _timer.with_timeout(_timer.now() + send_snapshot_timeout, std::move(f));
} catch (logical_timer::timed_out<raft::snapshot_reply>& e) {
// The future will probably get a broken_promise exception after we destroy the guard.
(void)e.get_future().discard_result().handle_exception_type([] (const broken_promise&) {});
throw timed_out_error{};
}
// co_await ensures that `guard` is destroyed before we leave `_gate`
});
}
virtual future<raft::read_barrier_reply> execute_read_barrier_on_leader(raft::server_id dst) override {
auto id = _counter++;
promise<raft::read_barrier_reply> p;
auto f = p.get_future();
_reply_promises.emplace(id, std::move(p));
auto guard = defer([this, id] { _reply_promises.erase(id); });
_send(dst, execute_barrier_on_leader {
.reply_id = id
});
co_return co_await with_gate(_gate,
[&, guard = std::move(guard), f = std::move(f)] () mutable -> future<raft::read_barrier_reply> {
// TODO configurable
static const raft::logical_clock::duration execute_read_barrier_on_leader_timeout = 20_t;
// TODO: catch aborts from the abort_source as well
co_return co_await _timer.with_timeout(_timer.now() + execute_read_barrier_on_leader_timeout, std::move(f));
// co_await ensures that `guard` is destroyed before we leave `_gate`
});
}
virtual future<> send_append_entries(raft::server_id dst, const raft::append_request& m) override {
_send(dst, m);
co_return;
}
virtual void send_append_entries_reply(raft::server_id dst, const raft::append_reply& m) override {
_send(dst, m);
}
virtual void send_vote_request(raft::server_id dst, const raft::vote_request& m) override {
_send(dst, m);
}
virtual void send_vote_reply(raft::server_id dst, const raft::vote_reply& m) override {
_send(dst, m);
}
virtual void send_timeout_now(raft::server_id dst, const raft::timeout_now& m) override {
_send(dst, m);
}
virtual void send_read_quorum(raft::server_id dst, const raft::read_quorum& m) override {
_send(dst, m);
}
virtual void send_read_quorum_reply(raft::server_id dst, const raft::read_quorum_reply& m) override {
_send(dst, m);
}
virtual void add_server(raft::server_id, raft::server_info) override {
}
virtual void remove_server(raft::server_id) override {
}
virtual future<> abort() override {
return _gate.close();
}
void tick() {
_timer.tick();
}
};
template <typename State>
class persistence : public raft::persistence {
snapshots_t<State>& _snapshots;
std::pair<raft::snapshot_descriptor, State> _stored_snapshot;
std::pair<raft::term_t, raft::server_id> _stored_term_and_vote;
// Invariants:
// 1. for each entry except the first, the raft index is equal to the raft index of the previous entry plus one.
// 2. the index of the first entry is <= _stored_snapshot.first.idx + 1.
// 3. the index of the last entry is >= _stored_snapshot.first.idx.
// Informally, the last two invariants say that the stored log intersects or ``touches'' the snapshot ``on the right side''.
raft::log_entries _stored_entries;
// Returns an iterator to the entry in `_stored_entries` whose raft index is `idx` if the entry exists.
// If all entries in `_stored_entries` have greater indexes, returns the first one.
// If all entries have smaller indexes, returns end().
raft::log_entries::iterator find(raft::index_t idx) {
// The correctness of this depends on the `_stored_entries` invariant.
auto b = _stored_entries.begin();
if (b == _stored_entries.end() || (*b)->idx >= idx) {
return b;
}
return b + std::min((idx - (*b)->idx).get_value(), _stored_entries.size());
}
public:
// If this is the first server of a cluster, it must be initialized with a singleton configuration
// containing opnly this server's ID which must be also provided here as `init_config_id`.
// Otherwise it must be initialized with an empty configuration (it will be added to the cluster
// through a configuration change) and `init_config_id` must be `nullopt`.
persistence(snapshots_t<State>& snaps, std::optional<raft::server_id> init_config_id, State init_state)
: _snapshots(snaps)
, _stored_snapshot(
raft::snapshot_descriptor{
.config = init_config_id ? raft::configuration{*init_config_id} : raft::configuration{}
},
std::move(init_state))
, _stored_term_and_vote(raft::term_t{1}, raft::server_id{})
{}
virtual future<> store_term_and_vote(raft::term_t term, raft::server_id vote) override {
_stored_term_and_vote = std::pair{term, vote};
co_return;
}
virtual future<std::pair<raft::term_t, raft::server_id>> load_term_and_vote() override {
co_return _stored_term_and_vote;
}
virtual future<> store_snapshot_descriptor(const raft::snapshot_descriptor& snap, size_t preserve_log_entries) override {
// The snapshot's index cannot be smaller than the index of the first stored entry minus one;
// that would create a ``gap'' in the log.
assert(_stored_entries.empty() || snap.idx + 1 >= _stored_entries.front()->idx);
auto it = _snapshots.find(snap.id);
assert(it != _snapshots.end());
_stored_snapshot = {snap, it->second};
if (!_stored_entries.empty() && snap.idx > _stored_entries.back()->idx) {
// Clear the log in order to not create a gap.
_stored_entries.clear();
co_return;
}
auto first_to_remain = snap.idx + 1 >= preserve_log_entries ? raft::index_t{snap.idx + 1 - preserve_log_entries} : raft::index_t{0};
_stored_entries.erase(_stored_entries.begin(), find(first_to_remain));
co_return;
}
virtual future<raft::snapshot_descriptor> load_snapshot_descriptor() override {
auto [snap, state] = _stored_snapshot;
_snapshots.insert_or_assign(snap.id, std::move(state));
co_return snap;
}
virtual future<> store_log_entries(const std::vector<raft::log_entry_ptr>& entries) override {
if (entries.empty()) {
co_return;
}
// The raft server is supposed to provide entries in strictly increasing order,
// hence the following assertions.
if (_stored_entries.empty()) {
assert(entries.front()->idx == _stored_snapshot.first.idx + 1);
} else {
assert(entries.front()->idx == _stored_entries.back()->idx + 1);
}
_stored_entries.push_back(entries[0]);
for (size_t i = 1; i < entries.size(); ++i) {
assert(entries[i]->idx == entries[i-1]->idx + 1);
_stored_entries.push_back(entries[i]);
}
co_return;
}
virtual future<raft::log_entries> load_log() override {
co_return _stored_entries;
}
virtual future<> truncate_log(raft::index_t idx) override {
_stored_entries.erase(find(idx), _stored_entries.end());
co_return;
}
virtual future<> abort() override {
// There are no yields anywhere in our methods so no need to wait for anything.
// We assume that our methods won't be called after `abort()`.
// TODO: is this assumption correct?
co_return;
}
};
// A failure detector using heartbeats for deciding whether to convict a server
// as failed. We convict a server if we don't receive a heartbeat for a long enough time.
// `failure_detector` assumes a message-passing method given by a `send_heartbeat_t` function
// through the constructor for sending heartbeats and assumes that `receive_heartbeat` is called
// whenever another server sends a message to us.
// To decide who to send heartbeats to we use the ``current knowledge'' of servers in the network
// which is updated through `add_server` and `remove_server` functions.
class failure_detector : public raft::failure_detector {
public:
using send_heartbeat_t = std::function<void(raft::server_id dst)>;
private:
raft::logical_clock _clock;
// The set of known servers, used to broadcast heartbeats.
std::unordered_set<raft::server_id> _known;
// The last time we received a heartbeat from a server.
std::unordered_map<raft::server_id, raft::logical_clock::time_point> _last_heard;
// The last time we sent a heartbeat.
raft::logical_clock::time_point _last_beat;
// How long from the last received heartbeat does it take to convict a node as dead.
const raft::logical_clock::duration _convict_threshold;
send_heartbeat_t _send_heartbeat;
public:
failure_detector(raft::logical_clock::duration convict_threshold, send_heartbeat_t f)
: _convict_threshold(convict_threshold), _send_heartbeat(std::move(f))
{
send_heartbeats();
assert(_last_beat == _clock.now());
}
void receive_heartbeat(raft::server_id src) {
assert(_known.contains(src));
_last_heard[src] = std::max(_clock.now(), _last_heard[src]);
}
void tick() {
_clock.advance();
// TODO: make it adjustable
static const raft::logical_clock::duration _heartbeat_period = 10_t;
if (_last_beat + _heartbeat_period <= _clock.now()) {
send_heartbeats();
}
}
void send_heartbeats() {
for (auto& dst : _known) {
_send_heartbeat(dst);
}
_last_beat = _clock.now();
}
// We expect a server to be added through this function before we receive a heartbeat from it.
void add_server(raft::server_id id) {
_known.insert(id);
}
void remove_server(raft::server_id id) {
_known.erase(id);
_last_heard.erase(id);
}
bool is_alive(raft::server_id id) override {
return _clock.now() < _last_heard[id] + _convict_threshold;
}
};
// `network` is a simple priority queue of `event`s, where an `event` is a message associated
// with its planned delivery time. The queue uses a logical clock to decide when to deliver messages.
// It delives all messages whose associated times are smaller than the ``current time'', the latter
// determined by the number of `tick()` calls.
//
// Note: the actual delivery happens through a function that is passed in the `network` constructor.
// The function may return `false` (for whatever reason) denoting that it failed to deliver the message.
// In this case network will backup this message and retry the delivery on every later `tick` until
// it succeeds.
template <typename Payload>
class network {
public:
// When the time comes to deliver a message we use this function.
using deliver_t = std::function<void(raft::server_id src, raft::server_id dst, const Payload&)>;
private:
struct message {
raft::server_id src;
raft::server_id dst;
// shared ptr to implement duplication of messages
lw_shared_ptr<Payload> payload;
};
struct event {
raft::logical_clock::time_point time;
message msg;
};
deliver_t _deliver;
// A min-heap of event occurences compared by their time points.
std::vector<event> _events;
// Comparator for the `_events` min-heap.
static bool cmp(const event& o1, const event& o2) {
return o1.time > o2.time;
}
// A pair (dst, [src1, src2, ...]) in this set denotes that `dst`
// does not receive messages from src1, src2, ...
std::unordered_map<raft::server_id, std::unordered_set<raft::server_id>> _grudges;
raft::logical_clock _clock;
// How long does it take to deliver a message?
// TODO: use a random distribution or let the user change this dynamically
raft::logical_clock::duration _delivery_delay;
public:
network(raft::logical_clock::duration delivery_delay, deliver_t f)
: _deliver(std::move(f)), _delivery_delay(delivery_delay) {}
void send(raft::server_id src, raft::server_id dst, Payload payload) {
// Predict the delivery time in advance.
// Our prediction may be wrong if a grudge exists at this expected moment of delivery.
// Messages may also be reordered.
auto delivery_time = _clock.now() + _delivery_delay;
_events.push_back(event{delivery_time, message{src, dst, make_lw_shared<Payload>(std::move(payload))}});
std::push_heap(_events.begin(), _events.end(), cmp);
}
void tick() {
_clock.advance();
deliver();
}
void add_grudge(raft::server_id src, raft::server_id dst) {
_grudges[dst].insert(src);
}
void remove_grudge(raft::server_id src, raft::server_id dst) {
_grudges[dst].erase(src);
}
private:
void deliver() {
// Deliver every message whose time has come.
while (!_events.empty() && _events.front().time <= _clock.now()) {
auto& [_, m] = _events.front();
if (!_grudges[m.dst].contains(m.src)) {
_deliver(m.src, m.dst, *m.payload);
} else {
// A grudge means that we drop the message.
}
std::pop_heap(_events.begin(), _events.end(), cmp);
_events.pop_back();
}
}
};
// A queue of messages that have arrived at a given Raft server and are waiting to be processed
// by that server (which may be a long computation, hence returning a `future<>`).
// Its purpose is to serve as a ``bridge'' between `network` and a server's `rpc` instance.
// The `network`'s delivery function will `push()` a message onto this queue and `receive_fiber()`
// will eventually forward the message to `rpc` by calling `rpc::receive()`.
// `push()` may fail if the queue is full, meaning that the queue expects the caller (`network`
// in our case) to retry later.
template <typename State>
class delivery_queue {
struct delivery {
raft::server_id src;
typename rpc<State>::message_t payload;
};
struct aborted_exception {};
seastar::queue<delivery> _queue;
rpc<State>& _rpc;
std::optional<future<>> _receive_fiber;
public:
delivery_queue(rpc<State>& rpc)
: _queue(std::numeric_limits<size_t>::max()), _rpc(rpc) {
}
~delivery_queue() {
assert(!_receive_fiber);
}
void push(raft::server_id src, const typename rpc<State>::message_t& p) {
assert(_receive_fiber);
bool pushed = _queue.push(delivery{src, p});
// The queue is practically unbounded...
assert(pushed);
// If the queue is growing then the test infrastructure must have some kind of a liveness problem
// (which may eventually cause OOM). Let's warn the user.
if (_queue.size() > 100) {
tlogger.warn("delivery_queue: large queue size ({})", _queue.size());
}
}
// Start the receiving fiber.
// Can be executed at most once. When restarting a ``crashed'' server, create a new queue.
void start() {
assert(!_receive_fiber);
_receive_fiber = receive_fiber();
}
// Stop the receiving fiber (if it's running). The returned future resolves
// when the fiber finishes. Must be called before destruction (unless the fiber was never started).
future<> abort() {
_queue.abort(std::make_exception_ptr(aborted_exception{}));
if (_receive_fiber) {
try {
co_await *std::exchange(_receive_fiber, std::nullopt);
} catch (const aborted_exception&) {}
}
}
private:
future<> receive_fiber() {
// TODO: configurable
static const size_t _max_receive_concurrency = 20;
std::vector<delivery> batch;
while (true) {
// TODO: there is most definitely a better way to do this, but let's assume this is good enough (for now...)
// Unfortunately seastar does not yet have a multi-consumer queue implementation.
batch.push_back(co_await _queue.pop_eventually());
while (!_queue.empty() && batch.size() < _max_receive_concurrency) {
batch.push_back(_queue.pop());
}
co_await parallel_for_each(batch, [&] (delivery& m) {
return _rpc.receive(m.src, std::move(m.payload));
});
batch.clear();
}
}
};
using reconfigure_result_t = std::variant<std::monostate,
timed_out_error, raft::not_a_leader, raft::dropped_entry, raft::commit_status_unknown, raft::conf_change_in_progress>;
future<reconfigure_result_t> reconfigure(
const std::vector<raft::server_id>& ids,
raft::logical_clock::time_point timeout,
logical_timer& timer,
raft::server& server) {
raft::server_address_set config;
for (auto id : ids) {
config.insert(raft::server_address { .id = id });
}
try {
co_await timer.with_timeout(timeout, [&server, config = std::move(config)] () {
return server.set_configuration(std::move(config));
}());
co_return std::monostate{};
} catch (raft::not_a_leader e) {
co_return e;
} catch (raft::dropped_entry e) {
co_return e;
} catch (raft::commit_status_unknown e) {
co_return e;
} catch (raft::conf_change_in_progress e) {
co_return e;
} catch (logical_timer::timed_out<void> e) {
(void)e.get_future().discard_result()
.handle_exception([] (std::exception_ptr eptr) {
try {
std::rethrow_exception(eptr);
} catch (const raft::dropped_entry&) {
} catch (const raft::commit_status_unknown&) {
} catch (const raft::not_a_leader&) {
} catch (const raft::stopped_error&) {
}
});
co_return timed_out_error{};
}
}
// Contains a `raft::server` and other facilities needed for it and the underlying
// modules (persistence, rpc, etc.) to run, and to communicate with the external environment.
template <PureStateMachine M>
class raft_server {
raft::server_id _id;
std::unique_ptr<snapshots_t<typename M::state_t>> _snapshots;
std::unique_ptr<delivery_queue<typename M::state_t>> _queue;
std::unique_ptr<raft::server> _server;
// The following objects are owned by _server:
impure_state_machine<M>& _sm;
rpc<typename M::state_t>& _rpc;
bool _started = false;
bool _stopped = false;
// Used to ensure that when `abort()` returns there are
// no more in-progress methods running on this object.
seastar::gate _gate;
public:
// Create a `raft::server` with the given `id` and all other facilities required
// by the server (the state machine, RPC instance and so on). The server will use
// `send_rpc` to send RPC messages to other servers and `fd` for failure detection.
//
// If this is the first server in the cluster, pass `first_server = true`; this will
// cause the server to be created with a non-empty singleton configuration containing itself.
// Otherwise, pass `first_server = false`; that server, in order to function, must be then added
// by the existing cluster through a configuration change.
//
// The created server is not started yet; use `start` for that.
static std::unique_ptr<raft_server> create(
raft::server_id id,
shared_ptr<failure_detector> fd,
raft::server::configuration cfg,
bool first_server,
typename rpc<typename M::state_t>::send_message_t send_rpc) {
using state_t = typename M::state_t;
auto snapshots = std::make_unique<snapshots_t<state_t>>();
auto sm = std::make_unique<impure_state_machine<M>>(*snapshots);
auto rpc_ = std::make_unique<rpc<state_t>>(*snapshots, std::move(send_rpc));
auto persistence_ = std::make_unique<persistence<state_t>>(*snapshots, first_server ? std::optional{id} : std::nullopt, M::init);
auto queue = std::make_unique<delivery_queue<state_t>>(*rpc_);
auto& sm_ref = *sm;
auto& rpc_ref = *rpc_;
auto server = raft::create_server(
id, std::move(rpc_), std::move(sm), std::move(persistence_), std::move(fd),
std::move(cfg));
return std::make_unique<raft_server>(initializer{
._id = id,
._snapshots = std::move(snapshots),
._queue = std::move(queue),
._server = std::move(server),
._sm = sm_ref,
._rpc = rpc_ref
});
}
~raft_server() {
assert(!_started || _stopped);
}
raft_server(const raft_server&&) = delete;
raft_server(raft_server&&) = delete;
// Start the server. Can be called at most once.
//
// TODO: implement server ``crashes'' and ``restarts''.
// A crashed server needs a new delivery queue to be created in order to restart but must
// reuse the previous `persistence`. Perhaps the delivery queue should be created in `start`?
future<> start() {
assert(!_started);
_started = true;
co_await _server->start();
_queue->start();
}
// Stop the given server. Must be called before the server is destroyed
// (unless it was never started in the first place).
future<> abort() {
auto f = _gate.close();
// Abort everything before waiting on the gate close future
// so currently running operations finish earlier.
if (_started) {
co_await _queue->abort();
co_await _server->abort();
}
co_await std::move(f);
_stopped = true;
}
void tick() {
assert(_started);
_rpc.tick();
_server->tick();
}
future<call_result_t<M>> call(
typename M::input_t input,
raft::logical_clock::time_point timeout,
logical_timer& timer) {
assert(_started);
return with_gate(_gate, [this, input = std::move(input), timeout, &timer] {
return ::call(std::move(input), timeout, timer, *_server, _sm);
});
}
future<reconfigure_result_t> reconfigure(
const std::vector<raft::server_id>& ids,
raft::logical_clock::time_point timeout,
logical_timer& timer) {
assert(_started);
return with_gate(_gate, [this, &ids, timeout, &timer] {
return ::reconfigure(ids, timeout, timer, *_server);
});
}
bool is_leader() const {
return _server->is_leader();
}
raft::server_id id() const {
return _id;
}
void deliver(raft::server_id src, const typename rpc<typename M::state_t>::message_t& m) {
assert(_started);
if (!_gate.is_closed()) {
_queue->push(src, m);
}
}
private:
struct initializer {
raft::server_id _id;
std::unique_ptr<snapshots_t<typename M::state_t>> _snapshots;
std::unique_ptr<delivery_queue<typename M::state_t>> _queue;
std::unique_ptr<raft::server> _server;
impure_state_machine<M>& _sm;
rpc<typename M::state_t>& _rpc;
};
raft_server(initializer i)
: _id(i._id)
, _snapshots(std::move(i._snapshots))
, _queue(std::move(i._queue))
, _server(std::move(i._server))
, _sm(i._sm)
, _rpc(i._rpc) {
}
friend std::unique_ptr<raft_server> std::make_unique<raft_server, raft_server::initializer>(initializer&&);
};
static raft::server_id to_raft_id(size_t id) {
// Raft uses UUID 0 as special case.
assert(id > 0);
return raft::server_id{utils::UUID{0, id}};
}
struct environment_config {
raft::logical_clock::duration network_delay;
raft::logical_clock::duration fd_convict_threshold;
};
// A set of `raft_server`s connected by a `network`.
//
// The `network` is initialized with a message delivery function
// which notifies the destination's failure detector on each message
// and if the message contains an RPC payload, pushes it into the destination's
// `delivery_queue`.
//
// Needs to be periodically `tick()`ed which ticks the network
// and underlying servers.
template <PureStateMachine M>
class environment : public seastar::weakly_referencable<environment<M>> {
using input_t = typename M::output_t;
using state_t = typename M::state_t;
using output_t = typename M::output_t;
struct route {
std::unique_ptr<raft_server<M>> _server;
shared_ptr<failure_detector> _fd;
};
// Passed to newly created failure detectors.
const raft::logical_clock::duration _fd_convict_threshold;
// Used to deliver messages coming from the network to appropriate servers and their failure detectors.
// Also keeps the servers and the failure detectors alive (owns them).
// Before we show a Raft server to others we must add it to this map.
std::unordered_map<raft::server_id, route> _routes;
// Used to create a new ID in `new_server`.
size_t _next_id = 1;
// Engaged optional: RPC message, nullopt: heartbeat
using message_t = std::optional<typename rpc<state_t>::message_t>;
network<message_t> _network;
bool _stopped = false;
// Used to ensure that when `abort()` returns there are
// no more in-progress methods running on this object.
seastar::gate _gate;
public:
environment(environment_config cfg)
: _fd_convict_threshold(cfg.fd_convict_threshold), _network(cfg.network_delay,
[this] (raft::server_id src, raft::server_id dst, const message_t& m) {
auto& [s, fd] = _routes.at(dst);
fd->receive_heartbeat(src);
if (m) {
s->deliver(src, *m);
}
}) {
}
~environment() {
assert(_routes.empty() || _stopped);
}
environment(const environment&) = delete;
environment(environment&&) = delete;
void tick_network() {
_network.tick();
}
// TODO: adjustable/randomizable ticking ratios
void tick_servers() {
for (auto& [_, r] : _routes) {
r._server->tick();
r._fd->tick();
}
}
// Creates and starts a server with a local (uniquely owned) failure detector,
// connects it to the network and returns its ID.
//
// If `first == true` the server is created with a singleton configuration containing itself.
// Otherwise it is created with an empty configuration. The user must explicitly ask for a configuration change
// if they want to make a cluster (group) out of this server and other existing servers.
// The user should be able to create multiple clusters by calling `new_server` multiple times with `first = true`.
// (`first` means ``first in group'').
future<raft::server_id> new_server(bool first, raft::server::configuration cfg = {}) {
return with_gate(_gate, [this, first, cfg = std::move(cfg)] () -> future<raft::server_id> {
auto id = to_raft_id(_next_id++);
// TODO: in the future we want to simulate multiple raft servers running on a single ``node'',
// sharing a single failure detector. We will then likely split `new_server` into two steps: `new_node` and `new_server`,
// the first creating the failure detector for a node and wiring it up, the second creating a server on a given node.
// We will also possibly need to introduce some kind of ``node IDs'' which `failure_detector` (and `network`)
// will operate on (currently they operate on `raft::server_id`s, assuming a 1-1 mapping of server-to-node).
auto fd = seastar::make_shared<failure_detector>(_fd_convict_threshold, [id, this] (raft::server_id dst) {
_network.send(id, dst, std::nullopt);
});
auto srv = raft_server<M>::create(id, fd, std::move(cfg), first,
[id, this] (raft::server_id dst, typename rpc<state_t>::message_t m) {
_network.send(id, dst, {std::move(m)});
});
co_await srv->start();
// Add us to other servers' failure detectors.
for (auto& [_, r] : _routes) {
r._fd->add_server(id);
}
// Add other servers to our failure detector.
for (auto& [id, _] : _routes) {
fd->add_server(id);
}
_routes.emplace(id, route{std::move(srv), std::move(fd)});
co_return id;
});
}
raft_server<M>& get_server(raft::server_id id) {
return *_routes.at(id)._server;
}
network<message_t>& get_network() {
return _network;
}
// Must be called before we are destroyed unless `new_server` was never called.
future<> abort() {
// Close the gate before iterating over _routes to prevent concurrent modification by other methods.
co_await _gate.close();
for (auto& [_, r] : _routes) {
co_await r._server->abort();
}
_stopped = true;
}
};
template <PureStateMachine M, std::invocable<environment<M>&, ticker&> F>
auto with_env_and_ticker(environment_config cfg, F f) {
return do_with(std::move(f), std::make_unique<environment<M>>(std::move(cfg)), std::make_unique<ticker>(tlogger),
[] (F& f, std::unique_ptr<environment<M>>& env, std::unique_ptr<ticker>& t) {
return f(*env, *t).finally([&env_ = env, &t_ = t] () mutable -> future<> {
// move into coroutine body so they don't get destroyed with the lambda (on first co_await)
auto& env = env_;
auto& t = t_;
// We abort the environment before the ticker as the environment may require time to advance
// in order to finish (e.g. some operations may need to timeout).
co_await env->abort();
tlogger.trace("environment aborted");
co_await t->abort();
tlogger.trace("ticker aborted");
});
});
}
struct ExReg {
// Replaces the state with `x` and returns the previous state.
struct exchange { int32_t x; };
// Returns the state.
struct read {};
// Return value for `exchange` or `read`.
struct ret { int32_t x; };
using state_t = int32_t;
using input_t = std::variant<read, exchange>;
using output_t = ret;
static std::pair<state_t, output_t> delta(state_t curr, input_t input) {
using res_t = std::pair<state_t, output_t>;
return std::visit(make_visitor(
[&curr] (const exchange& w) -> res_t {
return {w.x, ret{curr}};
},
[&curr] (const read&) -> res_t {
return {curr, ret{curr}};
}
), input);
}
static const state_t init;
};
const ExReg::state_t ExReg::init = 0;
namespace ser {
template <>
struct serializer<ExReg::exchange> {
template <typename Output>
static void write(Output& buf, const ExReg::exchange& op) { serializer<int32_t>::write(buf, op.x); };
template <typename Input>
static ExReg::exchange read(Input& buf) { return { serializer<int32_t>::read(buf) }; }
template <typename Input>
static void skip(Input& buf) { serializer<int32_t>::skip(buf); }
};
template <>
struct serializer<ExReg::read> {
template <typename Output>
static void write(Output& buf, const ExReg::read&) {};
template <typename Input>
static ExReg::read read(Input& buf) { return {}; }
template <typename Input>
static void skip(Input& buf) {}
};
}
bool operator==(ExReg::ret a, ExReg::ret b) { return a.x == b.x; }
std::ostream& operator<<(std::ostream& os, const ExReg::ret& r) {
return os << format("ret{{{}}}", r.x);
}
std::ostream& operator<<(std::ostream& os, const ExReg::read&) {
return os << "read";
}
std::ostream& operator<<(std::ostream& os, const ExReg::exchange& e) {
return os << format("xng{{{}}}", e.x);
}
// Wait until either one of `nodes` in `env` becomes a leader, or time point `timeout` is reached according to `timer` (whichever happens first).
// If the leader is found, returns it. Otherwise throws a `logical_timer::timed_out` exception.
//
// Note: the returned node may have been a leader the moment we found it, but may have just stepped down
// the moment we return it. It may be useful to call this function multiple times during cluster
// stabilization periods in order to find a node that will successfully answer calls.
template <PureStateMachine M>
struct wait_for_leader {
// FIXME: change into free function after clang bug #50345 is fixed
future<raft::server_id> operator()(
environment<M>& env,
std::vector<raft::server_id> nodes,
logical_timer& timer,
raft::logical_clock::time_point timeout) {
auto l = co_await timer.with_timeout(timeout, [] (weak_ptr<environment<M>> env, std::vector<raft::server_id> nodes) -> future<raft::server_id> {
while (true) {
if (!env) {
co_return raft::server_id{};
}
auto it = std::find_if(nodes.begin(), nodes.end(), [&env] (raft::server_id id) { return env->get_server(id).is_leader(); });
if (it != nodes.end()) {
co_return *it;
}
co_await seastar::later();
}
}(env.weak_from_this(), std::move(nodes)));
assert(l != raft::server_id{});
// Note: `l` may no longer be a leader at this point if there was a yield at the `co_await` above
// and `l` decided to step down, was restarted, or just got removed from the configuration.
co_return l;
}
};
SEASTAR_TEST_CASE(basic_test) {
logical_timer timer;
environment_config cfg {
.network_delay = 5_t,
.fd_convict_threshold = 50_t,
};
co_await with_env_and_ticker<ExReg>(cfg, [&timer] (environment<ExReg>& env, ticker& t) -> future<> {
using output_t = typename ExReg::output_t;
t.start({
{1, [&] {
env.tick_network();
timer.tick();
}},
{10, [&] {
env.tick_servers();
}}
}, 10'000);
auto leader_id = co_await env.new_server(true);
// Wait at most 1000 ticks for the server to elect itself as a leader.
assert(co_await wait_for_leader<ExReg>{}(env, {leader_id}, timer, timer.now() + 1000_t) == leader_id);
auto call = [&] (ExReg::input_t input, raft::logical_clock::duration timeout) {
return env.get_server(leader_id).call(std::move(input), timer.now() + timeout, timer);
};
auto eq = [] (const call_result_t<ExReg>& r, const output_t& expected) {
return std::holds_alternative<output_t>(r) && std::get<output_t>(r) == expected;
};
for (int i = 1; i <= 100; ++i) {
assert(eq(co_await call(ExReg::exchange{i}, 100_t), ExReg::ret{i - 1}));
}
tlogger.debug("100 exchanges - single server - passed");
auto id2 = co_await env.new_server(false);
auto id3 = co_await env.new_server(false);
tlogger.debug("Started 2 more servers, changing configuration");
assert(std::holds_alternative<std::monostate>(
co_await env.get_server(leader_id).reconfigure({leader_id, id2, id3}, timer.now() + 100_t, timer)));
tlogger.debug("Configuration changed");
co_await call(ExReg::exchange{0}, 100_t);
for (int i = 1; i <= 100; ++i) {
assert(eq(co_await call(ExReg::exchange{i}, 100_t), ExReg::ret{i - 1}));
}
tlogger.debug("100 exchanges - three servers - passed");
// concurrent calls
std::vector<future<call_result_t<ExReg>>> futs;
for (int i = 0; i < 100; ++i) {
futs.push_back(call(ExReg::read{}, 100_t));
co_await timer.sleep(2_t);
}
for (int i = 0; i < 100; ++i) {
assert(eq(co_await std::move(futs[i]), ExReg::ret{100}));
}
tlogger.debug("100 concurrent reads - three servers - passed");
});
tlogger.debug("Finished");
}
// A snapshot was being taken with the wrong term (current term instead of the term at the snapshotted index).
// This is a regression test for that bug.
SEASTAR_TEST_CASE(snapshot_uses_correct_term_test) {
logical_timer timer;
environment_config cfg {
.network_delay = 1_t,
.fd_convict_threshold = 10_t,
};
co_await with_env_and_ticker<ExReg>(cfg, [&timer] (environment<ExReg>& env, ticker& t) -> future<> {
t.start({
{1, [&] {
env.tick_network();
timer.tick();
}},
{10, [&] {
env.tick_servers();
}}
}, 10'000);
auto id1 = co_await env.new_server(true,
raft::server::configuration{
// It's easier to catch the problem when we send entries one by one, not in batches.
.append_request_threshold = 1,
});
assert(co_await wait_for_leader<ExReg>{}(env, {id1}, timer, timer.now() + 1000_t) == id1);
auto id2 = co_await env.new_server(true,
raft::server::configuration{
.append_request_threshold = 1,
});
assert(std::holds_alternative<std::monostate>(
co_await env.get_server(id1).reconfigure({id1, id2}, timer.now() + 100_t, timer)));
// Append a bunch of entries
for (int i = 1; i <= 10; ++i) {
assert(std::holds_alternative<typename ExReg::ret>(
co_await env.get_server(id1).call(ExReg::exchange{0}, timer.now() + 100_t, timer)));
}
assert(env.get_server(id1).is_leader());
// Force a term increase by partitioning the network and waiting for the leader to step down
tlogger.trace("add grudge");
env.get_network().add_grudge(id2, id1);
env.get_network().add_grudge(id1, id2);
while (env.get_server(id1).is_leader()) {
co_await seastar::later();
}
tlogger.trace("remove grudge");
env.get_network().remove_grudge(id2, id1);
env.get_network().remove_grudge(id1, id2);
auto l = co_await wait_for_leader<ExReg>{}(env, {id1, id2}, timer, timer.now() + 1000_t);
tlogger.trace("last leader: {}", l);
// Now the current term is greater than the term of the first couple of entries.
// Join another server with a small snapshot_threshold.
// The leader will send entries to this server one by one (due to small append_request_threshold),
// so the joining server will apply entries one by one or in small batches (depends on the timing),
// making it likely that it decides to take a snapshot at an entry with term lower than the current one.
// If we are (un)lucky and we take a snapshot at the last appended entry, the node will refuse all
// later append_entries requests due to non-matching term at the last appended entry. Note: due to this
// requirement, the test is nondeterministic and doesn't always catch the bug (it depends on a race
// between applier_fiber and io_fiber), but it does catch it in a significant number of runs.
// It's also a lot easier to catch this in dev than in debug, for instance.
// If we catch the bug, the reconfigure request below will time out.
auto id3 = co_await env.new_server(false,
raft::server::configuration{
.snapshot_threshold = 5,
.snapshot_trailing = 2,
});
assert(std::holds_alternative<std::monostate>(
co_await env.get_server(l).reconfigure({l, id3}, timer.now() + 1000_t, timer)));
});
}
// Regression test for the following bug: when we took a snapshot, we forgot to save the configuration.
// This caused each node in the cluster to eventually forget the cluster configuration.
SEASTAR_TEST_CASE(snapshotting_preserves_config_test) {
logical_timer timer;
environment_config cfg {
.network_delay = 1_t,
.fd_convict_threshold = 10_t,
};
co_await with_env_and_ticker<ExReg>(cfg, [&timer] (environment<ExReg>& env, ticker& t) -> future<> {
t.start({
{1, [&] {
env.tick_network();
timer.tick();
}},
{10, [&] {
env.tick_servers();
}}
}, 10'000);
auto id1 = co_await env.new_server(true,
raft::server::configuration{
.snapshot_threshold = 5,
.snapshot_trailing = 1,
});
assert(co_await wait_for_leader<ExReg>{}(env, {id1}, timer, timer.now() + 1000_t) == id1);
auto id2 = co_await env.new_server(false,
raft::server::configuration{
.snapshot_threshold = 5,
.snapshot_trailing = 1,
});
assert(std::holds_alternative<std::monostate>(
co_await env.get_server(id1).reconfigure({id1, id2}, timer.now() + 100_t, timer)));
// Append a bunch of entries
for (int i = 1; i <= 10; ++i) {
assert(std::holds_alternative<typename ExReg::ret>(
co_await env.get_server(id1).call(ExReg::exchange{0}, timer.now() + 100_t, timer)));
}
assert(env.get_server(id1).is_leader());
// Partition the network, forcing the leader to step down.
tlogger.trace("add grudge");
env.get_network().add_grudge(id2, id1);
env.get_network().add_grudge(id1, id2);
while (env.get_server(id1).is_leader()) {
co_await seastar::later();
}
tlogger.trace("remove grudge");
env.get_network().remove_grudge(id2, id1);
env.get_network().remove_grudge(id1, id2);
// With the bug this would timeout, the cluster is unable to elect a leader without the configuration.
auto l = co_await wait_for_leader<ExReg>{}(env, {id1, id2}, timer, timer.now() + 1000_t);
tlogger.trace("last leader: {}", l);
});
}
// Given a function `F` which takes a `raft::server_id` argument and returns a variant type
// which contains `not_a_leader`, repeatedly calls `F` until it returns something else than
// `not_a_leader` or until we reach a limit, whichever happens first.
// The maximum number of calls until we give up is specified by `bounces`.
// The initial `raft::server_id` argument provided to `F` is specified as an argument
// to this function (`srv_id`). If the initial call returns `not_a_leader`, then:
// - if the result contained a different leader ID, we will use it in the next call,
// sleeping for `known_leader_delay` first,
// - otherwise we will take the next ID from the `known` set, sleeping for
// `unknown_leader_delay` first.
// The returned result contains the result of the last call to `F` and the last
// server ID passed to `F`.
template <typename F>
struct bouncing {
using future_type = std::invoke_result_t<F, raft::server_id>;
using value_type = typename future_type::value_type;
static_assert(boost::mp11::mp_contains<value_type, raft::not_a_leader>::value);
F _f;
bouncing(F f) : _f(std::move(f)) {}
// FIXME: change this into a free function after clang bug #50345 is fixed.
future<std::pair<value_type, raft::server_id>> operator()(
logical_timer& timer,
std::unordered_set<raft::server_id> known,
raft::server_id srv_id,
size_t bounces,
raft::logical_clock::duration known_leader_delay,
raft::logical_clock::duration unknown_leader_delay
) {
auto it = known.find(srv_id);
while (true) {
auto res = co_await _f(srv_id);
if (auto n_a_l = std::get_if<raft::not_a_leader>(&res); n_a_l && bounces) {
--bounces;
if (n_a_l->leader) {
assert(n_a_l->leader != srv_id);
co_await timer.sleep(known_leader_delay);
srv_id = n_a_l->leader;
} else {
co_await timer.sleep(unknown_leader_delay);
assert(!known.empty());
if (it == known.end() || ++it == known.end()) {
it = known.begin();
}
srv_id = *it;
}
continue;
}
co_return std::pair{res, srv_id};
}
}
};
// An operation representing a call to the Raft cluster with a specific state machine input.
// We may bounce a number of times if the server returns `not_a_leader` before giving up.
template <PureStateMachine M>
struct raft_call {
typename M::input_t input;
raft::logical_clock::duration timeout;
using result_type = call_result_t<M>;
struct state_type {
environment<M>& env;
// The set of servers that may be part of the current configuration.
// Sometimes we don't know the exact configuration, e.g. after a failed configuration change.
const std::unordered_set<raft::server_id>& known;
logical_timer& timer;
};
future<result_type> execute(state_type& s, const operation::context& ctx) {
// TODO a stable contact point used by a given thread would be preferable;
// the thread would switch only if necessary (the contact point left the configuration).
// Currently we choose the contact point randomly each time.
assert(s.known.size() > 0);
static std::mt19937 engine{0};
auto it = s.known.begin();
std::advance(it, std::uniform_int_distribution<size_t>{0, s.known.size() - 1}(engine));
auto contact = *it;
tlogger.debug("db call start inp {} tid {} start time {} current time {} contact {}", input, ctx.thread, ctx.start, s.timer.now(), contact);
auto [res, last] = co_await bouncing{[input = input, timeout = s.timer.now() + timeout, &timer = s.timer, &env = s.env] (raft::server_id id) {
return env.get_server(id).call(input, timeout, timer);
}}(s.timer, s.known, contact, 6, 10_t, 10_t);
tlogger.debug("db call end inp {} tid {} start time {} current time {} last contact {}", input, ctx.thread, ctx.start, s.timer.now(), last);
co_return res;
}
friend std::ostream& operator<<(std::ostream& os, const raft_call& c) {
return os << format("raft_call{{input:{},timeout:{}}}", c.input, c.timeout);
}
};
// An operation that partitions the network in half.
// During the partition, no server from one half can contact any server from the other;
// the partition is symmetric.
// For odd number of nodes, ensures that the current leader (if there is one) is in the minority.
template <PureStateMachine M>
class network_majority_grudge {
raft::logical_clock::duration _duration;
public:
struct state_type {
environment<M>& env;
const std::unordered_set<raft::server_id>& known;
logical_timer& timer;
std::mt19937 rnd;
};
using result_type = std::monostate;
network_majority_grudge(raft::logical_clock::duration d) : _duration(d) {
static_assert(operation::Executable<network_majority_grudge<M>>);
}
future<result_type> execute(state_type& s, const operation::context& ctx) {
std::vector<raft::server_id> nodes{s.known.begin(), s.known.end()};
std::shuffle(nodes.begin(), nodes.end(), s.rnd);
auto mid = nodes.begin() + (nodes.size() / 2);
if (nodes.size() % 2) {
// Odd number of nodes, let's ensure that the leader (if there is one) is in the minority
auto it = std::find_if(mid, nodes.end(), [&env = s.env] (raft::server_id id) { return env.get_server(id).is_leader(); });
if (it != nodes.end()) {
std::swap(*nodes.begin(), *it);
}
}
// Note: creating the grudges has O(n^2) complexity, where n is the cluster size.
// May be problematic for (very) large clusters.
for (auto x = nodes.begin(); x != mid; ++x) {
for (auto y = mid; y != nodes.end(); ++y) {
s.env.get_network().add_grudge(*x, *y);
s.env.get_network().add_grudge(*y, *x);
}
}
tlogger.debug("network_majority_grudge start tid {} start time {} current time {} duration {} grudge: {} vs {}",
ctx.thread, ctx.start, s.timer.now(),
_duration,
std::vector<raft::server_id>{nodes.begin(), mid},
std::vector<raft::server_id>{mid, nodes.end()});
co_await s.timer.sleep(_duration);
tlogger.debug("network_majority_grudge end tid {} start time {} current time {}", ctx.thread, ctx.start, s.timer.now());
// Some servers in `nodes` may already be gone at this point but network doesn't care.
// It's safe to call `remove_grudge`.
for (auto x = nodes.begin(); x != mid; ++x) {
for (auto y = mid; y != nodes.end(); ++y) {
s.env.get_network().remove_grudge(*x, *y);
s.env.get_network().remove_grudge(*y, *x);
}
}
co_return std::monostate{};
}
friend std::ostream& operator<<(std::ostream& os, const network_majority_grudge& p) {
return os << format("network_majority_grudge{{duration:{}}}", p._duration);
}
};
// Must be executed sequentially.
template <PureStateMachine M>
struct reconfiguration {
raft::logical_clock::duration timeout;
struct state_type {
const std::vector<raft::server_id> all_servers;
environment<M>& env;
// a subset of all_servers that we modify;
// the set of servers which may potentially be in the current configuration
std::unordered_set<raft::server_id>& known;
logical_timer& timer;
std::mt19937 rnd;
};
using result_type = reconfigure_result_t;
future<result_type> execute(state_type& s, const operation::context& ctx) {
assert(s.all_servers.size() > 1);
std::vector<raft::server_id> nodes{s.all_servers.begin(), s.all_servers.end()};
std::shuffle(nodes.begin(), nodes.end(), s.rnd);
nodes.resize(std::uniform_int_distribution<size_t>{1, nodes.size()}(s.rnd));
assert(s.known.size() > 0);
auto [res, last] = co_await bouncing{[&nodes, timeout = s.timer.now() + timeout, &timer = s.timer, &env = s.env] (raft::server_id id) {
return env.get_server(id).reconfigure(nodes, timeout, timer);
}}(s.timer, s.known, *s.known.begin(), 10, 10_t, 10_t);
std::visit(make_visitor(
[&, last = last] (std::monostate) {
tlogger.debug("reconfig successful from {} to {} by {}", s.known, nodes, last);
s.known = std::unordered_set<raft::server_id>{nodes.begin(), nodes.end()};
// TODO: include the old leader as well in case it's not part of the new config?
// it may remain a leader for some time...
},
[&, last = last] (raft::not_a_leader& e) {
tlogger.debug("reconfig failed, not a leader: {} tried {} by {}", e, nodes, last);
},
[&, last = last] (auto& e) {
s.known.merge(std::unordered_set<raft::server_id>{nodes.begin(), nodes.end()});
tlogger.debug("reconfig failed: {}, tried {} after merge {} by {}", e, nodes, s.known, last);
}
), res);
co_return res;
}
friend std::ostream& operator<<(std::ostream& os, const reconfiguration& r) {
return os << format("reconfiguration{{timeout:{}}}", r.timeout);
}
};
namespace std {
std::ostream& operator<<(std::ostream& os, const std::monostate&) {
return os << "";
}
template <typename T, typename... Ts>
std::ostream& operator<<(std::ostream& os, const std::variant<T, Ts...>& v) {
std::visit([&os] (auto& arg) { os << arg; }, v);
return os;
}
} // namespace std
namespace operation {
std::ostream& operator<<(std::ostream& os, const thread_id& tid) {
return os << format("thread_id{{{}}}", tid.id);
}
} // namespace operation
// An immutable sequence of integers.
class append_seq {
public:
using elem_t = int32_t;
private:
// This represents the sequence of integers from _seq->begin() to _seq->begin() + _end.
// The underlying vector *_seq may however be shared by other instances of `append_seq`.
// If only one instance is appending, the operation is O(1). However, each subsequent
// append performed by another instance sharing this vector must perform a copy.
lw_shared_ptr<std::vector<elem_t>> _seq; // always engaged
size_t _end; // <= _seq.size()
elem_t _digest; // sum of all elements modulo `magic`
static const elem_t magic = 54313;
public:
append_seq(std::vector<elem_t> v) : _seq{make_lw_shared<std::vector<elem_t>>(std::move(v))}, _end{_seq->size()}, _digest{0} {
for (auto x : *_seq) {
_digest = digest_append(_digest, x);
}
}
static elem_t digest_append(elem_t d, elem_t x) {
assert(0 <= d < magic);
auto y = (d + x) % magic;
assert(digest_remove(y, x) == d);
return y;
}
static elem_t digest_remove(elem_t d, elem_t x) {
assert(0 <= d < magic);
auto y = (d - x) % magic;
return y < 0 ? y + magic : y;
}
elem_t digest() const {
return _digest;
}
append_seq append(elem_t x) const {
assert(_seq);
assert(_end <= _seq->size());
auto seq = _seq;
if (_end < seq->size()) {
// The shared sequence was already appended beyond _end by someone else.
// We need to copy everything so we don't break the other guy.
seq = make_lw_shared<std::vector<elem_t>>(seq->begin(), seq->begin() + _end);
}
seq->push_back(x);
return {std::move(seq), _end + 1, digest_append(_digest, x)};
}
elem_t operator[](size_t idx) const {
assert(_seq);
assert(idx < _end);
assert(_end <= _seq->size());
return (*_seq)[idx];
}
bool empty() const {
return _end == 0;
}
std::pair<append_seq, elem_t> pop() {
assert(_seq);
assert(_end <= _seq->size());
assert(0 < _end);
return {{_seq, _end - 1, digest_remove(_digest, (*_seq)[_end - 1])}, (*_seq)[_end - 1]};
}
friend std::ostream& operator<<(std::ostream& os, const append_seq& s) {
// TODO: don't copy the elements
std::vector<elem_t> v{s._seq->begin(), s._seq->begin() + s._end};
return os << format("v {} _end {}", v, s._end);
}
private:
append_seq(lw_shared_ptr<std::vector<elem_t>> seq, size_t end, elem_t d)
: _seq(std::move(seq)), _end(end), _digest(d) {}
};
struct AppendReg {
struct append { int32_t x; };
struct ret { int32_t x; append_seq prev; };
using state_t = append_seq;
using input_t = append;
using output_t = ret;
static std::pair<state_t, output_t> delta(const state_t& curr, input_t input) {
return {curr.append(input.x), {input.x, curr}};
}
static thread_local const state_t init;
};
thread_local const AppendReg::state_t AppendReg::init{{0}};
namespace ser {
template <>
struct serializer<AppendReg::append> {
template <typename Output>
static void write(Output& buf, const AppendReg::append& op) { serializer<int32_t>::write(buf, op.x); };
template <typename Input>
static AppendReg::append read(Input& buf) { return { serializer<int32_t>::read(buf) }; }
template <typename Input>
static void skip(Input& buf) { serializer<int32_t>::skip(buf); }
};
}
// TODO: do some useful logging in case of consistency violation
struct append_reg_model {
using elem_t = typename append_seq::elem_t;
struct entry {
elem_t elem;
elem_t digest;
};
std::vector<entry> seq{{0, 0}};
std::unordered_map<elem_t, size_t> index{{0, 0}};
std::unordered_set<elem_t> banned;
std::unordered_set<elem_t> returned;
std::unordered_set<elem_t> in_progress;
void invocation(elem_t x) {
assert(!index.contains(x));
assert(!in_progress.contains(x));
in_progress.insert(x);
}
void return_success(elem_t x, append_seq prev) {
assert(!returned.contains(x));
assert(x != 0);
assert(!prev.empty());
completion(x, std::move(prev));
returned.insert(x);
}
void return_failure(elem_t x) {
assert(!index.contains(x));
assert(in_progress.contains(x));
banned.insert(x);
in_progress.erase(x);
}
private:
void completion(elem_t x, append_seq prev) {
if (prev.empty()) {
assert(x == 0);
return;
}
assert(x != 0);
assert(!banned.contains(x));
assert(in_progress.contains(x) || index.contains(x));
auto [prev_prev, prev_x] = prev.pop();
if (auto it = index.find(x); it != index.end()) {
// This element was already completed.
auto idx = it->second;
assert(0 < idx);
assert(idx < seq.size());
assert(prev_x == seq[idx - 1].elem);
assert(prev.digest() == seq[idx - 1].digest);
return;
}
// A new completion.
// First, recursively complete the previous elements...
completion(prev_x, std::move(prev_prev));
// Check that the existing tail matches our tail.
assert(!seq.empty());
assert(prev_x == seq.back().elem);
assert(prev.digest() == seq.back().digest);
// All previous elements were completed, so the new element belongs at the end.
index.emplace(x, seq.size());
seq.push_back(entry{x, append_seq::digest_append(seq.back().digest, x)});
in_progress.erase(x);
}
};
std::ostream& operator<<(std::ostream& os, const AppendReg::append& a) {
return os << format("append{{{}}}", a.x);
}
std::ostream& operator<<(std::ostream& os, const AppendReg::ret& r) {
return os << format("ret{{{}, {}}}", r.x, r.prev);
}
SEASTAR_TEST_CASE(basic_generator_test) {
using op_type = operation::invocable<operation::either_of<
raft_call<AppendReg>,
network_majority_grudge<AppendReg>
>>;
using history_t = utils::chunked_vector<std::variant<op_type, operation::completion<op_type>>>;
static_assert(operation::Invocable<op_type>);
logical_timer timer;
environment_config cfg {
.network_delay = 3_t,
.fd_convict_threshold = 50_t,
};
co_await with_env_and_ticker<AppendReg>(cfg, [&cfg, &timer] (environment<AppendReg>& env, ticker& t) -> future<> {
t.start({
{1, [&] {
env.tick_network();
timer.tick();
}},
{10, [&] {
env.tick_servers();
}}
}, 200'000);
auto leader_id = co_await env.new_server(true);
// Wait for the server to elect itself as a leader.
assert(co_await wait_for_leader<AppendReg>{}(env, {leader_id}, timer, timer.now() + 1000_t) == leader_id);
size_t no_servers = 5;
std::unordered_set<raft::server_id> servers{leader_id};
for (size_t i = 1; i < no_servers; ++i) {
servers.insert(co_await env.new_server(false));
}
assert(std::holds_alternative<std::monostate>(
co_await env.get_server(leader_id).reconfigure(
std::vector<raft::server_id>{servers.begin(), servers.end()}, timer.now() + 100_t, timer)));
auto threads = operation::make_thread_set(servers.size() + 1);
auto nemesis_thread = some(threads);
auto seed = tests::random::get_int<int32_t>();
// TODO: make it dynamic based on the current configuration
std::unordered_set<raft::server_id>& known = servers;
raft_call<AppendReg>::state_type db_call_state {
.env = env,
.known = known,
.timer = timer
};
network_majority_grudge<AppendReg>::state_type network_majority_grudge_state {
.env = env,
.known = known,
.timer = timer,
.rnd = std::mt19937{seed}
};
auto init_state = op_type::state_type{std::move(db_call_state), std::move(network_majority_grudge_state)};
using namespace generator;
// For reference to ``real life'' suppose 1_t ~= 10ms. Then:
// 10_t (server tick) ~= 100ms
// network delay = 3_t ~= 30ms
// election timeout = 10 server ticks = 100_t ~= 1s
// thus, to enforce leader election, need a majority to convict the current leader for > 100_t ~= 1s,
// failure detector convict threshold = 50 srv ticks = 500_t ~= 5s
// so need to partition for > 600_t ~= 6s
// choose network partition duration uniformly from [600_t-600_t/3, 600_t+600_t/3] = [400_t, 800_t]
// ~= [4s, 8s] -> ~1/2 partitions should cause an election
// we will set request timeout 600_t ~= 6s and partition every 1200_t ~= 12s
auto gen = op_limit(500,
pin(nemesis_thread,
stagger(seed, timer.now() + 200_t, 1200_t, 1200_t,
random(seed, [] (std::mt19937& engine) {
static std::uniform_int_distribution<raft::logical_clock::rep> dist{400, 800};
return op_type{network_majority_grudge<AppendReg>{raft::logical_clock::duration{dist(engine)}}};
})
),
stagger(seed, timer.now(), 0_t, 50_t,
sequence(1, [] (int32_t i) {
assert(i > 0);
return op_type{raft_call<AppendReg>{AppendReg::append{i}, 200_t}};
})
)
)
);
class consistency_checker {
append_reg_model _model;
public:
consistency_checker() : _model{} {}
void operator()(op_type o) {
tlogger.debug("invocation {}", o);
if (auto call_op = std::get_if<raft_call<AppendReg>>(&o.op)) {
_model.invocation(call_op->input.x);
}
}
void operator()(operation::completion<op_type> c) {
auto res = std::get_if<op_type::result_type>(&c.result);
assert(res);
if (auto call_res = std::get_if<raft_call<AppendReg>::result_type>(res)) {
std::visit(make_visitor(
[this] (AppendReg::output_t& out) {
tlogger.debug("completion x: {} prev digest: {}", out.x, out.prev.digest());
_model.return_success(out.x, std::move(out.prev));
},
[] (raft::not_a_leader& e) {
// TODO: this is a definite failure, mark it
// _model.return_failure(...)
},
[] (raft::commit_status_unknown& e) {
// TODO assert: only allowed if reconfigurations happen?
// assert(false); TODO debug this
},
[] (auto&) { }
), *call_res);
} else {
tlogger.debug("completion {}", c);
}
}
};
history_t history;
interpreter<op_type, decltype(gen), consistency_checker> interp{
std::move(gen), std::move(threads), 1_t, std::move(init_state), timer,
consistency_checker{}};
co_await interp.run();
tlogger.debug("Finished generator run, time: {}", timer.now());
// Liveness check: we must be able to obtain a final response after all the nemeses have stopped.
// Due to possible multiple leaders at this point and the cluster stabilizing (for example there
// may be no leader right now, the current leader may be stepping down etc.) we may need to try
// sending requests multiple times to different servers to obtain the last result.
auto limit = timer.now() + 10000_t;
size_t cnt = 0;
for (; timer.now() < limit; ++cnt) {
tlogger.debug("Trying to obtain last result: attempt number {}", cnt + 1);
auto now = timer.now();
auto leader = co_await wait_for_leader<AppendReg>{}(env,
std::vector<raft::server_id>{servers.begin(), servers.end()}, timer, limit)
.handle_exception_type([&timer, now] (logical_timer::timed_out<raft::server_id>) -> raft::server_id {
tlogger.error("Failed to find a leader after {} ticks at the end of test.", timer.now() - now);
assert(false);
});
if (env.get_server(leader).is_leader()) {
tlogger.debug("Leader {} found after {} ticks", leader, timer.now() - now);
} else {
tlogger.warn("Leader {} found after {} ticks, but suddenly lost leadership", leader, timer.now() - now);
continue;
}
for (auto& s: servers) {
auto& srv = env.get_server(s);
if (srv.is_leader() && s != leader) {
tlogger.debug("There is another leader: {}", s);
}
}
auto [res, last_attempted_server] = co_await bouncing{[&timer, &env] (raft::server_id id) {
return env.get_server(id).call(AppendReg::append{-1}, timer.now() + 200_t, timer);
}}(timer, known, leader, known.size() + 1, 10_t, 10_t);
if (std::holds_alternative<typename AppendReg::ret>(res)) {
tlogger.debug("Last result: {}", res);
co_return;
}
tlogger.warn("Failed to obtain last result at end of test: {} returned by {}", res, last_attempted_server);
}
tlogger.error("Failed to obtain a final successful response at the end of the test. Number of attempts: {}", cnt);
assert(false);
});
}
test: raft: randomized_nemesis_test: improve the bouncing algorithm
The bouncing algorithm tries to send a request to other servers in the
configuration after it receives a `not_a_leader` response.
Improve the algorithm so it doesn't try the same server twice.
/*
* Copyright (C) 2021-present ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <seastar/core/reactor.hh>
#include <seastar/testing/test_case.hh>
#include <seastar/core/timed_out_error.hh>
#include <seastar/core/coroutine.hh>
#include <seastar/coroutine/maybe_yield.hh>
#include <seastar/core/gate.hh>
#include <seastar/core/queue.hh>
#include <seastar/core/future-util.hh>
#include <seastar/core/weak_ptr.hh>
#include <seastar/util/defer.hh>
#include "raft/server.hh"
#include "raft/logical_clock.hh"
#include "serializer.hh"
#include "serializer_impl.hh"
#include "idl/uuid.dist.hh"
#include "idl/uuid.dist.impl.hh"
#include "test/lib/random_utils.hh"
#include "test/raft/logical_timer.hh"
#include "test/raft/ticker.hh"
#include "test/raft/generator.hh"
#include "to_string.hh"
using namespace seastar;
using namespace std::chrono_literals;
seastar::logger tlogger("randomized_nemesis_test");
// A direct translaction of a mathematical definition of a state machine
// (see e.g. Wikipedia) as a C++ concept. Implementations of this concept
// do not store the state, they only define the types, the transition function
// (which is a pure function), and the initial state (which is a constant).
template <typename M> concept PureStateMachine =
requires (typename M::state_t s, typename M::input_t i) {
// The type of all possible states.
typename M::state_t;
// The type of all possible inputs (commands).
typename M::input_t;
// The type of all possible outputs.
typename M::output_t;
// The transition function (a pure function - no side effects). It takes a state
// and an input, and returns the next state and the output produced
// by applying the input to the given state.
{ M::delta(s, i) } -> std::same_as<std::pair<typename M::state_t, typename M::output_t>>;
// The initial state, of type `state_t`.
M::init;
requires std::is_same_v<const typename M::state_t, decltype(M::init)>;
};
// Used to uniquely identify commands passed into `apply` in order to return
// the outputs of these commands. See `impure_state_machine` and `call`.
using cmd_id_t = utils::UUID;
// A set of in-memory snapshots maintained by a single Raft server.
// The different parts of the server (the state machine, persistence,
// rpc) will share a single `snapshots_t`.
template <typename State>
using snapshots_t = std::unordered_map<raft::snapshot_id, State>;
// To replicate a state machine, our Raft implementation requires it to
// be represented with the `raft::state_machine` interface.
//
// `impure_state_machine` is an implementation of `raft::state_machine`
// that wraps a `PureStateMachine`. It keeps a variable of type `state_t`
// representing the current state. In `apply` it deserializes the given
// command into `input_t`, uses the transition (`delta`) function to
// produce the next state and output, replaces its current state with the
// obtained state and returns the output (more on that below); it does so
// sequentially for every given command. We can think of `PureStateMachine`
// as the actual state machine - the business logic, and `impure_state_machine`
// as the ``boilerplate'' that allows the pure machine to be replicated
// by Raft and communicate with the external world.
//
// The interface also requires maintainance of snapshots. We use the
// `snapshots_t` introduced above; `impure_state_machine` keeps a reference to `snapshots_t`
// because it will share it with an implementation of `raft::persistence`.
template <PureStateMachine M>
class impure_state_machine : public raft::state_machine {
typename M::state_t _val;
snapshots_t<typename M::state_t>& _snapshots;
// Used to ensure that when `abort()` returns there are
// no more in-progress methods running on this object.
seastar::gate _gate;
// To obtain output from an applied command, the client (see `call`)
// first allocates a channel in this data structure by calling `with_output_channel`
// and makes the returned command ID a part of the command passed to Raft.
// When (if) we eventually apply the command, we use the ID to find the output channel
// here and push the output to the client waiting on the other end.
// The channel is allocated only on the local server where `with_output_channel`
// was called; other replicas of the state machine will therefore not find the ID
// in their instances of `_output_channels` so they just drop the output.
std::unordered_map<cmd_id_t, promise<typename M::output_t>> _output_channels;
public:
impure_state_machine(snapshots_t<typename M::state_t>& snapshots)
: _val(M::init), _snapshots(snapshots) {}
future<> apply(std::vector<raft::command_cref> cmds) override {
co_await with_gate(_gate, [this, cmds = std::move(cmds)] () mutable -> future<> {
for (auto& cref : cmds) {
_gate.check();
auto is = ser::as_input_stream(cref);
auto cmd_id = ser::deserialize(is, boost::type<cmd_id_t>{});
auto input = ser::deserialize(is, boost::type<typename M::input_t>{});
auto [new_state, output] = M::delta(std::move(_val), std::move(input));
_val = std::move(new_state);
auto it = _output_channels.find(cmd_id);
if (it != _output_channels.end()) {
// We are on the leader server where the client submitted the command
// and waits for the output. Send it to them.
it->second.set_value(std::move(output));
_output_channels.erase(it);
} else {
// This is not the leader on which the command was submitted,
// or it is but the client already gave up on us and deallocated the channel.
// In any case we simply drop the output.
}
co_await coroutine::maybe_yield();
}
});
}
future<raft::snapshot_id> take_snapshot() override {
auto id = raft::snapshot_id::create_random_id();
assert(_snapshots.emplace(id, _val).second);
co_return id;
}
void drop_snapshot(raft::snapshot_id id) override {
_snapshots.erase(id);
}
future<> load_snapshot(raft::snapshot_id id) override {
auto it = _snapshots.find(id);
assert(it != _snapshots.end()); // dunno if the snapshot can actually be missing
_val = it->second;
co_return;
}
future<> abort() override {
return _gate.close();
}
struct output_channel_dropped : public raft::error {
output_channel_dropped() : error("output channel dropped") {}
};
// Before sending a command to Raft, the client must obtain a command ID
// and an output channel using this function.
template <typename F>
future<typename M::output_t> with_output_channel(F f) {
return with_gate(_gate, [this, f = std::move(f)] () mutable -> future<typename M::output_t> {
promise<typename M::output_t> p;
auto fut = p.get_future();
auto cmd_id = utils::make_random_uuid();
assert(_output_channels.emplace(cmd_id, std::move(p)).second);
auto guard = defer([this, cmd_id] {
auto it = _output_channels.find(cmd_id);
if (it != _output_channels.end()) {
it->second.set_exception(output_channel_dropped{});
_output_channels.erase(it);
}
});
return f(cmd_id, std::move(fut)).finally([guard = std::move(guard)] {});
});
}
};
// TODO: serializable concept?
template <typename Input>
raft::command make_command(const cmd_id_t& cmd_id, const Input& input) {
raft::command cmd;
ser::serialize(cmd, cmd_id);
ser::serialize(cmd, input);
return cmd;
}
// TODO: handle other errors?
template <PureStateMachine M>
using call_result_t = std::variant<typename M::output_t, timed_out_error, raft::not_a_leader, raft::dropped_entry, raft::commit_status_unknown>;
// Sends a given `input` as a command to `server`, waits until the command gets replicated
// and applied on that server and returns the produced output.
//
// The wait time is limited using `timeout` which is a logical time point referring to the
// logical clock used by `timer`. Standard way to use is to pass `timer.now() + X_t`
// as the time point, where `X` is the maximum number of ticks that we wait for.
//
// `sm` must be a reference to the state machine owned by `server`.
//
// The `server` may currently be a follower, in which case it will return a `not_a_leader` error.
template <PureStateMachine M>
future<call_result_t<M>> call(
typename M::input_t input,
raft::logical_clock::time_point timeout,
logical_timer& timer,
raft::server& server,
impure_state_machine<M>& sm) {
using output_channel_dropped = typename impure_state_machine<M>::output_channel_dropped;
return sm.with_output_channel([&, input = std::move(input), timeout] (cmd_id_t cmd_id, future<typename M::output_t> f) {
return timer.with_timeout(timeout, [&] (typename M::input_t input, future<typename M::output_t> f) {
return server.add_entry(
make_command(std::move(cmd_id), std::move(input)),
raft::wait_type::applied
).then_wrapped([output_f = std::move(f)] (future<> add_entry_f) mutable {
if (add_entry_f.failed()) {
// We need to discard `output_f`; the only expected exception is:
(void)output_f.discard_result().handle_exception_type([] (const output_channel_dropped&) {});
std::rethrow_exception(add_entry_f.get_exception());
}
return std::move(output_f);
});
}(std::move(input), std::move(f)));
}).then([] (typename M::output_t output) {
return make_ready_future<call_result_t<M>>(std::move(output));
}).handle_exception([] (std::exception_ptr eptr) {
try {
std::rethrow_exception(eptr);
} catch (raft::not_a_leader e) {
return make_ready_future<call_result_t<M>>(e);
} catch (raft::dropped_entry e) {
return make_ready_future<call_result_t<M>>(e);
} catch (raft::commit_status_unknown e) {
return make_ready_future<call_result_t<M>>(e);
} catch (logical_timer::timed_out<typename M::output_t> e) {
(void)e.get_future().discard_result()
.handle_exception([] (std::exception_ptr eptr) {
try {
std::rethrow_exception(eptr);
} catch (const output_channel_dropped&) {
} catch (const raft::dropped_entry&) {
} catch (const raft::commit_status_unknown&) {
} catch (const raft::not_a_leader&) {
} catch (const raft::stopped_error&) {
}
});
return make_ready_future<call_result_t<M>>(timed_out_error{});
}
});
}
// Allows a Raft server to communicate with other servers.
// The implementation is mostly boilerplate. It assumes that there exists a method of message passing
// given by a `send_message_t` function (passed in the constructor) for sending and by the `receive`
// function for receiving messages.
//
// We also keep a reference to a `snapshots_t` set to be shared with the `impure_state_machine`
// on the same server. We access this set when we receive or send a snapshot message.
template <typename State>
class rpc : public raft::rpc {
using reply_id_t = uint32_t;
struct snapshot_message {
raft::install_snapshot ins;
State snapshot_payload;
reply_id_t reply_id;
};
struct snapshot_reply_message {
raft::snapshot_reply reply;
reply_id_t reply_id;
};
struct execute_barrier_on_leader {
reply_id_t reply_id;
};
struct execute_barrier_on_leader_reply {
raft::read_barrier_reply reply;
reply_id_t reply_id;
};
public:
using message_t = std::variant<
snapshot_message,
snapshot_reply_message,
raft::append_request,
raft::append_reply,
raft::vote_request,
raft::vote_reply,
raft::timeout_now,
raft::read_quorum,
raft::read_quorum_reply,
execute_barrier_on_leader,
execute_barrier_on_leader_reply>;
using send_message_t = std::function<void(raft::server_id dst, message_t)>;
private:
snapshots_t<State>& _snapshots;
logical_timer _timer;
send_message_t _send;
// Before we send a snapshot apply request we create a promise-future pair,
// allocate a new ID, and put the promise here under that ID. We then send the ID
// together with the request and wait on the future.
// When (if) a reply returns, we take the ID from the reply (which is the same
// as the ID in the corresponding request), take the promise under that ID
// and push the reply through that promise.
std::unordered_map<reply_id_t, std::variant<promise<raft::snapshot_reply>, promise<raft::read_barrier_reply>>> _reply_promises;
reply_id_t _counter = 0;
// Used to ensure that when `abort()` returns there are
// no more in-progress methods running on this object.
seastar::gate _gate;
public:
rpc(snapshots_t<State>& snaps, send_message_t send)
: _snapshots(snaps), _send(std::move(send)) {
}
// Message is delivered to us
future<> receive(raft::server_id src, message_t payload) {
assert(_client);
auto& c = *_client;
co_await std::visit(make_visitor(
[&] (snapshot_message m) -> future<> {
_snapshots.emplace(m.ins.snp.id, std::move(m.snapshot_payload));
co_await with_gate(_gate, [&] () -> future<> {
auto reply = co_await c.apply_snapshot(src, std::move(m.ins));
_send(src, snapshot_reply_message{
.reply = std::move(reply),
.reply_id = m.reply_id
});
});
},
[this] (snapshot_reply_message m) -> future<> {
auto it = _reply_promises.find(m.reply_id);
if (it != _reply_promises.end()) {
std::get<promise<raft::snapshot_reply>>(it->second).set_value(std::move(m.reply));
}
co_return;
},
[&] (raft::append_request m) -> future<> {
c.append_entries(src, std::move(m));
co_return;
},
[&] (raft::append_reply m) -> future<> {
c.append_entries_reply(src, std::move(m));
co_return;
},
[&] (raft::vote_request m) -> future<> {
c.request_vote(src, std::move(m));
co_return;
},
[&] (raft::vote_reply m) -> future<> {
c.request_vote_reply(src, std::move(m));
co_return;
},
[&] (raft::timeout_now m) -> future<> {
c.timeout_now_request(src, std::move(m));
co_return;
},
[&] (raft::read_quorum m) -> future<> {
c.read_quorum_request(src, std::move(m));
co_return;
},
[&] (raft::read_quorum_reply m) -> future<> {
c.read_quorum_reply(src, std::move(m));
co_return;
},
[&] (execute_barrier_on_leader m) -> future<> {
co_await with_gate(_gate, [&] () -> future<> {
auto reply = co_await c.execute_read_barrier(src);
_send(src, execute_barrier_on_leader_reply{
.reply = std::move(reply),
.reply_id = m.reply_id
});
});
},
[this] (execute_barrier_on_leader_reply m) -> future<> {
auto it = _reply_promises.find(m.reply_id);
if (it != _reply_promises.end()) {
std::get<promise<raft::read_barrier_reply>>(it->second).set_value(std::move(m.reply));
}
co_return;
}
), std::move(payload));
}
// This is the only function of `raft::rpc` which actually expects a response.
virtual future<raft::snapshot_reply> send_snapshot(raft::server_id dst, const raft::install_snapshot& ins, seastar::abort_source&) override {
auto it = _snapshots.find(ins.snp.id);
assert(it != _snapshots.end());
auto id = _counter++;
promise<raft::snapshot_reply> p;
auto f = p.get_future();
_reply_promises.emplace(id, std::move(p));
auto guard = defer([this, id] { _reply_promises.erase(id); });
_send(dst, snapshot_message{
.ins = ins,
.snapshot_payload = it->second,
.reply_id = id
});
// The message receival function on the other side, when it receives the snapshot message,
// will apply the snapshot and send `id` back to us in the snapshot reply message (see `receive`,
// `snapshot_message` case). When we receive the reply, we shall find `id` in `_reply_promises`
// and push the reply through the promise, which will resolve `f` (see `receive`, `snapshot_reply_message`
// case).
co_return co_await with_gate(_gate,
[&, guard = std::move(guard), f = std::move(f)] () mutable -> future<raft::snapshot_reply> {
// TODO configurable
static const raft::logical_clock::duration send_snapshot_timeout = 20_t;
// TODO: catch aborts from the abort_source as well
try {
co_return co_await _timer.with_timeout(_timer.now() + send_snapshot_timeout, std::move(f));
} catch (logical_timer::timed_out<raft::snapshot_reply>& e) {
// The future will probably get a broken_promise exception after we destroy the guard.
(void)e.get_future().discard_result().handle_exception_type([] (const broken_promise&) {});
throw timed_out_error{};
}
// co_await ensures that `guard` is destroyed before we leave `_gate`
});
}
virtual future<raft::read_barrier_reply> execute_read_barrier_on_leader(raft::server_id dst) override {
auto id = _counter++;
promise<raft::read_barrier_reply> p;
auto f = p.get_future();
_reply_promises.emplace(id, std::move(p));
auto guard = defer([this, id] { _reply_promises.erase(id); });
_send(dst, execute_barrier_on_leader {
.reply_id = id
});
co_return co_await with_gate(_gate,
[&, guard = std::move(guard), f = std::move(f)] () mutable -> future<raft::read_barrier_reply> {
// TODO configurable
static const raft::logical_clock::duration execute_read_barrier_on_leader_timeout = 20_t;
// TODO: catch aborts from the abort_source as well
co_return co_await _timer.with_timeout(_timer.now() + execute_read_barrier_on_leader_timeout, std::move(f));
// co_await ensures that `guard` is destroyed before we leave `_gate`
});
}
virtual future<> send_append_entries(raft::server_id dst, const raft::append_request& m) override {
_send(dst, m);
co_return;
}
virtual void send_append_entries_reply(raft::server_id dst, const raft::append_reply& m) override {
_send(dst, m);
}
virtual void send_vote_request(raft::server_id dst, const raft::vote_request& m) override {
_send(dst, m);
}
virtual void send_vote_reply(raft::server_id dst, const raft::vote_reply& m) override {
_send(dst, m);
}
virtual void send_timeout_now(raft::server_id dst, const raft::timeout_now& m) override {
_send(dst, m);
}
virtual void send_read_quorum(raft::server_id dst, const raft::read_quorum& m) override {
_send(dst, m);
}
virtual void send_read_quorum_reply(raft::server_id dst, const raft::read_quorum_reply& m) override {
_send(dst, m);
}
virtual void add_server(raft::server_id, raft::server_info) override {
}
virtual void remove_server(raft::server_id) override {
}
virtual future<> abort() override {
return _gate.close();
}
void tick() {
_timer.tick();
}
};
template <typename State>
class persistence : public raft::persistence {
snapshots_t<State>& _snapshots;
std::pair<raft::snapshot_descriptor, State> _stored_snapshot;
std::pair<raft::term_t, raft::server_id> _stored_term_and_vote;
// Invariants:
// 1. for each entry except the first, the raft index is equal to the raft index of the previous entry plus one.
// 2. the index of the first entry is <= _stored_snapshot.first.idx + 1.
// 3. the index of the last entry is >= _stored_snapshot.first.idx.
// Informally, the last two invariants say that the stored log intersects or ``touches'' the snapshot ``on the right side''.
raft::log_entries _stored_entries;
// Returns an iterator to the entry in `_stored_entries` whose raft index is `idx` if the entry exists.
// If all entries in `_stored_entries` have greater indexes, returns the first one.
// If all entries have smaller indexes, returns end().
raft::log_entries::iterator find(raft::index_t idx) {
// The correctness of this depends on the `_stored_entries` invariant.
auto b = _stored_entries.begin();
if (b == _stored_entries.end() || (*b)->idx >= idx) {
return b;
}
return b + std::min((idx - (*b)->idx).get_value(), _stored_entries.size());
}
public:
// If this is the first server of a cluster, it must be initialized with a singleton configuration
// containing opnly this server's ID which must be also provided here as `init_config_id`.
// Otherwise it must be initialized with an empty configuration (it will be added to the cluster
// through a configuration change) and `init_config_id` must be `nullopt`.
persistence(snapshots_t<State>& snaps, std::optional<raft::server_id> init_config_id, State init_state)
: _snapshots(snaps)
, _stored_snapshot(
raft::snapshot_descriptor{
.config = init_config_id ? raft::configuration{*init_config_id} : raft::configuration{}
},
std::move(init_state))
, _stored_term_and_vote(raft::term_t{1}, raft::server_id{})
{}
virtual future<> store_term_and_vote(raft::term_t term, raft::server_id vote) override {
_stored_term_and_vote = std::pair{term, vote};
co_return;
}
virtual future<std::pair<raft::term_t, raft::server_id>> load_term_and_vote() override {
co_return _stored_term_and_vote;
}
virtual future<> store_snapshot_descriptor(const raft::snapshot_descriptor& snap, size_t preserve_log_entries) override {
// The snapshot's index cannot be smaller than the index of the first stored entry minus one;
// that would create a ``gap'' in the log.
assert(_stored_entries.empty() || snap.idx + 1 >= _stored_entries.front()->idx);
auto it = _snapshots.find(snap.id);
assert(it != _snapshots.end());
_stored_snapshot = {snap, it->second};
if (!_stored_entries.empty() && snap.idx > _stored_entries.back()->idx) {
// Clear the log in order to not create a gap.
_stored_entries.clear();
co_return;
}
auto first_to_remain = snap.idx + 1 >= preserve_log_entries ? raft::index_t{snap.idx + 1 - preserve_log_entries} : raft::index_t{0};
_stored_entries.erase(_stored_entries.begin(), find(first_to_remain));
co_return;
}
virtual future<raft::snapshot_descriptor> load_snapshot_descriptor() override {
auto [snap, state] = _stored_snapshot;
_snapshots.insert_or_assign(snap.id, std::move(state));
co_return snap;
}
virtual future<> store_log_entries(const std::vector<raft::log_entry_ptr>& entries) override {
if (entries.empty()) {
co_return;
}
// The raft server is supposed to provide entries in strictly increasing order,
// hence the following assertions.
if (_stored_entries.empty()) {
assert(entries.front()->idx == _stored_snapshot.first.idx + 1);
} else {
assert(entries.front()->idx == _stored_entries.back()->idx + 1);
}
_stored_entries.push_back(entries[0]);
for (size_t i = 1; i < entries.size(); ++i) {
assert(entries[i]->idx == entries[i-1]->idx + 1);
_stored_entries.push_back(entries[i]);
}
co_return;
}
virtual future<raft::log_entries> load_log() override {
co_return _stored_entries;
}
virtual future<> truncate_log(raft::index_t idx) override {
_stored_entries.erase(find(idx), _stored_entries.end());
co_return;
}
virtual future<> abort() override {
// There are no yields anywhere in our methods so no need to wait for anything.
// We assume that our methods won't be called after `abort()`.
// TODO: is this assumption correct?
co_return;
}
};
// A failure detector using heartbeats for deciding whether to convict a server
// as failed. We convict a server if we don't receive a heartbeat for a long enough time.
// `failure_detector` assumes a message-passing method given by a `send_heartbeat_t` function
// through the constructor for sending heartbeats and assumes that `receive_heartbeat` is called
// whenever another server sends a message to us.
// To decide who to send heartbeats to we use the ``current knowledge'' of servers in the network
// which is updated through `add_server` and `remove_server` functions.
class failure_detector : public raft::failure_detector {
public:
using send_heartbeat_t = std::function<void(raft::server_id dst)>;
private:
raft::logical_clock _clock;
// The set of known servers, used to broadcast heartbeats.
std::unordered_set<raft::server_id> _known;
// The last time we received a heartbeat from a server.
std::unordered_map<raft::server_id, raft::logical_clock::time_point> _last_heard;
// The last time we sent a heartbeat.
raft::logical_clock::time_point _last_beat;
// How long from the last received heartbeat does it take to convict a node as dead.
const raft::logical_clock::duration _convict_threshold;
send_heartbeat_t _send_heartbeat;
public:
failure_detector(raft::logical_clock::duration convict_threshold, send_heartbeat_t f)
: _convict_threshold(convict_threshold), _send_heartbeat(std::move(f))
{
send_heartbeats();
assert(_last_beat == _clock.now());
}
void receive_heartbeat(raft::server_id src) {
assert(_known.contains(src));
_last_heard[src] = std::max(_clock.now(), _last_heard[src]);
}
void tick() {
_clock.advance();
// TODO: make it adjustable
static const raft::logical_clock::duration _heartbeat_period = 10_t;
if (_last_beat + _heartbeat_period <= _clock.now()) {
send_heartbeats();
}
}
void send_heartbeats() {
for (auto& dst : _known) {
_send_heartbeat(dst);
}
_last_beat = _clock.now();
}
// We expect a server to be added through this function before we receive a heartbeat from it.
void add_server(raft::server_id id) {
_known.insert(id);
}
void remove_server(raft::server_id id) {
_known.erase(id);
_last_heard.erase(id);
}
bool is_alive(raft::server_id id) override {
return _clock.now() < _last_heard[id] + _convict_threshold;
}
};
// `network` is a simple priority queue of `event`s, where an `event` is a message associated
// with its planned delivery time. The queue uses a logical clock to decide when to deliver messages.
// It delives all messages whose associated times are smaller than the ``current time'', the latter
// determined by the number of `tick()` calls.
//
// Note: the actual delivery happens through a function that is passed in the `network` constructor.
// The function may return `false` (for whatever reason) denoting that it failed to deliver the message.
// In this case network will backup this message and retry the delivery on every later `tick` until
// it succeeds.
template <typename Payload>
class network {
public:
// When the time comes to deliver a message we use this function.
using deliver_t = std::function<void(raft::server_id src, raft::server_id dst, const Payload&)>;
private:
struct message {
raft::server_id src;
raft::server_id dst;
// shared ptr to implement duplication of messages
lw_shared_ptr<Payload> payload;
};
struct event {
raft::logical_clock::time_point time;
message msg;
};
deliver_t _deliver;
// A min-heap of event occurences compared by their time points.
std::vector<event> _events;
// Comparator for the `_events` min-heap.
static bool cmp(const event& o1, const event& o2) {
return o1.time > o2.time;
}
// A pair (dst, [src1, src2, ...]) in this set denotes that `dst`
// does not receive messages from src1, src2, ...
std::unordered_map<raft::server_id, std::unordered_set<raft::server_id>> _grudges;
raft::logical_clock _clock;
// How long does it take to deliver a message?
// TODO: use a random distribution or let the user change this dynamically
raft::logical_clock::duration _delivery_delay;
public:
network(raft::logical_clock::duration delivery_delay, deliver_t f)
: _deliver(std::move(f)), _delivery_delay(delivery_delay) {}
void send(raft::server_id src, raft::server_id dst, Payload payload) {
// Predict the delivery time in advance.
// Our prediction may be wrong if a grudge exists at this expected moment of delivery.
// Messages may also be reordered.
auto delivery_time = _clock.now() + _delivery_delay;
_events.push_back(event{delivery_time, message{src, dst, make_lw_shared<Payload>(std::move(payload))}});
std::push_heap(_events.begin(), _events.end(), cmp);
}
void tick() {
_clock.advance();
deliver();
}
void add_grudge(raft::server_id src, raft::server_id dst) {
_grudges[dst].insert(src);
}
void remove_grudge(raft::server_id src, raft::server_id dst) {
_grudges[dst].erase(src);
}
private:
void deliver() {
// Deliver every message whose time has come.
while (!_events.empty() && _events.front().time <= _clock.now()) {
auto& [_, m] = _events.front();
if (!_grudges[m.dst].contains(m.src)) {
_deliver(m.src, m.dst, *m.payload);
} else {
// A grudge means that we drop the message.
}
std::pop_heap(_events.begin(), _events.end(), cmp);
_events.pop_back();
}
}
};
// A queue of messages that have arrived at a given Raft server and are waiting to be processed
// by that server (which may be a long computation, hence returning a `future<>`).
// Its purpose is to serve as a ``bridge'' between `network` and a server's `rpc` instance.
// The `network`'s delivery function will `push()` a message onto this queue and `receive_fiber()`
// will eventually forward the message to `rpc` by calling `rpc::receive()`.
// `push()` may fail if the queue is full, meaning that the queue expects the caller (`network`
// in our case) to retry later.
template <typename State>
class delivery_queue {
struct delivery {
raft::server_id src;
typename rpc<State>::message_t payload;
};
struct aborted_exception {};
seastar::queue<delivery> _queue;
rpc<State>& _rpc;
std::optional<future<>> _receive_fiber;
public:
delivery_queue(rpc<State>& rpc)
: _queue(std::numeric_limits<size_t>::max()), _rpc(rpc) {
}
~delivery_queue() {
assert(!_receive_fiber);
}
void push(raft::server_id src, const typename rpc<State>::message_t& p) {
assert(_receive_fiber);
bool pushed = _queue.push(delivery{src, p});
// The queue is practically unbounded...
assert(pushed);
// If the queue is growing then the test infrastructure must have some kind of a liveness problem
// (which may eventually cause OOM). Let's warn the user.
if (_queue.size() > 100) {
tlogger.warn("delivery_queue: large queue size ({})", _queue.size());
}
}
// Start the receiving fiber.
// Can be executed at most once. When restarting a ``crashed'' server, create a new queue.
void start() {
assert(!_receive_fiber);
_receive_fiber = receive_fiber();
}
// Stop the receiving fiber (if it's running). The returned future resolves
// when the fiber finishes. Must be called before destruction (unless the fiber was never started).
future<> abort() {
_queue.abort(std::make_exception_ptr(aborted_exception{}));
if (_receive_fiber) {
try {
co_await *std::exchange(_receive_fiber, std::nullopt);
} catch (const aborted_exception&) {}
}
}
private:
future<> receive_fiber() {
// TODO: configurable
static const size_t _max_receive_concurrency = 20;
std::vector<delivery> batch;
while (true) {
// TODO: there is most definitely a better way to do this, but let's assume this is good enough (for now...)
// Unfortunately seastar does not yet have a multi-consumer queue implementation.
batch.push_back(co_await _queue.pop_eventually());
while (!_queue.empty() && batch.size() < _max_receive_concurrency) {
batch.push_back(_queue.pop());
}
co_await parallel_for_each(batch, [&] (delivery& m) {
return _rpc.receive(m.src, std::move(m.payload));
});
batch.clear();
}
}
};
using reconfigure_result_t = std::variant<std::monostate,
timed_out_error, raft::not_a_leader, raft::dropped_entry, raft::commit_status_unknown, raft::conf_change_in_progress>;
future<reconfigure_result_t> reconfigure(
const std::vector<raft::server_id>& ids,
raft::logical_clock::time_point timeout,
logical_timer& timer,
raft::server& server) {
raft::server_address_set config;
for (auto id : ids) {
config.insert(raft::server_address { .id = id });
}
try {
co_await timer.with_timeout(timeout, [&server, config = std::move(config)] () {
return server.set_configuration(std::move(config));
}());
co_return std::monostate{};
} catch (raft::not_a_leader e) {
co_return e;
} catch (raft::dropped_entry e) {
co_return e;
} catch (raft::commit_status_unknown e) {
co_return e;
} catch (raft::conf_change_in_progress e) {
co_return e;
} catch (logical_timer::timed_out<void> e) {
(void)e.get_future().discard_result()
.handle_exception([] (std::exception_ptr eptr) {
try {
std::rethrow_exception(eptr);
} catch (const raft::dropped_entry&) {
} catch (const raft::commit_status_unknown&) {
} catch (const raft::not_a_leader&) {
} catch (const raft::stopped_error&) {
}
});
co_return timed_out_error{};
}
}
// Contains a `raft::server` and other facilities needed for it and the underlying
// modules (persistence, rpc, etc.) to run, and to communicate with the external environment.
template <PureStateMachine M>
class raft_server {
raft::server_id _id;
std::unique_ptr<snapshots_t<typename M::state_t>> _snapshots;
std::unique_ptr<delivery_queue<typename M::state_t>> _queue;
std::unique_ptr<raft::server> _server;
// The following objects are owned by _server:
impure_state_machine<M>& _sm;
rpc<typename M::state_t>& _rpc;
bool _started = false;
bool _stopped = false;
// Used to ensure that when `abort()` returns there are
// no more in-progress methods running on this object.
seastar::gate _gate;
public:
// Create a `raft::server` with the given `id` and all other facilities required
// by the server (the state machine, RPC instance and so on). The server will use
// `send_rpc` to send RPC messages to other servers and `fd` for failure detection.
//
// If this is the first server in the cluster, pass `first_server = true`; this will
// cause the server to be created with a non-empty singleton configuration containing itself.
// Otherwise, pass `first_server = false`; that server, in order to function, must be then added
// by the existing cluster through a configuration change.
//
// The created server is not started yet; use `start` for that.
static std::unique_ptr<raft_server> create(
raft::server_id id,
shared_ptr<failure_detector> fd,
raft::server::configuration cfg,
bool first_server,
typename rpc<typename M::state_t>::send_message_t send_rpc) {
using state_t = typename M::state_t;
auto snapshots = std::make_unique<snapshots_t<state_t>>();
auto sm = std::make_unique<impure_state_machine<M>>(*snapshots);
auto rpc_ = std::make_unique<rpc<state_t>>(*snapshots, std::move(send_rpc));
auto persistence_ = std::make_unique<persistence<state_t>>(*snapshots, first_server ? std::optional{id} : std::nullopt, M::init);
auto queue = std::make_unique<delivery_queue<state_t>>(*rpc_);
auto& sm_ref = *sm;
auto& rpc_ref = *rpc_;
auto server = raft::create_server(
id, std::move(rpc_), std::move(sm), std::move(persistence_), std::move(fd),
std::move(cfg));
return std::make_unique<raft_server>(initializer{
._id = id,
._snapshots = std::move(snapshots),
._queue = std::move(queue),
._server = std::move(server),
._sm = sm_ref,
._rpc = rpc_ref
});
}
~raft_server() {
assert(!_started || _stopped);
}
raft_server(const raft_server&&) = delete;
raft_server(raft_server&&) = delete;
// Start the server. Can be called at most once.
//
// TODO: implement server ``crashes'' and ``restarts''.
// A crashed server needs a new delivery queue to be created in order to restart but must
// reuse the previous `persistence`. Perhaps the delivery queue should be created in `start`?
future<> start() {
assert(!_started);
_started = true;
co_await _server->start();
_queue->start();
}
// Stop the given server. Must be called before the server is destroyed
// (unless it was never started in the first place).
future<> abort() {
auto f = _gate.close();
// Abort everything before waiting on the gate close future
// so currently running operations finish earlier.
if (_started) {
co_await _queue->abort();
co_await _server->abort();
}
co_await std::move(f);
_stopped = true;
}
void tick() {
assert(_started);
_rpc.tick();
_server->tick();
}
future<call_result_t<M>> call(
typename M::input_t input,
raft::logical_clock::time_point timeout,
logical_timer& timer) {
assert(_started);
return with_gate(_gate, [this, input = std::move(input), timeout, &timer] {
return ::call(std::move(input), timeout, timer, *_server, _sm);
});
}
future<reconfigure_result_t> reconfigure(
const std::vector<raft::server_id>& ids,
raft::logical_clock::time_point timeout,
logical_timer& timer) {
assert(_started);
return with_gate(_gate, [this, &ids, timeout, &timer] {
return ::reconfigure(ids, timeout, timer, *_server);
});
}
bool is_leader() const {
return _server->is_leader();
}
raft::server_id id() const {
return _id;
}
void deliver(raft::server_id src, const typename rpc<typename M::state_t>::message_t& m) {
assert(_started);
if (!_gate.is_closed()) {
_queue->push(src, m);
}
}
private:
struct initializer {
raft::server_id _id;
std::unique_ptr<snapshots_t<typename M::state_t>> _snapshots;
std::unique_ptr<delivery_queue<typename M::state_t>> _queue;
std::unique_ptr<raft::server> _server;
impure_state_machine<M>& _sm;
rpc<typename M::state_t>& _rpc;
};
raft_server(initializer i)
: _id(i._id)
, _snapshots(std::move(i._snapshots))
, _queue(std::move(i._queue))
, _server(std::move(i._server))
, _sm(i._sm)
, _rpc(i._rpc) {
}
friend std::unique_ptr<raft_server> std::make_unique<raft_server, raft_server::initializer>(initializer&&);
};
static raft::server_id to_raft_id(size_t id) {
// Raft uses UUID 0 as special case.
assert(id > 0);
return raft::server_id{utils::UUID{0, id}};
}
struct environment_config {
raft::logical_clock::duration network_delay;
raft::logical_clock::duration fd_convict_threshold;
};
// A set of `raft_server`s connected by a `network`.
//
// The `network` is initialized with a message delivery function
// which notifies the destination's failure detector on each message
// and if the message contains an RPC payload, pushes it into the destination's
// `delivery_queue`.
//
// Needs to be periodically `tick()`ed which ticks the network
// and underlying servers.
template <PureStateMachine M>
class environment : public seastar::weakly_referencable<environment<M>> {
using input_t = typename M::output_t;
using state_t = typename M::state_t;
using output_t = typename M::output_t;
struct route {
std::unique_ptr<raft_server<M>> _server;
shared_ptr<failure_detector> _fd;
};
// Passed to newly created failure detectors.
const raft::logical_clock::duration _fd_convict_threshold;
// Used to deliver messages coming from the network to appropriate servers and their failure detectors.
// Also keeps the servers and the failure detectors alive (owns them).
// Before we show a Raft server to others we must add it to this map.
std::unordered_map<raft::server_id, route> _routes;
// Used to create a new ID in `new_server`.
size_t _next_id = 1;
// Engaged optional: RPC message, nullopt: heartbeat
using message_t = std::optional<typename rpc<state_t>::message_t>;
network<message_t> _network;
bool _stopped = false;
// Used to ensure that when `abort()` returns there are
// no more in-progress methods running on this object.
seastar::gate _gate;
public:
environment(environment_config cfg)
: _fd_convict_threshold(cfg.fd_convict_threshold), _network(cfg.network_delay,
[this] (raft::server_id src, raft::server_id dst, const message_t& m) {
auto& [s, fd] = _routes.at(dst);
fd->receive_heartbeat(src);
if (m) {
s->deliver(src, *m);
}
}) {
}
~environment() {
assert(_routes.empty() || _stopped);
}
environment(const environment&) = delete;
environment(environment&&) = delete;
void tick_network() {
_network.tick();
}
// TODO: adjustable/randomizable ticking ratios
void tick_servers() {
for (auto& [_, r] : _routes) {
r._server->tick();
r._fd->tick();
}
}
// Creates and starts a server with a local (uniquely owned) failure detector,
// connects it to the network and returns its ID.
//
// If `first == true` the server is created with a singleton configuration containing itself.
// Otherwise it is created with an empty configuration. The user must explicitly ask for a configuration change
// if they want to make a cluster (group) out of this server and other existing servers.
// The user should be able to create multiple clusters by calling `new_server` multiple times with `first = true`.
// (`first` means ``first in group'').
future<raft::server_id> new_server(bool first, raft::server::configuration cfg = {}) {
return with_gate(_gate, [this, first, cfg = std::move(cfg)] () -> future<raft::server_id> {
auto id = to_raft_id(_next_id++);
// TODO: in the future we want to simulate multiple raft servers running on a single ``node'',
// sharing a single failure detector. We will then likely split `new_server` into two steps: `new_node` and `new_server`,
// the first creating the failure detector for a node and wiring it up, the second creating a server on a given node.
// We will also possibly need to introduce some kind of ``node IDs'' which `failure_detector` (and `network`)
// will operate on (currently they operate on `raft::server_id`s, assuming a 1-1 mapping of server-to-node).
auto fd = seastar::make_shared<failure_detector>(_fd_convict_threshold, [id, this] (raft::server_id dst) {
_network.send(id, dst, std::nullopt);
});
auto srv = raft_server<M>::create(id, fd, std::move(cfg), first,
[id, this] (raft::server_id dst, typename rpc<state_t>::message_t m) {
_network.send(id, dst, {std::move(m)});
});
co_await srv->start();
// Add us to other servers' failure detectors.
for (auto& [_, r] : _routes) {
r._fd->add_server(id);
}
// Add other servers to our failure detector.
for (auto& [id, _] : _routes) {
fd->add_server(id);
}
_routes.emplace(id, route{std::move(srv), std::move(fd)});
co_return id;
});
}
raft_server<M>& get_server(raft::server_id id) {
return *_routes.at(id)._server;
}
network<message_t>& get_network() {
return _network;
}
// Must be called before we are destroyed unless `new_server` was never called.
future<> abort() {
// Close the gate before iterating over _routes to prevent concurrent modification by other methods.
co_await _gate.close();
for (auto& [_, r] : _routes) {
co_await r._server->abort();
}
_stopped = true;
}
};
template <PureStateMachine M, std::invocable<environment<M>&, ticker&> F>
auto with_env_and_ticker(environment_config cfg, F f) {
return do_with(std::move(f), std::make_unique<environment<M>>(std::move(cfg)), std::make_unique<ticker>(tlogger),
[] (F& f, std::unique_ptr<environment<M>>& env, std::unique_ptr<ticker>& t) {
return f(*env, *t).finally([&env_ = env, &t_ = t] () mutable -> future<> {
// move into coroutine body so they don't get destroyed with the lambda (on first co_await)
auto& env = env_;
auto& t = t_;
// We abort the environment before the ticker as the environment may require time to advance
// in order to finish (e.g. some operations may need to timeout).
co_await env->abort();
tlogger.trace("environment aborted");
co_await t->abort();
tlogger.trace("ticker aborted");
});
});
}
struct ExReg {
// Replaces the state with `x` and returns the previous state.
struct exchange { int32_t x; };
// Returns the state.
struct read {};
// Return value for `exchange` or `read`.
struct ret { int32_t x; };
using state_t = int32_t;
using input_t = std::variant<read, exchange>;
using output_t = ret;
static std::pair<state_t, output_t> delta(state_t curr, input_t input) {
using res_t = std::pair<state_t, output_t>;
return std::visit(make_visitor(
[&curr] (const exchange& w) -> res_t {
return {w.x, ret{curr}};
},
[&curr] (const read&) -> res_t {
return {curr, ret{curr}};
}
), input);
}
static const state_t init;
};
const ExReg::state_t ExReg::init = 0;
namespace ser {
template <>
struct serializer<ExReg::exchange> {
template <typename Output>
static void write(Output& buf, const ExReg::exchange& op) { serializer<int32_t>::write(buf, op.x); };
template <typename Input>
static ExReg::exchange read(Input& buf) { return { serializer<int32_t>::read(buf) }; }
template <typename Input>
static void skip(Input& buf) { serializer<int32_t>::skip(buf); }
};
template <>
struct serializer<ExReg::read> {
template <typename Output>
static void write(Output& buf, const ExReg::read&) {};
template <typename Input>
static ExReg::read read(Input& buf) { return {}; }
template <typename Input>
static void skip(Input& buf) {}
};
}
bool operator==(ExReg::ret a, ExReg::ret b) { return a.x == b.x; }
std::ostream& operator<<(std::ostream& os, const ExReg::ret& r) {
return os << format("ret{{{}}}", r.x);
}
std::ostream& operator<<(std::ostream& os, const ExReg::read&) {
return os << "read";
}
std::ostream& operator<<(std::ostream& os, const ExReg::exchange& e) {
return os << format("xng{{{}}}", e.x);
}
// Wait until either one of `nodes` in `env` becomes a leader, or time point `timeout` is reached according to `timer` (whichever happens first).
// If the leader is found, returns it. Otherwise throws a `logical_timer::timed_out` exception.
//
// Note: the returned node may have been a leader the moment we found it, but may have just stepped down
// the moment we return it. It may be useful to call this function multiple times during cluster
// stabilization periods in order to find a node that will successfully answer calls.
template <PureStateMachine M>
struct wait_for_leader {
// FIXME: change into free function after clang bug #50345 is fixed
future<raft::server_id> operator()(
environment<M>& env,
std::vector<raft::server_id> nodes,
logical_timer& timer,
raft::logical_clock::time_point timeout) {
auto l = co_await timer.with_timeout(timeout, [] (weak_ptr<environment<M>> env, std::vector<raft::server_id> nodes) -> future<raft::server_id> {
while (true) {
if (!env) {
co_return raft::server_id{};
}
auto it = std::find_if(nodes.begin(), nodes.end(), [&env] (raft::server_id id) { return env->get_server(id).is_leader(); });
if (it != nodes.end()) {
co_return *it;
}
co_await seastar::later();
}
}(env.weak_from_this(), std::move(nodes)));
assert(l != raft::server_id{});
// Note: `l` may no longer be a leader at this point if there was a yield at the `co_await` above
// and `l` decided to step down, was restarted, or just got removed from the configuration.
co_return l;
}
};
SEASTAR_TEST_CASE(basic_test) {
logical_timer timer;
environment_config cfg {
.network_delay = 5_t,
.fd_convict_threshold = 50_t,
};
co_await with_env_and_ticker<ExReg>(cfg, [&timer] (environment<ExReg>& env, ticker& t) -> future<> {
using output_t = typename ExReg::output_t;
t.start({
{1, [&] {
env.tick_network();
timer.tick();
}},
{10, [&] {
env.tick_servers();
}}
}, 10'000);
auto leader_id = co_await env.new_server(true);
// Wait at most 1000 ticks for the server to elect itself as a leader.
assert(co_await wait_for_leader<ExReg>{}(env, {leader_id}, timer, timer.now() + 1000_t) == leader_id);
auto call = [&] (ExReg::input_t input, raft::logical_clock::duration timeout) {
return env.get_server(leader_id).call(std::move(input), timer.now() + timeout, timer);
};
auto eq = [] (const call_result_t<ExReg>& r, const output_t& expected) {
return std::holds_alternative<output_t>(r) && std::get<output_t>(r) == expected;
};
for (int i = 1; i <= 100; ++i) {
assert(eq(co_await call(ExReg::exchange{i}, 100_t), ExReg::ret{i - 1}));
}
tlogger.debug("100 exchanges - single server - passed");
auto id2 = co_await env.new_server(false);
auto id3 = co_await env.new_server(false);
tlogger.debug("Started 2 more servers, changing configuration");
assert(std::holds_alternative<std::monostate>(
co_await env.get_server(leader_id).reconfigure({leader_id, id2, id3}, timer.now() + 100_t, timer)));
tlogger.debug("Configuration changed");
co_await call(ExReg::exchange{0}, 100_t);
for (int i = 1; i <= 100; ++i) {
assert(eq(co_await call(ExReg::exchange{i}, 100_t), ExReg::ret{i - 1}));
}
tlogger.debug("100 exchanges - three servers - passed");
// concurrent calls
std::vector<future<call_result_t<ExReg>>> futs;
for (int i = 0; i < 100; ++i) {
futs.push_back(call(ExReg::read{}, 100_t));
co_await timer.sleep(2_t);
}
for (int i = 0; i < 100; ++i) {
assert(eq(co_await std::move(futs[i]), ExReg::ret{100}));
}
tlogger.debug("100 concurrent reads - three servers - passed");
});
tlogger.debug("Finished");
}
// A snapshot was being taken with the wrong term (current term instead of the term at the snapshotted index).
// This is a regression test for that bug.
SEASTAR_TEST_CASE(snapshot_uses_correct_term_test) {
logical_timer timer;
environment_config cfg {
.network_delay = 1_t,
.fd_convict_threshold = 10_t,
};
co_await with_env_and_ticker<ExReg>(cfg, [&timer] (environment<ExReg>& env, ticker& t) -> future<> {
t.start({
{1, [&] {
env.tick_network();
timer.tick();
}},
{10, [&] {
env.tick_servers();
}}
}, 10'000);
auto id1 = co_await env.new_server(true,
raft::server::configuration{
// It's easier to catch the problem when we send entries one by one, not in batches.
.append_request_threshold = 1,
});
assert(co_await wait_for_leader<ExReg>{}(env, {id1}, timer, timer.now() + 1000_t) == id1);
auto id2 = co_await env.new_server(true,
raft::server::configuration{
.append_request_threshold = 1,
});
assert(std::holds_alternative<std::monostate>(
co_await env.get_server(id1).reconfigure({id1, id2}, timer.now() + 100_t, timer)));
// Append a bunch of entries
for (int i = 1; i <= 10; ++i) {
assert(std::holds_alternative<typename ExReg::ret>(
co_await env.get_server(id1).call(ExReg::exchange{0}, timer.now() + 100_t, timer)));
}
assert(env.get_server(id1).is_leader());
// Force a term increase by partitioning the network and waiting for the leader to step down
tlogger.trace("add grudge");
env.get_network().add_grudge(id2, id1);
env.get_network().add_grudge(id1, id2);
while (env.get_server(id1).is_leader()) {
co_await seastar::later();
}
tlogger.trace("remove grudge");
env.get_network().remove_grudge(id2, id1);
env.get_network().remove_grudge(id1, id2);
auto l = co_await wait_for_leader<ExReg>{}(env, {id1, id2}, timer, timer.now() + 1000_t);
tlogger.trace("last leader: {}", l);
// Now the current term is greater than the term of the first couple of entries.
// Join another server with a small snapshot_threshold.
// The leader will send entries to this server one by one (due to small append_request_threshold),
// so the joining server will apply entries one by one or in small batches (depends on the timing),
// making it likely that it decides to take a snapshot at an entry with term lower than the current one.
// If we are (un)lucky and we take a snapshot at the last appended entry, the node will refuse all
// later append_entries requests due to non-matching term at the last appended entry. Note: due to this
// requirement, the test is nondeterministic and doesn't always catch the bug (it depends on a race
// between applier_fiber and io_fiber), but it does catch it in a significant number of runs.
// It's also a lot easier to catch this in dev than in debug, for instance.
// If we catch the bug, the reconfigure request below will time out.
auto id3 = co_await env.new_server(false,
raft::server::configuration{
.snapshot_threshold = 5,
.snapshot_trailing = 2,
});
assert(std::holds_alternative<std::monostate>(
co_await env.get_server(l).reconfigure({l, id3}, timer.now() + 1000_t, timer)));
});
}
// Regression test for the following bug: when we took a snapshot, we forgot to save the configuration.
// This caused each node in the cluster to eventually forget the cluster configuration.
SEASTAR_TEST_CASE(snapshotting_preserves_config_test) {
logical_timer timer;
environment_config cfg {
.network_delay = 1_t,
.fd_convict_threshold = 10_t,
};
co_await with_env_and_ticker<ExReg>(cfg, [&timer] (environment<ExReg>& env, ticker& t) -> future<> {
t.start({
{1, [&] {
env.tick_network();
timer.tick();
}},
{10, [&] {
env.tick_servers();
}}
}, 10'000);
auto id1 = co_await env.new_server(true,
raft::server::configuration{
.snapshot_threshold = 5,
.snapshot_trailing = 1,
});
assert(co_await wait_for_leader<ExReg>{}(env, {id1}, timer, timer.now() + 1000_t) == id1);
auto id2 = co_await env.new_server(false,
raft::server::configuration{
.snapshot_threshold = 5,
.snapshot_trailing = 1,
});
assert(std::holds_alternative<std::monostate>(
co_await env.get_server(id1).reconfigure({id1, id2}, timer.now() + 100_t, timer)));
// Append a bunch of entries
for (int i = 1; i <= 10; ++i) {
assert(std::holds_alternative<typename ExReg::ret>(
co_await env.get_server(id1).call(ExReg::exchange{0}, timer.now() + 100_t, timer)));
}
assert(env.get_server(id1).is_leader());
// Partition the network, forcing the leader to step down.
tlogger.trace("add grudge");
env.get_network().add_grudge(id2, id1);
env.get_network().add_grudge(id1, id2);
while (env.get_server(id1).is_leader()) {
co_await seastar::later();
}
tlogger.trace("remove grudge");
env.get_network().remove_grudge(id2, id1);
env.get_network().remove_grudge(id1, id2);
// With the bug this would timeout, the cluster is unable to elect a leader without the configuration.
auto l = co_await wait_for_leader<ExReg>{}(env, {id1, id2}, timer, timer.now() + 1000_t);
tlogger.trace("last leader: {}", l);
});
}
// Given a function `F` which takes a `raft::server_id` argument and returns a variant type
// which contains `not_a_leader`, repeatedly calls `F` until it returns something else than
// `not_a_leader` or until we reach a limit, whichever happens first.
// The maximum number of calls until we give up is specified by `bounces`.
// The initial `raft::server_id` argument provided to `F` is specified as an argument
// to this function (`srv_id`). If the initial call returns `not_a_leader`, then:
// - if the result contained a different leader ID and we didn't already try that ID,
// we will use it in the next call, sleeping for `known_leader_delay` first,
// - otherwise we will take the next ID from the `known` set, sleeping for
// `unknown_leader_delay` first; no ID will be tried twice.
// The returned result contains the result of the last call to `F` and the last
// server ID passed to `F`.
template <typename F>
struct bouncing {
using future_type = std::invoke_result_t<F, raft::server_id>;
using value_type = typename future_type::value_type;
static_assert(boost::mp11::mp_contains<value_type, raft::not_a_leader>::value);
F _f;
bouncing(F f) : _f(std::move(f)) {}
// FIXME: change this into a free function after clang bug #50345 is fixed.
future<std::pair<value_type, raft::server_id>> operator()(
logical_timer& timer,
std::unordered_set<raft::server_id> known,
raft::server_id srv_id,
size_t bounces,
raft::logical_clock::duration known_leader_delay,
raft::logical_clock::duration unknown_leader_delay
) {
tlogger.trace("bouncing call: starting with {}", srv_id);
std::unordered_set<raft::server_id> tried;
while (true) {
auto res = co_await _f(srv_id);
tried.insert(srv_id);
known.erase(srv_id);
if (auto n_a_l = std::get_if<raft::not_a_leader>(&res); n_a_l && bounces) {
--bounces;
if (n_a_l->leader) {
assert(n_a_l->leader != srv_id);
if (!tried.contains(n_a_l->leader)) {
co_await timer.sleep(known_leader_delay);
srv_id = n_a_l->leader;
tlogger.trace("bouncing call: got `not_a_leader`, rerouted to {}", srv_id);
continue;
}
}
if (!known.empty()) {
srv_id = *known.begin();
if (n_a_l->leader) {
tlogger.trace("bouncing call: got `not_a_leader`, rerouted to {}, but already tried it; trying {}", n_a_l->leader, srv_id);
} else {
tlogger.trace("bouncing call: got `not_a_leader`, no reroute, trying {}", srv_id);
}
continue;
}
}
co_return std::pair{res, srv_id};
}
}
};
// An operation representing a call to the Raft cluster with a specific state machine input.
// We may bounce a number of times if the server returns `not_a_leader` before giving up.
template <PureStateMachine M>
struct raft_call {
typename M::input_t input;
raft::logical_clock::duration timeout;
using result_type = call_result_t<M>;
struct state_type {
environment<M>& env;
// The set of servers that may be part of the current configuration.
// Sometimes we don't know the exact configuration, e.g. after a failed configuration change.
const std::unordered_set<raft::server_id>& known;
logical_timer& timer;
};
future<result_type> execute(state_type& s, const operation::context& ctx) {
// TODO a stable contact point used by a given thread would be preferable;
// the thread would switch only if necessary (the contact point left the configuration).
// Currently we choose the contact point randomly each time.
assert(s.known.size() > 0);
static std::mt19937 engine{0};
auto it = s.known.begin();
std::advance(it, std::uniform_int_distribution<size_t>{0, s.known.size() - 1}(engine));
auto contact = *it;
tlogger.debug("db call start inp {} tid {} start time {} current time {} contact {}", input, ctx.thread, ctx.start, s.timer.now(), contact);
auto [res, last] = co_await bouncing{[input = input, timeout = s.timer.now() + timeout, &timer = s.timer, &env = s.env] (raft::server_id id) {
return env.get_server(id).call(input, timeout, timer);
}}(s.timer, s.known, contact, 6, 10_t, 10_t);
tlogger.debug("db call end inp {} tid {} start time {} current time {} last contact {}", input, ctx.thread, ctx.start, s.timer.now(), last);
co_return res;
}
friend std::ostream& operator<<(std::ostream& os, const raft_call& c) {
return os << format("raft_call{{input:{},timeout:{}}}", c.input, c.timeout);
}
};
// An operation that partitions the network in half.
// During the partition, no server from one half can contact any server from the other;
// the partition is symmetric.
// For odd number of nodes, ensures that the current leader (if there is one) is in the minority.
template <PureStateMachine M>
class network_majority_grudge {
raft::logical_clock::duration _duration;
public:
struct state_type {
environment<M>& env;
const std::unordered_set<raft::server_id>& known;
logical_timer& timer;
std::mt19937 rnd;
};
using result_type = std::monostate;
network_majority_grudge(raft::logical_clock::duration d) : _duration(d) {
static_assert(operation::Executable<network_majority_grudge<M>>);
}
future<result_type> execute(state_type& s, const operation::context& ctx) {
std::vector<raft::server_id> nodes{s.known.begin(), s.known.end()};
std::shuffle(nodes.begin(), nodes.end(), s.rnd);
auto mid = nodes.begin() + (nodes.size() / 2);
if (nodes.size() % 2) {
// Odd number of nodes, let's ensure that the leader (if there is one) is in the minority
auto it = std::find_if(mid, nodes.end(), [&env = s.env] (raft::server_id id) { return env.get_server(id).is_leader(); });
if (it != nodes.end()) {
std::swap(*nodes.begin(), *it);
}
}
// Note: creating the grudges has O(n^2) complexity, where n is the cluster size.
// May be problematic for (very) large clusters.
for (auto x = nodes.begin(); x != mid; ++x) {
for (auto y = mid; y != nodes.end(); ++y) {
s.env.get_network().add_grudge(*x, *y);
s.env.get_network().add_grudge(*y, *x);
}
}
tlogger.debug("network_majority_grudge start tid {} start time {} current time {} duration {} grudge: {} vs {}",
ctx.thread, ctx.start, s.timer.now(),
_duration,
std::vector<raft::server_id>{nodes.begin(), mid},
std::vector<raft::server_id>{mid, nodes.end()});
co_await s.timer.sleep(_duration);
tlogger.debug("network_majority_grudge end tid {} start time {} current time {}", ctx.thread, ctx.start, s.timer.now());
// Some servers in `nodes` may already be gone at this point but network doesn't care.
// It's safe to call `remove_grudge`.
for (auto x = nodes.begin(); x != mid; ++x) {
for (auto y = mid; y != nodes.end(); ++y) {
s.env.get_network().remove_grudge(*x, *y);
s.env.get_network().remove_grudge(*y, *x);
}
}
co_return std::monostate{};
}
friend std::ostream& operator<<(std::ostream& os, const network_majority_grudge& p) {
return os << format("network_majority_grudge{{duration:{}}}", p._duration);
}
};
// Must be executed sequentially.
template <PureStateMachine M>
struct reconfiguration {
raft::logical_clock::duration timeout;
struct state_type {
const std::vector<raft::server_id> all_servers;
environment<M>& env;
// a subset of all_servers that we modify;
// the set of servers which may potentially be in the current configuration
std::unordered_set<raft::server_id>& known;
logical_timer& timer;
std::mt19937 rnd;
};
using result_type = reconfigure_result_t;
future<result_type> execute(state_type& s, const operation::context& ctx) {
assert(s.all_servers.size() > 1);
std::vector<raft::server_id> nodes{s.all_servers.begin(), s.all_servers.end()};
std::shuffle(nodes.begin(), nodes.end(), s.rnd);
nodes.resize(std::uniform_int_distribution<size_t>{1, nodes.size()}(s.rnd));
assert(s.known.size() > 0);
auto [res, last] = co_await bouncing{[&nodes, timeout = s.timer.now() + timeout, &timer = s.timer, &env = s.env] (raft::server_id id) {
return env.get_server(id).reconfigure(nodes, timeout, timer);
}}(s.timer, s.known, *s.known.begin(), 10, 10_t, 10_t);
std::visit(make_visitor(
[&, last = last] (std::monostate) {
tlogger.debug("reconfig successful from {} to {} by {}", s.known, nodes, last);
s.known = std::unordered_set<raft::server_id>{nodes.begin(), nodes.end()};
// TODO: include the old leader as well in case it's not part of the new config?
// it may remain a leader for some time...
},
[&, last = last] (raft::not_a_leader& e) {
tlogger.debug("reconfig failed, not a leader: {} tried {} by {}", e, nodes, last);
},
[&, last = last] (auto& e) {
s.known.merge(std::unordered_set<raft::server_id>{nodes.begin(), nodes.end()});
tlogger.debug("reconfig failed: {}, tried {} after merge {} by {}", e, nodes, s.known, last);
}
), res);
co_return res;
}
friend std::ostream& operator<<(std::ostream& os, const reconfiguration& r) {
return os << format("reconfiguration{{timeout:{}}}", r.timeout);
}
};
namespace std {
std::ostream& operator<<(std::ostream& os, const std::monostate&) {
return os << "";
}
template <typename T, typename... Ts>
std::ostream& operator<<(std::ostream& os, const std::variant<T, Ts...>& v) {
std::visit([&os] (auto& arg) { os << arg; }, v);
return os;
}
} // namespace std
namespace operation {
std::ostream& operator<<(std::ostream& os, const thread_id& tid) {
return os << format("thread_id{{{}}}", tid.id);
}
} // namespace operation
// An immutable sequence of integers.
class append_seq {
public:
using elem_t = int32_t;
private:
// This represents the sequence of integers from _seq->begin() to _seq->begin() + _end.
// The underlying vector *_seq may however be shared by other instances of `append_seq`.
// If only one instance is appending, the operation is O(1). However, each subsequent
// append performed by another instance sharing this vector must perform a copy.
lw_shared_ptr<std::vector<elem_t>> _seq; // always engaged
size_t _end; // <= _seq.size()
elem_t _digest; // sum of all elements modulo `magic`
static const elem_t magic = 54313;
public:
append_seq(std::vector<elem_t> v) : _seq{make_lw_shared<std::vector<elem_t>>(std::move(v))}, _end{_seq->size()}, _digest{0} {
for (auto x : *_seq) {
_digest = digest_append(_digest, x);
}
}
static elem_t digest_append(elem_t d, elem_t x) {
assert(0 <= d < magic);
auto y = (d + x) % magic;
assert(digest_remove(y, x) == d);
return y;
}
static elem_t digest_remove(elem_t d, elem_t x) {
assert(0 <= d < magic);
auto y = (d - x) % magic;
return y < 0 ? y + magic : y;
}
elem_t digest() const {
return _digest;
}
append_seq append(elem_t x) const {
assert(_seq);
assert(_end <= _seq->size());
auto seq = _seq;
if (_end < seq->size()) {
// The shared sequence was already appended beyond _end by someone else.
// We need to copy everything so we don't break the other guy.
seq = make_lw_shared<std::vector<elem_t>>(seq->begin(), seq->begin() + _end);
}
seq->push_back(x);
return {std::move(seq), _end + 1, digest_append(_digest, x)};
}
elem_t operator[](size_t idx) const {
assert(_seq);
assert(idx < _end);
assert(_end <= _seq->size());
return (*_seq)[idx];
}
bool empty() const {
return _end == 0;
}
std::pair<append_seq, elem_t> pop() {
assert(_seq);
assert(_end <= _seq->size());
assert(0 < _end);
return {{_seq, _end - 1, digest_remove(_digest, (*_seq)[_end - 1])}, (*_seq)[_end - 1]};
}
friend std::ostream& operator<<(std::ostream& os, const append_seq& s) {
// TODO: don't copy the elements
std::vector<elem_t> v{s._seq->begin(), s._seq->begin() + s._end};
return os << format("v {} _end {}", v, s._end);
}
private:
append_seq(lw_shared_ptr<std::vector<elem_t>> seq, size_t end, elem_t d)
: _seq(std::move(seq)), _end(end), _digest(d) {}
};
struct AppendReg {
struct append { int32_t x; };
struct ret { int32_t x; append_seq prev; };
using state_t = append_seq;
using input_t = append;
using output_t = ret;
static std::pair<state_t, output_t> delta(const state_t& curr, input_t input) {
return {curr.append(input.x), {input.x, curr}};
}
static thread_local const state_t init;
};
thread_local const AppendReg::state_t AppendReg::init{{0}};
namespace ser {
template <>
struct serializer<AppendReg::append> {
template <typename Output>
static void write(Output& buf, const AppendReg::append& op) { serializer<int32_t>::write(buf, op.x); };
template <typename Input>
static AppendReg::append read(Input& buf) { return { serializer<int32_t>::read(buf) }; }
template <typename Input>
static void skip(Input& buf) { serializer<int32_t>::skip(buf); }
};
}
// TODO: do some useful logging in case of consistency violation
struct append_reg_model {
using elem_t = typename append_seq::elem_t;
struct entry {
elem_t elem;
elem_t digest;
};
std::vector<entry> seq{{0, 0}};
std::unordered_map<elem_t, size_t> index{{0, 0}};
std::unordered_set<elem_t> banned;
std::unordered_set<elem_t> returned;
std::unordered_set<elem_t> in_progress;
void invocation(elem_t x) {
assert(!index.contains(x));
assert(!in_progress.contains(x));
in_progress.insert(x);
}
void return_success(elem_t x, append_seq prev) {
assert(!returned.contains(x));
assert(x != 0);
assert(!prev.empty());
completion(x, std::move(prev));
returned.insert(x);
}
void return_failure(elem_t x) {
assert(!index.contains(x));
assert(in_progress.contains(x));
banned.insert(x);
in_progress.erase(x);
}
private:
void completion(elem_t x, append_seq prev) {
if (prev.empty()) {
assert(x == 0);
return;
}
assert(x != 0);
assert(!banned.contains(x));
assert(in_progress.contains(x) || index.contains(x));
auto [prev_prev, prev_x] = prev.pop();
if (auto it = index.find(x); it != index.end()) {
// This element was already completed.
auto idx = it->second;
assert(0 < idx);
assert(idx < seq.size());
assert(prev_x == seq[idx - 1].elem);
assert(prev.digest() == seq[idx - 1].digest);
return;
}
// A new completion.
// First, recursively complete the previous elements...
completion(prev_x, std::move(prev_prev));
// Check that the existing tail matches our tail.
assert(!seq.empty());
assert(prev_x == seq.back().elem);
assert(prev.digest() == seq.back().digest);
// All previous elements were completed, so the new element belongs at the end.
index.emplace(x, seq.size());
seq.push_back(entry{x, append_seq::digest_append(seq.back().digest, x)});
in_progress.erase(x);
}
};
std::ostream& operator<<(std::ostream& os, const AppendReg::append& a) {
return os << format("append{{{}}}", a.x);
}
std::ostream& operator<<(std::ostream& os, const AppendReg::ret& r) {
return os << format("ret{{{}, {}}}", r.x, r.prev);
}
SEASTAR_TEST_CASE(basic_generator_test) {
using op_type = operation::invocable<operation::either_of<
raft_call<AppendReg>,
network_majority_grudge<AppendReg>
>>;
using history_t = utils::chunked_vector<std::variant<op_type, operation::completion<op_type>>>;
static_assert(operation::Invocable<op_type>);
logical_timer timer;
environment_config cfg {
.network_delay = 3_t,
.fd_convict_threshold = 50_t,
};
co_await with_env_and_ticker<AppendReg>(cfg, [&cfg, &timer] (environment<AppendReg>& env, ticker& t) -> future<> {
t.start({
{1, [&] {
env.tick_network();
timer.tick();
}},
{10, [&] {
env.tick_servers();
}}
}, 200'000);
auto leader_id = co_await env.new_server(true);
// Wait for the server to elect itself as a leader.
assert(co_await wait_for_leader<AppendReg>{}(env, {leader_id}, timer, timer.now() + 1000_t) == leader_id);
size_t no_servers = 5;
std::unordered_set<raft::server_id> servers{leader_id};
for (size_t i = 1; i < no_servers; ++i) {
servers.insert(co_await env.new_server(false));
}
assert(std::holds_alternative<std::monostate>(
co_await env.get_server(leader_id).reconfigure(
std::vector<raft::server_id>{servers.begin(), servers.end()}, timer.now() + 100_t, timer)));
auto threads = operation::make_thread_set(servers.size() + 1);
auto nemesis_thread = some(threads);
auto seed = tests::random::get_int<int32_t>();
// TODO: make it dynamic based on the current configuration
std::unordered_set<raft::server_id>& known = servers;
raft_call<AppendReg>::state_type db_call_state {
.env = env,
.known = known,
.timer = timer
};
network_majority_grudge<AppendReg>::state_type network_majority_grudge_state {
.env = env,
.known = known,
.timer = timer,
.rnd = std::mt19937{seed}
};
auto init_state = op_type::state_type{std::move(db_call_state), std::move(network_majority_grudge_state)};
using namespace generator;
// For reference to ``real life'' suppose 1_t ~= 10ms. Then:
// 10_t (server tick) ~= 100ms
// network delay = 3_t ~= 30ms
// election timeout = 10 server ticks = 100_t ~= 1s
// thus, to enforce leader election, need a majority to convict the current leader for > 100_t ~= 1s,
// failure detector convict threshold = 50 srv ticks = 500_t ~= 5s
// so need to partition for > 600_t ~= 6s
// choose network partition duration uniformly from [600_t-600_t/3, 600_t+600_t/3] = [400_t, 800_t]
// ~= [4s, 8s] -> ~1/2 partitions should cause an election
// we will set request timeout 600_t ~= 6s and partition every 1200_t ~= 12s
auto gen = op_limit(500,
pin(nemesis_thread,
stagger(seed, timer.now() + 200_t, 1200_t, 1200_t,
random(seed, [] (std::mt19937& engine) {
static std::uniform_int_distribution<raft::logical_clock::rep> dist{400, 800};
return op_type{network_majority_grudge<AppendReg>{raft::logical_clock::duration{dist(engine)}}};
})
),
stagger(seed, timer.now(), 0_t, 50_t,
sequence(1, [] (int32_t i) {
assert(i > 0);
return op_type{raft_call<AppendReg>{AppendReg::append{i}, 200_t}};
})
)
)
);
class consistency_checker {
append_reg_model _model;
public:
consistency_checker() : _model{} {}
void operator()(op_type o) {
tlogger.debug("invocation {}", o);
if (auto call_op = std::get_if<raft_call<AppendReg>>(&o.op)) {
_model.invocation(call_op->input.x);
}
}
void operator()(operation::completion<op_type> c) {
auto res = std::get_if<op_type::result_type>(&c.result);
assert(res);
if (auto call_res = std::get_if<raft_call<AppendReg>::result_type>(res)) {
std::visit(make_visitor(
[this] (AppendReg::output_t& out) {
tlogger.debug("completion x: {} prev digest: {}", out.x, out.prev.digest());
_model.return_success(out.x, std::move(out.prev));
},
[] (raft::not_a_leader& e) {
// TODO: this is a definite failure, mark it
// _model.return_failure(...)
},
[] (raft::commit_status_unknown& e) {
// TODO assert: only allowed if reconfigurations happen?
// assert(false); TODO debug this
},
[] (auto&) { }
), *call_res);
} else {
tlogger.debug("completion {}", c);
}
}
};
history_t history;
interpreter<op_type, decltype(gen), consistency_checker> interp{
std::move(gen), std::move(threads), 1_t, std::move(init_state), timer,
consistency_checker{}};
co_await interp.run();
tlogger.debug("Finished generator run, time: {}", timer.now());
// Liveness check: we must be able to obtain a final response after all the nemeses have stopped.
// Due to possible multiple leaders at this point and the cluster stabilizing (for example there
// may be no leader right now, the current leader may be stepping down etc.) we may need to try
// sending requests multiple times to different servers to obtain the last result.
auto limit = timer.now() + 10000_t;
size_t cnt = 0;
for (; timer.now() < limit; ++cnt) {
tlogger.debug("Trying to obtain last result: attempt number {}", cnt + 1);
auto now = timer.now();
auto leader = co_await wait_for_leader<AppendReg>{}(env,
std::vector<raft::server_id>{servers.begin(), servers.end()}, timer, limit)
.handle_exception_type([&timer, now] (logical_timer::timed_out<raft::server_id>) -> raft::server_id {
tlogger.error("Failed to find a leader after {} ticks at the end of test.", timer.now() - now);
assert(false);
});
if (env.get_server(leader).is_leader()) {
tlogger.debug("Leader {} found after {} ticks", leader, timer.now() - now);
} else {
tlogger.warn("Leader {} found after {} ticks, but suddenly lost leadership", leader, timer.now() - now);
continue;
}
for (auto& s: servers) {
auto& srv = env.get_server(s);
if (srv.is_leader() && s != leader) {
tlogger.debug("There is another leader: {}", s);
}
}
auto [res, last_attempted_server] = co_await bouncing{[&timer, &env] (raft::server_id id) {
return env.get_server(id).call(AppendReg::append{-1}, timer.now() + 200_t, timer);
}}(timer, known, leader, known.size() + 1, 10_t, 10_t);
if (std::holds_alternative<typename AppendReg::ret>(res)) {
tlogger.debug("Last result: {}", res);
co_return;
}
tlogger.warn("Failed to obtain last result at end of test: {} returned by {}", res, last_attempted_server);
}
tlogger.error("Failed to obtain a final successful response at the end of the test. Number of attempts: {}", cnt);
assert(false);
});
}
|
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "OgreStableHeaders.h"
#include "OgreHardwarePixelBuffer.h"
#include "OgreImage.h"
#include "OgreTexture.h"
namespace Ogre {
const char* Texture::CUBEMAP_SUFFIXES[] = {"_rt", "_lf", "_up", "_dn", "_fr", "_bk"};
//--------------------------------------------------------------------------
Texture::Texture(ResourceManager* creator, const String& name,
ResourceHandle handle, const String& group, bool isManual,
ManualResourceLoader* loader)
: Resource(creator, name, handle, group, isManual, loader),
// init defaults; can be overridden before load()
mHeight(512),
mWidth(512),
mDepth(1),
mNumRequestedMipmaps(0),
mNumMipmaps(0),
mMipmapsHardwareGenerated(false),
mGamma(1.0f),
mHwGamma(false),
mFSAA(0),
mTextureType(TEX_TYPE_2D),
mFormat(PF_UNKNOWN),
mUsage(TU_DEFAULT),
mSrcFormat(PF_UNKNOWN),
mSrcWidth(0),
mSrcHeight(0),
mSrcDepth(0),
mDesiredFormat(PF_UNKNOWN),
mDesiredIntegerBitDepth(0),
mDesiredFloatBitDepth(0),
mTreatLuminanceAsAlpha(false),
mInternalResourcesCreated(false)
{
if (createParamDictionary("Texture"))
{
// Define the parameters that have to be present to load
// from a generic source; actually there are none, since when
// predeclaring, you use a texture file which includes all the
// information required.
}
// Set some defaults for default load path
if (TextureManager::getSingletonPtr())
{
TextureManager& tmgr = TextureManager::getSingleton();
setNumMipmaps(tmgr.getDefaultNumMipmaps());
setDesiredBitDepths(tmgr.getPreferredIntegerBitDepth(), tmgr.getPreferredFloatBitDepth());
}
}
//--------------------------------------------------------------------------
void Texture::loadRawData( DataStreamPtr& stream,
ushort uWidth, ushort uHeight, PixelFormat eFormat)
{
Image img;
img.loadRawData(stream, uWidth, uHeight, 1, eFormat);
loadImage(img);
}
//--------------------------------------------------------------------------
void Texture::loadImage( const Image &img )
{
LoadingState old = mLoadingState.load();
if (old!=LOADSTATE_UNLOADED && old!=LOADSTATE_PREPARED) return;
if (!mLoadingState.compare_exchange_strong(old,LOADSTATE_LOADING)) return;
// Scope lock for actual loading
try
{
OGRE_LOCK_AUTO_MUTEX;
std::vector<const Image*> imagePtrs;
imagePtrs.push_back(&img);
_loadImages( imagePtrs );
}
catch (...)
{
// Reset loading in-progress flag in case failed for some reason
mLoadingState.store(old);
// Re-throw
throw;
}
mLoadingState.store(LOADSTATE_LOADED);
// Notify manager
if(mCreator)
mCreator->_notifyResourceLoaded(this);
// No deferred loading events since this method is not called in background
}
//--------------------------------------------------------------------------
void Texture::setFormat(PixelFormat pf)
{
mFormat = pf;
mDesiredFormat = pf;
mSrcFormat = pf;
}
//--------------------------------------------------------------------------
bool Texture::hasAlpha(void) const
{
return PixelUtil::hasAlpha(mFormat);
}
//--------------------------------------------------------------------------
void Texture::setDesiredIntegerBitDepth(ushort bits)
{
mDesiredIntegerBitDepth = bits;
}
//--------------------------------------------------------------------------
ushort Texture::getDesiredIntegerBitDepth(void) const
{
return mDesiredIntegerBitDepth;
}
//--------------------------------------------------------------------------
void Texture::setDesiredFloatBitDepth(ushort bits)
{
mDesiredFloatBitDepth = bits;
}
//--------------------------------------------------------------------------
ushort Texture::getDesiredFloatBitDepth(void) const
{
return mDesiredFloatBitDepth;
}
//--------------------------------------------------------------------------
void Texture::setDesiredBitDepths(ushort integerBits, ushort floatBits)
{
mDesiredIntegerBitDepth = integerBits;
mDesiredFloatBitDepth = floatBits;
}
//--------------------------------------------------------------------------
void Texture::setTreatLuminanceAsAlpha(bool asAlpha)
{
mTreatLuminanceAsAlpha = asAlpha;
}
//--------------------------------------------------------------------------
bool Texture::getTreatLuminanceAsAlpha(void) const
{
return mTreatLuminanceAsAlpha;
}
//--------------------------------------------------------------------------
size_t Texture::calculateSize(void) const
{
return getNumFaces() * PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat);
}
//--------------------------------------------------------------------------
size_t Texture::getNumFaces(void) const
{
return getTextureType() == TEX_TYPE_CUBE_MAP ? 6 : 1;
}
//--------------------------------------------------------------------------
void Texture::_loadImages( const ConstImagePtrList& images )
{
if(images.empty())
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot load empty vector of images",
"Texture::loadImages");
// Set desired texture size and properties from images[0]
mSrcWidth = mWidth = images[0]->getWidth();
mSrcHeight = mHeight = images[0]->getHeight();
mSrcDepth = mDepth = images[0]->getDepth();
if(!mLayerNames.empty() && mTextureType != TEX_TYPE_CUBE_MAP)
mDepth = mLayerNames.size();
// Get source image format and adjust if required
mSrcFormat = images[0]->getFormat();
if (mTreatLuminanceAsAlpha && mSrcFormat == PF_L8)
{
mSrcFormat = PF_A8;
}
if (mDesiredFormat != PF_UNKNOWN)
{
// If have desired format, use it
mFormat = mDesiredFormat;
}
else
{
// Get the format according with desired bit depth
mFormat = PixelUtil::getFormatForBitDepths(mSrcFormat, mDesiredIntegerBitDepth, mDesiredFloatBitDepth);
}
// The custom mipmaps in the image have priority over everything
uint32 imageMips = images[0]->getNumMipmaps();
if(imageMips > 0)
{
mNumMipmaps = mNumRequestedMipmaps = images[0]->getNumMipmaps();
// Disable flag for auto mip generation
mUsage &= ~TU_AUTOMIPMAP;
}
// Create the texture
createInternalResources();
// Check if we're loading one image with multiple faces
// or a vector of images representing the faces
size_t faces;
bool multiImage; // Load from multiple images?
if(images.size() > 1)
{
faces = images.size();
multiImage = true;
}
else
{
faces = images[0]->getNumFaces();
multiImage = false;
}
// Check whether number of faces in images exceeds number of faces
// in this texture. If so, clamp it.
if(faces > getNumFaces())
faces = getNumFaces();
if (TextureManager::getSingleton().getVerbose()) {
// Say what we're doing
Log::Stream str = LogManager::getSingleton().stream();
str << "Texture '" << mName << "': Loading " << faces << " faces"
<< "(" << PixelUtil::getFormatName(images[0]->getFormat()) << ","
<< images[0]->getWidth() << "x" << images[0]->getHeight() << "x"
<< images[0]->getDepth() << ")";
if (!(mMipmapsHardwareGenerated && mNumMipmaps == 0))
{
str << " with " << mNumMipmaps;
if(mUsage & TU_AUTOMIPMAP)
{
if (mMipmapsHardwareGenerated)
str << " hardware";
str << " generated mipmaps";
}
else
{
str << " custom mipmaps";
}
if(multiImage)
str << " from multiple Images.";
else
str << " from Image.";
}
// Print data about first destination surface
const auto& buf = getBuffer(0, 0);
str << " Internal format is " << PixelUtil::getFormatName(buf->getFormat()) << ","
<< buf->getWidth() << "x" << buf->getHeight() << "x" << buf->getDepth() << ".";
}
// Main loading loop
// imageMips == 0 if the image has no custom mipmaps, otherwise contains the number of custom mips
for(size_t mip = 0; mip <= std::min(mNumMipmaps, imageMips); ++mip)
{
for(size_t i = 0; i < std::max(faces, images.size()); ++i)
{
PixelBox src;
size_t face = (mDepth == 1) ? i : 0; // depth = 1, then cubemap face else 3d/ array layer
auto buffer = getBuffer(face, mip);
Box dst(0, 0, 0, buffer->getWidth(), buffer->getHeight(), buffer->getDepth());
if(multiImage)
{
// Load from multiple images
src = images[i]->getPixelBox(0, mip);
// set dst layer
if(mDepth > 1)
{
dst.front = i;
dst.back = i + 1;
}
}
else
{
// Load from faces of images[0]
src = images[0]->getPixelBox(i, mip);
}
// Sets to treated format in case is difference
src.format = mSrcFormat;
if(mGamma != 1.0f) {
// Apply gamma correction
// Do not overwrite original image but do gamma correction in temporary buffer
MemoryDataStream buf(PixelUtil::getMemorySize(src.getWidth(), src.getHeight(),
src.getDepth(), src.format));
PixelBox corrected = PixelBox(src.getWidth(), src.getHeight(), src.getDepth(), src.format, buf.getPtr());
PixelUtil::bulkPixelConversion(src, corrected);
Image::applyGamma(corrected.data, mGamma, corrected.getConsecutiveSize(),
static_cast<uchar>(PixelUtil::getNumElemBits(src.format)));
// Destination: entire texture. blitFromMemory does the scaling to
// a power of two for us when needed
buffer->blitFromMemory(corrected, dst);
}
else
{
// Destination: entire texture. blitFromMemory does the scaling to
// a power of two for us when needed
buffer->blitFromMemory(src, dst);
}
}
}
// Update size (the final size, not including temp space)
mSize = getNumFaces() * PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat);
}
//-----------------------------------------------------------------------------
void Texture::createInternalResources(void)
{
if (!mInternalResourcesCreated)
{
createInternalResourcesImpl();
mInternalResourcesCreated = true;
}
}
//-----------------------------------------------------------------------------
void Texture::freeInternalResources(void)
{
if (mInternalResourcesCreated)
{
mSurfaceList.clear();
freeInternalResourcesImpl();
mInternalResourcesCreated = false;
}
}
//-----------------------------------------------------------------------------
void Texture::unloadImpl(void)
{
freeInternalResources();
}
//-----------------------------------------------------------------------------
void Texture::copyToTexture( TexturePtr& target )
{
if(target->getNumFaces() != getNumFaces())
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Texture types must match",
"Texture::copyToTexture");
}
size_t numMips = std::min(getNumMipmaps(), target->getNumMipmaps());
if((mUsage & TU_AUTOMIPMAP) || (target->getUsage()&TU_AUTOMIPMAP))
numMips = 0;
for(unsigned int face=0; face<getNumFaces(); face++)
{
for(unsigned int mip=0; mip<=numMips; mip++)
{
target->getBuffer(face, mip)->blit(getBuffer(face, mip));
}
}
}
//---------------------------------------------------------------------
String Texture::getSourceFileType() const
{
if (mName.empty())
return BLANKSTRING;
String::size_type pos = mName.find_last_of('.');
if (pos != String::npos && pos < (mName.length() - 1))
{
String ext = mName.substr(pos + 1);
StringUtil::toLowerCase(ext);
return ext;
}
// No extension
auto dstream = ResourceGroupManager::getSingleton().openResource(
mName, mGroup, NULL, false);
if (!dstream && getTextureType() == TEX_TYPE_CUBE_MAP)
{
// try again with one of the faces (non-dds)
dstream = ResourceGroupManager::getSingleton().openResource(mName + "_rt", mGroup, NULL, false);
}
return dstream ? Image::getFileExtFromMagic(dstream) : BLANKSTRING;
}
const HardwarePixelBufferSharedPtr& Texture::getBuffer(size_t face, size_t mipmap)
{
if (face >= getNumFaces())
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Face index out of range", "Texture::getBuffer");
}
if (mipmap > mNumMipmaps)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Mipmap index out of range", "Texture::getBuffer");
}
unsigned long idx = face * (mNumMipmaps + 1) + mipmap;
assert(idx < mSurfaceList.size());
return mSurfaceList[idx];
}
//---------------------------------------------------------------------
void Texture::convertToImage(Image& destImage, bool includeMipMaps)
{
uint32 numMips = includeMipMaps? getNumMipmaps() + 1 : 1;
size_t dataSize = Image::calculateSize(numMips,
getNumFaces(), getWidth(), getHeight(), getDepth(), getFormat());
void* pixData = OGRE_MALLOC(dataSize, Ogre::MEMCATEGORY_GENERAL);
// if there are multiple faces and mipmaps we must pack them into the data
// faces, then mips
void* currentPixData = pixData;
for (size_t face = 0; face < getNumFaces(); ++face)
{
uint32 width = getWidth();
uint32 height = getHeight();
uint32 depth = getDepth();
for (uint32 mip = 0; mip < numMips; ++mip)
{
size_t mipDataSize = PixelUtil::getMemorySize(width, height, depth, getFormat());
Ogre::PixelBox pixBox(width, height, depth, getFormat(), currentPixData);
getBuffer(face, mip)->blitToMemory(pixBox);
currentPixData = (void*)((char*)currentPixData + mipDataSize);
if(width != 1)
width /= 2;
if(height != 1)
height /= 2;
if(depth != 1)
depth /= 2;
}
}
// load, and tell Image to delete the memory when it's done.
destImage.loadDynamicImage((Ogre::uchar*)pixData, getWidth(), getHeight(), getDepth(), getFormat(), true,
getNumFaces(), numMips - 1);
}
//--------------------------------------------------------------------------
void Texture::getCustomAttribute(const String&, void*)
{
}
void Texture::readImage(LoadedImages& imgs, const String& name, const String& ext, bool haveNPOT)
{
DataStreamPtr dstream = ResourceGroupManager::getSingleton().openResource(name, mGroup, this);
imgs.push_back(Image());
Image& img = imgs.back();
img.load(dstream, ext);
if( haveNPOT )
return;
// Scale to nearest power of 2
uint32 w = Bitwise::firstPO2From(img.getWidth());
uint32 h = Bitwise::firstPO2From(img.getHeight());
if((img.getWidth() != w) || (img.getHeight() != h))
img.resize(w, h);
}
void Texture::prepareImpl(void)
{
if (mUsage & TU_RENDERTARGET)
return;
const RenderSystemCapabilities* renderCaps =
Root::getSingleton().getRenderSystem()->getCapabilities();
bool haveNPOT = renderCaps->hasCapability(RSC_NON_POWER_OF_2_TEXTURES) ||
(renderCaps->getNonPOW2TexturesLimited() && mNumMipmaps == 0);
String baseName, ext;
StringUtil::splitBaseFilename(mName, baseName, ext);
LoadedImages loadedImages;
try
{
if(mLayerNames.empty())
{
readImage(loadedImages, mName, ext, haveNPOT);
// If this is a volumetric texture set the texture type flag accordingly.
// If this is a cube map, set the texture type flag accordingly.
if (loadedImages[0].hasFlag(IF_CUBEMAP))
mTextureType = TEX_TYPE_CUBE_MAP;
// If this is a volumetric texture set the texture type flag accordingly.
if (loadedImages[0].getDepth() > 1 && mTextureType != TEX_TYPE_2D_ARRAY)
mTextureType = TEX_TYPE_3D;
}
}
catch(const FileNotFoundException&)
{
if(mTextureType == TEX_TYPE_CUBE_MAP)
{
mLayerNames.resize(6);
for (size_t i = 0; i < 6; i++)
mLayerNames[i] = StringUtil::format("%s%s.%s", baseName.c_str(), CUBEMAP_SUFFIXES[i], ext.c_str());
}
else if (mTextureType == TEX_TYPE_2D_ARRAY)
{ // ignore
}
else
throw; // rethrow
}
// read sub-images
for(const String& name : mLayerNames)
{
StringUtil::splitBaseFilename(name, baseName, ext);
readImage(loadedImages, name, ext, haveNPOT);
}
// If compressed and 0 custom mipmap, disable auto mip generation and
// disable software mipmap creation.
// Not supported by GLES.
if (PixelUtil::isCompressed(loadedImages[0].getFormat()) &&
!renderCaps->hasCapability(RSC_AUTOMIPMAP_COMPRESSED) && loadedImages[0].getNumMipmaps() == 0)
{
mNumMipmaps = mNumRequestedMipmaps = 0;
// Disable flag for auto mip generation
mUsage &= ~TU_AUTOMIPMAP;
}
// avoid copying Image data
std::swap(mLoadedImages, loadedImages);
}
void Texture::unprepareImpl()
{
mLoadedImages.clear();
}
void Texture::loadImpl()
{
if (mUsage & TU_RENDERTARGET)
{
createInternalResources();
return;
}
LoadedImages loadedImages;
// Now the only copy is on the stack and will be cleaned in case of
// exceptions being thrown from _loadImages
std::swap(loadedImages, mLoadedImages);
// Call internal _loadImages, not loadImage since that's external and
// will determine load status etc again
ConstImagePtrList imagePtrs;
for (size_t i = 0; i < loadedImages.size(); ++i)
{
imagePtrs.push_back(&loadedImages[i]);
}
_loadImages(imagePtrs);
}
}
Main: Texture - assert that we are not loading an empty image
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "OgreStableHeaders.h"
#include "OgreHardwarePixelBuffer.h"
#include "OgreImage.h"
#include "OgreTexture.h"
namespace Ogre {
const char* Texture::CUBEMAP_SUFFIXES[] = {"_rt", "_lf", "_up", "_dn", "_fr", "_bk"};
//--------------------------------------------------------------------------
Texture::Texture(ResourceManager* creator, const String& name,
ResourceHandle handle, const String& group, bool isManual,
ManualResourceLoader* loader)
: Resource(creator, name, handle, group, isManual, loader),
// init defaults; can be overridden before load()
mHeight(512),
mWidth(512),
mDepth(1),
mNumRequestedMipmaps(0),
mNumMipmaps(0),
mMipmapsHardwareGenerated(false),
mGamma(1.0f),
mHwGamma(false),
mFSAA(0),
mTextureType(TEX_TYPE_2D),
mFormat(PF_UNKNOWN),
mUsage(TU_DEFAULT),
mSrcFormat(PF_UNKNOWN),
mSrcWidth(0),
mSrcHeight(0),
mSrcDepth(0),
mDesiredFormat(PF_UNKNOWN),
mDesiredIntegerBitDepth(0),
mDesiredFloatBitDepth(0),
mTreatLuminanceAsAlpha(false),
mInternalResourcesCreated(false)
{
if (createParamDictionary("Texture"))
{
// Define the parameters that have to be present to load
// from a generic source; actually there are none, since when
// predeclaring, you use a texture file which includes all the
// information required.
}
// Set some defaults for default load path
if (TextureManager::getSingletonPtr())
{
TextureManager& tmgr = TextureManager::getSingleton();
setNumMipmaps(tmgr.getDefaultNumMipmaps());
setDesiredBitDepths(tmgr.getPreferredIntegerBitDepth(), tmgr.getPreferredFloatBitDepth());
}
}
//--------------------------------------------------------------------------
void Texture::loadRawData( DataStreamPtr& stream,
ushort uWidth, ushort uHeight, PixelFormat eFormat)
{
Image img;
img.loadRawData(stream, uWidth, uHeight, 1, eFormat);
loadImage(img);
}
//--------------------------------------------------------------------------
void Texture::loadImage( const Image &img )
{
OgreAssert(img.getSize(), "cannot load empty image");
LoadingState old = mLoadingState.load();
if (old!=LOADSTATE_UNLOADED && old!=LOADSTATE_PREPARED) return;
if (!mLoadingState.compare_exchange_strong(old,LOADSTATE_LOADING)) return;
// Scope lock for actual loading
try
{
OGRE_LOCK_AUTO_MUTEX;
std::vector<const Image*> imagePtrs;
imagePtrs.push_back(&img);
_loadImages( imagePtrs );
}
catch (...)
{
// Reset loading in-progress flag in case failed for some reason
mLoadingState.store(old);
// Re-throw
throw;
}
mLoadingState.store(LOADSTATE_LOADED);
// Notify manager
if(mCreator)
mCreator->_notifyResourceLoaded(this);
// No deferred loading events since this method is not called in background
}
//--------------------------------------------------------------------------
void Texture::setFormat(PixelFormat pf)
{
mFormat = pf;
mDesiredFormat = pf;
mSrcFormat = pf;
}
//--------------------------------------------------------------------------
bool Texture::hasAlpha(void) const
{
return PixelUtil::hasAlpha(mFormat);
}
//--------------------------------------------------------------------------
void Texture::setDesiredIntegerBitDepth(ushort bits)
{
mDesiredIntegerBitDepth = bits;
}
//--------------------------------------------------------------------------
ushort Texture::getDesiredIntegerBitDepth(void) const
{
return mDesiredIntegerBitDepth;
}
//--------------------------------------------------------------------------
void Texture::setDesiredFloatBitDepth(ushort bits)
{
mDesiredFloatBitDepth = bits;
}
//--------------------------------------------------------------------------
ushort Texture::getDesiredFloatBitDepth(void) const
{
return mDesiredFloatBitDepth;
}
//--------------------------------------------------------------------------
void Texture::setDesiredBitDepths(ushort integerBits, ushort floatBits)
{
mDesiredIntegerBitDepth = integerBits;
mDesiredFloatBitDepth = floatBits;
}
//--------------------------------------------------------------------------
void Texture::setTreatLuminanceAsAlpha(bool asAlpha)
{
mTreatLuminanceAsAlpha = asAlpha;
}
//--------------------------------------------------------------------------
bool Texture::getTreatLuminanceAsAlpha(void) const
{
return mTreatLuminanceAsAlpha;
}
//--------------------------------------------------------------------------
size_t Texture::calculateSize(void) const
{
return getNumFaces() * PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat);
}
//--------------------------------------------------------------------------
size_t Texture::getNumFaces(void) const
{
return getTextureType() == TEX_TYPE_CUBE_MAP ? 6 : 1;
}
//--------------------------------------------------------------------------
void Texture::_loadImages( const ConstImagePtrList& images )
{
if(images.empty())
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot load empty vector of images",
"Texture::loadImages");
// Set desired texture size and properties from images[0]
mSrcWidth = mWidth = images[0]->getWidth();
mSrcHeight = mHeight = images[0]->getHeight();
mSrcDepth = mDepth = images[0]->getDepth();
if(!mLayerNames.empty() && mTextureType != TEX_TYPE_CUBE_MAP)
mDepth = mLayerNames.size();
// Get source image format and adjust if required
mSrcFormat = images[0]->getFormat();
if (mTreatLuminanceAsAlpha && mSrcFormat == PF_L8)
{
mSrcFormat = PF_A8;
}
if (mDesiredFormat != PF_UNKNOWN)
{
// If have desired format, use it
mFormat = mDesiredFormat;
}
else
{
// Get the format according with desired bit depth
mFormat = PixelUtil::getFormatForBitDepths(mSrcFormat, mDesiredIntegerBitDepth, mDesiredFloatBitDepth);
}
// The custom mipmaps in the image have priority over everything
uint32 imageMips = images[0]->getNumMipmaps();
if(imageMips > 0)
{
mNumMipmaps = mNumRequestedMipmaps = images[0]->getNumMipmaps();
// Disable flag for auto mip generation
mUsage &= ~TU_AUTOMIPMAP;
}
// Create the texture
createInternalResources();
// Check if we're loading one image with multiple faces
// or a vector of images representing the faces
size_t faces;
bool multiImage; // Load from multiple images?
if(images.size() > 1)
{
faces = images.size();
multiImage = true;
}
else
{
faces = images[0]->getNumFaces();
multiImage = false;
}
// Check whether number of faces in images exceeds number of faces
// in this texture. If so, clamp it.
if(faces > getNumFaces())
faces = getNumFaces();
if (TextureManager::getSingleton().getVerbose()) {
// Say what we're doing
Log::Stream str = LogManager::getSingleton().stream();
str << "Texture '" << mName << "': Loading " << faces << " faces"
<< "(" << PixelUtil::getFormatName(images[0]->getFormat()) << ","
<< images[0]->getWidth() << "x" << images[0]->getHeight() << "x"
<< images[0]->getDepth() << ")";
if (!(mMipmapsHardwareGenerated && mNumMipmaps == 0))
{
str << " with " << mNumMipmaps;
if(mUsage & TU_AUTOMIPMAP)
{
if (mMipmapsHardwareGenerated)
str << " hardware";
str << " generated mipmaps";
}
else
{
str << " custom mipmaps";
}
if(multiImage)
str << " from multiple Images.";
else
str << " from Image.";
}
// Print data about first destination surface
const auto& buf = getBuffer(0, 0);
str << " Internal format is " << PixelUtil::getFormatName(buf->getFormat()) << ","
<< buf->getWidth() << "x" << buf->getHeight() << "x" << buf->getDepth() << ".";
}
// Main loading loop
// imageMips == 0 if the image has no custom mipmaps, otherwise contains the number of custom mips
for(size_t mip = 0; mip <= std::min(mNumMipmaps, imageMips); ++mip)
{
for(size_t i = 0; i < std::max(faces, images.size()); ++i)
{
PixelBox src;
size_t face = (mDepth == 1) ? i : 0; // depth = 1, then cubemap face else 3d/ array layer
auto buffer = getBuffer(face, mip);
Box dst(0, 0, 0, buffer->getWidth(), buffer->getHeight(), buffer->getDepth());
if(multiImage)
{
// Load from multiple images
src = images[i]->getPixelBox(0, mip);
// set dst layer
if(mDepth > 1)
{
dst.front = i;
dst.back = i + 1;
}
}
else
{
// Load from faces of images[0]
src = images[0]->getPixelBox(i, mip);
}
// Sets to treated format in case is difference
src.format = mSrcFormat;
if(mGamma != 1.0f) {
// Apply gamma correction
// Do not overwrite original image but do gamma correction in temporary buffer
MemoryDataStream buf(PixelUtil::getMemorySize(src.getWidth(), src.getHeight(),
src.getDepth(), src.format));
PixelBox corrected = PixelBox(src.getWidth(), src.getHeight(), src.getDepth(), src.format, buf.getPtr());
PixelUtil::bulkPixelConversion(src, corrected);
Image::applyGamma(corrected.data, mGamma, corrected.getConsecutiveSize(),
static_cast<uchar>(PixelUtil::getNumElemBits(src.format)));
// Destination: entire texture. blitFromMemory does the scaling to
// a power of two for us when needed
buffer->blitFromMemory(corrected, dst);
}
else
{
// Destination: entire texture. blitFromMemory does the scaling to
// a power of two for us when needed
buffer->blitFromMemory(src, dst);
}
}
}
// Update size (the final size, not including temp space)
mSize = getNumFaces() * PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat);
}
//-----------------------------------------------------------------------------
void Texture::createInternalResources(void)
{
if (!mInternalResourcesCreated)
{
createInternalResourcesImpl();
mInternalResourcesCreated = true;
}
}
//-----------------------------------------------------------------------------
void Texture::freeInternalResources(void)
{
if (mInternalResourcesCreated)
{
mSurfaceList.clear();
freeInternalResourcesImpl();
mInternalResourcesCreated = false;
}
}
//-----------------------------------------------------------------------------
void Texture::unloadImpl(void)
{
freeInternalResources();
}
//-----------------------------------------------------------------------------
void Texture::copyToTexture( TexturePtr& target )
{
if(target->getNumFaces() != getNumFaces())
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Texture types must match",
"Texture::copyToTexture");
}
size_t numMips = std::min(getNumMipmaps(), target->getNumMipmaps());
if((mUsage & TU_AUTOMIPMAP) || (target->getUsage()&TU_AUTOMIPMAP))
numMips = 0;
for(unsigned int face=0; face<getNumFaces(); face++)
{
for(unsigned int mip=0; mip<=numMips; mip++)
{
target->getBuffer(face, mip)->blit(getBuffer(face, mip));
}
}
}
//---------------------------------------------------------------------
String Texture::getSourceFileType() const
{
if (mName.empty())
return BLANKSTRING;
String::size_type pos = mName.find_last_of('.');
if (pos != String::npos && pos < (mName.length() - 1))
{
String ext = mName.substr(pos + 1);
StringUtil::toLowerCase(ext);
return ext;
}
// No extension
auto dstream = ResourceGroupManager::getSingleton().openResource(
mName, mGroup, NULL, false);
if (!dstream && getTextureType() == TEX_TYPE_CUBE_MAP)
{
// try again with one of the faces (non-dds)
dstream = ResourceGroupManager::getSingleton().openResource(mName + "_rt", mGroup, NULL, false);
}
return dstream ? Image::getFileExtFromMagic(dstream) : BLANKSTRING;
}
const HardwarePixelBufferSharedPtr& Texture::getBuffer(size_t face, size_t mipmap)
{
if (face >= getNumFaces())
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Face index out of range", "Texture::getBuffer");
}
if (mipmap > mNumMipmaps)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Mipmap index out of range", "Texture::getBuffer");
}
unsigned long idx = face * (mNumMipmaps + 1) + mipmap;
assert(idx < mSurfaceList.size());
return mSurfaceList[idx];
}
//---------------------------------------------------------------------
void Texture::convertToImage(Image& destImage, bool includeMipMaps)
{
uint32 numMips = includeMipMaps? getNumMipmaps() + 1 : 1;
size_t dataSize = Image::calculateSize(numMips,
getNumFaces(), getWidth(), getHeight(), getDepth(), getFormat());
void* pixData = OGRE_MALLOC(dataSize, Ogre::MEMCATEGORY_GENERAL);
// if there are multiple faces and mipmaps we must pack them into the data
// faces, then mips
void* currentPixData = pixData;
for (size_t face = 0; face < getNumFaces(); ++face)
{
uint32 width = getWidth();
uint32 height = getHeight();
uint32 depth = getDepth();
for (uint32 mip = 0; mip < numMips; ++mip)
{
size_t mipDataSize = PixelUtil::getMemorySize(width, height, depth, getFormat());
Ogre::PixelBox pixBox(width, height, depth, getFormat(), currentPixData);
getBuffer(face, mip)->blitToMemory(pixBox);
currentPixData = (void*)((char*)currentPixData + mipDataSize);
if(width != 1)
width /= 2;
if(height != 1)
height /= 2;
if(depth != 1)
depth /= 2;
}
}
// load, and tell Image to delete the memory when it's done.
destImage.loadDynamicImage((Ogre::uchar*)pixData, getWidth(), getHeight(), getDepth(), getFormat(), true,
getNumFaces(), numMips - 1);
}
//--------------------------------------------------------------------------
void Texture::getCustomAttribute(const String&, void*)
{
}
void Texture::readImage(LoadedImages& imgs, const String& name, const String& ext, bool haveNPOT)
{
DataStreamPtr dstream = ResourceGroupManager::getSingleton().openResource(name, mGroup, this);
imgs.push_back(Image());
Image& img = imgs.back();
img.load(dstream, ext);
if( haveNPOT )
return;
// Scale to nearest power of 2
uint32 w = Bitwise::firstPO2From(img.getWidth());
uint32 h = Bitwise::firstPO2From(img.getHeight());
if((img.getWidth() != w) || (img.getHeight() != h))
img.resize(w, h);
}
void Texture::prepareImpl(void)
{
if (mUsage & TU_RENDERTARGET)
return;
const RenderSystemCapabilities* renderCaps =
Root::getSingleton().getRenderSystem()->getCapabilities();
bool haveNPOT = renderCaps->hasCapability(RSC_NON_POWER_OF_2_TEXTURES) ||
(renderCaps->getNonPOW2TexturesLimited() && mNumMipmaps == 0);
String baseName, ext;
StringUtil::splitBaseFilename(mName, baseName, ext);
LoadedImages loadedImages;
try
{
if(mLayerNames.empty())
{
readImage(loadedImages, mName, ext, haveNPOT);
// If this is a volumetric texture set the texture type flag accordingly.
// If this is a cube map, set the texture type flag accordingly.
if (loadedImages[0].hasFlag(IF_CUBEMAP))
mTextureType = TEX_TYPE_CUBE_MAP;
// If this is a volumetric texture set the texture type flag accordingly.
if (loadedImages[0].getDepth() > 1 && mTextureType != TEX_TYPE_2D_ARRAY)
mTextureType = TEX_TYPE_3D;
}
}
catch(const FileNotFoundException&)
{
if(mTextureType == TEX_TYPE_CUBE_MAP)
{
mLayerNames.resize(6);
for (size_t i = 0; i < 6; i++)
mLayerNames[i] = StringUtil::format("%s%s.%s", baseName.c_str(), CUBEMAP_SUFFIXES[i], ext.c_str());
}
else if (mTextureType == TEX_TYPE_2D_ARRAY)
{ // ignore
}
else
throw; // rethrow
}
// read sub-images
for(const String& name : mLayerNames)
{
StringUtil::splitBaseFilename(name, baseName, ext);
readImage(loadedImages, name, ext, haveNPOT);
}
// If compressed and 0 custom mipmap, disable auto mip generation and
// disable software mipmap creation.
// Not supported by GLES.
if (PixelUtil::isCompressed(loadedImages[0].getFormat()) &&
!renderCaps->hasCapability(RSC_AUTOMIPMAP_COMPRESSED) && loadedImages[0].getNumMipmaps() == 0)
{
mNumMipmaps = mNumRequestedMipmaps = 0;
// Disable flag for auto mip generation
mUsage &= ~TU_AUTOMIPMAP;
}
// avoid copying Image data
std::swap(mLoadedImages, loadedImages);
}
void Texture::unprepareImpl()
{
mLoadedImages.clear();
}
void Texture::loadImpl()
{
if (mUsage & TU_RENDERTARGET)
{
createInternalResources();
return;
}
LoadedImages loadedImages;
// Now the only copy is on the stack and will be cleaned in case of
// exceptions being thrown from _loadImages
std::swap(loadedImages, mLoadedImages);
// Call internal _loadImages, not loadImage since that's external and
// will determine load status etc again
ConstImagePtrList imagePtrs;
for (size_t i = 0; i < loadedImages.size(); ++i)
{
imagePtrs.push_back(&loadedImages[i]);
}
_loadImages(imagePtrs);
}
}
|
#include "ImagePyramidAccess.hpp"
#include <FAST/Data/ImagePyramid.hpp>
#include <FAST/Algorithms/ImageChannelConverter/ImageChannelConverter.hpp>
#include <FAST/Utility.hpp>
#include <openslide/openslide.h>
#include <tiffio.h>
#include <FAST/Data/Image.hpp>
#include <jpeglib.h>
namespace fast {
ImagePyramidAccess::ImagePyramidAccess(
std::vector<ImagePyramidLevel> levels,
openslide_t* fileHandle,
TIFF* tiffHandle,
std::ifstream* vsiHandle,
std::vector<vsi_tile_header>& vsiTiles,
std::shared_ptr<ImagePyramid> imagePyramid,
bool write,
std::unordered_set<std::string>& initializedPatchList,
std::mutex& readMutex) : m_initializedPatchList(initializedPatchList), m_readMutex(readMutex) {
if(levels.size() == 0)
throw Exception("Image pyramid has no levels");
m_image = imagePyramid;
m_levels = levels;
m_write = write;
m_fileHandle = fileHandle;
m_tiffHandle = tiffHandle;
m_vsiHandle = vsiHandle;
m_vsiTiles = vsiTiles;
}
void ImagePyramidAccess::release() {
m_image->accessFinished();
}
ImagePyramidAccess::~ImagePyramidAccess() {
release();
}
ImagePyramidPatch ImagePyramidAccess::getPatch(std::string tile) {
auto parts = split(tile, "_");
if(parts.size() != 3)
throw Exception("incorrect tile format");
int level = std::stoi(parts[0]);
int tile_x = std::stoi(parts[1]);
int tile_y = std::stoi(parts[2]);
return getPatch(level, tile_x, tile_y);
}
void jpegErrorExit(j_common_ptr cinfo) {
char jpegLastErrorMsg[JMSG_LENGTH_MAX];
// Create message
( *( cinfo->err->format_message ) ) ( cinfo, jpegLastErrorMsg );
throw std::runtime_error( jpegLastErrorMsg );
}
void ImagePyramidAccess::readVSITileToBuffer(vsi_tile_header tile, uchar* data) {
auto buffer = make_uninitialized_unique<char[]>(tile.numbytes);
// Reading VSI tiles is not thread safe
{
std::lock_guard<std::mutex> lock(m_readMutex);
m_vsiHandle->seekg(tile.offset);
m_vsiHandle->read(buffer.get(), tile.numbytes);
}
// TODO assuming JPEG here
jpeg_decompress_struct cinfo;
jpeg_error_mgr jerr; //error handling
jpeg_source_mgr src_mem;
jerr.error_exit = jpegErrorExit;
cinfo.err = jpeg_std_error(&jerr);
try {
jpeg_create_decompress(&cinfo);
jpeg_mem_src(&cinfo, (uchar*)buffer.get(), tile.numbytes);
int ret = jpeg_read_header(&cinfo, false);
if(ret != 1) {
throw Exception("Jpeg error..");
}
//cinfo.jpeg_color_space = JCS_YCbCr;
//cinfo.jpeg_color_space = JCS_RGB;
jpeg_start_decompress(&cinfo);
unsigned char* line = data;
while (cinfo.output_scanline < cinfo.output_height) {
jpeg_read_scanlines (&cinfo, &line, 1);
line += 3*cinfo.output_width;
}
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
} catch(std::exception &e) {
jpeg_destroy_decompress( &cinfo );
throw Exception("JPEG error: " + std::string(e.what())); // or return an error code
}
}
std::unique_ptr<uchar[]> ImagePyramidAccess::getPatchData(int level, int x, int y, int width, int height) {
const int levelWidth = m_image->getLevelWidth(level);
const int levelHeight = m_image->getLevelHeight(level);
const int channels = m_image->getNrOfChannels();
const int tileWidth = m_image->getLevelTileWidth(level);
const int tileHeight = m_image->getLevelTileHeight(level);
auto data = std::make_unique<uchar[]>(width*height*channels);
if(m_tiffHandle != nullptr) {
// Read all tiles within region, then crop
if(!isPatchInitialized(level, x, y)) {
// Tile has not be initialized, fill with zeros and return..
// TODO Do not try render these patches..
std::memset(data.get(), 0, width*height*channels);
return data;
}
if(width == tileWidth && height == tileHeight) {
std::lock_guard<std::mutex> lock(m_readMutex);
TIFFSetDirectory(m_tiffHandle, level);
int bytesRead = TIFFReadTile(m_tiffHandle, (void *) data.get(), x, y, 0, 0);
} else if(width < tileWidth || height < tileHeight) {
auto tileData = std::make_unique<uchar[]>(tileWidth*tileHeight*channels);
{
std::lock_guard<std::mutex> lock(m_readMutex);
TIFFSetDirectory(m_tiffHandle, level);
// In TIFF all tiles have the same size, thus they are padded..
int bytesRead = TIFFReadTile(m_tiffHandle, (void *) tileData.get(), x, y, 0, 0);
}
// Remove padding
for(int dy = 0; dy < height; ++dy) {
for(int dx = 0; dx < width; ++dx) {
data[dx + dy*width] = tileData[dx + dy*tileWidth];
}
}
} else if(width > tileWidth || height > tileHeight) {
// TODO implement
throw Exception("Encountered unqueal tile and request size. Not implemented. "
+ std::to_string(width) + " " + std::to_string(tileWidth) + " "
+ std::to_string(height) + " " + std::to_string(tileHeight)
);
throw NotImplementedException();
// TODO how to do this fast?
/*
int startTileX =;
int startTileY =;
int endTileX =;
int endTileY =;
auto dataBuffer = std::make_unique<char[]>(tileWidth * tileHeight * channels);
int offsetX =;
int offsetY =;
for (int x = startTileX; x <= endTileX; ++x) {
for (int y = startTileY; y <= endTileY; ++y) {
TIFFReadTile(m_tiffHandle, (void *) dataBuffer.get(), x, y, 0, 0);
for (int)
}
}
*/
}
} else if(m_fileHandle != nullptr) {
int scale = (float)m_image->getFullWidth()/levelWidth;
#ifndef WIN32
// HACK for black edge frames on ubuntu linux 20.04. This seems to be an issue with openslide or underlying libraries
if(level != 0) { // only occurs on levels != 0
// Reading scale pixels further in eliminates the problem for some reason...
x = x == 0 ? x+1 : x;
y = y == 0 ? y+1 : y;
}
#endif
openslide_read_region(m_fileHandle, (uint32_t*)data.get(), x * scale, y * scale, level, width, height);
} else if(!m_vsiTiles.empty()) {
if(width == tileWidth && height == tileHeight) {
vsi_tile_header tile;
bool found = false;
for(int i = 0; i < m_vsiTiles.size(); ++i) {
vsi_tile_header currentTile = m_vsiTiles[i];
if(currentTile.level != level)
continue;
if(currentTile.coord[0] != x / m_image->getLevelTileWidth(level) || currentTile.coord[1] != y / m_image->getLevelTileHeight(level))
continue;
tile = currentTile;
found = true;
break;
}
if(!found)
throw Exception("Could not find tile for getPathcData in VSI");
readVSITileToBuffer(tile, data.get());
} else {
std::vector<vsi_tile_header> tilesToRead;
int firstTileX = x / m_image->getLevelTileWidth(level);
int firstTileY = y / m_image->getLevelTileHeight(level);
int lastTileX = std::ceil((float)(x + width) / m_image->getLevelTileWidth(level));
int lastTileY = std::ceil((float)(y + height) / m_image->getLevelTileHeight(level));
// How many tiles we are supposed to have
const int targetNumberOfTiles = (lastTileX-firstTileX)*(lastTileY-firstTileY);
for(int i = 0; i < m_vsiTiles.size(); ++i) {
vsi_tile_header currentTile = m_vsiTiles[i];
if(currentTile.level != level)
continue;
if(
!((currentTile.coord[0] >= firstTileX && currentTile.coord[0] < lastTileX) &&
(currentTile.coord[1] >= firstTileY && currentTile.coord[1] < lastTileY)))
continue;
tilesToRead.push_back(currentTile);
}
if(tilesToRead.empty())
throw Exception("Tiles to ready empty");
auto fullTileBuffer = make_uninitialized_unique<uchar[]>(tileWidth*tileHeight*targetNumberOfTiles*channels);
if(tilesToRead.size() != targetNumberOfTiles) { // Some tiles are missing.. (edge case) fill with some blank value
if(channels > 1) {
std::memset(fullTileBuffer.get(), 255, tileWidth*tileHeight*targetNumberOfTiles*channels);
} else {
std::memset(fullTileBuffer.get(), 0, tileWidth*tileHeight*targetNumberOfTiles*channels);
}
}
const auto fullTileBufferWidth = (lastTileX-firstTileX)*tileWidth;
// Read tile to buffer
auto tileBuffer = make_uninitialized_unique<uchar[]>(tileWidth*tileHeight*channels); // assume full tiles of same size for all
for(auto tile : tilesToRead) {
const int tileX = (tile.coord[0]-firstTileX)*tileWidth;
const int tileY = (tile.coord[1]-firstTileY)*tileHeight;
readVSITileToBuffer(tile, tileBuffer.get());
// Stitch tile into full buffer
for(int cy = 0; cy < tileHeight; ++cy) {
for(int cx = 0; cx < tileWidth; ++cx) {
for(int channel = 0; channel < channels; ++channel) {
fullTileBuffer[(tileX + cx + (tileY + cy)*fullTileBufferWidth)*channels + channel] = tileBuffer[(cx + cy*tileWidth)*channels + channel];
}
}
}
}
// Crop the full buffer to data[]
const int offsetX = x - firstTileX*tileWidth;
const int offsetY = y - firstTileY*tileHeight;
for(int cy = offsetY; cy < offsetY + height; ++cy) {
for(int cx = offsetX; cx < offsetX + width; ++cx) {
for(int channel = 0; channel < channels; ++channel) {
data[(cx - offsetX + (cy - offsetY) * width)*channels + channel] = fullTileBuffer[(cx + cy * fullTileBufferWidth)*channels + channel];
}
}
}
}
} else {
auto levelData = m_levels[level];
for(int cy = y; cy < std::min(y + height, levelHeight); ++cy) {
for(int cx = x; cx < std::min(x + width, levelWidth); ++cx) {
for(int channel = 0; channel < channels; ++channel) {
data[(cx - x + (cy - y) * width)*channels + channel] = levelData.data[(cx + cy * levelWidth)*channels + channel];
}
}
}
}
return data;
}
ImagePyramidPatch ImagePyramidAccess::getPatch(int level, int tile_x, int tile_y) {
// Create patch
int levelWidth = m_image->getLevelWidth(level);
int levelHeight = m_image->getLevelHeight(level);
int levelTileWidth = m_image->getLevelTileWidth(level);
int levelTileHeight = m_image->getLevelTileHeight(level);
int tilesX = m_image->getLevelTilesX(level);
int tilesY = m_image->getLevelTilesY(level);
ImagePyramidPatch tile;
tile.offsetX = tile_x * levelTileWidth;
tile.offsetY = tile_y * levelTileHeight;
tile.width = levelTileWidth;
if(tile_x == tilesX - 1)
tile.width = levelWidth - tile.offsetX;
tile.height = levelTileHeight;
if(tile_y == tilesY - 1)
tile.height = levelHeight - tile.offsetY;
// Read the actual data
tile.data = getPatchData(level, tile.offsetX, tile.offsetY, tile.width, tile.height);
return tile;
}
std::shared_ptr<Image> ImagePyramidAccess::getLevelAsImage(int level) {
if(level < 0 || level >= m_image->getNrOfLevels())
throw Exception("Incorrect level given to getLevelAsImage" + std::to_string(level));
int width = m_image->getLevelWidth(level);
int height = m_image->getLevelHeight(level);
if(width > 16384 || height > 16384)
throw Exception("Image level is too large to convert into a FAST image");
return getPatchAsImage(level, 0, 0, width, height, true);
}
std::shared_ptr<Image> ImagePyramidAccess::getPatchAsImage(int level, int offsetX, int offsetY, int width, int height, bool convertToRGB) {
if(width > 16384 || height > 16384)
throw Exception("Image level is too large to convert into a FAST image");
if(offsetX < 0 || offsetY < 0 || width <= 0 || height <= 0)
throw Exception("Offset and size must be positive");
if(offsetX + width > m_image->getLevelWidth(level) || offsetY + height > m_image->getLevelHeight(level))
throw Exception("offset + size exceeds level size");
auto data = getPatchData(level, offsetX, offsetY, width, height);
float scale = m_image->getLevelScale(level);
auto spacing = m_image->getSpacing();
auto image = Image::create(width, height, TYPE_UINT8, m_image->getNrOfChannels(), std::move(data));
image->setSpacing(Vector3f(
spacing.x()*scale,
spacing.y()*scale,
1.0f
));
// Set transformation
auto T = Transform::create(Vector3f(offsetX*scale, offsetY*scale, 0.0f));
image->setTransform(T);
SceneGraph::setParentNode(image, std::dynamic_pointer_cast<SpatialDataObject>(m_image));
if(m_fileHandle != nullptr && convertToRGB) {
// Data is stored as BGRA, need to delete alpha channel and reverse it
auto channelConverter = ImageChannelConverter::New();
channelConverter->setChannelsToRemove(false, false, false, true);
channelConverter->setReverseChannels(true);
channelConverter->setInputData(image);
image = channelConverter->updateAndGetOutputData<Image>();
}
return image;
}
std::shared_ptr<Image> ImagePyramidAccess::getPatchAsImage(int level, int tileX, int tileY, bool convertToRGB) {
int levelWidth = m_image->getLevelWidth(level);
int levelHeight = m_image->getLevelHeight(level);
int tilesX = m_image->getLevelTilesX(level);
int tilesY = m_image->getLevelTilesY(level);
int levelTileWidth = m_image->getLevelTileWidth(level);
int levelTileHeight = m_image->getLevelTileHeight(level);
ImagePyramidPatch tile;
tile.offsetX = tileX * levelTileWidth;
tile.offsetY = tileY * levelTileHeight;
tile.width = levelTileWidth;
if(tileX == tilesX - 1)
tile.width = levelWidth - tile.offsetX;
tile.height = levelTileHeight;
if(tileY == tilesY - 1)
tile.height = levelHeight - tile.offsetY;
// Read the actual data
auto data = getPatchData(level, tile.offsetX, tile.offsetY, tile.width, tile.height);
float scale = m_image->getLevelScale(level);
Vector3f spacing = m_image->getSpacing();
auto image = Image::create(tile.width, tile.height, TYPE_UINT8, m_image->getNrOfChannels(), std::move(data));
image->setSpacing(Vector3f(
scale*spacing.x(),
scale*spacing.y(),
1.0f
));
// TODO Set transformation
SceneGraph::setParentNode(image, std::dynamic_pointer_cast<SpatialDataObject>(m_image));
if(m_fileHandle != nullptr && convertToRGB) {
// Data is stored as BGRA, need to delete alpha channel and reverse it
auto channelConverter = ImageChannelConverter::New();
channelConverter->setChannelsToRemove(false, false, false, true);
channelConverter->setReverseChannels(true);
channelConverter->setInputData(image);
return channelConverter->updateAndGetOutputData<Image>();
} else {
return image;
}
}
void ImagePyramidAccess::setPatch(int level, int x, int y, Image::pointer patch) {
if(m_tiffHandle == nullptr)
throw Exception("setPatch only available for TIFF backend ImagePyramids");
if(m_image->getLevelTileWidth(level) > patch->getWidth() || m_image->getLevelTileHeight(level) > patch->getHeight()) {
// Padding needed
auto paddedImage = Image::create(m_image->getLevelTileWidth(level), m_image->getLevelTileHeight(level), patch->getDataType(), m_image->getNrOfChannels());
if(m_image->getNrOfChannels() >= 3) {
paddedImage->fill(255);
} else {
paddedImage->fill(0);
}
auto device = std::dynamic_pointer_cast<OpenCLDevice>(DeviceManager::getInstance()->getDefaultDevice());
{
auto dest = paddedImage->getOpenCLImageAccess(ACCESS_READ_WRITE, device);
auto src = patch->getOpenCLImageAccess(ACCESS_READ, device);
device->getCommandQueue().enqueueCopyImage(*src->get2DImage(), *dest->get2DImage(),
createOrigoRegion(), createOrigoRegion(),
createRegion(patch->getSize()));
device->getCommandQueue().finish();
}
patch = paddedImage;
}
// Write tile to this level
auto patchAccess = patch->getImageAccess(ACCESS_READ);
auto data = (uchar*)patchAccess->get();
uint32_t tile_id;
{
std::lock_guard<std::mutex> lock(m_readMutex);
TIFFSetDirectory(m_tiffHandle, level);
TIFFWriteTile(m_tiffHandle, (void *) data, x, y, 0, 0);
TIFFCheckpointDirectory(m_tiffHandle);
tile_id = TIFFComputeTile(m_tiffHandle, x, y, 0, 0);
}
m_initializedPatchList.insert(std::to_string(level) + "-" + std::to_string(tile_id));
// Add patch to list of dirty patches, so the renderer can update it if needed
int levelWidth = m_image->getLevelWidth(level);
int levelHeight = m_image->getLevelHeight(level);
const int tilesX = m_image->getLevelTilesX(level);
const int tilesY = m_image->getLevelTilesY(level);
int patchIdX = std::floor(((float)x / levelWidth) * tilesX);
int patchIdY = std::floor(((float)y / levelHeight) * tilesY);
m_image->setDirtyPatch(level, patchIdX, patchIdY);
// TODO Propagate upwards
auto previousData = std::make_unique<uchar[]>(patch->getNrOfVoxels()*patch->getNrOfChannels());
std::memcpy(previousData.get(), data, patch->getNrOfVoxels()*patch->getNrOfChannels());
const auto channels = m_image->getNrOfChannels();
while(level < m_image->getNrOfLevels()-1) {
const auto previousTileWidth = m_image->getLevelTileWidth(level);
const auto previousTileHeight = m_image->getLevelTileHeight(level);
++level;
x /= 2;
y /= 2;
const auto tileWidth = m_image->getLevelTileWidth(level);
const auto tileHeight = m_image->getLevelTileHeight(level);
int offsetX = x % tileWidth > 0 ? 1 : 0;
int offsetY = y % tileHeight > 0 ? 1 : 0;
x -= offsetX*tileWidth/2;
y -= offsetY*tileHeight/2;
// Get existing tile. This gets the tile in which x, y is contained in, not where it starts..
auto newData = getPatchData(level, x, y, tileWidth, tileHeight);
// Downsample tile from previous level and add it to existing tile
for(int dy = 0; dy < tileHeight/2; ++dy) {
for(int dx = 0; dx < tileWidth/2; ++dx) {
newData[dx + offsetX*tileWidth/2 + (dy+offsetY*tileHeight/2)*tileWidth] =
(uchar)round((float)(previousData[dx*2 + dy*2*previousTileWidth] +
previousData[dx*2 + 1 + dy*2*previousTileWidth] +
previousData[dx*2 + 1 + (dy*2+1)*previousTileWidth] +
previousData[dx*2 + (dy*2+1)*previousTileWidth])/4);
}
}
{
std::lock_guard<std::mutex> lock(m_readMutex);
TIFFSetDirectory(m_tiffHandle, level);
TIFFWriteTile(m_tiffHandle, (void *) newData.get(), x, y, 0, 0);
TIFFCheckpointDirectory(m_tiffHandle);
tile_id = TIFFComputeTile(m_tiffHandle, x, y, 0, 0);
}
previousData = std::move(newData);
int levelWidth = m_image->getLevelWidth(level);
int levelHeight = m_image->getLevelHeight(level);
const int tilesX = m_image->getLevelTilesX(level);
const int tilesY = m_image->getLevelTilesY(level);
int patchIdX = std::floor(((float)x / levelWidth) * tilesX);
int patchIdY = std::floor(((float)y / levelHeight) * tilesY);
m_image->setDirtyPatch(level, patchIdX, patchIdY);
m_initializedPatchList.insert(std::to_string(level) + "-" + std::to_string(tile_id));
}
}
bool ImagePyramidAccess::isPatchInitialized(uint level, uint x, uint y) {
if(m_image->isPyramidFullyInitialized())
return true;
std::lock_guard<std::mutex> lock(m_readMutex);
TIFFSetDirectory(m_tiffHandle, level);
auto tile = TIFFComputeTile(m_tiffHandle, x, y, 0, 0);
return m_initializedPatchList.count(std::to_string(level) + "-" + std::to_string(tile)) > 0;
}
}
Improved storage and rendering for single-channel (segmentation) image pyramids
#include "ImagePyramidAccess.hpp"
#include <FAST/Data/ImagePyramid.hpp>
#include <FAST/Algorithms/ImageChannelConverter/ImageChannelConverter.hpp>
#include <FAST/Utility.hpp>
#include <openslide/openslide.h>
#include <tiffio.h>
#include <FAST/Data/Image.hpp>
#include <jpeglib.h>
namespace fast {
ImagePyramidAccess::ImagePyramidAccess(
std::vector<ImagePyramidLevel> levels,
openslide_t* fileHandle,
TIFF* tiffHandle,
std::ifstream* vsiHandle,
std::vector<vsi_tile_header>& vsiTiles,
std::shared_ptr<ImagePyramid> imagePyramid,
bool write,
std::unordered_set<std::string>& initializedPatchList,
std::mutex& readMutex) : m_initializedPatchList(initializedPatchList), m_readMutex(readMutex) {
if(levels.size() == 0)
throw Exception("Image pyramid has no levels");
m_image = imagePyramid;
m_levels = levels;
m_write = write;
m_fileHandle = fileHandle;
m_tiffHandle = tiffHandle;
m_vsiHandle = vsiHandle;
m_vsiTiles = vsiTiles;
}
void ImagePyramidAccess::release() {
m_image->accessFinished();
}
ImagePyramidAccess::~ImagePyramidAccess() {
release();
}
ImagePyramidPatch ImagePyramidAccess::getPatch(std::string tile) {
auto parts = split(tile, "_");
if(parts.size() != 3)
throw Exception("incorrect tile format");
int level = std::stoi(parts[0]);
int tile_x = std::stoi(parts[1]);
int tile_y = std::stoi(parts[2]);
return getPatch(level, tile_x, tile_y);
}
void jpegErrorExit(j_common_ptr cinfo) {
char jpegLastErrorMsg[JMSG_LENGTH_MAX];
// Create message
( *( cinfo->err->format_message ) ) ( cinfo, jpegLastErrorMsg );
throw std::runtime_error( jpegLastErrorMsg );
}
void ImagePyramidAccess::readVSITileToBuffer(vsi_tile_header tile, uchar* data) {
auto buffer = make_uninitialized_unique<char[]>(tile.numbytes);
// Reading VSI tiles is not thread safe
{
std::lock_guard<std::mutex> lock(m_readMutex);
m_vsiHandle->seekg(tile.offset);
m_vsiHandle->read(buffer.get(), tile.numbytes);
}
// TODO assuming JPEG here
jpeg_decompress_struct cinfo;
jpeg_error_mgr jerr; //error handling
jpeg_source_mgr src_mem;
jerr.error_exit = jpegErrorExit;
cinfo.err = jpeg_std_error(&jerr);
try {
jpeg_create_decompress(&cinfo);
jpeg_mem_src(&cinfo, (uchar*)buffer.get(), tile.numbytes);
int ret = jpeg_read_header(&cinfo, false);
if(ret != 1) {
throw Exception("Jpeg error..");
}
//cinfo.jpeg_color_space = JCS_YCbCr;
//cinfo.jpeg_color_space = JCS_RGB;
jpeg_start_decompress(&cinfo);
unsigned char* line = data;
while (cinfo.output_scanline < cinfo.output_height) {
jpeg_read_scanlines (&cinfo, &line, 1);
line += 3*cinfo.output_width;
}
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
} catch(std::exception &e) {
jpeg_destroy_decompress( &cinfo );
throw Exception("JPEG error: " + std::string(e.what())); // or return an error code
}
}
std::unique_ptr<uchar[]> ImagePyramidAccess::getPatchData(int level, int x, int y, int width, int height) {
const int levelWidth = m_image->getLevelWidth(level);
const int levelHeight = m_image->getLevelHeight(level);
const int channels = m_image->getNrOfChannels();
const int tileWidth = m_image->getLevelTileWidth(level);
const int tileHeight = m_image->getLevelTileHeight(level);
auto data = std::make_unique<uchar[]>(width*height*channels);
if(m_tiffHandle != nullptr) {
// Read all tiles within region, then crop
if(!isPatchInitialized(level, x, y)) {
// Tile has not be initialized, fill with zeros and return..
// TODO Do not try render these patches..
std::memset(data.get(), 0, width*height*channels);
return data;
}
if(width == tileWidth && height == tileHeight) {
std::lock_guard<std::mutex> lock(m_readMutex);
TIFFSetDirectory(m_tiffHandle, level);
int bytesRead = TIFFReadTile(m_tiffHandle, (void *) data.get(), x, y, 0, 0);
} else if(width < tileWidth || height < tileHeight) {
auto tileData = std::make_unique<uchar[]>(tileWidth*tileHeight*channels);
{
std::lock_guard<std::mutex> lock(m_readMutex);
TIFFSetDirectory(m_tiffHandle, level);
// In TIFF all tiles have the same size, thus they are padded..
int bytesRead = TIFFReadTile(m_tiffHandle, (void *) tileData.get(), x, y, 0, 0);
}
// Remove padding
for(int dy = 0; dy < height; ++dy) {
for(int dx = 0; dx < width; ++dx) {
data[dx + dy*width] = tileData[dx + dy*tileWidth];
}
}
} else if(width > tileWidth || height > tileHeight) {
// TODO implement
throw Exception("Encountered unqueal tile and request size. Not implemented. "
+ std::to_string(width) + " " + std::to_string(tileWidth) + " "
+ std::to_string(height) + " " + std::to_string(tileHeight)
);
throw NotImplementedException();
// TODO how to do this fast?
/*
int startTileX =;
int startTileY =;
int endTileX =;
int endTileY =;
auto dataBuffer = std::make_unique<char[]>(tileWidth * tileHeight * channels);
int offsetX =;
int offsetY =;
for (int x = startTileX; x <= endTileX; ++x) {
for (int y = startTileY; y <= endTileY; ++y) {
TIFFReadTile(m_tiffHandle, (void *) dataBuffer.get(), x, y, 0, 0);
for (int)
}
}
*/
}
} else if(m_fileHandle != nullptr) {
int scale = (float)m_image->getFullWidth()/levelWidth;
#ifndef WIN32
// HACK for black edge frames on ubuntu linux 20.04. This seems to be an issue with openslide or underlying libraries
if(level != 0) { // only occurs on levels != 0
// Reading scale pixels further in eliminates the problem for some reason...
x = x == 0 ? x+1 : x;
y = y == 0 ? y+1 : y;
}
#endif
openslide_read_region(m_fileHandle, (uint32_t*)data.get(), x * scale, y * scale, level, width, height);
} else if(!m_vsiTiles.empty()) {
if(width == tileWidth && height == tileHeight) {
vsi_tile_header tile;
bool found = false;
for(int i = 0; i < m_vsiTiles.size(); ++i) {
vsi_tile_header currentTile = m_vsiTiles[i];
if(currentTile.level != level)
continue;
if(currentTile.coord[0] != x / m_image->getLevelTileWidth(level) || currentTile.coord[1] != y / m_image->getLevelTileHeight(level))
continue;
tile = currentTile;
found = true;
break;
}
if(!found)
throw Exception("Could not find tile for getPathcData in VSI");
readVSITileToBuffer(tile, data.get());
} else {
std::vector<vsi_tile_header> tilesToRead;
int firstTileX = x / m_image->getLevelTileWidth(level);
int firstTileY = y / m_image->getLevelTileHeight(level);
int lastTileX = std::ceil((float)(x + width) / m_image->getLevelTileWidth(level));
int lastTileY = std::ceil((float)(y + height) / m_image->getLevelTileHeight(level));
// How many tiles we are supposed to have
const int targetNumberOfTiles = (lastTileX-firstTileX)*(lastTileY-firstTileY);
for(int i = 0; i < m_vsiTiles.size(); ++i) {
vsi_tile_header currentTile = m_vsiTiles[i];
if(currentTile.level != level)
continue;
if(
!((currentTile.coord[0] >= firstTileX && currentTile.coord[0] < lastTileX) &&
(currentTile.coord[1] >= firstTileY && currentTile.coord[1] < lastTileY)))
continue;
tilesToRead.push_back(currentTile);
}
if(tilesToRead.empty())
throw Exception("Tiles to ready empty");
auto fullTileBuffer = make_uninitialized_unique<uchar[]>(tileWidth*tileHeight*targetNumberOfTiles*channels);
if(tilesToRead.size() != targetNumberOfTiles) { // Some tiles are missing.. (edge case) fill with some blank value
if(channels > 1) {
std::memset(fullTileBuffer.get(), 255, tileWidth*tileHeight*targetNumberOfTiles*channels);
} else {
std::memset(fullTileBuffer.get(), 0, tileWidth*tileHeight*targetNumberOfTiles*channels);
}
}
const auto fullTileBufferWidth = (lastTileX-firstTileX)*tileWidth;
// Read tile to buffer
auto tileBuffer = make_uninitialized_unique<uchar[]>(tileWidth*tileHeight*channels); // assume full tiles of same size for all
for(auto tile : tilesToRead) {
const int tileX = (tile.coord[0]-firstTileX)*tileWidth;
const int tileY = (tile.coord[1]-firstTileY)*tileHeight;
readVSITileToBuffer(tile, tileBuffer.get());
// Stitch tile into full buffer
for(int cy = 0; cy < tileHeight; ++cy) {
for(int cx = 0; cx < tileWidth; ++cx) {
for(int channel = 0; channel < channels; ++channel) {
fullTileBuffer[(tileX + cx + (tileY + cy)*fullTileBufferWidth)*channels + channel] = tileBuffer[(cx + cy*tileWidth)*channels + channel];
}
}
}
}
// Crop the full buffer to data[]
const int offsetX = x - firstTileX*tileWidth;
const int offsetY = y - firstTileY*tileHeight;
for(int cy = offsetY; cy < offsetY + height; ++cy) {
for(int cx = offsetX; cx < offsetX + width; ++cx) {
for(int channel = 0; channel < channels; ++channel) {
data[(cx - offsetX + (cy - offsetY) * width)*channels + channel] = fullTileBuffer[(cx + cy * fullTileBufferWidth)*channels + channel];
}
}
}
}
} else {
auto levelData = m_levels[level];
for(int cy = y; cy < std::min(y + height, levelHeight); ++cy) {
for(int cx = x; cx < std::min(x + width, levelWidth); ++cx) {
for(int channel = 0; channel < channels; ++channel) {
data[(cx - x + (cy - y) * width)*channels + channel] = levelData.data[(cx + cy * levelWidth)*channels + channel];
}
}
}
}
return data;
}
ImagePyramidPatch ImagePyramidAccess::getPatch(int level, int tile_x, int tile_y) {
// Create patch
int levelWidth = m_image->getLevelWidth(level);
int levelHeight = m_image->getLevelHeight(level);
int levelTileWidth = m_image->getLevelTileWidth(level);
int levelTileHeight = m_image->getLevelTileHeight(level);
int tilesX = m_image->getLevelTilesX(level);
int tilesY = m_image->getLevelTilesY(level);
ImagePyramidPatch tile;
tile.offsetX = tile_x * levelTileWidth;
tile.offsetY = tile_y * levelTileHeight;
tile.width = levelTileWidth;
if(tile_x == tilesX - 1)
tile.width = levelWidth - tile.offsetX;
tile.height = levelTileHeight;
if(tile_y == tilesY - 1)
tile.height = levelHeight - tile.offsetY;
// Read the actual data
tile.data = getPatchData(level, tile.offsetX, tile.offsetY, tile.width, tile.height);
return tile;
}
std::shared_ptr<Image> ImagePyramidAccess::getLevelAsImage(int level) {
if(level < 0 || level >= m_image->getNrOfLevels())
throw Exception("Incorrect level given to getLevelAsImage" + std::to_string(level));
int width = m_image->getLevelWidth(level);
int height = m_image->getLevelHeight(level);
if(width > 16384 || height > 16384)
throw Exception("Image level is too large to convert into a FAST image");
return getPatchAsImage(level, 0, 0, width, height, true);
}
std::shared_ptr<Image> ImagePyramidAccess::getPatchAsImage(int level, int offsetX, int offsetY, int width, int height, bool convertToRGB) {
if(width > 16384 || height > 16384)
throw Exception("Image level is too large to convert into a FAST image");
if(offsetX < 0 || offsetY < 0 || width <= 0 || height <= 0)
throw Exception("Offset and size must be positive");
if(offsetX + width > m_image->getLevelWidth(level) || offsetY + height > m_image->getLevelHeight(level))
throw Exception("offset + size exceeds level size");
auto data = getPatchData(level, offsetX, offsetY, width, height);
float scale = m_image->getLevelScale(level);
auto spacing = m_image->getSpacing();
auto image = Image::create(width, height, TYPE_UINT8, m_image->getNrOfChannels(), std::move(data));
image->setSpacing(Vector3f(
spacing.x()*scale,
spacing.y()*scale,
1.0f
));
// Set transformation
auto T = Transform::create(Vector3f(offsetX*scale, offsetY*scale, 0.0f));
image->setTransform(T);
SceneGraph::setParentNode(image, std::dynamic_pointer_cast<SpatialDataObject>(m_image));
if(m_fileHandle != nullptr && convertToRGB) {
// Data is stored as BGRA, need to delete alpha channel and reverse it
auto channelConverter = ImageChannelConverter::New();
channelConverter->setChannelsToRemove(false, false, false, true);
channelConverter->setReverseChannels(true);
channelConverter->setInputData(image);
image = channelConverter->updateAndGetOutputData<Image>();
}
return image;
}
std::shared_ptr<Image> ImagePyramidAccess::getPatchAsImage(int level, int tileX, int tileY, bool convertToRGB) {
int levelWidth = m_image->getLevelWidth(level);
int levelHeight = m_image->getLevelHeight(level);
int tilesX = m_image->getLevelTilesX(level);
int tilesY = m_image->getLevelTilesY(level);
int levelTileWidth = m_image->getLevelTileWidth(level);
int levelTileHeight = m_image->getLevelTileHeight(level);
ImagePyramidPatch tile;
tile.offsetX = tileX * levelTileWidth;
tile.offsetY = tileY * levelTileHeight;
tile.width = levelTileWidth;
if(tileX == tilesX - 1)
tile.width = levelWidth - tile.offsetX;
tile.height = levelTileHeight;
if(tileY == tilesY - 1)
tile.height = levelHeight - tile.offsetY;
// Read the actual data
auto data = getPatchData(level, tile.offsetX, tile.offsetY, tile.width, tile.height);
float scale = m_image->getLevelScale(level);
Vector3f spacing = m_image->getSpacing();
auto image = Image::create(tile.width, tile.height, TYPE_UINT8, m_image->getNrOfChannels(), std::move(data));
image->setSpacing(Vector3f(
scale*spacing.x(),
scale*spacing.y(),
1.0f
));
// TODO Set transformation
SceneGraph::setParentNode(image, std::dynamic_pointer_cast<SpatialDataObject>(m_image));
if(m_fileHandle != nullptr && convertToRGB) {
// Data is stored as BGRA, need to delete alpha channel and reverse it
auto channelConverter = ImageChannelConverter::New();
channelConverter->setChannelsToRemove(false, false, false, true);
channelConverter->setReverseChannels(true);
channelConverter->setInputData(image);
return channelConverter->updateAndGetOutputData<Image>();
} else {
return image;
}
}
void ImagePyramidAccess::setPatch(int level, int x, int y, Image::pointer patch) {
if(m_tiffHandle == nullptr)
throw Exception("setPatch only available for TIFF backend ImagePyramids");
if(m_image->getLevelTileWidth(level) > patch->getWidth() || m_image->getLevelTileHeight(level) > patch->getHeight()) {
// Padding needed
auto paddedImage = Image::create(m_image->getLevelTileWidth(level), m_image->getLevelTileHeight(level), patch->getDataType(), m_image->getNrOfChannels());
if(m_image->getNrOfChannels() >= 3) {
paddedImage->fill(255);
} else {
paddedImage->fill(0);
}
auto device = std::dynamic_pointer_cast<OpenCLDevice>(DeviceManager::getInstance()->getDefaultDevice());
{
auto dest = paddedImage->getOpenCLImageAccess(ACCESS_READ_WRITE, device);
auto src = patch->getOpenCLImageAccess(ACCESS_READ, device);
device->getCommandQueue().enqueueCopyImage(*src->get2DImage(), *dest->get2DImage(),
createOrigoRegion(), createOrigoRegion(),
createRegion(patch->getSize()));
device->getCommandQueue().finish();
}
patch = paddedImage;
}
// Write tile to this level
auto patchAccess = patch->getImageAccess(ACCESS_READ);
auto data = (uchar*)patchAccess->get();
uint32_t tile_id;
{
std::lock_guard<std::mutex> lock(m_readMutex);
TIFFSetDirectory(m_tiffHandle, level);
TIFFWriteTile(m_tiffHandle, (void *) data, x, y, 0, 0);
TIFFCheckpointDirectory(m_tiffHandle);
tile_id = TIFFComputeTile(m_tiffHandle, x, y, 0, 0);
}
m_initializedPatchList.insert(std::to_string(level) + "-" + std::to_string(tile_id));
// Add patch to list of dirty patches, so the renderer can update it if needed
int levelWidth = m_image->getLevelWidth(level);
int levelHeight = m_image->getLevelHeight(level);
const int tilesX = m_image->getLevelTilesX(level);
const int tilesY = m_image->getLevelTilesY(level);
int patchIdX = std::floor(((float)x / levelWidth) * tilesX);
int patchIdY = std::floor(((float)y / levelHeight) * tilesY);
m_image->setDirtyPatch(level, patchIdX, patchIdY);
// Propagate upwards
auto previousData = std::make_unique<uchar[]>(patch->getNrOfVoxels()*patch->getNrOfChannels());
std::memcpy(previousData.get(), data, patch->getNrOfVoxels()*patch->getNrOfChannels());
const auto channels = m_image->getNrOfChannels();
while(level < m_image->getNrOfLevels()-1) {
const auto previousTileWidth = m_image->getLevelTileWidth(level);
const auto previousTileHeight = m_image->getLevelTileHeight(level);
++level;
x /= 2;
y /= 2;
const auto tileWidth = m_image->getLevelTileWidth(level);
const auto tileHeight = m_image->getLevelTileHeight(level);
int offsetX = x % tileWidth > 0 ? 1 : 0;
int offsetY = y % tileHeight > 0 ? 1 : 0;
x -= offsetX*tileWidth/2;
y -= offsetY*tileHeight/2;
// Get existing tile. This gets the tile in which x, y is contained in, not where it starts..
auto newData = getPatchData(level, x, y, tileWidth, tileHeight);
// Downsample tile from previous level and add it to existing tile
if(m_image->getNrOfChannels() >= 3) {
// Use average if RGB(A) image
for(int dy = 0; dy < tileHeight/2; ++dy) {
for(int dx = 0; dx < tileWidth/2; ++dx) {
newData[dx + offsetX*tileWidth/2 + (dy+offsetY*tileHeight/2)*tileWidth] =
(uchar)round((float)(previousData[dx*2 + dy*2*previousTileWidth] +
previousData[dx*2 + 1 + dy*2*previousTileWidth] +
previousData[dx*2 + 1 + (dy*2+1)*previousTileWidth] +
previousData[dx*2 + (dy*2+1)*previousTileWidth])/4);
}
}
} else {
// Use majority vote if single channel image.
for(int dy = 0; dy < tileHeight/2; ++dy) {
for(int dx = 0; dx < tileWidth/2; ++dx) {
/*
// This is more correct, but 100 times slower than just doing max.
std::vector<uchar> list = {
previousData[dx*2 + dy*2*previousTileWidth],
previousData[dx*2 + 1 + dy*2*previousTileWidth],
previousData[dx*2 + 1 + (dy*2+1)*previousTileWidth],
previousData[dx*2 + (dy*2+1)*previousTileWidth]
};
std::sort(list.begin(), list.end());
if(list[0] == list[1]) { // If there is more than of element 0, it should be placed as element 1
newData[dx + offsetX*tileWidth/2 + (dy+offsetY*tileHeight/2)*tileWidth] = list[0];
} else { // If not, it means that there is more than 1 of element 1, OR all 4 values are different and its no matter which is picked.
newData[dx + offsetX*tileWidth/2 + (dy+offsetY*tileHeight/2)*tileWidth] = list[2];
}*/
// Just do max? 0.006 milliseconds
uchar list[4] = {
previousData[dx*2 + dy*2*previousTileWidth],
previousData[dx*2 + 1 + dy*2*previousTileWidth],
previousData[dx*2 + 1 + (dy*2+1)*previousTileWidth],
previousData[dx*2 + (dy*2+1)*previousTileWidth]
};
newData[dx + offsetX*tileWidth/2 + (dy+offsetY*tileHeight/2)*tileWidth] = std::max(std::max(std::max(list[0], list[1]), list[2]), list[3]);
}
}
}
{
std::lock_guard<std::mutex> lock(m_readMutex);
TIFFSetDirectory(m_tiffHandle, level);
TIFFWriteTile(m_tiffHandle, (void *) newData.get(), x, y, 0, 0);
TIFFCheckpointDirectory(m_tiffHandle);
tile_id = TIFFComputeTile(m_tiffHandle, x, y, 0, 0);
}
previousData = std::move(newData);
int levelWidth = m_image->getLevelWidth(level);
int levelHeight = m_image->getLevelHeight(level);
const int tilesX = m_image->getLevelTilesX(level);
const int tilesY = m_image->getLevelTilesY(level);
int patchIdX = std::floor(((float)x / levelWidth) * tilesX);
int patchIdY = std::floor(((float)y / levelHeight) * tilesY);
m_image->setDirtyPatch(level, patchIdX, patchIdY);
m_initializedPatchList.insert(std::to_string(level) + "-" + std::to_string(tile_id));
}
}
bool ImagePyramidAccess::isPatchInitialized(uint level, uint x, uint y) {
if(m_image->isPyramidFullyInitialized())
return true;
std::lock_guard<std::mutex> lock(m_readMutex);
TIFFSetDirectory(m_tiffHandle, level);
auto tile = TIFFComputeTile(m_tiffHandle, x, y, 0, 0);
return m_initializedPatchList.count(std::to_string(level) + "-" + std::to_string(tile)) > 0;
}
} |
/* -------------------------------------------------------------------------- *
* OpenSim: Component.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2017 Stanford University and the Authors *
* Author(s): Ajay Seth, Michael Sherman *
* Contributor(s): Ayman Habib *
* *
* 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. *
* -------------------------------------------------------------------------- */
// INCLUDES
#include "Component.h"
#include "OpenSim/Common/IO.h"
#include "XMLDocument.h"
#include <unordered_map>
#include <set>
#include <regex>
using namespace SimTK;
namespace OpenSim {
//==============================================================================
// COMPONENT MEASURE
//==============================================================================
// Every OpenSim::Component is associated with a Simbody Measure of type
// ComponentMeasure defined here. This provides a full set of realize()
// methods for performing computations with System resources that are maintained
// at the Component base level, such as calculating state derivatives.
template <class T>
class ComponentMeasure : public SimTK::Measure_<T> {
public:
SimTK_MEASURE_HANDLE_PREAMBLE(ComponentMeasure, SimTK::Measure_<T>);
ComponentMeasure(SimTK::Subsystem& sub,
const OpenSim::Component& mc)
: SimTK::Measure_<T>(sub, new Implementation(mc),
SimTK::AbstractMeasure::SetHandle()) {}
SimTK_MEASURE_HANDLE_POSTSCRIPT(ComponentMeasure, SimTK::Measure_<T>);
};
template <class T>
class ComponentMeasure<T>::Implementation
: public SimTK::Measure_<T>::Implementation {
public:
// Don't allocate a value cache entry since this measure's value is
// just a dummy.
explicit Implementation(const Component& c)
: SimTK::Measure_<T>::Implementation(0), _Component(c) {}
// Implementations of Measure_<T>::Implementation virtual methods.
Implementation* cloneVirtual() const override final
{ return new Implementation(*this); }
int getNumTimeDerivativesVirtual() const override final {return 0;}
SimTK::Stage getDependsOnStageVirtual(int order) const override final
{ return SimTK::Stage::Empty; }
const T& getUncachedValueVirtual
(const SimTK::State& s, int derivOrder) const override final
{ return this->getValueZero(); }
void realizeMeasureTopologyVirtual(SimTK::State& s) const override final
{ _Component.extendRealizeTopology(s); }
void realizeMeasureModelVirtual(SimTK::State& s) const override final
{ _Component.extendRealizeModel(s); }
void realizeMeasureInstanceVirtual(const SimTK::State& s)
const override final
{ _Component.extendRealizeInstance(s); }
void realizeMeasureTimeVirtual(const SimTK::State& s) const override final
{ _Component.extendRealizeTime(s); }
void realizeMeasurePositionVirtual(const SimTK::State& s)
const override final
{ _Component.extendRealizePosition(s); }
void realizeMeasureVelocityVirtual(const SimTK::State& s)
const override final
{ _Component.extendRealizeVelocity(s); }
void realizeMeasureDynamicsVirtual(const SimTK::State& s)
const override final
{ _Component.extendRealizeDynamics(s); }
void realizeMeasureAccelerationVirtual(const SimTK::State& s)
const override final
{ _Component.extendRealizeAcceleration(s); }
void realizeMeasureReportVirtual(const SimTK::State& s)
const override final
{ _Component.extendRealizeReport(s); }
private:
const Component& _Component;
};
//==============================================================================
// COMPONENT
//==============================================================================
Component::Component() : Object()
{
constructProperty_components();
}
Component::Component(const std::string& fileName, bool updFromXMLNode)
: Object(fileName, updFromXMLNode)
{
constructProperty_components();
}
Component::Component(SimTK::Xml::Element& element) : Object(element)
{
constructProperty_components();
}
bool Component::isComponentInOwnershipTree(const Component* subcomponent) const {
//get to the root Component
const Component* root = this;
while (root->hasOwner()) {
root = &(root->getOwner());
}
// if the root has no immediate subcomponents do not bother
// checking if the subcomponent is in the ownership tree
if ((root->getNumImmediateSubcomponents() > 0)) {
auto components = root->getComponentList<Component>();
for (auto& c : components) {
if (subcomponent == &c) return true;
}
}
return false;
}
void Component::addComponent(Component* subcomponent)
{
OPENSIM_THROW_IF(isComponentInOwnershipTree(subcomponent),
ComponentAlreadyPartOfOwnershipTree,
subcomponent->getName(), getName());
updProperty_components().adoptAndAppendValue(subcomponent);
finalizeFromProperties();
prependComponentPathToConnecteePath(*subcomponent);
// allow the derived Component to perform secondary operations
// in response to the inclusion of the subcomponent
extendAddComponent(subcomponent);
}
void Component::prependComponentPathToConnecteePath(
Component& subcomponent) {
const std::string compPath = subcomponent.getAbsolutePathString();
const Component& root = subcomponent.getRoot();
for (auto& comp : subcomponent.updComponentList()) {
for (auto& it : comp._socketsTable) {
if (!root.hasComponent(it.second->getConnecteePath()))
it.second->prependComponentPathToConnecteePath(compPath);
}
for (auto& it : comp._inputsTable) {
it.second->prependComponentPathToConnecteePath(compPath);
}
}
}
void Component::finalizeFromProperties()
{
reset();
// last opportunity to modify Object names based on properties
if (!hasOwner()) {
// only call when Component is root since method is recursive
makeObjectNamesConsistentWithProperties();
}
// TODO use a flag to set whether we are lenient on having nameless
// Components. For backward compatibility we need to be able to
// handle nameless components so assign them their class name
// - aseth
if (getName().empty()) {
setName(IO::Lowercase(getConcreteClassName()));
}
OPENSIM_THROW_IF( getName().empty(), ComponentHasNoName,
getConcreteClassName() );
ComponentPath cp;
OPENSIM_THROW_IF( !cp.isLegalPathElement(getName()), InvalidComponentName,
getName(), cp.getInvalidChars(), getConcreteClassName());
for (auto& comp : _memberSubcomponents) {
comp->setOwner(*this);
}
for (auto& comp : _adoptedSubcomponents) {
comp->setOwner(*this);
}
// Provide sockets, inputs, and outputs with a pointer to its component
// (this) so that they can invoke the component's methods.
for (auto& it : _socketsTable) {
it.second->setOwner(*this);
// Let the Socket handle any errors in the connectee_name property.
it.second->checkConnecteePathProperty();
}
for (auto& it : _inputsTable) {
it.second->setOwner(*this);
// Let the Socket handle any errors in the connectee_name property.
it.second->checkConnecteePathProperty();
}
for (auto& it : _outputsTable) {
it.second->setOwner(*this);
}
markPropertiesAsSubcomponents();
componentsFinalizeFromProperties();
// The following block is used to ensure that deserialized names of
// Components are unique so they can be used to unambiguously locate
// and connect all loaded Components. If a duplicate is encountered,
// it is assigned a unique name.
auto subs = getImmediateSubcomponents();
std::set<std::string> names{};
// increment the count of duplicates to use as a unique suffix
int count{ 0 };
// temp variable to hold the unique name used to rename a duplicate
std::string uniqueName{};
for (auto& sub : subs) {
const std::string& name = sub->getName();
// reset duplicate count and search name
count = 0;
uniqueName = name;
// while the name is still not unique keep incrementing the count
while (names.find(uniqueName) != names.cend()) {
// In the future this should become an Exception
//OPENSIM_THROW(SubcomponentsWithDuplicateName, getName(), searchName);
// for now, rename the duplicately named subcomponent
// but first test the uniqueness of the name (the while condition)
uniqueName = name + "_" + std::to_string(count++);
}
if (count > 0) { // if a duplicate
// Warn of the problem
log_warn("{} '{}' has subcomponents with duplicate name '{}'. "
"The duplicate is being renamed to '{}'.",
getConcreteClassName(), getName(), name, uniqueName);
// Now rename the subcomponent with its verified unique name
Component* mutableSub = const_cast<Component *>(sub.get());
mutableSub->setName(uniqueName);
}
// keep track of unique names
names.insert(uniqueName);
}
// End of duplicate finding and renaming.
extendFinalizeFromProperties();
setObjectIsUpToDateWithProperties();
}
// Base class implementation of virtual method.
// Call finalizeFromProperties on all subcomponents
void Component::componentsFinalizeFromProperties() const
{
for (auto& comp : _memberSubcomponents) {
const_cast<Component*>(comp.get())
->finalizeFromProperties();
}
for (auto& comp : _propertySubcomponents) {
const_cast<Component*>(comp.get())
->finalizeFromProperties();
}
for (auto& comp : _adoptedSubcomponents) {
const_cast<Component*>(comp.get())
->finalizeFromProperties();
}
}
// Base class implementation of non-virtual finalizeConnections method.
void Component::finalizeConnections(Component& root)
{
if (!isObjectUpToDateWithProperties()){
// if edits occur between construction and connect() this is
// the last chance to finalize before addToSystem.
finalizeFromProperties();
}
for (auto& it : _socketsTable) {
auto& socket = it.second;
try {
socket->finalizeConnection(root);
}
catch (const std::exception& x) {
OPENSIM_THROW_FRMOBJ(Exception, "Failed to connect Socket '" +
socket->getName() + "' of type " +
socket->getConnecteeTypeName() +
" (details: " + x.what() + ").");
}
}
for (auto& it : _inputsTable) {
auto& input = it.second;
try {
input->finalizeConnection(root);
}
catch (const std::exception& x) {
OPENSIM_THROW_FRMOBJ(Exception, "Failed to connect Input '" +
input->getName() + "' of type " + input->getConnecteeTypeName()
+ " (details: " + x.what() + ").");
}
}
// Allow derived Components to handle/check their connections and also
// override the order in which its subcomponents are ordered when
// adding subcomponents to the System
extendFinalizeConnections(root);
// Allow subcomponents to form their connections
componentsFinalizeConnections(root);
// Forming connections changes the Socket which is a property
// Remark as upToDate.
setObjectIsUpToDateWithProperties();
}
// invoke connect on all (sub)components of this component
void Component::componentsFinalizeConnections(Component& root)
{
// enable the subcomponents the opportunity to connect themselves
for (unsigned int i = 0; i<_memberSubcomponents.size(); ++i) {
_memberSubcomponents[i].upd()->finalizeConnections(root);
}
for(unsigned int i=0; i<_propertySubcomponents.size(); ++i){
_propertySubcomponents[i].get()->finalizeConnections(root);
}
for (unsigned int i = 0; i<_adoptedSubcomponents.size(); ++i) {
_adoptedSubcomponents[i].upd()->finalizeConnections(root);
}
}
void Component::clearConnections()
{
// First give the subcomponents the opportunity to disconnect themselves
for (unsigned int i = 0; i<_memberSubcomponents.size(); i++) {
_memberSubcomponents[i]->clearConnections();
}
for (unsigned int i = 0; i<_propertySubcomponents.size(); i++){
_propertySubcomponents[i]->clearConnections();
}
for (unsigned int i = 0; i<_adoptedSubcomponents.size(); i++) {
_adoptedSubcomponents[i]->clearConnections();
}
//Now cycle through and disconnect all sockets for this component
for (auto& it : _socketsTable) {
it.second->disconnect();
}
// Must also clear the input's connections.
for (auto& it : _inputsTable) {
it.second->disconnect();
}
//now clear all the stored system indices from this component
reset();
}
void Component::addToSystem(SimTK::MultibodySystem& system) const
{
// If being asked to be added to the same System that it is already
// a part, there is nothing to be done.
if (hasSystem() && (&getSystem() == &system)) {
return;
}
baseAddToSystem(system);
extendAddToSystem(system);
componentsAddToSystem(system);
extendAddToSystemAfterSubcomponents(system);
}
// Base class implementation of virtual method.
// Every Component owns an underlying SimTK::Measure
// which is a ComponentMeasure<T> and is added to the System's default
// subsystem. That measure is used only for the side effect of its realize()
// methods being called; its value is not used.
void Component::baseAddToSystem(SimTK::MultibodySystem& system) const
{
if (!isObjectUpToDateWithProperties()) {
std::string msg = "Component " + getConcreteClassName() + "::" + getName();
msg += " cannot extendAddToSystem until it is up-to-date with its properties.";
throw Exception(msg);
}
// Clear cached list of all related StateVariables if any from a previous
// System.
_allStateVariables.clear();
// Briefly get write access to the Component to record some
// information associated with the System; that info is const after this.
Component* mutableThis = const_cast<Component *>(this);
mutableThis->_system = system;
// Allocate the ComponentMeasure, point it to this Component for
// making realize() calls, and add it to the system's default subsystem.
ComponentMeasure<double> mcMeasure(system.updDefaultSubsystem(), *this);
mutableThis->_simTKcomponentIndex = mcMeasure.getSubsystemMeasureIndex();
}
void Component::componentsAddToSystem(SimTK::MultibodySystem& system) const
{
// If _orderedSubcomponents is specified, then use this Component's
// specification for the order in which subcomponents are added. At a
// minimum the order for all immediate subcomponents must be specified.
if (_orderedSubcomponents.size() >= getNumImmediateSubcomponents()) {
for (const auto& compRef : _orderedSubcomponents) {
compRef->addToSystem(system);
}
}
else if (_orderedSubcomponents.size() == 0) {
// Otherwise, invoke on all immediate subcomponents in tree order
auto mySubcomponents = getImmediateSubcomponents();
for (const auto& compRef : mySubcomponents) {
compRef->addToSystem(system);
}
}
else {
OPENSIM_THROW_FRMOBJ(Exception,
"_orderedSubcomponents specified, but its size does not reflect the "
"the number of immediate subcomponents. Verify that you have included "
"all immediate subcomponents in the ordered list."
)
}
}
void Component::initStateFromProperties(SimTK::State& state) const
{
extendInitStateFromProperties(state);
componentsInitStateFromProperties(state);
}
void Component::componentsInitStateFromProperties(SimTK::State& state) const
{
for (unsigned int i = 0; i<_memberSubcomponents.size(); ++i)
_memberSubcomponents[i]->initStateFromProperties(state);
for (unsigned int i = 0; i<_propertySubcomponents.size(); ++i)
_propertySubcomponents[i]->initStateFromProperties(state);
for (unsigned int i = 0; i<_adoptedSubcomponents.size(); ++i)
_adoptedSubcomponents[i]->initStateFromProperties(state);
}
void Component::setPropertiesFromState(const SimTK::State& state)
{
extendSetPropertiesFromState(state);
componentsSetPropertiesFromState(state);
}
void Component::componentsSetPropertiesFromState(const SimTK::State& state)
{
for (unsigned int i = 0; i<_memberSubcomponents.size(); ++i)
_memberSubcomponents[i]->setPropertiesFromState(state);
for (unsigned int i = 0; i<_propertySubcomponents.size(); ++i)
_propertySubcomponents[i]->setPropertiesFromState(state);
for (unsigned int i = 0; i<_adoptedSubcomponents.size(); ++i)
_adoptedSubcomponents[i]->setPropertiesFromState(state);
}
// Base class implementation of virtual method. Note that we're not handling
// subcomponents here; this method gets called from extendRealizeAcceleration()
// which will be invoked for each (sub) component by its own ComponentMeasure.
void Component::computeStateVariableDerivatives(const SimTK::State& s) const
{
int nsv = getNumStateVariablesAddedByComponent();
if(nsv > 0){
int nasv = 0;
std::map<std::string, StateVariableInfo>::const_iterator it;
for(it = _namedStateVariableInfo.begin();
it != _namedStateVariableInfo.end(); ++it){
const StateVariable& sv = *it->second.stateVariable;
const AddedStateVariable *asv =
dynamic_cast<const AddedStateVariable *>(&sv);
if(asv) nasv++;
}
if(nasv > 0){
std::stringstream msg;
msg << "Component " + getConcreteClassName()+"::"+getName();
msg << " added " << nasv << " state variables and ";
msg << " must specify their derivatives." << std::endl;
throw Exception(msg.str());
}
}
}
void Component::
addModelingOption(const std::string& optionName, int maxFlagValue) const
{
// don't add modeling option if there is another state with the same
// name for this component
std::map<std::string, ModelingOptionInfo>::const_iterator it;
it = _namedModelingOptionInfo.find(optionName);
if(it != _namedModelingOptionInfo.end())
throw Exception("Component::addModelingOption: Modeling option '"
+ optionName + "' already exists.");
// assign a "slot" for a modeling option by name
// modeling option index will be invalid by default
// upon allocation during realizeTopology the index will be set
_namedModelingOptionInfo[optionName] = ModelingOptionInfo(maxFlagValue);
}
void Component::addStateVariable(const std::string& stateVariableName,
const SimTK::Stage& invalidatesStage,
bool isHidden) const
{
if( (invalidatesStage < Stage::Position) ||
(invalidatesStage > Stage::Dynamics)) {
throw Exception("Component::addStateVariable: invalidatesStage "
"must be Position, Velocity or Dynamics.");
}
// Allocate space for a new state variable
AddedStateVariable* asv =
new AddedStateVariable(stateVariableName, *this, invalidatesStage, isHidden);
// Add it to the Component and let it take ownership
addStateVariable(asv);
}
void Component::addStateVariable(Component::StateVariable* stateVariable) const
{
const std::string& stateVariableName = stateVariable->getName();
// don't add state if there is another state variable with the same name
// for this component
std::map<std::string, StateVariableInfo>::const_iterator it;
it = _namedStateVariableInfo.find(stateVariableName);
if(it != _namedStateVariableInfo.end()){
throw Exception("Component::addStateVariable: State variable '" +
stateVariableName + "' already exists.");
}
int order = (int)_namedStateVariableInfo.size();
// assign a "slot" for a state variable by name
// state variable index will be invalid by default
// upon allocation during realizeTopology the index will be set
_namedStateVariableInfo[stateVariableName] =
StateVariableInfo(stateVariable, order);
const AddedStateVariable* asv =
dynamic_cast<const Component::AddedStateVariable *>(stateVariable);
// Now automatically add a cache variable to hold the derivative
// to enable a similar interface for setting and getting the derivatives
// based on the creator specified state name
if(asv){
addCacheVariable(stateVariableName+"_deriv", 0.0, Stage::Dynamics);
}
}
void Component::addDiscreteVariable(const std::string& discreteVariableName,
SimTK::Stage invalidatesStage) const
{
// don't add discrete var if there is another discrete variable with the
// same name for this component
std::map<std::string, DiscreteVariableInfo>::const_iterator it;
it = _namedDiscreteVariableInfo.find(discreteVariableName);
if(it != _namedDiscreteVariableInfo.end()){
throw Exception("Component::addDiscreteVariable: discrete variable '" +
discreteVariableName + "' already exists.");
}
// assign "slots" for the discrete variables by name
// discrete variable indices will be invalid by default
// upon allocation during realizeTopology the indices will be set
_namedDiscreteVariableInfo[discreteVariableName] =
DiscreteVariableInfo(invalidatesStage);
}
// Get the value of a ModelingOption flag for this Component.
int Component::
getModelingOption(const SimTK::State& s, const std::string& name) const
{
std::map<std::string, ModelingOptionInfo>::const_iterator it;
it = _namedModelingOptionInfo.find(name);
if(it != _namedModelingOptionInfo.end()) {
SimTK::DiscreteVariableIndex dvIndex = it->second.index;
return SimTK::Value<int>::downcast(
getDefaultSubsystem().getDiscreteVariable(s, dvIndex)).get();
} else {
std::stringstream msg;
msg << "Component::getModelingOption: ERR- name '" << name
<< "' not found.\n "
<< "for component '"<< getName() << "' of type "
<< getConcreteClassName();
throw Exception(msg.str(),__FILE__,__LINE__);
return -1;
}
}
// Set the value of a discrete variable allocated by this Component by name.
void Component::
setModelingOption(SimTK::State& s, const std::string& name, int flag) const
{
std::map<std::string, ModelingOptionInfo>::const_iterator it;
it = _namedModelingOptionInfo.find(name);
if(it != _namedModelingOptionInfo.end()) {
SimTK::DiscreteVariableIndex dvIndex = it->second.index;
if(flag > it->second.maxOptionValue){
std::stringstream msg;
msg << "Component::setModelingOption: "<< name
<< " flag cannot exceed "<< it->second.maxOptionValue <<".\n ";
throw Exception(msg.str(),__FILE__,__LINE__);
}
SimTK::Value<int>::downcast(
getDefaultSubsystem().updDiscreteVariable(s, dvIndex)).upd() = flag;
} else {
std::stringstream msg;
msg << "Component::setModelingOption: modeling option " << name
<< " not found.\n ";
throw Exception(msg.str(),__FILE__,__LINE__);
}
}
unsigned Component::printComponentsMatching(const std::string& substring) const
{
auto components = getComponentList();
components.setFilter(ComponentFilterAbsolutePathNameContainsString(substring));
unsigned count = 0;
for (const auto& comp : components) {
log_cout(comp.getAbsolutePathString());
++count;
}
return count;
}
int Component::getNumStateVariables() const
{
// Must have already called initSystem.
OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem);
//Get the number of state variables added (or exposed) by this Component
int ns = getNumStateVariablesAddedByComponent();
// And then include the states of its subcomponents
for (unsigned int i = 0; i<_memberSubcomponents.size(); i++)
ns += _memberSubcomponents[i]->getNumStateVariables();
for(unsigned int i=0; i<_propertySubcomponents.size(); i++)
ns += _propertySubcomponents[i]->getNumStateVariables();
for (unsigned int i = 0; i<_adoptedSubcomponents.size(); i++)
ns += _adoptedSubcomponents[i]->getNumStateVariables();
return ns;
}
const Component& Component::getOwner() const
{
if (!hasOwner()) {
std::string msg = "Component '" + getName() + "'::getOwner(). " +
"Has no owner assigned.\n" +
"Make sure the component was added to the Model " +
"(or another component).";
throw Exception(msg);
}
return _owner.getRef();
}
bool Component::hasOwner() const
{
return !_owner.empty();
}
const Component& Component::getRoot() const {
const Component* root = this;
while (root->hasOwner()) {
root = &root->getOwner();
}
return *root;
}
void Component::setOwner(const Component& owner)
{
if (&owner == this) {
std::string msg = "Component '" + getName() + "'::setOwner(). " +
"Attempted to set itself as its owner.";
throw Exception(msg);
}
else if (_owner.get() == &owner) {
return;
}
_owner.reset(&owner);
}
std::string Component::getAbsolutePathString() const
{
if (!hasOwner()) return "/";
std::string absPathName("/" + getName());
const Component* up = this;
while (up && up->hasOwner()) {
up = &up->getOwner();
if (up->hasOwner())
absPathName.insert(0, "/" + up->getName());
}
return absPathName;
}
ComponentPath Component::getAbsolutePath() const
{
if (!hasOwner()) return ComponentPath({}, true);
std::vector<std::string> pathVec;
pathVec.push_back(getName());
const Component* up = this;
while (up && up->hasOwner()) {
up = &up->getOwner();
if (up->hasOwner())
pathVec.insert(pathVec.begin(), up->getName());
}
return ComponentPath(pathVec, true);
}
std::string Component::getRelativePathString(const Component& wrt) const
{
return getRelativePath(wrt).toString();
}
ComponentPath Component::getRelativePath(const Component& wrt) const
{
ComponentPath thisP = getAbsolutePath();
ComponentPath wrtP = wrt.getAbsolutePath();
return thisP.formRelativePath(wrtP);
}
const Component::StateVariable* Component::
traverseToStateVariable(const std::string& pathName) const
{
// Must have already called initSystem.
OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem);
ComponentPath svPath(pathName);
const StateVariable* found = nullptr;
if (svPath.getNumPathLevels() == 1) {
// There was no slash. The state variable should be in this component.
auto it = _namedStateVariableInfo.find(pathName);
if (it != _namedStateVariableInfo.end()) {
return it->second.stateVariable.get();
}
} else if (svPath.getNumPathLevels() > 1) {
const auto& compPath = svPath.getParentPath();
const Component* comp = traversePathToComponent<Component>(compPath);
if (comp) {
// This is the leaf of the path:
const auto& varName = svPath.getComponentName();
found = comp->traverseToStateVariable(varName);
}
}
return found;
}
// Get the names of "continuous" state variables maintained by the Component and
// its subcomponents.
Array<std::string> Component::getStateVariableNames() const
{
// Must have already called initSystem.
OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem);
Array<std::string> stateNames = getStateVariableNamesAddedByComponent();
for (int i = 0; i < stateNames.size(); ++i) {
stateNames[i] = (getAbsolutePathString() + "/" + stateNames[i]);
}
for (auto& comp : getComponentList<Component>()) {
const std::string& pathName = comp.getAbsolutePathString();// *this);
Array<std::string> subStateNames =
comp.getStateVariableNamesAddedByComponent();
for (int i = 0; i < subStateNames.size(); ++i) {
stateNames.append(pathName + "/" + subStateNames[i]);
}
}
return stateNames;
}
// Get the value of a state variable allocated by this Component.
double Component::
getStateVariableValue(const SimTK::State& s, const std::string& name) const
{
// Must have already called initSystem.
OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem);
// find the state variable with this component or its subcomponents
const StateVariable* rsv = traverseToStateVariable(name);
if (rsv) {
return rsv->getValue(s);
}
std::stringstream msg;
msg << "Component::getStateVariableValue: ERR- state named '" << name
<< "' not found in " << getName() << " of type " << getConcreteClassName();
throw Exception(msg.str(),__FILE__,__LINE__);
return SimTK::NaN;
}
// Get the value of a state variable derivative computed by this Component.
double Component::
getStateVariableDerivativeValue(const SimTK::State& state,
const std::string& name) const
{
// Must have already called initSystem.
OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem);
computeStateVariableDerivatives(state);
std::map<std::string, StateVariableInfo>::const_iterator it;
it = _namedStateVariableInfo.find(name);
if(it != _namedStateVariableInfo.end()) {
return it->second.stateVariable->getDerivative(state);
}
else{
// otherwise find the component that variable belongs to
const StateVariable* rsv = traverseToStateVariable(name);
if (rsv) {
return rsv->getDerivative(state);
}
}
std::stringstream msg;
msg << "Component::getStateVariableDerivative: ERR- variable name '" << name
<< "' not found.\n "
<< getName() << " of type " << getConcreteClassName()
<< " has " << getNumStateVariables() << " states.";
throw Exception(msg.str(),__FILE__,__LINE__);
return SimTK::NaN;
}
// Set the value of a state variable allocated by this Component given its name
// for this component.
void Component::
setStateVariableValue(State& s, const std::string& name, double value) const
{
// Must have already called initSystem.
OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem);
// find the state variable
const StateVariable* rsv = traverseToStateVariable(name);
if(rsv){ // find required rummaging through the state variable names
return rsv->setValue(s, value);
}
std::stringstream msg;
msg << "Component::setStateVariable: ERR- state named '" << name
<< "' not found in " << getName() << " of type "
<< getConcreteClassName() << ".\n";
throw Exception(msg.str(),__FILE__,__LINE__);
}
bool Component::isAllStatesVariablesListValid() const
{
int nsv = getNumStateVariables();
// Consider the list of all StateVariables to be valid if all of
// the following conditions are true:
// 1. Component is up-to-date with its Properties
// 2. a System has been associated with the list of StateVariables
// 3. The list of all StateVariables is correctly sized (initialized)
// 4. The System associated with the StateVariables is the current System
// TODO: Enable the isObjectUpToDateWithProperties() check when computing
// the path of the GeomtryPath does not involve updating its PathPointSet.
// This change dirties the GeometryPath which is a property of a Muscle which
// is property of the Model. Therefore, during integration the Model is not
// up-to-date and this causes a rebuilding of the cached StateVariables list.
// See GeometryPath::computePath() for the corresponding TODO that must be
// addressed before we can re-enable the isObjectUpToDateWithProperties
// check.
// It has been verified that the adding Components will invalidate the state
// variables associated with the Model and force the list to be rebuilt.
bool valid = //isObjectUpToDateWithProperties() && // 1.
!_statesAssociatedSystem.empty() && // 2.
(int)_allStateVariables.size() == nsv && // 3.
getSystem().isSameSystem(_statesAssociatedSystem.getRef()); // 4.
return valid;
}
// Get all values of the state variables allocated by this Component. Includes
// state variables allocated by its subcomponents.
SimTK::Vector Component::
getStateVariableValues(const SimTK::State& state) const
{
// Must have already called initSystem.
OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem);
int nsv = getNumStateVariables();
// if the StateVariables are invalid (see above) rebuild the list
if (!isAllStatesVariablesListValid()) {
_statesAssociatedSystem.reset(&getSystem());
_allStateVariables.clear();
_allStateVariables.resize(nsv);
Array<std::string> names = getStateVariableNames();
for (int i = 0; i < nsv; ++i)
_allStateVariables[i].reset(traverseToStateVariable(names[i]));
}
Vector stateVariableValues(nsv, SimTK::NaN);
for(int i=0; i<nsv; ++i){
stateVariableValues[i]= _allStateVariables[i]->getValue(state);
}
return stateVariableValues;
}
// Set all values of the state variables allocated by this Component. Includes
// state variables allocated by its subcomponents.
void Component::
setStateVariableValues(SimTK::State& state,
const SimTK::Vector& values) const
{
// Must have already called initSystem.
OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem);
int nsv = getNumStateVariables();
SimTK_ASSERT(values.size() == nsv,
"Component::setStateVariableValues() number values does not match the "
"number of state variables.");
// if the StateVariables are invalid (see above) rebuild the list
if (!isAllStatesVariablesListValid()) {
_statesAssociatedSystem.reset(&getSystem());
_allStateVariables.clear();
_allStateVariables.resize(nsv);
Array<std::string> names = getStateVariableNames();
for (int i = 0; i < nsv; ++i)
_allStateVariables[i].reset(traverseToStateVariable(names[i]));
}
for(int i=0; i<nsv; ++i){
_allStateVariables[i]->setValue(state, values[i]);
}
}
// Set the derivative of a state variable computed by this Component by name.
void Component::
setStateVariableDerivativeValue(const State& state,
const std::string& name, double value) const
{
std::map<std::string, StateVariableInfo>::const_iterator it;
it = _namedStateVariableInfo.find(name);
if(it != _namedStateVariableInfo.end()) {
const StateVariable& sv = *it->second.stateVariable;
sv.setDerivative(state, value);
}
else{
std::stringstream msg;
msg << "Component::setStateVariableDerivative: ERR- name '" << name
<< "' not found.\n "
<< getName() << " of type " << getConcreteClassName()
<< " has " << getNumStateVariables() << " states.";
throw Exception(msg.str(),__FILE__,__LINE__);
}
}
// Get the value of a discrete variable allocated by this Component by name.
double Component::
getDiscreteVariableValue(const SimTK::State& s, const std::string& name) const
{
// Must have already called initSystem.
OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem);
std::map<std::string, DiscreteVariableInfo>::const_iterator it;
it = _namedDiscreteVariableInfo.find(name);
if(it != _namedDiscreteVariableInfo.end()) {
SimTK::DiscreteVariableIndex dvIndex = it->second.index;
return SimTK::Value<double>::downcast(
getDefaultSubsystem().getDiscreteVariable(s, dvIndex)).get();
} else {
std::stringstream msg;
msg << "Component::getDiscreteVariable: ERR- name '" << name
<< "' not found.\n "
<< "for component '"<< getName() << "' of type "
<< getConcreteClassName();
throw Exception(msg.str(),__FILE__,__LINE__);
return SimTK::NaN;
}
}
// Set the value of a discrete variable allocated by this Component by name.
void Component::
setDiscreteVariableValue(SimTK::State& s, const std::string& name, double value) const
{
// Must have already called initSystem.
OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem);
std::map<std::string, DiscreteVariableInfo>::const_iterator it;
it = _namedDiscreteVariableInfo.find(name);
if(it != _namedDiscreteVariableInfo.end()) {
SimTK::DiscreteVariableIndex dvIndex = it->second.index;
SimTK::Value<double>::downcast(
getDefaultSubsystem().updDiscreteVariable(s, dvIndex)).upd() = value;
} else {
std::stringstream msg;
msg << "Component::setDiscreteVariable: ERR- name '" << name
<< "' not found.\n "
<< "for component '"<< getName() << "' of type "
<< getConcreteClassName();
throw Exception(msg.str(),__FILE__,__LINE__);
}
}
SimTK::CacheEntryIndex Component::getCacheVariableIndex(const std::string& name) const
{
auto it = this->_namedCacheVariables.find(name);
if (it != this->_namedCacheVariables.end()) {
return it->second.index();
}
std::stringstream msg;
msg << "Cache variable with name '" << name << "' not found: maybe the cache variable was not allocated with `Component::addCacheVariable`?";
OPENSIM_THROW_FRMOBJ(Exception, msg.str());
}
bool Component::isCacheVariableValid(const SimTK::State& state, const std::string& name) const
{
const SimTK::DefaultSystemSubsystem& subsystem = this->getDefaultSubsystem();
const SimTK::CacheEntryIndex idx = this->getCacheVariableIndex(name);
return subsystem.isCacheValueRealized(state, idx);
}
void Component::markCacheVariableValid(const SimTK::State& state, const std::string& name) const
{
const SimTK::DefaultSystemSubsystem& subsystem = this->getDefaultSubsystem();
const SimTK::CacheEntryIndex idx = this->getCacheVariableIndex(name);
subsystem.markCacheValueRealized(state, idx);
}
void Component::markCacheVariableInvalid(const SimTK::State& state, const std::string& name) const
{
const SimTK::DefaultSystemSubsystem& subsystem = this->getDefaultSubsystem();
const SimTK::CacheEntryIndex idx = this->getCacheVariableIndex(name);
subsystem.markCacheValueNotRealized(state, idx);
}
bool Component::constructOutputForStateVariable(const std::string& name)
{
auto func = [name](const Component* comp,
const SimTK::State& s, const std::string&,
double& result) -> void {
result = comp->getStateVariableValue(s, name);
};
return constructOutput<double>(name, func, SimTK::Stage::Model);
}
// helper method to specify the order of subcomponents.
void Component::setNextSubcomponentInSystem(const Component& sub) const
{
auto it =
std::find(_orderedSubcomponents.begin(), _orderedSubcomponents.end(),
SimTK::ReferencePtr<const Component>(&sub));
if (it == _orderedSubcomponents.end()) {
_orderedSubcomponents.push_back(SimTK::ReferencePtr<const Component>(&sub));
}
}
void Component::updateFromXMLNode(SimTK::Xml::Element& node, int versionNumber)
{
// During deserialization, some components' clone() may
// finalizeFromProperties(). Upating from XML can then cause stale pointers.
// We must make sure to clear any pointers to properties that may exist
// in this component.
reset();
if (versionNumber < XMLDocument::getLatestVersion()) {
if (versionNumber < 30500) {
// In 3.3 and earlier, spaces in names were tolerated. Spaces are
// no longer acceptable in Component names.
if (node.hasAttribute("name")) {
auto name = node.getRequiredAttribute("name").getValue();
if (name.find_first_of("\n\t ") < std::string::npos) {
log_warn("{} name '{}' contains whitespace.",
getConcreteClassName(), name);
name.erase(
std::remove_if(name.begin(), name.end(), ::isspace),
name.end());
node.setAttributeValue("name", name);
log_warn("It was renamed to '{}'.", name);
}
}
else { // As 4.0 all Components must have a name. If none, assign one.
// Note: in finalizeFromProperties(), the Component will ensure
// that names are unique by travesing its list of subcomponents
// and renaming any duplicates.
node.setAttributeValue("name",
IO::Lowercase(getConcreteClassName()));
}
}
if (versionNumber < 30508) {
// Here's an example of the change this function might make:
// Previous: <connectors>
// <Connector_PhysicalFrame_ name="parent">
// <connectee_name>...</connectee_name>
// </Connector_PhysicalFrame_>
// </connectors>
// New: <connector_parent_connectee_name>...
// </connector_parent_connectee_name>
//
XMLDocument::updateConnectors30508(node);
}
if(versionNumber < 30510) {
// Before -- <connector_....> ... </connector_...>
// After -- <socket_...> ... </socket_...>
for(auto iter = node.element_begin();
iter != node.element_end();
++iter) {
std::string oldName{"connector"};
std::string newName{"socket"};
auto tagname = iter->getElementTag();
auto pos = tagname.find(oldName);
if(pos != std::string::npos) {
tagname.replace(pos, oldName.length(), newName);
iter->setElementTag(tagname);
}
}
}
if (versionNumber <= 30516) {
// Rename xml tags for socket_*_connectee_name to socket_*
std::string connecteeNameString = "_connectee_name";
for (auto iter = node.element_begin();
iter != node.element_end();
++iter) {
auto tagname = iter->getElementTag();
if (std::regex_match(tagname, std::regex("(socket_|input_)(.*)(_connectee_name)"))) {
auto pos = tagname.find(connecteeNameString);
if (pos != std::string::npos) {
tagname.replace(pos, connecteeNameString.length(), "");
iter->setElementTag(tagname);
}
}
else if (std::regex_match(tagname, std::regex("(input_)(.*)(_connectee_names)"))) {
auto pos = tagname.find(connecteeNameString);
if (pos != std::string::npos) {
tagname.replace(pos, connecteeNameString.length()+1, "");
iter->setElementTag(tagname);
}
}
}
}
}
Super::updateFromXMLNode(node, versionNumber);
}
// mark components owned as properties as subcomponents
void Component::markPropertiesAsSubcomponents()
{
// Method can be invoked for either constructing a new Component
// or the properties have been modified. In the latter case
// we must make sure that pointers to old properties are cleared
_propertySubcomponents.clear();
// Now mark properties that are Components as subcomponents
//loop over all its properties
for (int i = 0; i < getNumProperties(); ++i) {
auto& prop = getPropertyByIndex(i);
// check if property is of type Object
if (prop.isObjectProperty()) {
// a property is a list so cycle through its contents
for (int j = 0; j < prop.size(); ++j) {
const Object& obj = prop.getValueAsObject(j);
// if the object is a Component mark it
if (const Component* comp = dynamic_cast<const Component*>(&obj) ) {
markAsPropertySubcomponent(comp);
}
else {
// otherwise it may be a Set (of objects), and
// would prefer to do something like this to test:
// Set<Component>* objects = dynamic_cast<Set<Component>*>(obj)
// Instead we can see if the object has a property called
// "objects" which is a PropertyObjArray used by Set<T>.
// knowing the object Type is useful for debugging
// and it could be used to strengthen the test (e.g. scan
// for "Set" in the type name).
std::string objType = obj.getConcreteClassName();
if (obj.hasProperty("objects")) {
// get the PropertyObjArray if the object has one
auto& objectsProp = obj.getPropertyByName("objects");
// loop over the objects in the PropertyObjArray
for (int k = 0; k < objectsProp.size(); ++k) {
const Object& obj = objectsProp.getValueAsObject(k);
// if the object is a Component mark it
if (const Component* comp = dynamic_cast<const Component*>(&obj) )
markAsPropertySubcomponent(comp);
} // loop over objects and mark it if it is a component
} // end if property is a Set with "objects" inside
} // end of if/else property value is an Object or something else
} // loop over the property list
} // end if property is an Object
} // loop over properties
}
// mark a Component as a subcomponent of this one. If already a
// subcomponent, it is not added to the list again.
void Component::markAsPropertySubcomponent(const Component* component)
{
// Only add if the component is not already a part of this Component
SimTK::ReferencePtr<Component> compRef(const_cast<Component*>(component));
auto it =
std::find(_propertySubcomponents.begin(), _propertySubcomponents.end(), compRef);
if ( it == _propertySubcomponents.end() ){
// Must reconstruct the reference pointer in place in order
// to invoke move constructor from SimTK::Array::push_back
// otherwise it will copy and reset the Component pointer to null.
_propertySubcomponents.push_back(
SimTK::ReferencePtr<Component>(const_cast<Component*>(component)));
}
else{
auto compPath = component->getAbsolutePathString();
auto foundPath = it->get()->getAbsolutePathString();
OPENSIM_THROW( ComponentAlreadyPartOfOwnershipTree,
component->getName(), getName());
}
compRef->setOwner(*this);
}
// Include another Component as a subcomponent of this one. If already a
// subcomponent, it is not added to the list again.
void Component::adoptSubcomponent(Component* subcomponent)
{
OPENSIM_THROW_IF(subcomponent->hasOwner(),
ComponentAlreadyPartOfOwnershipTree,
subcomponent->getName(), this->getName());
//get the top-level component
const Component* top = this;
while (top->hasOwner())
top = &top->getOwner();
// cycle through all components from the top level component
// down to verify the component is not already in the tree
for (auto& comp : top->getComponentList<Component>()) {
OPENSIM_THROW_IF(subcomponent->hasOwner(),
ComponentAlreadyPartOfOwnershipTree,
subcomponent->getName(), comp.getName());
}
subcomponent->setOwner(*this);
_adoptedSubcomponents.push_back(SimTK::ClonePtr<Component>(subcomponent));
}
std::vector<SimTK::ReferencePtr<const Component>>
Component::getImmediateSubcomponents() const
{
std::vector<SimTK::ReferencePtr<const Component>> mySubcomponents;
for (auto& compRef : _memberSubcomponents) {
mySubcomponents.push_back(
SimTK::ReferencePtr<const Component>(compRef.get()) );
}
for (auto& compRef : _propertySubcomponents) {
mySubcomponents.push_back(
SimTK::ReferencePtr<const Component>(compRef.get()) );
}
for (auto& compRef : _adoptedSubcomponents) {
mySubcomponents.push_back(
SimTK::ReferencePtr<const Component>(compRef.get()) );
}
return mySubcomponents;
}
size_t Component::getNumMemberSubcomponents() const
{
return _memberSubcomponents.size();
}
size_t Component::getNumPropertySubcomponents() const
{
return _propertySubcomponents.size();
}
size_t Component::getNumAdoptedSubcomponents() const
{
return _adoptedSubcomponents.size();
}
int Component::getStateIndex(const std::string& name) const
{
std::map<std::string, StateVariableInfo>::const_iterator it;
it = _namedStateVariableInfo.find(name);
if(it != _namedStateVariableInfo.end()) {
return it->second.stateVariable->getVarIndex();
} else {
std::stringstream msg;
msg << "Component::getStateVariableSystemIndex: ERR- name '"
<< name << "' not found.\n "
<< "for component '"<< getName() << "' of type "
<< getConcreteClassName();
throw Exception(msg.str(),__FILE__,__LINE__);
return SimTK::InvalidIndex;
}
}
SimTK::SystemYIndex Component::
getStateVariableSystemIndex(const std::string& stateVariableName) const
{
//const SimTK::State& s = getSystem().getDefaultState();
std::map<std::string, StateVariableInfo>::const_iterator it;
it = _namedStateVariableInfo.find(stateVariableName);
if(it != _namedStateVariableInfo.end()){
return it->second.stateVariable->getSystemYIndex();
}
// Otherwise we have to search through subcomponents
SimTK::SystemYIndex yix;
for(unsigned int i = 0; i < _propertySubcomponents.size(); ++i) {
yix = _propertySubcomponents[i]->getStateVariableSystemIndex(stateVariableName);
if(yix.isValid()){
return yix;
}
}
if(!(yix.isValid())){
throw Exception(getConcreteClassName()
+ "::getStateVariableSystemIndex : state variable "
+ stateVariableName+" has an invalid index.");
}
return yix;
}
const SimTK::DiscreteVariableIndex Component::
getDiscreteVariableIndex(const std::string& name) const
{
std::map<std::string, DiscreteVariableInfo>::const_iterator it;
it = _namedDiscreteVariableInfo.find(name);
return it->second.index;
}
Array<std::string> Component::
getStateVariableNamesAddedByComponent() const
{
std::map<std::string, StateVariableInfo>::const_iterator it;
it = _namedStateVariableInfo.begin();
Array<std::string> names("",(int)_namedStateVariableInfo.size());
while(it != _namedStateVariableInfo.end()){
names[it->second.order] = it->first;
it++;
}
return names;
}
//------------------------------------------------------------------------------
// REALIZE TOPOLOGY
//------------------------------------------------------------------------------
// This is the base class implementation of a virtual method that can be
// overridden by derived model components, but they *must* invoke
// Super::extendRealizeTopology() as the first line in the overriding method so
// that this code is executed before theirs.
// This method is invoked from the ComponentMeasure associated with this
// Component.
// Note that subcomponent realize() methods will be invoked by their own
// ComponentMeasures, so we do not need to forward to subcomponents here.
void Component::extendRealizeTopology(SimTK::State& s) const
{
const SimTK::Subsystem& subSys = getSystem().getDefaultSubsystem();
Component *mutableThis = const_cast<Component*>(this);
// Allocate Modeling Option
if(_namedModelingOptionInfo.size()>0){
std::map<std::string, ModelingOptionInfo>::iterator it;
for (it = (mutableThis->_namedModelingOptionInfo).begin();
it !=_namedModelingOptionInfo.end(); ++it)
{
ModelingOptionInfo& moi = it->second;
moi.index = subSys.allocateDiscreteVariable
(s, SimTK::Stage::Instance, new SimTK::Value<int>(0));
}
}
// Allocate Continuous State Variables
if(_namedStateVariableInfo.size()>0){
SimTK::Vector zInit(1, 0.0);
std::map<std::string, StateVariableInfo>::iterator it;
for (it = (mutableThis->_namedStateVariableInfo).begin();
it != _namedStateVariableInfo.end(); ++it)
{
const StateVariable& sv = *it->second.stateVariable;
const AddedStateVariable* asv
= dynamic_cast<const AddedStateVariable *>(&sv);
if(asv){// add index information for added state variables
// make mutable just to update system allocated index ONLY!
AddedStateVariable* masv = const_cast<AddedStateVariable*>(asv);
masv->setVarIndex(subSys.allocateZ(s, zInit));
masv->setSubsystemIndex(getDefaultSubsystem().getMySubsystemIndex());
}
}
}
// Allocate Discrete State Variables
if(_namedDiscreteVariableInfo.size()>0){
std::map<std::string, DiscreteVariableInfo>::iterator it;
for (it = (mutableThis->_namedDiscreteVariableInfo).begin();
it != _namedDiscreteVariableInfo.end(); ++it)
{
DiscreteVariableInfo& dvi = it->second;
dvi.index = subSys.allocateDiscreteVariable
(s, dvi.invalidatesStage, new SimTK::Value<double>(0.0));
}
}
// allocate cache entry in the state
//
// BEWARE: the cache variables *must* be inserted into the SimTK::state
// in a deterministic order.
//
// The reason this is important is because:
//
// - some downstream code will take copies of the `SimTK::State`
// and expect indicies into the new state to also be able to
// index into the copy (they shouldn't do this, but do, and
// this code hardens against it)
//
// - to callers, it *feels* like the copy should be interchangable
// if the component is *logically* the same - the same component
// with the same cache vars etc. *should* produce the same state,
// right?
//
// - but `unordered_map` has no iteration order guarantees, so even
// the exact same component, at the same memory address, that is
// merely re-initialized, and calls `addCacheVariable` in the
// exact same order can still iterate the cache variables in
// a different order and (ultimately) produce an incompatible
// SimTK::State
//
// - this is because re-initialization does not necessarily
// reconstruct the backing containers. They may only have been
// `.clear()`ed, which *may* hold onto memory, which *may* affect
// (internal) insertion logic
//
// - the safest thing to assume is that the iteration order of
// `unordered_map` is non-deterministic. It isn't, but *essentially*
// is, because there are plenty of non-obvious ways to affect its
// iteration order
{
std::vector<std::reference_wrapper<const std::string>> keys;
keys.reserve(this->_namedCacheVariables.size());
for (auto& p : this->_namedCacheVariables) {
keys.emplace_back(p.first);
}
std::sort(keys.begin(), keys.end(), [](const std::string& a, const std::string& b) {
return a < b;
});
for (const std::string& k : keys) {
StoredCacheVariable& cv = this->_namedCacheVariables.at(k);
cv.maybeUninitIndex = subSys.allocateLazyCacheEntry(s, cv.dependsOnStage, cv.value->clone());
}
}
}
//------------------------------------------------------------------------------
// REALIZE ACCELERATION
//------------------------------------------------------------------------------
// Base class implementation of virtual method.
// Collect this component's state variable derivatives.
void Component::extendRealizeAcceleration(const SimTK::State& s) const
{
// don't bother computing derivatives if the component has no state variables
if(getNumStateVariablesAddedByComponent() > 0) {
const SimTK::Subsystem& subSys = getDefaultSubsystem();
// evaluate and set component state derivative values (in cache)
computeStateVariableDerivatives(s);
std::map<std::string, StateVariableInfo>::const_iterator it;
for (it = _namedStateVariableInfo.begin();
it != _namedStateVariableInfo.end(); ++it)
{
const StateVariable& sv = *it->second.stateVariable;
const AddedStateVariable* asv =
dynamic_cast<const AddedStateVariable*>(&sv);
if(asv)
// set corresponding system derivative value from
// cached value
subSys.updZDot(s)[ZIndex(asv->getVarIndex())] =
asv->getDerivative(s);
}
}
}
SimTK::MultibodySystem& Component::updSystem() const
{
OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem);
return _system.getRef();
}
//------------------------------------------------------------------------------
// OTHER REALIZE METHODS
//------------------------------------------------------------------------------
// Base class implementations of these virtual methods do nothing now but
// could do something in the future. Users must still invoke Super::realizeXXX()
// as the first line in their overrides to ensure future compatibility.
void Component::extendRealizeModel(SimTK::State& state) const {}
void Component::extendRealizeInstance(const SimTK::State& state) const {}
void Component::extendRealizeTime(const SimTK::State& state) const {}
void Component::extendRealizePosition(const SimTK::State& state) const {}
void Component::extendRealizeVelocity(const SimTK::State& state) const {}
void Component::extendRealizeDynamics(const SimTK::State& state) const {}
void Component::extendRealizeReport(const SimTK::State& state) const {}
//override virtual methods
double Component::AddedStateVariable::getValue(const SimTK::State& state) const
{
ZIndex zix(getVarIndex());
if(getSubsysIndex().isValid() && zix.isValid()){
const SimTK::Vector& z = getOwner().getDefaultSubsystem().getZ(state);
return z[ZIndex(zix)];
}
std::stringstream msg;
msg << "Component::AddedStateVariable::getValue: ERR- variable '"
<< getName() << "' is invalid for component " << getOwner().getName()
<< " of type " << getOwner().getConcreteClassName() <<".";
throw Exception(msg.str(),__FILE__,__LINE__);
return SimTK::NaN;
}
void Component::AddedStateVariable::setValue(SimTK::State& state, double value) const
{
ZIndex zix(getVarIndex());
if(getSubsysIndex().isValid() && zix.isValid()){
SimTK::Vector& z = getOwner().getDefaultSubsystem().updZ(state);
z[ZIndex(zix)] = value;
return;
}
std::stringstream msg;
msg << "Component::AddedStateVariable::setValue: ERR- variable '"
<< getName() << "' is invalid for component " << getOwner().getName()
<< " of type " << getOwner().getConcreteClassName() <<".";
throw Exception(msg.str(),__FILE__,__LINE__);
}
double Component::AddedStateVariable::
getDerivative(const SimTK::State& state) const
{
return getOwner().getCacheVariableValue<double>(state, getName()+"_deriv");
}
void Component::AddedStateVariable::
setDerivative(const SimTK::State& state, double deriv) const
{
getOwner().setCacheVariableValue<double>(state, getName()+"_deriv", deriv);
}
void Component::printSocketInfo() const {
std::string str = fmt::format("Sockets for component {} of type [{}] along "
"with connectee paths:", getName(),
getConcreteClassName());
if (getNumSockets() == 0)
str += " none";
log_cout(str);
size_t maxlenTypeName{}, maxlenSockName{};
for(const auto& sock : _socketsTable) {
maxlenTypeName = std::max(maxlenTypeName,
sock.second->getConnecteeTypeName().length());
maxlenSockName = std::max(maxlenSockName,
sock.second->getName().length());
}
maxlenTypeName += 6;
maxlenSockName += 1;
for (const auto& it : _socketsTable) {
const auto& socket = it.second;
// Right-justify the connectee type names and socket names.
str = fmt::format("{:>{}} {:>{}} : ",
fmt::format("[{}]", socket->getConnecteeTypeName()),
maxlenTypeName,
socket->getName(), maxlenSockName);
if (socket->getNumConnectees() == 0) {
str += "no connectees";
} else {
std::vector<std::string> connecteePaths;
for (unsigned i = 0; i < socket->getNumConnectees(); ++i) {
connecteePaths.push_back(socket->getConnecteePath(i));
}
// Join the connectee paths with spaces in between.
str += fmt::format("{}", fmt::join(connecteePaths, " "));
}
log_cout(str);
}
}
void Component::printInputInfo() const {
std::string str = fmt::format("Inputs for component {} of type [{}] along "
"with connectee paths:",
getName(), getConcreteClassName());
if (getNumInputs() == 0)
str += " none";
log_cout(str);
size_t maxlenTypeName{}, maxlenInputName{};
for(const auto& input : _inputsTable) {
maxlenTypeName = std::max(maxlenTypeName,
input.second->getConnecteeTypeName().length());
maxlenInputName = std::max(maxlenInputName,
input.second->getName().length());
}
maxlenTypeName += 6;
maxlenInputName += 1;
for (const auto& it : _inputsTable) {
const auto& input = it.second;
// Right-justify the connectee type names and input names.
str = fmt::format("{:>{}} {:>{}} : ",
fmt::format("[{}]", input->getConnecteeTypeName()),
maxlenTypeName,
input->getName(), maxlenInputName);
if (input->getNumConnectees() == 0 ||
(input->getNumConnectees() == 1 && input->getConnecteePath().empty())) {
str += "no connectees";
} else {
std::vector<std::string> connecteePaths;
for (unsigned i = 0; i < input->getNumConnectees(); ++i) {
connecteePaths.push_back(input->getConnecteePath(i));
// TODO as is, requires the input connections to be satisfied.
// std::cout << " (alias: " << input.getAlias(i) << ") ";
}
// Join the connectee paths with spaces in between.
str += fmt::format("{}", fmt::join(connecteePaths, " "));
}
log_cout(str);
}
}
void Component::printSubcomponentInfo() const {
printSubcomponentInfo<Component>();
}
void Component::printOutputInfo(const bool includeDescendants) const {
// Do not display header for Components with no outputs.
if (getNumOutputs() > 0) {
std::string msg = fmt::format("Outputs from {} [{}]",
getAbsolutePathString(),
getConcreteClassName());
msg += "\n" + std::string(msg.size(), '=');
log_cout(msg);
const auto& outputs = getOutputs();
size_t maxlen{};
for(const auto& output : outputs)
maxlen = std::max(maxlen, output.second->getTypeName().length());
maxlen += 6;
for(const auto& output : outputs) {
const auto& name = output.second->getTypeName();
log_cout("{:>{}} {}",
fmt::format("[{}]", output.second->getTypeName()),
maxlen, output.first);
}
log_cout("");
}
if (includeDescendants) {
for (const Component& thisComp : getComponentList<Component>()) {
// getComponentList() returns all descendants (i.e.,
// children, grandchildren, etc.) so set includeDescendants=false
// when calling on thisComp.
thisComp.printOutputInfo(false);
}
}
}
void Component::initComponentTreeTraversal(const Component &root) const {
// Going down the tree, this node is followed by all its children.
// The last child's successor (next) is the parent's successor.
const size_t nmsc = _memberSubcomponents.size();
const size_t npsc = _propertySubcomponents.size();
const size_t nasc = _adoptedSubcomponents.size();
if (!hasOwner()) {
// If this isn't the root component and it has no owner, then
// this is an orphan component and we likely failed to call
// finalizeFromProperties() on the root OR this is a clone that
// has not been added to the root (in which case would have an owner).
if (this != &root) {
OPENSIM_THROW(ComponentIsAnOrphan, getName(),
getConcreteClassName());
}
// if the root (have no owner) and have no components
else if (!(nmsc + npsc + nasc)) {
OPENSIM_THROW(ComponentIsRootWithNoSubcomponents,
getName(), getConcreteClassName());
}
}
const Component* last = nullptr;
for (unsigned int i = 0; i < nmsc; i++) {
if (i == nmsc - 1) {
_memberSubcomponents[i]->_nextComponent = _nextComponent.get();
last = _memberSubcomponents[i].get();
}
else {
_memberSubcomponents[i]->_nextComponent =
_memberSubcomponents[i + 1].get();
last = _memberSubcomponents[i + 1].get();
}
}
if (npsc) {
if (last)
last->_nextComponent = _propertySubcomponents[0].get();
for (unsigned int i = 0; i < npsc; i++) {
if (i == npsc - 1) {
_propertySubcomponents[i]->_nextComponent =
_nextComponent.get();
last = _propertySubcomponents[i].get();
}
else {
_propertySubcomponents[i]->_nextComponent =
_propertySubcomponents[i + 1].get();
last = _propertySubcomponents[i + 1].get();
}
}
}
if (nasc) {
if (last)
last->_nextComponent = _adoptedSubcomponents[0].get();
for (unsigned int i = 0; i <nasc; i++) {
if (i == nasc - 1) {
_adoptedSubcomponents[i]->_nextComponent = _nextComponent.get();
}
else {
_adoptedSubcomponents[i]->_nextComponent
= _adoptedSubcomponents[i + 1].get();
}
}
}
// recurse to handle children of subcomponents
for (unsigned int i = 0; i < nmsc; ++i) {
_memberSubcomponents[i]->initComponentTreeTraversal(root);
}
for (unsigned int i = 0; i < npsc; ++i) {
_propertySubcomponents[i]->initComponentTreeTraversal(root);
}
for (unsigned int i = 0; i < nasc; ++i) {
_adoptedSubcomponents[i]->initComponentTreeTraversal(root);
}
}
void Component::clearStateAllocations()
{
_namedModelingOptionInfo.clear();
_namedStateVariableInfo.clear();
_namedDiscreteVariableInfo.clear();
_namedCacheVariables.clear();
}
void Component::reset()
{
_system.reset();
_simTKcomponentIndex.invalidate();
clearStateAllocations();
_propertySubcomponents.clear();
_adoptedSubcomponents.clear();
resetSubcomponentOrder();
}
void Component::warnBeforePrint() const {
if (!isObjectUpToDateWithProperties()) return;
std::string message;
auto checkIfConnecteePathIsSet =
[](const Component& comp, std::string& message) {
for (const auto& it : comp._socketsTable) {
const auto& socket = it.second;
if (socket->isConnected() &&
((socket->isListSocket() &&
socket->getNumConnectees() == 0) ||
(!socket->isListSocket() &&
socket->getConnecteePath().empty()))) {
// TODO: Improve this condition by making sure the connectee
// name is correct.
message += " Socket '" + socket->getName() + "' in " +
comp.getConcreteClassName() + " at " +
comp.getAbsolutePathString() + "\n";
}
}
};
if (getNumImmediateSubcomponents() == 0) {
checkIfConnecteePathIsSet(*this, message);
} else {
for (const auto& comp : getComponentList()) {
checkIfConnecteePathIsSet(comp, message);
}
}
if (!message.empty()) {
std::stringstream buffer;
buffer << "Warning in " << getConcreteClassName()
<< "::print(): The following connections are not finalized "
"and will not appear in the resulting XML file. "
"Call finalizeConnections() before print().\n"
"To ignore, set the debug level to at least 1 "
"(e.g, by calling Object::setDebugLevel(1)) first.\n"
<< message << std::endl;
OPENSIM_THROW_FRMOBJ(Exception, buffer.str());
}
}
} // end of namespace OpenSim
Refactored Component::extendRealizeTopology to use for range loops
/* -------------------------------------------------------------------------- *
* OpenSim: Component.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2017 Stanford University and the Authors *
* Author(s): Ajay Seth, Michael Sherman *
* Contributor(s): Ayman Habib *
* *
* 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. *
* -------------------------------------------------------------------------- */
// INCLUDES
#include "Component.h"
#include "OpenSim/Common/IO.h"
#include "XMLDocument.h"
#include <unordered_map>
#include <set>
#include <regex>
using namespace SimTK;
namespace OpenSim {
//==============================================================================
// COMPONENT MEASURE
//==============================================================================
// Every OpenSim::Component is associated with a Simbody Measure of type
// ComponentMeasure defined here. This provides a full set of realize()
// methods for performing computations with System resources that are maintained
// at the Component base level, such as calculating state derivatives.
template <class T>
class ComponentMeasure : public SimTK::Measure_<T> {
public:
SimTK_MEASURE_HANDLE_PREAMBLE(ComponentMeasure, SimTK::Measure_<T>);
ComponentMeasure(SimTK::Subsystem& sub,
const OpenSim::Component& mc)
: SimTK::Measure_<T>(sub, new Implementation(mc),
SimTK::AbstractMeasure::SetHandle()) {}
SimTK_MEASURE_HANDLE_POSTSCRIPT(ComponentMeasure, SimTK::Measure_<T>);
};
template <class T>
class ComponentMeasure<T>::Implementation
: public SimTK::Measure_<T>::Implementation {
public:
// Don't allocate a value cache entry since this measure's value is
// just a dummy.
explicit Implementation(const Component& c)
: SimTK::Measure_<T>::Implementation(0), _Component(c) {}
// Implementations of Measure_<T>::Implementation virtual methods.
Implementation* cloneVirtual() const override final
{ return new Implementation(*this); }
int getNumTimeDerivativesVirtual() const override final {return 0;}
SimTK::Stage getDependsOnStageVirtual(int order) const override final
{ return SimTK::Stage::Empty; }
const T& getUncachedValueVirtual
(const SimTK::State& s, int derivOrder) const override final
{ return this->getValueZero(); }
void realizeMeasureTopologyVirtual(SimTK::State& s) const override final
{ _Component.extendRealizeTopology(s); }
void realizeMeasureModelVirtual(SimTK::State& s) const override final
{ _Component.extendRealizeModel(s); }
void realizeMeasureInstanceVirtual(const SimTK::State& s)
const override final
{ _Component.extendRealizeInstance(s); }
void realizeMeasureTimeVirtual(const SimTK::State& s) const override final
{ _Component.extendRealizeTime(s); }
void realizeMeasurePositionVirtual(const SimTK::State& s)
const override final
{ _Component.extendRealizePosition(s); }
void realizeMeasureVelocityVirtual(const SimTK::State& s)
const override final
{ _Component.extendRealizeVelocity(s); }
void realizeMeasureDynamicsVirtual(const SimTK::State& s)
const override final
{ _Component.extendRealizeDynamics(s); }
void realizeMeasureAccelerationVirtual(const SimTK::State& s)
const override final
{ _Component.extendRealizeAcceleration(s); }
void realizeMeasureReportVirtual(const SimTK::State& s)
const override final
{ _Component.extendRealizeReport(s); }
private:
const Component& _Component;
};
//==============================================================================
// COMPONENT
//==============================================================================
Component::Component() : Object()
{
constructProperty_components();
}
Component::Component(const std::string& fileName, bool updFromXMLNode)
: Object(fileName, updFromXMLNode)
{
constructProperty_components();
}
Component::Component(SimTK::Xml::Element& element) : Object(element)
{
constructProperty_components();
}
bool Component::isComponentInOwnershipTree(const Component* subcomponent) const {
//get to the root Component
const Component* root = this;
while (root->hasOwner()) {
root = &(root->getOwner());
}
// if the root has no immediate subcomponents do not bother
// checking if the subcomponent is in the ownership tree
if ((root->getNumImmediateSubcomponents() > 0)) {
auto components = root->getComponentList<Component>();
for (auto& c : components) {
if (subcomponent == &c) return true;
}
}
return false;
}
void Component::addComponent(Component* subcomponent)
{
OPENSIM_THROW_IF(isComponentInOwnershipTree(subcomponent),
ComponentAlreadyPartOfOwnershipTree,
subcomponent->getName(), getName());
updProperty_components().adoptAndAppendValue(subcomponent);
finalizeFromProperties();
prependComponentPathToConnecteePath(*subcomponent);
// allow the derived Component to perform secondary operations
// in response to the inclusion of the subcomponent
extendAddComponent(subcomponent);
}
void Component::prependComponentPathToConnecteePath(
Component& subcomponent) {
const std::string compPath = subcomponent.getAbsolutePathString();
const Component& root = subcomponent.getRoot();
for (auto& comp : subcomponent.updComponentList()) {
for (auto& it : comp._socketsTable) {
if (!root.hasComponent(it.second->getConnecteePath()))
it.second->prependComponentPathToConnecteePath(compPath);
}
for (auto& it : comp._inputsTable) {
it.second->prependComponentPathToConnecteePath(compPath);
}
}
}
void Component::finalizeFromProperties()
{
reset();
// last opportunity to modify Object names based on properties
if (!hasOwner()) {
// only call when Component is root since method is recursive
makeObjectNamesConsistentWithProperties();
}
// TODO use a flag to set whether we are lenient on having nameless
// Components. For backward compatibility we need to be able to
// handle nameless components so assign them their class name
// - aseth
if (getName().empty()) {
setName(IO::Lowercase(getConcreteClassName()));
}
OPENSIM_THROW_IF( getName().empty(), ComponentHasNoName,
getConcreteClassName() );
ComponentPath cp;
OPENSIM_THROW_IF( !cp.isLegalPathElement(getName()), InvalidComponentName,
getName(), cp.getInvalidChars(), getConcreteClassName());
for (auto& comp : _memberSubcomponents) {
comp->setOwner(*this);
}
for (auto& comp : _adoptedSubcomponents) {
comp->setOwner(*this);
}
// Provide sockets, inputs, and outputs with a pointer to its component
// (this) so that they can invoke the component's methods.
for (auto& it : _socketsTable) {
it.second->setOwner(*this);
// Let the Socket handle any errors in the connectee_name property.
it.second->checkConnecteePathProperty();
}
for (auto& it : _inputsTable) {
it.second->setOwner(*this);
// Let the Socket handle any errors in the connectee_name property.
it.second->checkConnecteePathProperty();
}
for (auto& it : _outputsTable) {
it.second->setOwner(*this);
}
markPropertiesAsSubcomponents();
componentsFinalizeFromProperties();
// The following block is used to ensure that deserialized names of
// Components are unique so they can be used to unambiguously locate
// and connect all loaded Components. If a duplicate is encountered,
// it is assigned a unique name.
auto subs = getImmediateSubcomponents();
std::set<std::string> names{};
// increment the count of duplicates to use as a unique suffix
int count{ 0 };
// temp variable to hold the unique name used to rename a duplicate
std::string uniqueName{};
for (auto& sub : subs) {
const std::string& name = sub->getName();
// reset duplicate count and search name
count = 0;
uniqueName = name;
// while the name is still not unique keep incrementing the count
while (names.find(uniqueName) != names.cend()) {
// In the future this should become an Exception
//OPENSIM_THROW(SubcomponentsWithDuplicateName, getName(), searchName);
// for now, rename the duplicately named subcomponent
// but first test the uniqueness of the name (the while condition)
uniqueName = name + "_" + std::to_string(count++);
}
if (count > 0) { // if a duplicate
// Warn of the problem
log_warn("{} '{}' has subcomponents with duplicate name '{}'. "
"The duplicate is being renamed to '{}'.",
getConcreteClassName(), getName(), name, uniqueName);
// Now rename the subcomponent with its verified unique name
Component* mutableSub = const_cast<Component *>(sub.get());
mutableSub->setName(uniqueName);
}
// keep track of unique names
names.insert(uniqueName);
}
// End of duplicate finding and renaming.
extendFinalizeFromProperties();
setObjectIsUpToDateWithProperties();
}
// Base class implementation of virtual method.
// Call finalizeFromProperties on all subcomponents
void Component::componentsFinalizeFromProperties() const
{
for (auto& comp : _memberSubcomponents) {
const_cast<Component*>(comp.get())
->finalizeFromProperties();
}
for (auto& comp : _propertySubcomponents) {
const_cast<Component*>(comp.get())
->finalizeFromProperties();
}
for (auto& comp : _adoptedSubcomponents) {
const_cast<Component*>(comp.get())
->finalizeFromProperties();
}
}
// Base class implementation of non-virtual finalizeConnections method.
void Component::finalizeConnections(Component& root)
{
if (!isObjectUpToDateWithProperties()){
// if edits occur between construction and connect() this is
// the last chance to finalize before addToSystem.
finalizeFromProperties();
}
for (auto& it : _socketsTable) {
auto& socket = it.second;
try {
socket->finalizeConnection(root);
}
catch (const std::exception& x) {
OPENSIM_THROW_FRMOBJ(Exception, "Failed to connect Socket '" +
socket->getName() + "' of type " +
socket->getConnecteeTypeName() +
" (details: " + x.what() + ").");
}
}
for (auto& it : _inputsTable) {
auto& input = it.second;
try {
input->finalizeConnection(root);
}
catch (const std::exception& x) {
OPENSIM_THROW_FRMOBJ(Exception, "Failed to connect Input '" +
input->getName() + "' of type " + input->getConnecteeTypeName()
+ " (details: " + x.what() + ").");
}
}
// Allow derived Components to handle/check their connections and also
// override the order in which its subcomponents are ordered when
// adding subcomponents to the System
extendFinalizeConnections(root);
// Allow subcomponents to form their connections
componentsFinalizeConnections(root);
// Forming connections changes the Socket which is a property
// Remark as upToDate.
setObjectIsUpToDateWithProperties();
}
// invoke connect on all (sub)components of this component
void Component::componentsFinalizeConnections(Component& root)
{
// enable the subcomponents the opportunity to connect themselves
for (unsigned int i = 0; i<_memberSubcomponents.size(); ++i) {
_memberSubcomponents[i].upd()->finalizeConnections(root);
}
for(unsigned int i=0; i<_propertySubcomponents.size(); ++i){
_propertySubcomponents[i].get()->finalizeConnections(root);
}
for (unsigned int i = 0; i<_adoptedSubcomponents.size(); ++i) {
_adoptedSubcomponents[i].upd()->finalizeConnections(root);
}
}
void Component::clearConnections()
{
// First give the subcomponents the opportunity to disconnect themselves
for (unsigned int i = 0; i<_memberSubcomponents.size(); i++) {
_memberSubcomponents[i]->clearConnections();
}
for (unsigned int i = 0; i<_propertySubcomponents.size(); i++){
_propertySubcomponents[i]->clearConnections();
}
for (unsigned int i = 0; i<_adoptedSubcomponents.size(); i++) {
_adoptedSubcomponents[i]->clearConnections();
}
//Now cycle through and disconnect all sockets for this component
for (auto& it : _socketsTable) {
it.second->disconnect();
}
// Must also clear the input's connections.
for (auto& it : _inputsTable) {
it.second->disconnect();
}
//now clear all the stored system indices from this component
reset();
}
void Component::addToSystem(SimTK::MultibodySystem& system) const
{
// If being asked to be added to the same System that it is already
// a part, there is nothing to be done.
if (hasSystem() && (&getSystem() == &system)) {
return;
}
baseAddToSystem(system);
extendAddToSystem(system);
componentsAddToSystem(system);
extendAddToSystemAfterSubcomponents(system);
}
// Base class implementation of virtual method.
// Every Component owns an underlying SimTK::Measure
// which is a ComponentMeasure<T> and is added to the System's default
// subsystem. That measure is used only for the side effect of its realize()
// methods being called; its value is not used.
void Component::baseAddToSystem(SimTK::MultibodySystem& system) const
{
if (!isObjectUpToDateWithProperties()) {
std::string msg = "Component " + getConcreteClassName() + "::" + getName();
msg += " cannot extendAddToSystem until it is up-to-date with its properties.";
throw Exception(msg);
}
// Clear cached list of all related StateVariables if any from a previous
// System.
_allStateVariables.clear();
// Briefly get write access to the Component to record some
// information associated with the System; that info is const after this.
Component* mutableThis = const_cast<Component *>(this);
mutableThis->_system = system;
// Allocate the ComponentMeasure, point it to this Component for
// making realize() calls, and add it to the system's default subsystem.
ComponentMeasure<double> mcMeasure(system.updDefaultSubsystem(), *this);
mutableThis->_simTKcomponentIndex = mcMeasure.getSubsystemMeasureIndex();
}
void Component::componentsAddToSystem(SimTK::MultibodySystem& system) const
{
// If _orderedSubcomponents is specified, then use this Component's
// specification for the order in which subcomponents are added. At a
// minimum the order for all immediate subcomponents must be specified.
if (_orderedSubcomponents.size() >= getNumImmediateSubcomponents()) {
for (const auto& compRef : _orderedSubcomponents) {
compRef->addToSystem(system);
}
}
else if (_orderedSubcomponents.size() == 0) {
// Otherwise, invoke on all immediate subcomponents in tree order
auto mySubcomponents = getImmediateSubcomponents();
for (const auto& compRef : mySubcomponents) {
compRef->addToSystem(system);
}
}
else {
OPENSIM_THROW_FRMOBJ(Exception,
"_orderedSubcomponents specified, but its size does not reflect the "
"the number of immediate subcomponents. Verify that you have included "
"all immediate subcomponents in the ordered list."
)
}
}
void Component::initStateFromProperties(SimTK::State& state) const
{
extendInitStateFromProperties(state);
componentsInitStateFromProperties(state);
}
void Component::componentsInitStateFromProperties(SimTK::State& state) const
{
for (unsigned int i = 0; i<_memberSubcomponents.size(); ++i)
_memberSubcomponents[i]->initStateFromProperties(state);
for (unsigned int i = 0; i<_propertySubcomponents.size(); ++i)
_propertySubcomponents[i]->initStateFromProperties(state);
for (unsigned int i = 0; i<_adoptedSubcomponents.size(); ++i)
_adoptedSubcomponents[i]->initStateFromProperties(state);
}
void Component::setPropertiesFromState(const SimTK::State& state)
{
extendSetPropertiesFromState(state);
componentsSetPropertiesFromState(state);
}
void Component::componentsSetPropertiesFromState(const SimTK::State& state)
{
for (unsigned int i = 0; i<_memberSubcomponents.size(); ++i)
_memberSubcomponents[i]->setPropertiesFromState(state);
for (unsigned int i = 0; i<_propertySubcomponents.size(); ++i)
_propertySubcomponents[i]->setPropertiesFromState(state);
for (unsigned int i = 0; i<_adoptedSubcomponents.size(); ++i)
_adoptedSubcomponents[i]->setPropertiesFromState(state);
}
// Base class implementation of virtual method. Note that we're not handling
// subcomponents here; this method gets called from extendRealizeAcceleration()
// which will be invoked for each (sub) component by its own ComponentMeasure.
void Component::computeStateVariableDerivatives(const SimTK::State& s) const
{
int nsv = getNumStateVariablesAddedByComponent();
if(nsv > 0){
int nasv = 0;
std::map<std::string, StateVariableInfo>::const_iterator it;
for(it = _namedStateVariableInfo.begin();
it != _namedStateVariableInfo.end(); ++it){
const StateVariable& sv = *it->second.stateVariable;
const AddedStateVariable *asv =
dynamic_cast<const AddedStateVariable *>(&sv);
if(asv) nasv++;
}
if(nasv > 0){
std::stringstream msg;
msg << "Component " + getConcreteClassName()+"::"+getName();
msg << " added " << nasv << " state variables and ";
msg << " must specify their derivatives." << std::endl;
throw Exception(msg.str());
}
}
}
void Component::
addModelingOption(const std::string& optionName, int maxFlagValue) const
{
// don't add modeling option if there is another state with the same
// name for this component
std::map<std::string, ModelingOptionInfo>::const_iterator it;
it = _namedModelingOptionInfo.find(optionName);
if(it != _namedModelingOptionInfo.end())
throw Exception("Component::addModelingOption: Modeling option '"
+ optionName + "' already exists.");
// assign a "slot" for a modeling option by name
// modeling option index will be invalid by default
// upon allocation during realizeTopology the index will be set
_namedModelingOptionInfo[optionName] = ModelingOptionInfo(maxFlagValue);
}
void Component::addStateVariable(const std::string& stateVariableName,
const SimTK::Stage& invalidatesStage,
bool isHidden) const
{
if( (invalidatesStage < Stage::Position) ||
(invalidatesStage > Stage::Dynamics)) {
throw Exception("Component::addStateVariable: invalidatesStage "
"must be Position, Velocity or Dynamics.");
}
// Allocate space for a new state variable
AddedStateVariable* asv =
new AddedStateVariable(stateVariableName, *this, invalidatesStage, isHidden);
// Add it to the Component and let it take ownership
addStateVariable(asv);
}
void Component::addStateVariable(Component::StateVariable* stateVariable) const
{
const std::string& stateVariableName = stateVariable->getName();
// don't add state if there is another state variable with the same name
// for this component
std::map<std::string, StateVariableInfo>::const_iterator it;
it = _namedStateVariableInfo.find(stateVariableName);
if(it != _namedStateVariableInfo.end()){
throw Exception("Component::addStateVariable: State variable '" +
stateVariableName + "' already exists.");
}
int order = (int)_namedStateVariableInfo.size();
// assign a "slot" for a state variable by name
// state variable index will be invalid by default
// upon allocation during realizeTopology the index will be set
_namedStateVariableInfo[stateVariableName] =
StateVariableInfo(stateVariable, order);
const AddedStateVariable* asv =
dynamic_cast<const Component::AddedStateVariable *>(stateVariable);
// Now automatically add a cache variable to hold the derivative
// to enable a similar interface for setting and getting the derivatives
// based on the creator specified state name
if(asv){
addCacheVariable(stateVariableName+"_deriv", 0.0, Stage::Dynamics);
}
}
void Component::addDiscreteVariable(const std::string& discreteVariableName,
SimTK::Stage invalidatesStage) const
{
// don't add discrete var if there is another discrete variable with the
// same name for this component
std::map<std::string, DiscreteVariableInfo>::const_iterator it;
it = _namedDiscreteVariableInfo.find(discreteVariableName);
if(it != _namedDiscreteVariableInfo.end()){
throw Exception("Component::addDiscreteVariable: discrete variable '" +
discreteVariableName + "' already exists.");
}
// assign "slots" for the discrete variables by name
// discrete variable indices will be invalid by default
// upon allocation during realizeTopology the indices will be set
_namedDiscreteVariableInfo[discreteVariableName] =
DiscreteVariableInfo(invalidatesStage);
}
// Get the value of a ModelingOption flag for this Component.
int Component::
getModelingOption(const SimTK::State& s, const std::string& name) const
{
std::map<std::string, ModelingOptionInfo>::const_iterator it;
it = _namedModelingOptionInfo.find(name);
if(it != _namedModelingOptionInfo.end()) {
SimTK::DiscreteVariableIndex dvIndex = it->second.index;
return SimTK::Value<int>::downcast(
getDefaultSubsystem().getDiscreteVariable(s, dvIndex)).get();
} else {
std::stringstream msg;
msg << "Component::getModelingOption: ERR- name '" << name
<< "' not found.\n "
<< "for component '"<< getName() << "' of type "
<< getConcreteClassName();
throw Exception(msg.str(),__FILE__,__LINE__);
return -1;
}
}
// Set the value of a discrete variable allocated by this Component by name.
void Component::
setModelingOption(SimTK::State& s, const std::string& name, int flag) const
{
std::map<std::string, ModelingOptionInfo>::const_iterator it;
it = _namedModelingOptionInfo.find(name);
if(it != _namedModelingOptionInfo.end()) {
SimTK::DiscreteVariableIndex dvIndex = it->second.index;
if(flag > it->second.maxOptionValue){
std::stringstream msg;
msg << "Component::setModelingOption: "<< name
<< " flag cannot exceed "<< it->second.maxOptionValue <<".\n ";
throw Exception(msg.str(),__FILE__,__LINE__);
}
SimTK::Value<int>::downcast(
getDefaultSubsystem().updDiscreteVariable(s, dvIndex)).upd() = flag;
} else {
std::stringstream msg;
msg << "Component::setModelingOption: modeling option " << name
<< " not found.\n ";
throw Exception(msg.str(),__FILE__,__LINE__);
}
}
unsigned Component::printComponentsMatching(const std::string& substring) const
{
auto components = getComponentList();
components.setFilter(ComponentFilterAbsolutePathNameContainsString(substring));
unsigned count = 0;
for (const auto& comp : components) {
log_cout(comp.getAbsolutePathString());
++count;
}
return count;
}
int Component::getNumStateVariables() const
{
// Must have already called initSystem.
OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem);
//Get the number of state variables added (or exposed) by this Component
int ns = getNumStateVariablesAddedByComponent();
// And then include the states of its subcomponents
for (unsigned int i = 0; i<_memberSubcomponents.size(); i++)
ns += _memberSubcomponents[i]->getNumStateVariables();
for(unsigned int i=0; i<_propertySubcomponents.size(); i++)
ns += _propertySubcomponents[i]->getNumStateVariables();
for (unsigned int i = 0; i<_adoptedSubcomponents.size(); i++)
ns += _adoptedSubcomponents[i]->getNumStateVariables();
return ns;
}
const Component& Component::getOwner() const
{
if (!hasOwner()) {
std::string msg = "Component '" + getName() + "'::getOwner(). " +
"Has no owner assigned.\n" +
"Make sure the component was added to the Model " +
"(or another component).";
throw Exception(msg);
}
return _owner.getRef();
}
bool Component::hasOwner() const
{
return !_owner.empty();
}
const Component& Component::getRoot() const {
const Component* root = this;
while (root->hasOwner()) {
root = &root->getOwner();
}
return *root;
}
void Component::setOwner(const Component& owner)
{
if (&owner == this) {
std::string msg = "Component '" + getName() + "'::setOwner(). " +
"Attempted to set itself as its owner.";
throw Exception(msg);
}
else if (_owner.get() == &owner) {
return;
}
_owner.reset(&owner);
}
std::string Component::getAbsolutePathString() const
{
if (!hasOwner()) return "/";
std::string absPathName("/" + getName());
const Component* up = this;
while (up && up->hasOwner()) {
up = &up->getOwner();
if (up->hasOwner())
absPathName.insert(0, "/" + up->getName());
}
return absPathName;
}
ComponentPath Component::getAbsolutePath() const
{
if (!hasOwner()) return ComponentPath({}, true);
std::vector<std::string> pathVec;
pathVec.push_back(getName());
const Component* up = this;
while (up && up->hasOwner()) {
up = &up->getOwner();
if (up->hasOwner())
pathVec.insert(pathVec.begin(), up->getName());
}
return ComponentPath(pathVec, true);
}
std::string Component::getRelativePathString(const Component& wrt) const
{
return getRelativePath(wrt).toString();
}
ComponentPath Component::getRelativePath(const Component& wrt) const
{
ComponentPath thisP = getAbsolutePath();
ComponentPath wrtP = wrt.getAbsolutePath();
return thisP.formRelativePath(wrtP);
}
const Component::StateVariable* Component::
traverseToStateVariable(const std::string& pathName) const
{
// Must have already called initSystem.
OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem);
ComponentPath svPath(pathName);
const StateVariable* found = nullptr;
if (svPath.getNumPathLevels() == 1) {
// There was no slash. The state variable should be in this component.
auto it = _namedStateVariableInfo.find(pathName);
if (it != _namedStateVariableInfo.end()) {
return it->second.stateVariable.get();
}
} else if (svPath.getNumPathLevels() > 1) {
const auto& compPath = svPath.getParentPath();
const Component* comp = traversePathToComponent<Component>(compPath);
if (comp) {
// This is the leaf of the path:
const auto& varName = svPath.getComponentName();
found = comp->traverseToStateVariable(varName);
}
}
return found;
}
// Get the names of "continuous" state variables maintained by the Component and
// its subcomponents.
Array<std::string> Component::getStateVariableNames() const
{
// Must have already called initSystem.
OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem);
Array<std::string> stateNames = getStateVariableNamesAddedByComponent();
for (int i = 0; i < stateNames.size(); ++i) {
stateNames[i] = (getAbsolutePathString() + "/" + stateNames[i]);
}
for (auto& comp : getComponentList<Component>()) {
const std::string& pathName = comp.getAbsolutePathString();// *this);
Array<std::string> subStateNames =
comp.getStateVariableNamesAddedByComponent();
for (int i = 0; i < subStateNames.size(); ++i) {
stateNames.append(pathName + "/" + subStateNames[i]);
}
}
return stateNames;
}
// Get the value of a state variable allocated by this Component.
double Component::
getStateVariableValue(const SimTK::State& s, const std::string& name) const
{
// Must have already called initSystem.
OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem);
// find the state variable with this component or its subcomponents
const StateVariable* rsv = traverseToStateVariable(name);
if (rsv) {
return rsv->getValue(s);
}
std::stringstream msg;
msg << "Component::getStateVariableValue: ERR- state named '" << name
<< "' not found in " << getName() << " of type " << getConcreteClassName();
throw Exception(msg.str(),__FILE__,__LINE__);
return SimTK::NaN;
}
// Get the value of a state variable derivative computed by this Component.
double Component::
getStateVariableDerivativeValue(const SimTK::State& state,
const std::string& name) const
{
// Must have already called initSystem.
OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem);
computeStateVariableDerivatives(state);
std::map<std::string, StateVariableInfo>::const_iterator it;
it = _namedStateVariableInfo.find(name);
if(it != _namedStateVariableInfo.end()) {
return it->second.stateVariable->getDerivative(state);
}
else{
// otherwise find the component that variable belongs to
const StateVariable* rsv = traverseToStateVariable(name);
if (rsv) {
return rsv->getDerivative(state);
}
}
std::stringstream msg;
msg << "Component::getStateVariableDerivative: ERR- variable name '" << name
<< "' not found.\n "
<< getName() << " of type " << getConcreteClassName()
<< " has " << getNumStateVariables() << " states.";
throw Exception(msg.str(),__FILE__,__LINE__);
return SimTK::NaN;
}
// Set the value of a state variable allocated by this Component given its name
// for this component.
void Component::
setStateVariableValue(State& s, const std::string& name, double value) const
{
// Must have already called initSystem.
OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem);
// find the state variable
const StateVariable* rsv = traverseToStateVariable(name);
if(rsv){ // find required rummaging through the state variable names
return rsv->setValue(s, value);
}
std::stringstream msg;
msg << "Component::setStateVariable: ERR- state named '" << name
<< "' not found in " << getName() << " of type "
<< getConcreteClassName() << ".\n";
throw Exception(msg.str(),__FILE__,__LINE__);
}
bool Component::isAllStatesVariablesListValid() const
{
int nsv = getNumStateVariables();
// Consider the list of all StateVariables to be valid if all of
// the following conditions are true:
// 1. Component is up-to-date with its Properties
// 2. a System has been associated with the list of StateVariables
// 3. The list of all StateVariables is correctly sized (initialized)
// 4. The System associated with the StateVariables is the current System
// TODO: Enable the isObjectUpToDateWithProperties() check when computing
// the path of the GeomtryPath does not involve updating its PathPointSet.
// This change dirties the GeometryPath which is a property of a Muscle which
// is property of the Model. Therefore, during integration the Model is not
// up-to-date and this causes a rebuilding of the cached StateVariables list.
// See GeometryPath::computePath() for the corresponding TODO that must be
// addressed before we can re-enable the isObjectUpToDateWithProperties
// check.
// It has been verified that the adding Components will invalidate the state
// variables associated with the Model and force the list to be rebuilt.
bool valid = //isObjectUpToDateWithProperties() && // 1.
!_statesAssociatedSystem.empty() && // 2.
(int)_allStateVariables.size() == nsv && // 3.
getSystem().isSameSystem(_statesAssociatedSystem.getRef()); // 4.
return valid;
}
// Get all values of the state variables allocated by this Component. Includes
// state variables allocated by its subcomponents.
SimTK::Vector Component::
getStateVariableValues(const SimTK::State& state) const
{
// Must have already called initSystem.
OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem);
int nsv = getNumStateVariables();
// if the StateVariables are invalid (see above) rebuild the list
if (!isAllStatesVariablesListValid()) {
_statesAssociatedSystem.reset(&getSystem());
_allStateVariables.clear();
_allStateVariables.resize(nsv);
Array<std::string> names = getStateVariableNames();
for (int i = 0; i < nsv; ++i)
_allStateVariables[i].reset(traverseToStateVariable(names[i]));
}
Vector stateVariableValues(nsv, SimTK::NaN);
for(int i=0; i<nsv; ++i){
stateVariableValues[i]= _allStateVariables[i]->getValue(state);
}
return stateVariableValues;
}
// Set all values of the state variables allocated by this Component. Includes
// state variables allocated by its subcomponents.
void Component::
setStateVariableValues(SimTK::State& state,
const SimTK::Vector& values) const
{
// Must have already called initSystem.
OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem);
int nsv = getNumStateVariables();
SimTK_ASSERT(values.size() == nsv,
"Component::setStateVariableValues() number values does not match the "
"number of state variables.");
// if the StateVariables are invalid (see above) rebuild the list
if (!isAllStatesVariablesListValid()) {
_statesAssociatedSystem.reset(&getSystem());
_allStateVariables.clear();
_allStateVariables.resize(nsv);
Array<std::string> names = getStateVariableNames();
for (int i = 0; i < nsv; ++i)
_allStateVariables[i].reset(traverseToStateVariable(names[i]));
}
for(int i=0; i<nsv; ++i){
_allStateVariables[i]->setValue(state, values[i]);
}
}
// Set the derivative of a state variable computed by this Component by name.
void Component::
setStateVariableDerivativeValue(const State& state,
const std::string& name, double value) const
{
std::map<std::string, StateVariableInfo>::const_iterator it;
it = _namedStateVariableInfo.find(name);
if(it != _namedStateVariableInfo.end()) {
const StateVariable& sv = *it->second.stateVariable;
sv.setDerivative(state, value);
}
else{
std::stringstream msg;
msg << "Component::setStateVariableDerivative: ERR- name '" << name
<< "' not found.\n "
<< getName() << " of type " << getConcreteClassName()
<< " has " << getNumStateVariables() << " states.";
throw Exception(msg.str(),__FILE__,__LINE__);
}
}
// Get the value of a discrete variable allocated by this Component by name.
double Component::
getDiscreteVariableValue(const SimTK::State& s, const std::string& name) const
{
// Must have already called initSystem.
OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem);
std::map<std::string, DiscreteVariableInfo>::const_iterator it;
it = _namedDiscreteVariableInfo.find(name);
if(it != _namedDiscreteVariableInfo.end()) {
SimTK::DiscreteVariableIndex dvIndex = it->second.index;
return SimTK::Value<double>::downcast(
getDefaultSubsystem().getDiscreteVariable(s, dvIndex)).get();
} else {
std::stringstream msg;
msg << "Component::getDiscreteVariable: ERR- name '" << name
<< "' not found.\n "
<< "for component '"<< getName() << "' of type "
<< getConcreteClassName();
throw Exception(msg.str(),__FILE__,__LINE__);
return SimTK::NaN;
}
}
// Set the value of a discrete variable allocated by this Component by name.
void Component::
setDiscreteVariableValue(SimTK::State& s, const std::string& name, double value) const
{
// Must have already called initSystem.
OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem);
std::map<std::string, DiscreteVariableInfo>::const_iterator it;
it = _namedDiscreteVariableInfo.find(name);
if(it != _namedDiscreteVariableInfo.end()) {
SimTK::DiscreteVariableIndex dvIndex = it->second.index;
SimTK::Value<double>::downcast(
getDefaultSubsystem().updDiscreteVariable(s, dvIndex)).upd() = value;
} else {
std::stringstream msg;
msg << "Component::setDiscreteVariable: ERR- name '" << name
<< "' not found.\n "
<< "for component '"<< getName() << "' of type "
<< getConcreteClassName();
throw Exception(msg.str(),__FILE__,__LINE__);
}
}
SimTK::CacheEntryIndex Component::getCacheVariableIndex(const std::string& name) const
{
auto it = this->_namedCacheVariables.find(name);
if (it != this->_namedCacheVariables.end()) {
return it->second.index();
}
std::stringstream msg;
msg << "Cache variable with name '" << name << "' not found: maybe the cache variable was not allocated with `Component::addCacheVariable`?";
OPENSIM_THROW_FRMOBJ(Exception, msg.str());
}
bool Component::isCacheVariableValid(const SimTK::State& state, const std::string& name) const
{
const SimTK::DefaultSystemSubsystem& subsystem = this->getDefaultSubsystem();
const SimTK::CacheEntryIndex idx = this->getCacheVariableIndex(name);
return subsystem.isCacheValueRealized(state, idx);
}
void Component::markCacheVariableValid(const SimTK::State& state, const std::string& name) const
{
const SimTK::DefaultSystemSubsystem& subsystem = this->getDefaultSubsystem();
const SimTK::CacheEntryIndex idx = this->getCacheVariableIndex(name);
subsystem.markCacheValueRealized(state, idx);
}
void Component::markCacheVariableInvalid(const SimTK::State& state, const std::string& name) const
{
const SimTK::DefaultSystemSubsystem& subsystem = this->getDefaultSubsystem();
const SimTK::CacheEntryIndex idx = this->getCacheVariableIndex(name);
subsystem.markCacheValueNotRealized(state, idx);
}
bool Component::constructOutputForStateVariable(const std::string& name)
{
auto func = [name](const Component* comp,
const SimTK::State& s, const std::string&,
double& result) -> void {
result = comp->getStateVariableValue(s, name);
};
return constructOutput<double>(name, func, SimTK::Stage::Model);
}
// helper method to specify the order of subcomponents.
void Component::setNextSubcomponentInSystem(const Component& sub) const
{
auto it =
std::find(_orderedSubcomponents.begin(), _orderedSubcomponents.end(),
SimTK::ReferencePtr<const Component>(&sub));
if (it == _orderedSubcomponents.end()) {
_orderedSubcomponents.push_back(SimTK::ReferencePtr<const Component>(&sub));
}
}
void Component::updateFromXMLNode(SimTK::Xml::Element& node, int versionNumber)
{
// During deserialization, some components' clone() may
// finalizeFromProperties(). Upating from XML can then cause stale pointers.
// We must make sure to clear any pointers to properties that may exist
// in this component.
reset();
if (versionNumber < XMLDocument::getLatestVersion()) {
if (versionNumber < 30500) {
// In 3.3 and earlier, spaces in names were tolerated. Spaces are
// no longer acceptable in Component names.
if (node.hasAttribute("name")) {
auto name = node.getRequiredAttribute("name").getValue();
if (name.find_first_of("\n\t ") < std::string::npos) {
log_warn("{} name '{}' contains whitespace.",
getConcreteClassName(), name);
name.erase(
std::remove_if(name.begin(), name.end(), ::isspace),
name.end());
node.setAttributeValue("name", name);
log_warn("It was renamed to '{}'.", name);
}
}
else { // As 4.0 all Components must have a name. If none, assign one.
// Note: in finalizeFromProperties(), the Component will ensure
// that names are unique by travesing its list of subcomponents
// and renaming any duplicates.
node.setAttributeValue("name",
IO::Lowercase(getConcreteClassName()));
}
}
if (versionNumber < 30508) {
// Here's an example of the change this function might make:
// Previous: <connectors>
// <Connector_PhysicalFrame_ name="parent">
// <connectee_name>...</connectee_name>
// </Connector_PhysicalFrame_>
// </connectors>
// New: <connector_parent_connectee_name>...
// </connector_parent_connectee_name>
//
XMLDocument::updateConnectors30508(node);
}
if(versionNumber < 30510) {
// Before -- <connector_....> ... </connector_...>
// After -- <socket_...> ... </socket_...>
for(auto iter = node.element_begin();
iter != node.element_end();
++iter) {
std::string oldName{"connector"};
std::string newName{"socket"};
auto tagname = iter->getElementTag();
auto pos = tagname.find(oldName);
if(pos != std::string::npos) {
tagname.replace(pos, oldName.length(), newName);
iter->setElementTag(tagname);
}
}
}
if (versionNumber <= 30516) {
// Rename xml tags for socket_*_connectee_name to socket_*
std::string connecteeNameString = "_connectee_name";
for (auto iter = node.element_begin();
iter != node.element_end();
++iter) {
auto tagname = iter->getElementTag();
if (std::regex_match(tagname, std::regex("(socket_|input_)(.*)(_connectee_name)"))) {
auto pos = tagname.find(connecteeNameString);
if (pos != std::string::npos) {
tagname.replace(pos, connecteeNameString.length(), "");
iter->setElementTag(tagname);
}
}
else if (std::regex_match(tagname, std::regex("(input_)(.*)(_connectee_names)"))) {
auto pos = tagname.find(connecteeNameString);
if (pos != std::string::npos) {
tagname.replace(pos, connecteeNameString.length()+1, "");
iter->setElementTag(tagname);
}
}
}
}
}
Super::updateFromXMLNode(node, versionNumber);
}
// mark components owned as properties as subcomponents
void Component::markPropertiesAsSubcomponents()
{
// Method can be invoked for either constructing a new Component
// or the properties have been modified. In the latter case
// we must make sure that pointers to old properties are cleared
_propertySubcomponents.clear();
// Now mark properties that are Components as subcomponents
//loop over all its properties
for (int i = 0; i < getNumProperties(); ++i) {
auto& prop = getPropertyByIndex(i);
// check if property is of type Object
if (prop.isObjectProperty()) {
// a property is a list so cycle through its contents
for (int j = 0; j < prop.size(); ++j) {
const Object& obj = prop.getValueAsObject(j);
// if the object is a Component mark it
if (const Component* comp = dynamic_cast<const Component*>(&obj) ) {
markAsPropertySubcomponent(comp);
}
else {
// otherwise it may be a Set (of objects), and
// would prefer to do something like this to test:
// Set<Component>* objects = dynamic_cast<Set<Component>*>(obj)
// Instead we can see if the object has a property called
// "objects" which is a PropertyObjArray used by Set<T>.
// knowing the object Type is useful for debugging
// and it could be used to strengthen the test (e.g. scan
// for "Set" in the type name).
std::string objType = obj.getConcreteClassName();
if (obj.hasProperty("objects")) {
// get the PropertyObjArray if the object has one
auto& objectsProp = obj.getPropertyByName("objects");
// loop over the objects in the PropertyObjArray
for (int k = 0; k < objectsProp.size(); ++k) {
const Object& obj = objectsProp.getValueAsObject(k);
// if the object is a Component mark it
if (const Component* comp = dynamic_cast<const Component*>(&obj) )
markAsPropertySubcomponent(comp);
} // loop over objects and mark it if it is a component
} // end if property is a Set with "objects" inside
} // end of if/else property value is an Object or something else
} // loop over the property list
} // end if property is an Object
} // loop over properties
}
// mark a Component as a subcomponent of this one. If already a
// subcomponent, it is not added to the list again.
void Component::markAsPropertySubcomponent(const Component* component)
{
// Only add if the component is not already a part of this Component
SimTK::ReferencePtr<Component> compRef(const_cast<Component*>(component));
auto it =
std::find(_propertySubcomponents.begin(), _propertySubcomponents.end(), compRef);
if ( it == _propertySubcomponents.end() ){
// Must reconstruct the reference pointer in place in order
// to invoke move constructor from SimTK::Array::push_back
// otherwise it will copy and reset the Component pointer to null.
_propertySubcomponents.push_back(
SimTK::ReferencePtr<Component>(const_cast<Component*>(component)));
}
else{
auto compPath = component->getAbsolutePathString();
auto foundPath = it->get()->getAbsolutePathString();
OPENSIM_THROW( ComponentAlreadyPartOfOwnershipTree,
component->getName(), getName());
}
compRef->setOwner(*this);
}
// Include another Component as a subcomponent of this one. If already a
// subcomponent, it is not added to the list again.
void Component::adoptSubcomponent(Component* subcomponent)
{
OPENSIM_THROW_IF(subcomponent->hasOwner(),
ComponentAlreadyPartOfOwnershipTree,
subcomponent->getName(), this->getName());
//get the top-level component
const Component* top = this;
while (top->hasOwner())
top = &top->getOwner();
// cycle through all components from the top level component
// down to verify the component is not already in the tree
for (auto& comp : top->getComponentList<Component>()) {
OPENSIM_THROW_IF(subcomponent->hasOwner(),
ComponentAlreadyPartOfOwnershipTree,
subcomponent->getName(), comp.getName());
}
subcomponent->setOwner(*this);
_adoptedSubcomponents.push_back(SimTK::ClonePtr<Component>(subcomponent));
}
std::vector<SimTK::ReferencePtr<const Component>>
Component::getImmediateSubcomponents() const
{
std::vector<SimTK::ReferencePtr<const Component>> mySubcomponents;
for (auto& compRef : _memberSubcomponents) {
mySubcomponents.push_back(
SimTK::ReferencePtr<const Component>(compRef.get()) );
}
for (auto& compRef : _propertySubcomponents) {
mySubcomponents.push_back(
SimTK::ReferencePtr<const Component>(compRef.get()) );
}
for (auto& compRef : _adoptedSubcomponents) {
mySubcomponents.push_back(
SimTK::ReferencePtr<const Component>(compRef.get()) );
}
return mySubcomponents;
}
size_t Component::getNumMemberSubcomponents() const
{
return _memberSubcomponents.size();
}
size_t Component::getNumPropertySubcomponents() const
{
return _propertySubcomponents.size();
}
size_t Component::getNumAdoptedSubcomponents() const
{
return _adoptedSubcomponents.size();
}
int Component::getStateIndex(const std::string& name) const
{
std::map<std::string, StateVariableInfo>::const_iterator it;
it = _namedStateVariableInfo.find(name);
if(it != _namedStateVariableInfo.end()) {
return it->second.stateVariable->getVarIndex();
} else {
std::stringstream msg;
msg << "Component::getStateVariableSystemIndex: ERR- name '"
<< name << "' not found.\n "
<< "for component '"<< getName() << "' of type "
<< getConcreteClassName();
throw Exception(msg.str(),__FILE__,__LINE__);
return SimTK::InvalidIndex;
}
}
SimTK::SystemYIndex Component::
getStateVariableSystemIndex(const std::string& stateVariableName) const
{
//const SimTK::State& s = getSystem().getDefaultState();
std::map<std::string, StateVariableInfo>::const_iterator it;
it = _namedStateVariableInfo.find(stateVariableName);
if(it != _namedStateVariableInfo.end()){
return it->second.stateVariable->getSystemYIndex();
}
// Otherwise we have to search through subcomponents
SimTK::SystemYIndex yix;
for(unsigned int i = 0; i < _propertySubcomponents.size(); ++i) {
yix = _propertySubcomponents[i]->getStateVariableSystemIndex(stateVariableName);
if(yix.isValid()){
return yix;
}
}
if(!(yix.isValid())){
throw Exception(getConcreteClassName()
+ "::getStateVariableSystemIndex : state variable "
+ stateVariableName+" has an invalid index.");
}
return yix;
}
const SimTK::DiscreteVariableIndex Component::
getDiscreteVariableIndex(const std::string& name) const
{
std::map<std::string, DiscreteVariableInfo>::const_iterator it;
it = _namedDiscreteVariableInfo.find(name);
return it->second.index;
}
Array<std::string> Component::
getStateVariableNamesAddedByComponent() const
{
std::map<std::string, StateVariableInfo>::const_iterator it;
it = _namedStateVariableInfo.begin();
Array<std::string> names("",(int)_namedStateVariableInfo.size());
while(it != _namedStateVariableInfo.end()){
names[it->second.order] = it->first;
it++;
}
return names;
}
//------------------------------------------------------------------------------
// REALIZE TOPOLOGY
//------------------------------------------------------------------------------
// This is the base class implementation of a virtual method that can be
// overridden by derived model components, but they *must* invoke
// Super::extendRealizeTopology() as the first line in the overriding method so
// that this code is executed before theirs.
// This method is invoked from the ComponentMeasure associated with this
// Component.
// Note that subcomponent realize() methods will be invoked by their own
// ComponentMeasures, so we do not need to forward to subcomponents here.
void Component::extendRealizeTopology(SimTK::State& s) const
{
const SimTK::Subsystem& subSys = getSystem().getDefaultSubsystem();
// Allocate Modeling Option
for (auto& kv : _namedModelingOptionInfo) {
ModelingOptionInfo& moi = kv.second;
moi.index = subSys.allocateDiscreteVariable(
s, SimTK::Stage::Instance, new SimTK::Value<int>(0));
}
// Allocate Continuous State Variables
SimTK::Vector zInit(1, 0.0);
for (auto& kv : _namedStateVariableInfo) {
const StateVariable& sv = *kv.second.stateVariable;
const AddedStateVariable* asv =
dynamic_cast<const AddedStateVariable*>(&sv);
if (asv) { // add index information for added state variables
// make mutable just to update system allocated index ONLY!
AddedStateVariable* masv = const_cast<AddedStateVariable*>(asv);
masv->setVarIndex(subSys.allocateZ(s, zInit));
masv->setSubsystemIndex(
getDefaultSubsystem().getMySubsystemIndex());
}
}
// Allocate Discrete State Variables
for (auto& kv : _namedDiscreteVariableInfo) {
DiscreteVariableInfo& dvi = kv.second;
dvi.index = subSys.allocateDiscreteVariable(
s, dvi.invalidatesStage, new SimTK::Value<double>(0.0));
}
// allocate cache entry in the state
//
// BEWARE: the cache variables *must* be inserted into the SimTK::state
// in a deterministic order.
//
// The reason this is important is because:
//
// - some downstream code will take copies of the `SimTK::State`
// and expect indicies into the new state to also be able to
// index into the copy (they shouldn't do this, but do, and
// this code hardens against it)
//
// - to callers, it *feels* like the copy should be interchangable
// if the component is *logically* the same - the same component
// with the same cache vars etc. *should* produce the same state,
// right?
//
// - but `unordered_map` has no iteration order guarantees, so even
// the exact same component, at the same memory address, that is
// merely re-initialized, and calls `addCacheVariable` in the
// exact same order can still iterate the cache variables in
// a different order and (ultimately) produce an incompatible
// SimTK::State
//
// - this is because re-initialization does not necessarily
// reconstruct the backing containers. They may only have been
// `.clear()`ed, which *may* hold onto memory, which *may* affect
// (internal) insertion logic
//
// - the safest thing to assume is that the iteration order of
// `unordered_map` is non-deterministic. It isn't, but *essentially*
// is, because there are plenty of non-obvious ways to affect its
// iteration order
{
std::vector<std::reference_wrapper<const std::string>> keys;
keys.reserve(this->_namedCacheVariables.size());
for (auto& p : this->_namedCacheVariables) {
keys.emplace_back(p.first);
}
std::sort(keys.begin(), keys.end(), [](const std::string& a, const std::string& b) {
return a < b;
});
for (const std::string& k : keys) {
StoredCacheVariable& cv = this->_namedCacheVariables.at(k);
cv.maybeUninitIndex = subSys.allocateLazyCacheEntry(s, cv.dependsOnStage, cv.value->clone());
}
}
}
//------------------------------------------------------------------------------
// REALIZE ACCELERATION
//------------------------------------------------------------------------------
// Base class implementation of virtual method.
// Collect this component's state variable derivatives.
void Component::extendRealizeAcceleration(const SimTK::State& s) const
{
// don't bother computing derivatives if the component has no state variables
if(getNumStateVariablesAddedByComponent() > 0) {
const SimTK::Subsystem& subSys = getDefaultSubsystem();
// evaluate and set component state derivative values (in cache)
computeStateVariableDerivatives(s);
std::map<std::string, StateVariableInfo>::const_iterator it;
for (it = _namedStateVariableInfo.begin();
it != _namedStateVariableInfo.end(); ++it)
{
const StateVariable& sv = *it->second.stateVariable;
const AddedStateVariable* asv =
dynamic_cast<const AddedStateVariable*>(&sv);
if(asv)
// set corresponding system derivative value from
// cached value
subSys.updZDot(s)[ZIndex(asv->getVarIndex())] =
asv->getDerivative(s);
}
}
}
SimTK::MultibodySystem& Component::updSystem() const
{
OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem);
return _system.getRef();
}
//------------------------------------------------------------------------------
// OTHER REALIZE METHODS
//------------------------------------------------------------------------------
// Base class implementations of these virtual methods do nothing now but
// could do something in the future. Users must still invoke Super::realizeXXX()
// as the first line in their overrides to ensure future compatibility.
void Component::extendRealizeModel(SimTK::State& state) const {}
void Component::extendRealizeInstance(const SimTK::State& state) const {}
void Component::extendRealizeTime(const SimTK::State& state) const {}
void Component::extendRealizePosition(const SimTK::State& state) const {}
void Component::extendRealizeVelocity(const SimTK::State& state) const {}
void Component::extendRealizeDynamics(const SimTK::State& state) const {}
void Component::extendRealizeReport(const SimTK::State& state) const {}
//override virtual methods
double Component::AddedStateVariable::getValue(const SimTK::State& state) const
{
ZIndex zix(getVarIndex());
if(getSubsysIndex().isValid() && zix.isValid()){
const SimTK::Vector& z = getOwner().getDefaultSubsystem().getZ(state);
return z[ZIndex(zix)];
}
std::stringstream msg;
msg << "Component::AddedStateVariable::getValue: ERR- variable '"
<< getName() << "' is invalid for component " << getOwner().getName()
<< " of type " << getOwner().getConcreteClassName() <<".";
throw Exception(msg.str(),__FILE__,__LINE__);
return SimTK::NaN;
}
void Component::AddedStateVariable::setValue(SimTK::State& state, double value) const
{
ZIndex zix(getVarIndex());
if(getSubsysIndex().isValid() && zix.isValid()){
SimTK::Vector& z = getOwner().getDefaultSubsystem().updZ(state);
z[ZIndex(zix)] = value;
return;
}
std::stringstream msg;
msg << "Component::AddedStateVariable::setValue: ERR- variable '"
<< getName() << "' is invalid for component " << getOwner().getName()
<< " of type " << getOwner().getConcreteClassName() <<".";
throw Exception(msg.str(),__FILE__,__LINE__);
}
double Component::AddedStateVariable::
getDerivative(const SimTK::State& state) const
{
return getOwner().getCacheVariableValue<double>(state, getName()+"_deriv");
}
void Component::AddedStateVariable::
setDerivative(const SimTK::State& state, double deriv) const
{
getOwner().setCacheVariableValue<double>(state, getName()+"_deriv", deriv);
}
void Component::printSocketInfo() const {
std::string str = fmt::format("Sockets for component {} of type [{}] along "
"with connectee paths:", getName(),
getConcreteClassName());
if (getNumSockets() == 0)
str += " none";
log_cout(str);
size_t maxlenTypeName{}, maxlenSockName{};
for(const auto& sock : _socketsTable) {
maxlenTypeName = std::max(maxlenTypeName,
sock.second->getConnecteeTypeName().length());
maxlenSockName = std::max(maxlenSockName,
sock.second->getName().length());
}
maxlenTypeName += 6;
maxlenSockName += 1;
for (const auto& it : _socketsTable) {
const auto& socket = it.second;
// Right-justify the connectee type names and socket names.
str = fmt::format("{:>{}} {:>{}} : ",
fmt::format("[{}]", socket->getConnecteeTypeName()),
maxlenTypeName,
socket->getName(), maxlenSockName);
if (socket->getNumConnectees() == 0) {
str += "no connectees";
} else {
std::vector<std::string> connecteePaths;
for (unsigned i = 0; i < socket->getNumConnectees(); ++i) {
connecteePaths.push_back(socket->getConnecteePath(i));
}
// Join the connectee paths with spaces in between.
str += fmt::format("{}", fmt::join(connecteePaths, " "));
}
log_cout(str);
}
}
void Component::printInputInfo() const {
std::string str = fmt::format("Inputs for component {} of type [{}] along "
"with connectee paths:",
getName(), getConcreteClassName());
if (getNumInputs() == 0)
str += " none";
log_cout(str);
size_t maxlenTypeName{}, maxlenInputName{};
for(const auto& input : _inputsTable) {
maxlenTypeName = std::max(maxlenTypeName,
input.second->getConnecteeTypeName().length());
maxlenInputName = std::max(maxlenInputName,
input.second->getName().length());
}
maxlenTypeName += 6;
maxlenInputName += 1;
for (const auto& it : _inputsTable) {
const auto& input = it.second;
// Right-justify the connectee type names and input names.
str = fmt::format("{:>{}} {:>{}} : ",
fmt::format("[{}]", input->getConnecteeTypeName()),
maxlenTypeName,
input->getName(), maxlenInputName);
if (input->getNumConnectees() == 0 ||
(input->getNumConnectees() == 1 && input->getConnecteePath().empty())) {
str += "no connectees";
} else {
std::vector<std::string> connecteePaths;
for (unsigned i = 0; i < input->getNumConnectees(); ++i) {
connecteePaths.push_back(input->getConnecteePath(i));
// TODO as is, requires the input connections to be satisfied.
// std::cout << " (alias: " << input.getAlias(i) << ") ";
}
// Join the connectee paths with spaces in between.
str += fmt::format("{}", fmt::join(connecteePaths, " "));
}
log_cout(str);
}
}
void Component::printSubcomponentInfo() const {
printSubcomponentInfo<Component>();
}
void Component::printOutputInfo(const bool includeDescendants) const {
// Do not display header for Components with no outputs.
if (getNumOutputs() > 0) {
std::string msg = fmt::format("Outputs from {} [{}]",
getAbsolutePathString(),
getConcreteClassName());
msg += "\n" + std::string(msg.size(), '=');
log_cout(msg);
const auto& outputs = getOutputs();
size_t maxlen{};
for(const auto& output : outputs)
maxlen = std::max(maxlen, output.second->getTypeName().length());
maxlen += 6;
for(const auto& output : outputs) {
const auto& name = output.second->getTypeName();
log_cout("{:>{}} {}",
fmt::format("[{}]", output.second->getTypeName()),
maxlen, output.first);
}
log_cout("");
}
if (includeDescendants) {
for (const Component& thisComp : getComponentList<Component>()) {
// getComponentList() returns all descendants (i.e.,
// children, grandchildren, etc.) so set includeDescendants=false
// when calling on thisComp.
thisComp.printOutputInfo(false);
}
}
}
void Component::initComponentTreeTraversal(const Component &root) const {
// Going down the tree, this node is followed by all its children.
// The last child's successor (next) is the parent's successor.
const size_t nmsc = _memberSubcomponents.size();
const size_t npsc = _propertySubcomponents.size();
const size_t nasc = _adoptedSubcomponents.size();
if (!hasOwner()) {
// If this isn't the root component and it has no owner, then
// this is an orphan component and we likely failed to call
// finalizeFromProperties() on the root OR this is a clone that
// has not been added to the root (in which case would have an owner).
if (this != &root) {
OPENSIM_THROW(ComponentIsAnOrphan, getName(),
getConcreteClassName());
}
// if the root (have no owner) and have no components
else if (!(nmsc + npsc + nasc)) {
OPENSIM_THROW(ComponentIsRootWithNoSubcomponents,
getName(), getConcreteClassName());
}
}
const Component* last = nullptr;
for (unsigned int i = 0; i < nmsc; i++) {
if (i == nmsc - 1) {
_memberSubcomponents[i]->_nextComponent = _nextComponent.get();
last = _memberSubcomponents[i].get();
}
else {
_memberSubcomponents[i]->_nextComponent =
_memberSubcomponents[i + 1].get();
last = _memberSubcomponents[i + 1].get();
}
}
if (npsc) {
if (last)
last->_nextComponent = _propertySubcomponents[0].get();
for (unsigned int i = 0; i < npsc; i++) {
if (i == npsc - 1) {
_propertySubcomponents[i]->_nextComponent =
_nextComponent.get();
last = _propertySubcomponents[i].get();
}
else {
_propertySubcomponents[i]->_nextComponent =
_propertySubcomponents[i + 1].get();
last = _propertySubcomponents[i + 1].get();
}
}
}
if (nasc) {
if (last)
last->_nextComponent = _adoptedSubcomponents[0].get();
for (unsigned int i = 0; i <nasc; i++) {
if (i == nasc - 1) {
_adoptedSubcomponents[i]->_nextComponent = _nextComponent.get();
}
else {
_adoptedSubcomponents[i]->_nextComponent
= _adoptedSubcomponents[i + 1].get();
}
}
}
// recurse to handle children of subcomponents
for (unsigned int i = 0; i < nmsc; ++i) {
_memberSubcomponents[i]->initComponentTreeTraversal(root);
}
for (unsigned int i = 0; i < npsc; ++i) {
_propertySubcomponents[i]->initComponentTreeTraversal(root);
}
for (unsigned int i = 0; i < nasc; ++i) {
_adoptedSubcomponents[i]->initComponentTreeTraversal(root);
}
}
void Component::clearStateAllocations()
{
_namedModelingOptionInfo.clear();
_namedStateVariableInfo.clear();
_namedDiscreteVariableInfo.clear();
_namedCacheVariables.clear();
}
void Component::reset()
{
_system.reset();
_simTKcomponentIndex.invalidate();
clearStateAllocations();
_propertySubcomponents.clear();
_adoptedSubcomponents.clear();
resetSubcomponentOrder();
}
void Component::warnBeforePrint() const {
if (!isObjectUpToDateWithProperties()) return;
std::string message;
auto checkIfConnecteePathIsSet =
[](const Component& comp, std::string& message) {
for (const auto& it : comp._socketsTable) {
const auto& socket = it.second;
if (socket->isConnected() &&
((socket->isListSocket() &&
socket->getNumConnectees() == 0) ||
(!socket->isListSocket() &&
socket->getConnecteePath().empty()))) {
// TODO: Improve this condition by making sure the connectee
// name is correct.
message += " Socket '" + socket->getName() + "' in " +
comp.getConcreteClassName() + " at " +
comp.getAbsolutePathString() + "\n";
}
}
};
if (getNumImmediateSubcomponents() == 0) {
checkIfConnecteePathIsSet(*this, message);
} else {
for (const auto& comp : getComponentList()) {
checkIfConnecteePathIsSet(comp, message);
}
}
if (!message.empty()) {
std::stringstream buffer;
buffer << "Warning in " << getConcreteClassName()
<< "::print(): The following connections are not finalized "
"and will not appear in the resulting XML file. "
"Call finalizeConnections() before print().\n"
"To ignore, set the debug level to at least 1 "
"(e.g, by calling Object::setDebugLevel(1)) first.\n"
<< message << std::endl;
OPENSIM_THROW_FRMOBJ(Exception, buffer.str());
}
}
} // end of namespace OpenSim
|
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
static const int QGRAPHICSSCENE_INDEXTIMER_TIMEOUT = 2000;
/*!
\class QGraphicsScene
\brief The QGraphicsScene class provides a surface for managing a large
number of 2D graphical items.
\since 4.2
\ingroup multimedia
\ingroup graphicsview-api
\mainclass
The class serves as a container for QGraphicsItems. It is used together
with QGraphicsView for visualizing graphical items, such as lines,
rectangles, text, or even custom items, on a 2D surface. QGraphicsScene is
part of \l{The Graphics View Framework}.
QGraphicsScene also provides functionality that lets you efficiently
determine both the location of items, and for determining what items are
visible within an arbitrary area on the scene. With the QGraphicsView
widget, you can either visualize the whole scene, or zoom in and view only
parts of the scene.
Example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 0
Note that QGraphicsScene has no visual appearance of its own; it only
manages the items. You need to create a QGraphicsView widget to visualize
the scene.
To add items to a scene, you start off by constructing a QGraphicsScene
object. Then, you have two options: either add your existing QGraphicsItem
objects by calling addItem(), or you can call one of the convenience
functions addEllipse(), addLine(), addPath(), addPixmap(), addPolygon(),
addRect(), or addText(), which all return a pointer to the newly added item.
The dimensions of the items added with these functions are relative to the
item's coordinate system, and the items position is initialized to (0,
0) in the scene.
You can then visualize the scene using QGraphicsView. When the scene
changes, (e.g., when an item moves or is transformed) QGraphicsScene
emits the changed() signal. To remove an item, call removeItem().
QGraphicsScene uses an indexing algorithm to manage the location of items
efficiently. By default, a BSP (Binary Space Partitioning) tree is used; an
algorithm suitable for large scenes where most items remain static (i.e.,
do not move around). You can choose to disable this index by calling
setItemIndexMethod(). For more information about the available indexing
algorithms, see the itemIndexMethod property.
The scene's bounding rect is set by calling setSceneRect(). Items can be
placed at any position on the scene, and the size of the scene is by
default unlimited. The scene rect is used only for internal bookkeeping,
maintaining the scene's item index. If the scene rect is unset,
QGraphicsScene will use the bounding area of all items, as returned by
itemsBoundingRect(), as the scene rect. However, itemsBoundingRect() is a
relatively time consuming function, as it operates by collecting
positional information for every item on the scene. Because of this, you
should always set the scene rect when operating on large scenes.
One of QGraphicsScene's greatest strengths is its ability to efficiently
determine the location of items. Even with millions of items on the scene,
the items() functions can determine the location of an item within few
milliseconds. There are several overloads to items(): one that finds items
at a certain position, one that finds items inside or intersecting with a
polygon or a rectangle, and more. The list of returned items is sorted by
stacking order, with the topmost item being the first item in the list.
For convenience, there is also an itemAt() function that returns the
topmost item at a given position.
QGraphicsScene maintains selection information for the scene. To select
items, call setSelectionArea(), and to clear the current selection, call
clearSelection(). Call selectedItems() to get the list of all selected
items.
\section1 Event Handling and Propagation
Another responsibility that QGraphicsScene has, is to propagate events
from QGraphicsView. To send an event to a scene, you construct an event
that inherits QEvent, and then send it using, for example,
QApplication::sendEvent(). event() is responsible for dispatching
the event to the individual items. Some common events are handled by
convenience event handlers. For example, key press events are handled by
keyPressEvent(), and mouse press events are handled by mousePressEvent().
Key events are delivered to the \e {focus item}. To set the focus item,
you can either call setFocusItem(), passing an item that accepts focus, or
the item itself can call QGraphicsItem::setFocus(). Call focusItem() to
get the current focus item. For compatibility with widgets, the scene also
maintains its own focus information. By default, the scene does not have
focus, and all key events are discarded. If setFocus() is called, or if an
item on the scene gains focus, the scene automatically gains focus. If the
scene has focus, hasFocus() will return true, and key events will be
forwarded to the focus item, if any. If the scene loses focus, (i.e.,
someone calls clearFocus(),) while an item has focus, the scene will
maintain its item focus information, and once the scene regains focus, it
will make sure the last focus item regains focus.
For mouse-over effects, QGraphicsScene dispatches \e {hover
events}. If an item accepts hover events (see
QGraphicsItem::acceptHoverEvents()), it will receive a \l
{QEvent::}{GraphicsSceneHoverEnter} event when the mouse enters
its area. As the mouse continues moving inside the item's area,
QGraphicsScene will send it \l {QEvent::}{GraphicsSceneHoverMove}
events. When the mouse leaves the item's area, the item will
receive a \l {QEvent::}{GraphicsSceneHoverLeave} event.
All mouse events are delivered to the current \e {mouse grabber}
item. An item becomes the scene's mouse grabber if it accepts
mouse events (see QGraphicsItem::acceptedMouseButtons()) and it
receives a mouse press. It stays the mouse grabber until it
receives a mouse release when no other mouse buttons are
pressed. You can call mouseGrabberItem() to determine what item is
currently grabbing the mouse.
\sa QGraphicsItem, QGraphicsView
*/
/*!
\enum QGraphicsScene::SceneLayer
\since 4.3
This enum describes the rendering layers in a QGraphicsScene. When
QGraphicsScene draws the scene contents, it renders each of these layers
separately, in order.
Each layer represents a flag that can be OR'ed together when calling
functions such as invalidate() or QGraphicsView::invalidateScene().
\value ItemLayer The item layer. QGraphicsScene renders all items are in
this layer by calling the virtual function drawItems(). The item layer is
drawn after the background layer, but before the foreground layer.
\value BackgroundLayer The background layer. QGraphicsScene renders the
scene's background in this layer by calling the virtual function
drawBackground(). The background layer is drawn first of all layers.
\value ForegroundLayer The foreground layer. QGraphicsScene renders the
scene's foreground in this layer by calling the virtual function
drawForeground(). The foreground layer is drawn last of all layers.
\value AllLayers All layers; this value represents a combination of all
three layers.
\sa invalidate(), QGraphicsView::invalidateScene()
*/
/*!
\enum QGraphicsScene::ItemIndexMethod
This enum describes the indexing algorithms QGraphicsScene provides for
managing positional information about items on the scene.
\value BspTreeIndex A Binary Space Partitioning tree is applied. All
QGraphicsScene's item location algorithms are of an order close to
logarithmic complexity, by making use of binary search. Adding, moving and
removing items is logarithmic. This approach is best for static scenes
(i.e., scenes where most items do not move).
\value NoIndex No index is applied. Item location is of linear complexity,
as all items on the scene are searched. Adding, moving and removing items,
however, is done in constant time. This approach is ideal for dynamic
scenes, where many items are added, moved or removed continuously.
\sa setItemIndexMethod(), bspTreeDepth
*/
#include "qgraphicsscene.h"
#ifndef QT_NO_GRAPHICSVIEW
#include "qgraphicsitem.h"
#include "qgraphicsitem_p.h"
#include "qgraphicslayout.h"
#include "qgraphicsscene_p.h"
#include "qgraphicssceneevent.h"
#include "qgraphicsview.h"
#include "qgraphicsview_p.h"
#include "qgraphicswidget.h"
#include "qgraphicswidget_p.h"
#include <QtCore/qdebug.h>
#include <QtCore/qlist.h>
#include <QtCore/qmath.h>
#include <QtCore/qrect.h>
#include <QtCore/qset.h>
#include <QtCore/qstack.h>
#include <QtCore/qtimer.h>
#include <QtCore/qvarlengtharray.h>
#include <QtGui/qapplication.h>
#include <QtGui/qdesktopwidget.h>
#include <QtGui/qevent.h>
#include <QtGui/qgraphicslayout.h>
#include <QtGui/qgraphicsproxywidget.h>
#include <QtGui/qgraphicswidget.h>
#include <QtGui/qmatrix.h>
#include <QtGui/qpaintengine.h>
#include <QtGui/qpainter.h>
#include <QtGui/qpixmapcache.h>
#include <QtGui/qpolygon.h>
#include <QtGui/qstyleoption.h>
#include <QtGui/qtooltip.h>
#include <QtGui/qtransform.h>
#include <private/qapplication_p.h>
#include <private/qobject_p.h>
#ifdef Q_WS_X11
#include <private/qt_x11_p.h>
#endif
QT_BEGIN_NAMESPACE
static inline bool QRectF_intersects(const QRectF &s, const QRectF &r)
{
qreal xp = s.left();
qreal yp = s.top();
qreal w = s.width();
qreal h = s.height();
qreal l1 = xp;
qreal r1 = xp;
if (w < 0)
l1 += w;
else
r1 += w;
qreal l2 = r.left();
qreal r2 = r.left();
if (w < 0)
l2 += r.width();
else
r2 += r.width();
if (l1 >= r2 || l2 >= r1)
return false;
qreal t1 = yp;
qreal b1 = yp;
if (h < 0)
t1 += h;
else
b1 += h;
qreal t2 = r.top();
qreal b2 = r.top();
if (r.height() < 0)
t2 += r.height();
else
b2 += r.height();
return !(t1 >= b2 || t2 >= b1);
}
// QRectF::intersects() returns false always if either the source or target
// rectangle's width or height are 0. This works around that problem.
static QRectF _q_adjustedRect(const QRectF &rect)
{
static const qreal p = (qreal)0.00001;
QRectF r = rect;
if (!r.width())
r.adjust(-p, 0, p, 0);
if (!r.height())
r.adjust(0, -p, 0, p);
return r;
}
static void _q_hoverFromMouseEvent(QGraphicsSceneHoverEvent *hover, const QGraphicsSceneMouseEvent *mouseEvent)
{
hover->setWidget(mouseEvent->widget());
hover->setPos(mouseEvent->pos());
hover->setScenePos(mouseEvent->scenePos());
hover->setScreenPos(mouseEvent->screenPos());
hover->setLastPos(mouseEvent->lastPos());
hover->setLastScenePos(mouseEvent->lastScenePos());
hover->setLastScreenPos(mouseEvent->lastScreenPos());
hover->setModifiers(mouseEvent->modifiers());
hover->setAccepted(mouseEvent->isAccepted());
}
/*!
\internal
*/
QGraphicsScenePrivate::QGraphicsScenePrivate()
: changedSignalMask(0),
indexMethod(QGraphicsScene::BspTreeIndex),
bspTreeDepth(0),
lastItemCount(0),
hasSceneRect(false),
updateAll(false),
calledEmitUpdated(false),
selectionChanging(0),
dirtyItemResetPending(false),
regenerateIndex(true),
purgePending(false),
indexTimerId(0),
restartIndexTimer(false),
stickyFocus(false),
hasFocus(false),
focusItem(0),
lastFocusItem(0),
tabFocusFirst(0),
activeWindow(0),
activationRefCount(0),
lastMouseGrabberItem(0),
lastMouseGrabberItemHasImplicitMouseGrab(false),
dragDropItem(0),
enterWidget(0),
lastDropAction(Qt::IgnoreAction),
painterStateProtection(true),
sortCacheEnabled(false),
updatingSortCache(false),
style(0)
{
}
/*!
\internal
*/
void QGraphicsScenePrivate::init()
{
Q_Q(QGraphicsScene);
// Keep this index so we can check for connected slots later on.
changedSignalMask = (1 << q->metaObject()->indexOfSignal("changed(QList<QRectF>)"));
qApp->d_func()->scene_list.append(q);
q->update();
}
/*!
\internal
*/
QList<QGraphicsItem *> QGraphicsScenePrivate::estimateItemsInRect(const QRectF &rect) const
{
const_cast<QGraphicsScenePrivate *>(this)->purgeRemovedItems();
const_cast<QGraphicsScenePrivate *>(this)->_q_updateSortCache();
if (indexMethod == QGraphicsScene::BspTreeIndex) {
// ### Only do this once in a while.
QGraphicsScenePrivate *that = const_cast<QGraphicsScenePrivate *>(this);
// Get items from BSP tree
QList<QGraphicsItem *> items = that->bspTree.items(rect);
// Fill in with any unindexed items
for (int i = 0; i < unindexedItems.size(); ++i) {
if (QGraphicsItem *item = unindexedItems.at(i)) {
if (!item->d_ptr->itemDiscovered && item->d_ptr->visible && !(item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)) {
QRectF boundingRect = item->sceneBoundingRect();
if (QRectF_intersects(boundingRect, rect)) {
item->d_ptr->itemDiscovered = 1;
items << item;
}
}
}
}
// Reset the discovered state of all discovered items
for (int i = 0; i < items.size(); ++i)
items.at(i)->d_func()->itemDiscovered = 0;
return items;
}
QList<QGraphicsItem *> itemsInRect;
for (int i = 0; i < unindexedItems.size(); ++i) {
if (QGraphicsItem *item = unindexedItems.at(i)) {
if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)
continue;
if (item->d_ptr->visible && item->effectiveOpacity() > qreal(0.0))
itemsInRect << item;
}
}
for (int i = 0; i < indexedItems.size(); ++i) {
if (QGraphicsItem *item = indexedItems.at(i)) {
if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)
continue;
if (item->d_ptr->visible && item->effectiveOpacity() > qreal(0.0))
itemsInRect << item;
}
}
return itemsInRect;
}
/*!
\internal
*/
void QGraphicsScenePrivate::addToIndex(QGraphicsItem *item)
{
if (indexMethod == QGraphicsScene::BspTreeIndex) {
if (item->d_func()->index != -1) {
bspTree.insertItem(item, item->sceneBoundingRect());
foreach (QGraphicsItem *child, item->children())
child->addToIndex();
} else {
// The BSP tree is regenerated if the number of items grows to a
// certain threshold, or if the bounding rect of the graph doubles in
// size.
startIndexTimer();
}
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::removeFromIndex(QGraphicsItem *item)
{
if (indexMethod == QGraphicsScene::BspTreeIndex) {
int index = item->d_func()->index;
if (index != -1) {
bspTree.removeItem(item, item->sceneBoundingRect());
freeItemIndexes << index;
indexedItems[index] = 0;
item->d_func()->index = -1;
unindexedItems << item;
foreach (QGraphicsItem *child, item->children())
child->removeFromIndex();
}
startIndexTimer();
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::resetIndex()
{
purgeRemovedItems();
if (indexMethod == QGraphicsScene::BspTreeIndex) {
for (int i = 0; i < indexedItems.size(); ++i) {
if (QGraphicsItem *item = indexedItems.at(i)) {
item->d_ptr->index = -1;
unindexedItems << item;
}
}
indexedItems.clear();
freeItemIndexes.clear();
regenerateIndex = true;
startIndexTimer();
}
}
static inline int intmaxlog(int n)
{
return (n > 0 ? qMax(qCeil(qLn(qreal(n)) / qLn(qreal(2))), 5) : 0);
}
/*!
\internal
*/
void QGraphicsScenePrivate::_q_updateIndex()
{
if (!indexTimerId)
return;
Q_Q(QGraphicsScene);
q->killTimer(indexTimerId);
indexTimerId = 0;
purgeRemovedItems();
// Add unindexedItems to indexedItems
QRectF unindexedItemsBoundingRect;
for (int i = 0; i < unindexedItems.size(); ++i) {
if (QGraphicsItem *item = unindexedItems.at(i)) {
unindexedItemsBoundingRect |= item->sceneBoundingRect();
if (!freeItemIndexes.isEmpty()) {
int freeIndex = freeItemIndexes.takeFirst();
item->d_func()->index = freeIndex;
indexedItems[freeIndex] = item;
} else {
item->d_func()->index = indexedItems.size();
indexedItems << item;
}
}
}
// Update growing scene rect.
QRectF oldGrowingItemsBoundingRect = growingItemsBoundingRect;
growingItemsBoundingRect |= unindexedItemsBoundingRect;
// Determine whether we should regenerate the BSP tree.
if (indexMethod == QGraphicsScene::BspTreeIndex) {
int depth = bspTreeDepth;
if (depth == 0) {
int oldDepth = intmaxlog(lastItemCount);
depth = intmaxlog(indexedItems.size());
static const int slack = 100;
if (bspTree.leafCount() == 0 || (oldDepth != depth && qAbs(lastItemCount - indexedItems.size()) > slack)) {
// ### Crude algorithm.
regenerateIndex = true;
}
}
// Regenerate the tree.
if (regenerateIndex) {
regenerateIndex = false;
bspTree.initialize(q->sceneRect(), depth);
unindexedItems = indexedItems;
lastItemCount = indexedItems.size();
q->update();
// Take this opportunity to reset our largest-item counter for
// untransformable items. When the items are inserted into the BSP
// tree, we'll get an accurate calculation.
largestUntransformableItem = QRectF();
}
}
// Insert all unindexed items into the tree.
for (int i = 0; i < unindexedItems.size(); ++i) {
if (QGraphicsItem *item = unindexedItems.at(i)) {
QRectF rect = item->sceneBoundingRect();
if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)
continue;
if (indexMethod == QGraphicsScene::BspTreeIndex)
bspTree.insertItem(item, rect);
// If the item ignores view transformations, update our
// largest-item-counter to ensure that the view can accurately
// discover untransformable items when drawing.
if (item->d_ptr->itemIsUntransformable()) {
QGraphicsItem *topmostUntransformable = item;
while (topmostUntransformable && (topmostUntransformable->d_ptr->ancestorFlags
& QGraphicsItemPrivate::AncestorIgnoresTransformations)) {
topmostUntransformable = topmostUntransformable->parentItem();
}
// ### Verify that this is the correct largest untransformable rectangle.
largestUntransformableItem |= item->mapToItem(topmostUntransformable, item->boundingRect()).boundingRect();
}
}
}
unindexedItems.clear();
// Notify scene rect changes.
if (!hasSceneRect && growingItemsBoundingRect != oldGrowingItemsBoundingRect)
emit q->sceneRectChanged(growingItemsBoundingRect);
}
/*!
\internal
*/
void QGraphicsScenePrivate::_q_emitUpdated()
{
Q_Q(QGraphicsScene);
calledEmitUpdated = false;
// Ensure all views are connected if anything is connected. This disables
// the optimization that items send updates directly to the views, but it
// needs to happen in order to keep compatibility with the behavior from
// Qt 4.4 and backward.
if (!views.isEmpty() && (connectedSignals & changedSignalMask)) {
for (int i = 0; i < views.size(); ++i) {
QGraphicsView *view = views.at(i);
if (!view->d_func()->connectedToScene) {
view->d_func()->connectedToScene = true;
q->connect(q, SIGNAL(changed(QList<QRectF>)),
views.at(i), SLOT(updateScene(QList<QRectF>)));
}
}
}
// Ensure all dirty items's current positions are recorded in the list of
// updated rects.
for (int i = 0; i < dirtyItems.size(); ++i)
updatedRects += dirtyItems.at(i)->sceneBoundingRect();
// Notify the changes to anybody interested.
QList<QRectF> oldUpdatedRects;
oldUpdatedRects = updateAll ? (QList<QRectF>() << q->sceneRect()) : updatedRects;
updateAll = false;
updatedRects.clear();
emit q->changed(oldUpdatedRects);
}
/*!
\internal
Updates all items in the pending update list. At this point, the list is
unlikely to contain partially constructed items.
*/
void QGraphicsScenePrivate::_q_updateLater()
{
foreach (QGraphicsItem *item, pendingUpdateItems)
item->update();
pendingUpdateItems.clear();
}
/*!
\internal
*/
void QGraphicsScenePrivate::_q_polishItems()
{
foreach (QGraphicsItem *item, unpolishedItems) {
if (!item->d_ptr->explicitlyHidden) {
item->itemChange(QGraphicsItem::ItemVisibleChange, true);
item->itemChange(QGraphicsItem::ItemVisibleHasChanged, true);
}
if (item->isWidget()) {
QEvent event(QEvent::Polish);
QApplication::sendEvent((QGraphicsWidget *)item, &event);
}
}
unpolishedItems.clear();
}
/*!
\internal
*/
void QGraphicsScenePrivate::_q_resetDirtyItems()
{
for (int i = 0; i < dirtyItems.size(); ++i) {
QGraphicsItem *item = dirtyItems.at(i);
item->d_ptr->dirty = 0;
item->d_ptr->dirtyChildren = 0;
}
dirtyItems.clear();
dirtyItemResetPending = false;
}
/*!
\internal
*/
void QGraphicsScenePrivate::resetDirtyItemsLater()
{
Q_Q(QGraphicsScene);
if (dirtyItemResetPending)
return;
// dirtyItems.reserve(indexedItems.size() + unindexedItems.size());
dirtyItemResetPending = true;
QMetaObject::invokeMethod(q, "_q_resetDirtyItems", Qt::QueuedConnection);
}
/*!
\internal
Schedules an item for removal. This function leaves some stale indexes
around in the BSP tree; these will be cleaned up the next time someone
triggers purgeRemovedItems().
Note: This function is called from QGraphicsItem's destructor. \a item is
being destroyed, so we cannot call any pure virtual functions on it (such
as boundingRect()). Also, it is unnecessary to update the item's own state
in any way.
### Refactoring: This function shares much functionality with removeItem()
*/
void QGraphicsScenePrivate::_q_removeItemLater(QGraphicsItem *item)
{
Q_Q(QGraphicsScene);
if (QGraphicsItem *parent = item->d_func()->parent) {
QVariant variant;
qVariantSetValue<QGraphicsItem *>(variant, item);
parent->itemChange(QGraphicsItem::ItemChildRemovedChange, variant);
parent->d_func()->children.removeAll(item);
}
// Clear focus on the item to remove any reference in the focusWidget
// chain.
item->clearFocus();
int index = item->d_func()->index;
if (index != -1) {
// Important: The index is useless until purgeRemovedItems() is
// called.
indexedItems[index] = (QGraphicsItem *)0;
if (!purgePending) {
purgePending = true;
q->update();
}
removedItems << item;
} else {
// Recently added items are purged immediately. unindexedItems() never
// contains stale items.
unindexedItems.removeAll(item);
q->update();
}
// Reset the mouse grabber and focus item data.
if (item == focusItem)
focusItem = 0;
if (item == lastFocusItem)
lastFocusItem = 0;
if (item == activeWindow) {
// ### deactivate...
activeWindow = 0;
}
// Disable selectionChanged() for individual items
++selectionChanging;
int oldSelectedItemsSize = selectedItems.size();
// Update selected & hovered item bookkeeping
selectedItems.remove(item);
hoverItems.removeAll(item);
pendingUpdateItems.removeAll(item);
cachedItemsUnderMouse.removeAll(item);
unpolishedItems.removeAll(item);
dirtyItems.removeAll(item);
//We remove all references of item from the sceneEventFilter arrays
QMultiMap<QGraphicsItem*, QGraphicsItem*>::iterator iterator = sceneEventFilters.begin();
while (iterator != sceneEventFilters.end()) {
if (iterator.value() == item || iterator.key() == item)
iterator = sceneEventFilters.erase(iterator);
else
++iterator;
}
// Remove from scene transform cache
int transformIndex = item->d_func()->sceneTransformIndex;
if (transformIndex != -1) {
validTransforms.setBit(transformIndex, 0);
freeSceneTransformSlots.append(transformIndex);
}
// Remove all children recursively.
foreach (QGraphicsItem *child, item->children())
_q_removeItemLater(child);
// Reset the mouse grabber
if (mouseGrabberItems.contains(item))
ungrabMouse(item, /* item is dying */ true);
// Reset the keyboard grabber
if (keyboardGrabberItems.contains(item))
ungrabKeyboard(item, /* item is dying */ true);
// Reset the last mouse grabber item
if (item == lastMouseGrabberItem)
lastMouseGrabberItem = 0;
// Reenable selectionChanged() for individual items
--selectionChanging;
if (!selectionChanging && selectedItems.size() != oldSelectedItemsSize)
emit q->selectionChanged();
}
/*!
\internal
Removes stale pointers from all data structures.
*/
void QGraphicsScenePrivate::purgeRemovedItems()
{
Q_Q(QGraphicsScene);
if (!purgePending && removedItems.isEmpty())
return;
// Remove stale items from the BSP tree.
if (indexMethod != QGraphicsScene::NoIndex)
bspTree.removeItems(removedItems);
// Purge this list.
removedItems.clear();
freeItemIndexes.clear();
for (int i = 0; i < indexedItems.size(); ++i) {
if (!indexedItems.at(i))
freeItemIndexes << i;
}
purgePending = false;
// No locality info for the items; update the whole scene.
q->update();
}
/*!
\internal
Starts or restarts the timer used for reindexing unindexed items.
*/
void QGraphicsScenePrivate::startIndexTimer()
{
Q_Q(QGraphicsScene);
if (indexTimerId) {
restartIndexTimer = true;
} else {
indexTimerId = q->startTimer(QGRAPHICSSCENE_INDEXTIMER_TIMEOUT);
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::addPopup(QGraphicsWidget *widget)
{
Q_ASSERT(widget);
Q_ASSERT(!popupWidgets.contains(widget));
popupWidgets << widget;
if (QGraphicsWidget *focusWidget = widget->focusWidget()) {
focusWidget->setFocus(Qt::PopupFocusReason);
} else {
grabKeyboard((QGraphicsItem *)widget);
if (focusItem && popupWidgets.size() == 1) {
QFocusEvent event(QEvent::FocusOut, Qt::PopupFocusReason);
sendEvent(focusItem, &event);
}
}
grabMouse((QGraphicsItem *)widget);
}
/*!
\internal
Remove \a widget from the popup list. Important notes:
\a widget is guaranteed to be in the list of popups, but it might not be
the last entry; you can hide any item in the pop list before the others,
and this must cause all later mouse grabbers to lose the grab.
*/
void QGraphicsScenePrivate::removePopup(QGraphicsWidget *widget, bool itemIsDying)
{
Q_ASSERT(widget);
int index = popupWidgets.indexOf(widget);
Q_ASSERT(index != -1);
for (int i = popupWidgets.size() - 1; i >= index; --i) {
QGraphicsWidget *widget = popupWidgets.takeLast();
ungrabMouse(widget, itemIsDying);
if (focusItem && popupWidgets.isEmpty()) {
QFocusEvent event(QEvent::FocusIn, Qt::PopupFocusReason);
sendEvent(focusItem, &event);
} else {
ungrabKeyboard((QGraphicsItem *)widget, itemIsDying);
}
if (!itemIsDying && widget->isVisible()) {
widget->hide();
widget->QGraphicsItem::d_ptr->explicitlyHidden = 0;
}
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::grabMouse(QGraphicsItem *item, bool implicit)
{
// Append to list of mouse grabber items, and send a mouse grab event.
if (mouseGrabberItems.contains(item)) {
if (mouseGrabberItems.last() == item)
qWarning("QGraphicsItem::grabMouse: already a mouse grabber");
else
qWarning("QGraphicsItem::grabMouse: already blocked by mouse grabber: %p",
mouseGrabberItems.last());
return;
}
// Send ungrab event to the last grabber.
if (!mouseGrabberItems.isEmpty()) {
QGraphicsItem *last = mouseGrabberItems.last();
if (lastMouseGrabberItemHasImplicitMouseGrab) {
// Implicit mouse grab is immediately lost.
last->ungrabMouse();
} else {
// Just send ungrab event to current grabber.
QEvent ungrabEvent(QEvent::UngrabMouse);
sendEvent(last, &ungrabEvent);
}
}
mouseGrabberItems << item;
lastMouseGrabberItemHasImplicitMouseGrab = implicit;
// Send grab event to current grabber.
QEvent grabEvent(QEvent::GrabMouse);
sendEvent(item, &grabEvent);
}
/*!
\internal
*/
void QGraphicsScenePrivate::ungrabMouse(QGraphicsItem *item, bool itemIsDying)
{
int index = mouseGrabberItems.indexOf(item);
if (index == -1) {
qWarning("QGraphicsItem::ungrabMouse: not a mouse grabber");
return;
}
if (item != mouseGrabberItems.last()) {
// Recursively ungrab the next mouse grabber until we reach this item
// to ensure state consistency.
ungrabMouse(mouseGrabberItems.at(index + 1), itemIsDying);
}
if (!popupWidgets.isEmpty() && item == popupWidgets.last()) {
// If the item is a popup, go via removePopup to ensure state
// consistency and that it gets hidden correctly - beware that
// removePopup() reenters this function to continue removing the grab.
removePopup((QGraphicsWidget *)item, itemIsDying);
return;
}
// Send notification about mouse ungrab.
if (!itemIsDying) {
QEvent event(QEvent::UngrabMouse);
sendEvent(item, &event);
}
// Remove the item from the list of grabbers. Whenever this happens, we
// reset the implicitGrab (there can be only ever be one implicit grabber
// in a scene, and it is always the latest grabber; if the implicit grab
// is lost, it is not automatically regained.
mouseGrabberItems.takeLast();
lastMouseGrabberItemHasImplicitMouseGrab = false;
// Send notification about mouse regrab. ### It's unfortunate that all the
// items get a GrabMouse event, but this is a rare case with a simple
// implementation and it does ensure a consistent state.
if (!itemIsDying && !mouseGrabberItems.isEmpty()) {
QGraphicsItem *last = mouseGrabberItems.last();
QEvent event(QEvent::GrabMouse);
sendEvent(last, &event);
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::clearMouseGrabber()
{
if (!mouseGrabberItems.isEmpty())
mouseGrabberItems.first()->ungrabMouse();
lastMouseGrabberItem = 0;
}
/*!
\internal
*/
void QGraphicsScenePrivate::grabKeyboard(QGraphicsItem *item)
{
if (keyboardGrabberItems.contains(item)) {
if (keyboardGrabberItems.last() == item)
qWarning("QGraphicsItem::grabKeyboard: already a keyboard grabber");
else
qWarning("QGraphicsItem::grabKeyboard: already blocked by keyboard grabber: %p",
keyboardGrabberItems.last());
return;
}
// Send ungrab event to the last grabber.
if (!keyboardGrabberItems.isEmpty()) {
// Just send ungrab event to current grabber.
QEvent ungrabEvent(QEvent::UngrabKeyboard);
sendEvent(keyboardGrabberItems.last(), &ungrabEvent);
}
keyboardGrabberItems << item;
// Send grab event to current grabber.
QEvent grabEvent(QEvent::GrabKeyboard);
sendEvent(item, &grabEvent);
}
/*!
\internal
*/
void QGraphicsScenePrivate::ungrabKeyboard(QGraphicsItem *item, bool itemIsDying)
{
int index = keyboardGrabberItems.lastIndexOf(item);
if (index == -1) {
qWarning("QGraphicsItem::ungrabKeyboard: not a keyboard grabber");
return;
}
if (item != keyboardGrabberItems.last()) {
// Recursively ungrab the topmost keyboard grabber until we reach this
// item to ensure state consistency.
ungrabKeyboard(keyboardGrabberItems.at(index + 1), itemIsDying);
}
// Send notification about keyboard ungrab.
if (!itemIsDying) {
QEvent event(QEvent::UngrabKeyboard);
sendEvent(item, &event);
}
// Remove the item from the list of grabbers.
keyboardGrabberItems.takeLast();
// Send notification about mouse regrab.
if (!itemIsDying && !keyboardGrabberItems.isEmpty()) {
QGraphicsItem *last = keyboardGrabberItems.last();
QEvent event(QEvent::GrabKeyboard);
sendEvent(last, &event);
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::clearKeyboardGrabber()
{
if (!keyboardGrabberItems.isEmpty())
ungrabKeyboard(keyboardGrabberItems.first());
}
/*!
Returns all items for the screen position in \a event.
*/
QList<QGraphicsItem *> QGraphicsScenePrivate::itemsAtPosition(const QPoint &screenPos,
const QPointF &scenePos,
QWidget *widget) const
{
Q_Q(const QGraphicsScene);
QGraphicsView *view = widget ? qobject_cast<QGraphicsView *>(widget->parentWidget()) : 0;
QList<QGraphicsItem *> items;
if (view)
items = view->items(view->viewport()->mapFromGlobal(screenPos));
else
items = q->items(scenePos);
return items;
}
/*!
\internal
Checks if item collides with the path and mode, but also checks that if it
doesn't collide, maybe its frame rect will.
*/
bool QGraphicsScenePrivate::itemCollidesWithPath(QGraphicsItem *item,
const QPainterPath &path,
Qt::ItemSelectionMode mode)
{
if (item->collidesWithPath(path, mode))
return true;
if (item->isWidget()) {
// Check if this is a window, and if its frame rect collides.
QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
if (widget->isWindow()) {
QRectF frameRect = widget->windowFrameRect();
QPainterPath framePath;
framePath.addRect(frameRect);
bool intersects = path.intersects(frameRect);
if (mode == Qt::IntersectsItemShape || mode == Qt::IntersectsItemBoundingRect)
return intersects || path.contains(frameRect.topLeft())
|| framePath.contains(path.elementAt(0));
return !intersects && path.contains(frameRect.topLeft());
}
}
return false;
}
/*!
\internal
*/
void QGraphicsScenePrivate::storeMouseButtonsForMouseGrabber(QGraphicsSceneMouseEvent *event)
{
for (int i = 0x1; i <= 0x10; i <<= 1) {
if (event->buttons() & i) {
mouseGrabberButtonDownPos.insert(Qt::MouseButton(i),
mouseGrabberItems.last()->d_ptr->genericMapFromScene(event->scenePos(),
event->widget()));
mouseGrabberButtonDownScenePos.insert(Qt::MouseButton(i), event->scenePos());
mouseGrabberButtonDownScreenPos.insert(Qt::MouseButton(i), event->screenPos());
}
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::installSceneEventFilter(QGraphicsItem *watched, QGraphicsItem *filter)
{
sceneEventFilters.insert(watched, filter);
}
/*!
\internal
*/
void QGraphicsScenePrivate::removeSceneEventFilter(QGraphicsItem *watched, QGraphicsItem *filter)
{
if (!sceneEventFilters.contains(watched))
return;
QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator it = sceneEventFilters.lowerBound(watched);
QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator end = sceneEventFilters.upperBound(watched);
do {
if (it.value() == filter)
it = sceneEventFilters.erase(it);
else
++it;
} while (it != end);
}
/*!
\internal
*/
bool QGraphicsScenePrivate::filterEvent(QGraphicsItem *item, QEvent *event)
{
if (item && !sceneEventFilters.contains(item))
return false;
QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator it = sceneEventFilters.lowerBound(item);
QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator end = sceneEventFilters.upperBound(item);
while (it != end) {
// ### The filterer and filteree might both be deleted.
if (it.value()->sceneEventFilter(it.key(), event))
return true;
++it;
}
return false;
}
/*!
\internal
This is the final dispatch point for any events from the scene to the
item. It filters the event first - if the filter returns true, the event
is considered to have been eaten by the filter, and is therefore stopped
(the default filter returns false). Then/otherwise, if the item is
enabled, the event is sent; otherwise it is stopped.
*/
bool QGraphicsScenePrivate::sendEvent(QGraphicsItem *item, QEvent *event)
{
if (filterEvent(item, event))
return false;
return (item && item->isEnabled()) ? item->sceneEvent(event) : false;
}
/*!
\internal
*/
void QGraphicsScenePrivate::cloneDragDropEvent(QGraphicsSceneDragDropEvent *dest,
QGraphicsSceneDragDropEvent *source)
{
dest->setWidget(source->widget());
dest->setPos(source->pos());
dest->setScenePos(source->scenePos());
dest->setScreenPos(source->screenPos());
dest->setButtons(source->buttons());
dest->setModifiers(source->modifiers());
dest->setPossibleActions(source->possibleActions());
dest->setProposedAction(source->proposedAction());
dest->setDropAction(source->dropAction());
dest->setSource(source->source());
dest->setMimeData(source->mimeData());
}
/*!
\internal
*/
void QGraphicsScenePrivate::sendDragDropEvent(QGraphicsItem *item,
QGraphicsSceneDragDropEvent *dragDropEvent)
{
dragDropEvent->setPos(item->d_ptr->genericMapFromScene(dragDropEvent->scenePos(), dragDropEvent->widget()));
sendEvent(item, dragDropEvent);
}
/*!
\internal
*/
void QGraphicsScenePrivate::sendHoverEvent(QEvent::Type type, QGraphicsItem *item,
QGraphicsSceneHoverEvent *hoverEvent)
{
QGraphicsSceneHoverEvent event(type);
event.setWidget(hoverEvent->widget());
event.setPos(item->d_ptr->genericMapFromScene(hoverEvent->scenePos(), hoverEvent->widget()));
event.setScenePos(hoverEvent->scenePos());
event.setScreenPos(hoverEvent->screenPos());
event.setLastPos(item->d_ptr->genericMapFromScene(hoverEvent->lastScenePos(), hoverEvent->widget()));
event.setLastScenePos(hoverEvent->lastScenePos());
event.setLastScreenPos(hoverEvent->lastScreenPos());
event.setModifiers(hoverEvent->modifiers());
sendEvent(item, &event);
}
/*!
\internal
*/
void QGraphicsScenePrivate::sendMouseEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
if (mouseEvent->button() == 0 && mouseEvent->buttons() == 0 && lastMouseGrabberItemHasImplicitMouseGrab) {
// ### This is a temporary fix for until we get proper mouse
// grab events.
clearMouseGrabber();
return;
}
QGraphicsItem *item = mouseGrabberItems.last();
for (int i = 0x1; i <= 0x10; i <<= 1) {
Qt::MouseButton button = Qt::MouseButton(i);
mouseEvent->setButtonDownPos(button, mouseGrabberButtonDownPos.value(button, item->d_ptr->genericMapFromScene(mouseEvent->scenePos(), mouseEvent->widget())));
mouseEvent->setButtonDownScenePos(button, mouseGrabberButtonDownScenePos.value(button, mouseEvent->scenePos()));
mouseEvent->setButtonDownScreenPos(button, mouseGrabberButtonDownScreenPos.value(button, mouseEvent->screenPos()));
}
mouseEvent->setPos(item->d_ptr->genericMapFromScene(mouseEvent->scenePos(), mouseEvent->widget()));
mouseEvent->setLastPos(item->d_ptr->genericMapFromScene(mouseEvent->lastScenePos(), mouseEvent->widget()));
sendEvent(item, mouseEvent);
}
/*!
\internal
*/
void QGraphicsScenePrivate::mousePressEventHandler(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_Q(QGraphicsScene);
// Ignore by default, unless we find a mouse grabber that accepts it.
mouseEvent->ignore();
// Deliver to any existing mouse grabber.
if (!mouseGrabberItems.isEmpty()) {
// The event is ignored by default, but we disregard the event's
// accepted state after delivery; the mouse is grabbed, after all.
sendMouseEvent(mouseEvent);
return;
}
// Start by determining the number of items at the current position.
// Reuse value from earlier calculations if possible.
if (cachedItemsUnderMouse.isEmpty()) {
cachedItemsUnderMouse = itemsAtPosition(mouseEvent->screenPos(),
mouseEvent->scenePos(),
mouseEvent->widget());
}
// Update window activation.
QGraphicsWidget *newActiveWindow = windowForItem(cachedItemsUnderMouse.value(0));
if (newActiveWindow != activeWindow)
q->setActiveWindow(newActiveWindow);
// Set focus on the topmost enabled item that can take focus.
bool setFocus = false;
foreach (QGraphicsItem *item, cachedItemsUnderMouse) {
if (item->isEnabled() && (item->flags() & QGraphicsItem::ItemIsFocusable)) {
if (!item->isWidget() || ((QGraphicsWidget *)item)->focusPolicy() & Qt::ClickFocus) {
setFocus = true;
if (item != q->focusItem())
q->setFocusItem(item, Qt::MouseFocusReason);
break;
}
}
}
// If nobody could take focus, clear it.
if (!stickyFocus && !setFocus)
q->setFocusItem(0, Qt::MouseFocusReason);
// Find a mouse grabber by sending mouse press events to all mouse grabber
// candidates one at a time, until the event is accepted. It's accepted by
// default, so the receiver has to explicitly ignore it for it to pass
// through.
foreach (QGraphicsItem *item, cachedItemsUnderMouse) {
if (!(item->acceptedMouseButtons() & mouseEvent->button())) {
// Skip items that don't accept the event's mouse button.
continue;
}
grabMouse(item, /* implicit = */ true);
mouseEvent->accept();
// check if the item we are sending to are disabled (before we send the event)
bool disabled = !item->isEnabled();
bool isWindow = item->isWindow();
if (mouseEvent->type() == QEvent::GraphicsSceneMouseDoubleClick && item != lastMouseGrabberItem) {
// If this item is different from the item that received the last
// mouse event, and mouseEvent is a doubleclick event, then the
// event is converted to a press. Known limitation:
// Triple-clicking will not generate a doubleclick, though.
QGraphicsSceneMouseEvent mousePress(QEvent::GraphicsSceneMousePress);
mousePress.accept();
mousePress.setButton(mouseEvent->button());
mousePress.setButtons(mouseEvent->buttons());
mousePress.setScreenPos(mouseEvent->screenPos());
mousePress.setScenePos(mouseEvent->scenePos());
mousePress.setModifiers(mouseEvent->modifiers());
mousePress.setWidget(mouseEvent->widget());
mousePress.setButtonDownPos(mouseEvent->button(),
mouseEvent->buttonDownPos(mouseEvent->button()));
mousePress.setButtonDownScenePos(mouseEvent->button(),
mouseEvent->buttonDownScenePos(mouseEvent->button()));
mousePress.setButtonDownScreenPos(mouseEvent->button(),
mouseEvent->buttonDownScreenPos(mouseEvent->button()));
sendMouseEvent(&mousePress);
mouseEvent->setAccepted(mousePress.isAccepted());
} else {
sendMouseEvent(mouseEvent);
}
bool dontSendUngrabEvents = mouseGrabberItems.isEmpty() || mouseGrabberItems.last() != item;
if (disabled) {
ungrabMouse(item, /* itemIsDying = */ dontSendUngrabEvents);
break;
}
if (mouseEvent->isAccepted()) {
if (!mouseGrabberItems.isEmpty())
storeMouseButtonsForMouseGrabber(mouseEvent);
lastMouseGrabberItem = item;
return;
}
ungrabMouse(item, /* itemIsDying = */ dontSendUngrabEvents);
// Don't propagate through windows.
if (isWindow)
break;
}
// Is the event still ignored? Then the mouse press goes to the scene.
// Reset the mouse grabber, clear the selection, clear focus, and leave
// the event ignored so that it can propagate through the originating
// view.
if (!mouseEvent->isAccepted()) {
clearMouseGrabber();
QGraphicsView *view = mouseEvent->widget() ? qobject_cast<QGraphicsView *>(mouseEvent->widget()->parentWidget()) : 0;
bool dontClearSelection = view && view->dragMode() == QGraphicsView::ScrollHandDrag;
if (!dontClearSelection) {
// Clear the selection if the originating view isn't in scroll
// hand drag mode. The view will clear the selection if no drag
// happened.
q->clearSelection();
}
}
}
QGraphicsWidget *QGraphicsScenePrivate::windowForItem(const QGraphicsItem *item) const
{
if (!item)
return 0;
do {
if (item->isWidget())
return static_cast<const QGraphicsWidget *>(item)->window();
item = item->parentItem();
} while (item);
return 0;
}
QList<QGraphicsItem *> QGraphicsScenePrivate::items_helper(const QRectF &rect,
Qt::ItemSelectionMode mode,
Qt::SortOrder order) const
{
QList<QGraphicsItem *> items;
QPainterPath path;
// The index returns a rough estimate of what items are inside the rect.
// Refine it by iterating through all returned items.
QRectF adjustedRect = _q_adjustedRect(rect);
foreach (QGraphicsItem *item, estimateItemsInRect(adjustedRect)) {
// Find the item's scene transform in a clever way.
QTransform x = item->sceneTransform();
bool keep = false;
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
QRectF br = _q_adjustedRect(item->boundingRect());
if (mode >= Qt::ContainsItemBoundingRect) {
// Rect intersects/contains item's bounding rect
QRectF mbr = x.mapRect(br);
if ((mode == Qt::IntersectsItemBoundingRect && QRectF_intersects(rect, mbr))
|| (mode == Qt::ContainsItemBoundingRect && rect != mbr && rect.contains(mbr))) {
items << item;
keep = true;
}
} else {
// Rect intersects/contains item's shape
if (QRectF_intersects(adjustedRect, x.mapRect(br))) {
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
if (path == QPainterPath())
path.addRect(rect);
if (itemCollidesWithPath(item, xinv.map(path), mode)) {
items << item;
keep = true;
}
}
}
}
if (keep && (item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) {
// Recurse into children that clip children.
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
if (x.type() <= QTransform::TxScale) {
// Rect
childItems_helper(&items, item, xinv.mapRect(rect), mode);
} else {
// Polygon
childItems_helper(&items, item, xinv.map(rect), mode);
}
}
}
}
if (order != Qt::SortOrder(-1))
sortItems(&items, order, sortCacheEnabled);
return items;
}
QList<QGraphicsItem *> QGraphicsScenePrivate::items_helper(const QPolygonF &polygon,
Qt::ItemSelectionMode mode,
Qt::SortOrder order) const
{
QList<QGraphicsItem *> items;
QRectF polyRect = _q_adjustedRect(polygon.boundingRect());
QPainterPath path;
// The index returns a rough estimate of what items are inside the rect.
// Refine it by iterating through all returned items.
foreach (QGraphicsItem *item, estimateItemsInRect(polyRect)) {
// Find the item's scene transform in a clever way.
QTransform x = item->sceneTransform();
bool keep = false;
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
QRectF br = _q_adjustedRect(item->boundingRect());
if (mode >= Qt::ContainsItemBoundingRect) {
// Polygon contains/intersects item's bounding rect
if (path == QPainterPath())
path.addPolygon(polygon);
if ((mode == Qt::IntersectsItemBoundingRect && path.intersects(x.mapRect(br)))
|| (mode == Qt::ContainsItemBoundingRect && path.contains(x.mapRect(br)))) {
items << item;
keep = true;
}
} else {
// Polygon contains/intersects item's shape
if (QRectF_intersects(polyRect, x.mapRect(br))) {
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
if (path == QPainterPath())
path.addPolygon(polygon);
if (itemCollidesWithPath(item, xinv.map(path), mode)) {
items << item;
keep = true;
}
}
}
}
if (keep && (item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) {
// Recurse into children that clip children.
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok)
childItems_helper(&items, item, xinv.map(polygon), mode);
}
}
if (order != Qt::SortOrder(-1))
sortItems(&items, order, sortCacheEnabled);
return items;
}
QList<QGraphicsItem *> QGraphicsScenePrivate::items_helper(const QPainterPath &path,
Qt::ItemSelectionMode mode,
Qt::SortOrder order) const
{
QList<QGraphicsItem *> items;
// The index returns a rough estimate of what items are inside the rect.
// Refine it by iterating through all returned items.
foreach (QGraphicsItem *item, estimateItemsInRect(_q_adjustedRect(path.controlPointRect()))) {
// Find the item's scene transform in a clever way.
QTransform x = item->sceneTransform();
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
QPainterPath mappedPath = xinv.map(path);
if (itemCollidesWithPath(item, mappedPath, mode)) {
items << item;
if (item->flags() & QGraphicsItem::ItemClipsChildrenToShape)
childItems_helper(&items, item, mappedPath, mode);
}
}
}
if (order != Qt::SortOrder(-1))
sortItems(&items, order, sortCacheEnabled);
return items;
}
void QGraphicsScenePrivate::childItems_helper(QList<QGraphicsItem *> *items,
const QGraphicsItem *parent,
const QRectF &rect,
Qt::ItemSelectionMode mode) const
{
QPainterPath path;
bool parentClip = (parent->flags() & QGraphicsItem::ItemClipsChildrenToShape);
QRectF r = !parentClip ? _q_adjustedRect(rect) : _q_adjustedRect(rect).intersected(_q_adjustedRect(parent->boundingRect()));
if (r.isEmpty())
return;
QList<QGraphicsItem *> &children = parent->d_ptr->children;
for (int i = 0; i < children.size(); ++i) {
QGraphicsItem *item = children.at(i);
if (item->d_ptr->hasTransform && !item->transform().isInvertible())
continue;
// Skip invisible items and all their children.
if (!item->d_ptr->visible || qFuzzyCompare(item->effectiveOpacity(), qreal(0.0)))
continue;
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
QRectF br = _q_adjustedRect(item->boundingRect());
QRectF mbr = item->mapRectToParent(br);
bool keep = false;
if (mode >= Qt::ContainsItemBoundingRect) {
// Rect intersects/contains item's bounding rect
if ((mode == Qt::IntersectsItemBoundingRect && QRectF_intersects(rect, mbr))
|| (mode == Qt::ContainsItemBoundingRect && rect != mbr && rect.contains(br))) {
items->append(item);
keep = true;
}
} else {
// Rect intersects/contains item's shape
if (QRectF_intersects(rect, mbr)) {
if (path == QPainterPath())
path.addRect(rect);
if (itemCollidesWithPath(item, item->mapFromParent(path), mode)) {
items->append(item);
keep = true;
}
}
}
if ((keep || !(item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) && !item->d_ptr->children.isEmpty()) {
// Recurse into children.
if (!item->d_ptr->hasTransform || item->transform().type() <= QTransform::TxScale) {
// Rect
childItems_helper(items, item, item->mapRectFromParent(rect), mode);
} else {
// Polygon
childItems_helper(items, item, item->mapFromParent(rect), mode);
}
}
}
}
void QGraphicsScenePrivate::childItems_helper(QList<QGraphicsItem *> *items,
const QGraphicsItem *parent,
const QPolygonF &polygon,
Qt::ItemSelectionMode mode) const
{
QPainterPath path;
bool parentClip = (parent->flags() & QGraphicsItem::ItemClipsChildrenToShape);
QRectF polyRect = _q_adjustedRect(polygon.boundingRect());
QRectF r = !parentClip ? polyRect : polyRect.intersected(_q_adjustedRect(parent->boundingRect()));
if (r.isEmpty())
return;
QList<QGraphicsItem *> &children = parent->d_ptr->children;
for (int i = 0; i < children.size(); ++i) {
QGraphicsItem *item = children.at(i);
if (item->d_ptr->hasTransform && !item->transform().isInvertible())
continue;
// Skip invisible items.
if (!item->d_ptr->visible || qFuzzyCompare(item->effectiveOpacity() + 1, qreal(1.0)))
continue;
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
QRectF br = _q_adjustedRect(item->boundingRect());
bool keep = false;
if (mode >= Qt::ContainsItemBoundingRect) {
// Polygon contains/intersects item's bounding rect
if (path == QPainterPath())
path.addPolygon(polygon);
if ((mode == Qt::IntersectsItemBoundingRect && path.intersects(item->mapRectToParent(br)))
|| (mode == Qt::ContainsItemBoundingRect && path.contains(item->mapRectToParent(br)))) {
items->append(item);
keep = true;
}
} else {
// Polygon contains/intersects item's shape
if (QRectF_intersects(polyRect, item->mapRectToParent(br))) {
if (path == QPainterPath())
path.addPolygon(polygon);
if (itemCollidesWithPath(item, item->mapFromParent(path), mode)) {
items->append(item);
keep = true;
}
}
}
if ((keep || !(item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) && !item->d_ptr->children.isEmpty()) {
// Recurse into children that clip children.
childItems_helper(items, item, item->mapFromParent(polygon), mode);
}
}
}
void QGraphicsScenePrivate::childItems_helper(QList<QGraphicsItem *> *items,
const QGraphicsItem *parent,
const QPainterPath &path,
Qt::ItemSelectionMode mode) const
{
bool parentClip = (parent->flags() & QGraphicsItem::ItemClipsChildrenToShape);
QPainterPath intersectedPath = !parentClip ? path : path.intersected(parent->shape());
if (intersectedPath.isEmpty())
return;
QList<QGraphicsItem *> &children = parent->d_ptr->children;
for (int i = 0; i < children.size(); ++i) {
QGraphicsItem *item = children.at(i);
// Skip invisible items.
if (!item->d_ptr->visible || qFuzzyCompare(item->effectiveOpacity(), qreal(0.0)))
continue;
QTransform x = item->sceneTransform();
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
QPainterPath mappedPath = xinv.map(path);
if (itemCollidesWithPath(item, mappedPath, mode)) {
items->append(item);
if (!item->d_ptr->children.isEmpty())
childItems_helper(items, item, mappedPath, mode);
}
}
}
}
void QGraphicsScenePrivate::invalidateSortCache()
{
Q_Q(QGraphicsScene);
if (!sortCacheEnabled || updatingSortCache)
return;
updatingSortCache = true;
QMetaObject::invokeMethod(q, "_q_updateSortCache", Qt::QueuedConnection);
}
/*!
\internal
Should not be exported, but we can't change that now.
### Qt 5: Remove symbol / make static
*/
inline bool qt_closestLeaf(const QGraphicsItem *item1, const QGraphicsItem *item2)
{
// Return true if sibling item1 is on top of item2.
const QGraphicsItemPrivate *d1 = item1->d_ptr;
const QGraphicsItemPrivate *d2 = item2->d_ptr;
bool f1 = d1->flags & QGraphicsItem::ItemStacksBehindParent;
bool f2 = d2->flags & QGraphicsItem::ItemStacksBehindParent;
if (f1 != f2) return f2;
qreal z1 = d1->z;
qreal z2 = d2->z;
return z1 != z2 ? z1 > z2 : item1 > item2;
}
/*!
\internal
Should not be exported, but we can't change that now.
*/
inline bool qt_closestItemFirst(const QGraphicsItem *item1, const QGraphicsItem *item2)
{
return QGraphicsScenePrivate::closestItemFirst_withoutCache(item1, item2);
}
/*!
Returns true if \a item1 is on top of \a item2.
\internal
*/
bool QGraphicsScenePrivate::closestItemFirst_withoutCache(const QGraphicsItem *item1, const QGraphicsItem *item2)
{
// Siblings? Just check their z-values.
const QGraphicsItemPrivate *d1 = item1->d_ptr;
const QGraphicsItemPrivate *d2 = item2->d_ptr;
if (d1->parent == d2->parent)
return qt_closestLeaf(item1, item2);
// Find common ancestor, and each item's ancestor closest to the common
// ancestor.
int item1Depth = d1->depth;
int item2Depth = d2->depth;
const QGraphicsItem *p = item1;
const QGraphicsItem *t1 = item1;
while (item1Depth > item2Depth && (p = p->d_ptr->parent)) {
if (p == item2) {
// item2 is one of item1's ancestors; item1 is on top
return !(t1->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent);
}
t1 = p;
--item1Depth;
}
p = item2;
const QGraphicsItem *t2 = item2;
while (item2Depth > item1Depth && (p = p->d_ptr->parent)) {
if (p == item1) {
// item1 is one of item2's ancestors; item1 is not on top
return (t2->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent);
}
t2 = p;
--item2Depth;
}
// item1Ancestor is now at the same level as item2Ancestor, but not the same.
const QGraphicsItem *a1 = t1;
const QGraphicsItem *a2 = t2;
while (a1) {
const QGraphicsItem *p1 = a1;
const QGraphicsItem *p2 = a2;
a1 = a1->parentItem();
a2 = a2->parentItem();
if (a1 && a1 == a2)
return qt_closestLeaf(p1, p2);
}
// No common ancestor? Then just compare the items' toplevels directly.
return qt_closestLeaf(t1->topLevelItem(), t2->topLevelItem());
}
/*!
Returns true if \a item2 is on top of \a item1.
\internal
*/
bool QGraphicsScenePrivate::closestItemLast_withoutCache(const QGraphicsItem *item1, const QGraphicsItem *item2)
{
return closestItemFirst_withoutCache(item2, item1);
}
void QGraphicsScenePrivate::climbTree(QGraphicsItem *item, int *stackingOrder)
{
if (!item->d_ptr->children.isEmpty()) {
QList<QGraphicsItem *> childList = item->d_ptr->children;
qSort(childList.begin(), childList.end(), qt_closestLeaf);
for (int i = 0; i < childList.size(); ++i) {
QGraphicsItem *item = childList.at(i);
if (!(item->flags() & QGraphicsItem::ItemStacksBehindParent))
climbTree(childList.at(i), stackingOrder);
}
item->d_ptr->globalStackingOrder = (*stackingOrder)++;
for (int i = 0; i < childList.size(); ++i) {
QGraphicsItem *item = childList.at(i);
if (item->flags() & QGraphicsItem::ItemStacksBehindParent)
climbTree(childList.at(i), stackingOrder);
}
} else {
item->d_ptr->globalStackingOrder = (*stackingOrder)++;
}
}
void QGraphicsScenePrivate::_q_updateSortCache()
{
_q_updateIndex();
if (!sortCacheEnabled || !updatingSortCache)
return;
updatingSortCache = false;
int stackingOrder = 0;
QList<QGraphicsItem *> topLevels;
for (int i = 0; i < indexedItems.size(); ++i) {
QGraphicsItem *item = indexedItems.at(i);
if (item && item->parentItem() == 0)
topLevels << item;
}
for (int i = 0; i < unindexedItems.size(); ++i) {
QGraphicsItem *item = unindexedItems.at(i);
if (item->parentItem() == 0)
topLevels << item;
}
qSort(topLevels.begin(), topLevels.end(), qt_closestLeaf);
for (int i = 0; i < topLevels.size(); ++i)
climbTree(topLevels.at(i), &stackingOrder);
}
void QGraphicsScenePrivate::sortItems(QList<QGraphicsItem *> *itemList, Qt::SortOrder order,
bool sortCacheEnabled)
{
if (sortCacheEnabled) {
if (order == Qt::AscendingOrder) {
qSort(itemList->begin(), itemList->end(), closestItemFirst_withCache);
} else if (order == Qt::DescendingOrder) {
qSort(itemList->begin(), itemList->end(), closestItemLast_withCache);
}
} else {
if (order == Qt::AscendingOrder) {
qSort(itemList->begin(), itemList->end(), closestItemFirst_withoutCache);
} else if (order == Qt::DescendingOrder) {
qSort(itemList->begin(), itemList->end(), closestItemLast_withoutCache);
}
}
}
/*!
\internal
Set the font and propagate the changes if the font is different from the
current font.
*/
void QGraphicsScenePrivate::setFont_helper(const QFont &font)
{
if (this->font == font && this->font.resolve() == font.resolve())
return;
updateFont(font);
}
/*!
\internal
Resolve the scene's font against the application font, and propagate the
changes too all items in the scene.
*/
void QGraphicsScenePrivate::resolveFont()
{
QFont naturalFont = qApp->font();
naturalFont.resolve(0);
QFont resolvedFont = font.resolve(naturalFont);
updateFont(resolvedFont);
}
/*!
\internal
Update the font, and whether or not it has changed, reresolve all fonts in
the scene.
*/
void QGraphicsScenePrivate::updateFont(const QFont &font)
{
Q_Q(QGraphicsScene);
// Update local font setting.
this->font = font;
// Resolve the fonts of all top-level widget items, or widget items
// whose parent is not a widget.
foreach (QGraphicsItem *item, q->items()) {
if (!item->parentItem()) {
// Resolvefont for an item is a noop operation, but
// every item can be a widget, or can have a widget
// childre.
item->d_ptr->resolveFont(font.resolve());
}
}
// Send the scene a FontChange event.
QEvent event(QEvent::FontChange);
QApplication::sendEvent(q, &event);
}
/*!
\internal
Set the palette and propagate the changes if the palette is different from
the current palette.
*/
void QGraphicsScenePrivate::setPalette_helper(const QPalette &palette)
{
if (this->palette == palette && this->palette.resolve() == palette.resolve())
return;
updatePalette(palette);
}
/*!
\internal
Resolve the scene's palette against the application palette, and propagate
the changes too all items in the scene.
*/
void QGraphicsScenePrivate::resolvePalette()
{
QPalette naturalPalette = qApp->palette();
naturalPalette.resolve(0);
QPalette resolvedPalette = palette.resolve(naturalPalette);
updatePalette(resolvedPalette);
}
/*!
\internal
Update the palette, and whether or not it has changed, reresolve all
palettes in the scene.
*/
void QGraphicsScenePrivate::updatePalette(const QPalette &palette)
{
Q_Q(QGraphicsScene);
// Update local palette setting.
this->palette = palette;
// Resolve the palettes of all top-level widget items, or widget items
// whose parent is not a widget.
foreach (QGraphicsItem *item, q->items()) {
if (!item->parentItem()) {
// Resolvefont for an item is a noop operation, but
// every item can be a widget, or can have a widget
// childre.
item->d_ptr->resolvePalette(palette.resolve());
}
}
// Send the scene a PaletteChange event.
QEvent event(QEvent::PaletteChange);
QApplication::sendEvent(q, &event);
}
/*!
Constructs a QGraphicsScene object. The \a parent parameter is
passed to QObject's constructor.
*/
QGraphicsScene::QGraphicsScene(QObject *parent)
: QObject(*new QGraphicsScenePrivate, parent)
{
d_func()->init();
}
/*!
Constructs a QGraphicsScene object, using \a sceneRect for its
scene rectangle. The \a parent parameter is passed to QObject's
constructor.
\sa sceneRect
*/
QGraphicsScene::QGraphicsScene(const QRectF &sceneRect, QObject *parent)
: QObject(*new QGraphicsScenePrivate, parent)
{
setSceneRect(sceneRect);
d_func()->init();
}
/*!
Constructs a QGraphicsScene object, using the rectangle specified
by (\a x, \a y), and the given \a width and \a height for its
scene rectangle. The \a parent parameter is passed to QObject's
constructor.
\sa sceneRect
*/
QGraphicsScene::QGraphicsScene(qreal x, qreal y, qreal width, qreal height, QObject *parent)
: QObject(*new QGraphicsScenePrivate, parent)
{
setSceneRect(x, y, width, height);
d_func()->init();
}
/*!
Destroys the QGraphicsScene object.
*/
QGraphicsScene::~QGraphicsScene()
{
Q_D(QGraphicsScene);
// Remove this scene from qApp's global scene list.
qApp->d_func()->scene_list.removeAll(this);
clear();
// Remove this scene from all associated views.
for (int j = 0; j < d->views.size(); ++j)
d->views.at(j)->setScene(0);
}
/*!
\property QGraphicsScene::sceneRect
\brief the scene rectangle; the bounding rectangle of the scene
The scene rectangle defines the extent of the scene. It is
primarily used by QGraphicsView to determine the view's default
scrollable area, and by QGraphicsScene to manage item indexing.
If unset, or if set to a null QRectF, sceneRect() will return the largest
bounding rect of all items on the scene since the scene was created (i.e.,
a rectangle that grows when items are added to or moved in the scene, but
never shrinks).
\sa width(), height(), QGraphicsView::sceneRect
*/
QRectF QGraphicsScene::sceneRect() const
{
Q_D(const QGraphicsScene);
const_cast<QGraphicsScenePrivate *>(d)->_q_updateIndex();
return d->hasSceneRect ? d->sceneRect : d->growingItemsBoundingRect;
}
void QGraphicsScene::setSceneRect(const QRectF &rect)
{
Q_D(QGraphicsScene);
if (rect != d->sceneRect) {
d->hasSceneRect = !rect.isNull();
d->sceneRect = rect;
d->resetIndex();
emit sceneRectChanged(rect);
}
}
/*!
\fn qreal QGraphicsScene::width() const
This convenience function is equivalent to calling sceneRect().width().
\sa height()
*/
/*!
\fn qreal QGraphicsScene::height() const
This convenience function is equivalent to calling \c sceneRect().height().
\sa width()
*/
/*!
Renders the \a source rect from scene into \a target, using \a painter. This
function is useful for capturing the contents of the scene onto a paint
device, such as a QImage (e.g., to take a screenshot), or for printing
with QPrinter. For example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 1
If \a source is a null rect, this function will use sceneRect() to
determine what to render. If \a target is a null rect, the dimensions of \a
painter's paint device will be used.
The source rect contents will be transformed according to \a
aspectRatioMode to fit into the target rect. By default, the aspect ratio
is kept, and \a source is scaled to fit in \a target.
\sa QGraphicsView::render()
*/
void QGraphicsScene::render(QPainter *painter, const QRectF &target, const QRectF &source,
Qt::AspectRatioMode aspectRatioMode)
{
Q_D(QGraphicsScene);
// Default source rect = scene rect
QRectF sourceRect = source;
if (sourceRect.isNull())
sourceRect = sceneRect();
// Default target rect = device rect
QRectF targetRect = target;
if (targetRect.isNull()) {
if (painter->device()->devType() == QInternal::Picture)
targetRect = sourceRect;
else
targetRect.setRect(0, 0, painter->device()->width(), painter->device()->height());
}
// Find the ideal x / y scaling ratio to fit \a source into \a target.
qreal xratio = targetRect.width() / sourceRect.width();
qreal yratio = targetRect.height() / sourceRect.height();
// Scale according to the aspect ratio mode.
switch (aspectRatioMode) {
case Qt::KeepAspectRatio:
xratio = yratio = qMin(xratio, yratio);
break;
case Qt::KeepAspectRatioByExpanding:
xratio = yratio = qMax(xratio, yratio);
break;
case Qt::IgnoreAspectRatio:
break;
}
// Find all items to draw, and reverse the list (we want to draw
// in reverse order).
QList<QGraphicsItem *> itemList = items(sourceRect, Qt::IntersectsItemBoundingRect);
QGraphicsItem **itemArray = new QGraphicsItem *[itemList.size()];
int numItems = itemList.size();
for (int i = 0; i < numItems; ++i)
itemArray[numItems - i - 1] = itemList.at(i);
itemList.clear();
painter->save();
// Transform the painter.
painter->setClipRect(targetRect);
QTransform painterTransform;
painterTransform *= QTransform()
.translate(targetRect.left(), targetRect.top())
.scale(xratio, yratio)
.translate(-sourceRect.left(), -sourceRect.top());
painter->setWorldTransform(painterTransform, true);
// Two unit vectors.
QLineF v1(0, 0, 1, 0);
QLineF v2(0, 0, 0, 1);
// Generate the style options
QStyleOptionGraphicsItem *styleOptionArray = new QStyleOptionGraphicsItem[numItems];
for (int i = 0; i < numItems; ++i) {
QGraphicsItem *item = itemArray[i];
QStyleOptionGraphicsItem option;
option.state = QStyle::State_None;
option.rect = item->boundingRect().toRect();
if (item->isSelected())
option.state |= QStyle::State_Selected;
if (item->isEnabled())
option.state |= QStyle::State_Enabled;
if (item->hasFocus())
option.state |= QStyle::State_HasFocus;
if (d->hoverItems.contains(item))
option.state |= QStyle::State_MouseOver;
if (item == mouseGrabberItem())
option.state |= QStyle::State_Sunken;
// Calculate a simple level-of-detail metric.
// ### almost identical code in QGraphicsView::paintEvent()
// and QGraphicsView::render() - consider refactoring
QTransform itemToDeviceTransform;
if (item->d_ptr->itemIsUntransformable()) {
itemToDeviceTransform = item->deviceTransform(painterTransform);
} else {
itemToDeviceTransform = item->sceneTransform() * painterTransform;
}
option.levelOfDetail = qSqrt(itemToDeviceTransform.map(v1).length() * itemToDeviceTransform.map(v2).length());
option.matrix = itemToDeviceTransform.toAffine(); //### discards perspective
option.exposedRect = item->boundingRect();
option.exposedRect &= itemToDeviceTransform.inverted().mapRect(targetRect);
styleOptionArray[i] = option;
}
// Render the scene.
drawBackground(painter, sourceRect);
drawItems(painter, numItems, itemArray, styleOptionArray);
drawForeground(painter, sourceRect);
delete [] itemArray;
delete [] styleOptionArray;
painter->restore();
}
/*!
\property QGraphicsScene::itemIndexMethod
\brief the item indexing method.
QGraphicsScene applies an indexing algorithm to the scene, to speed up
item discovery functions like items() and itemAt(). Indexing is most
efficient for static scenes (i.e., where items don't move around). For
dynamic scenes, or scenes with many animated items, the index bookkeeping
can outweight the fast lookup speeds.
For the common case, the default index method BspTreeIndex works fine. If
your scene uses many animations and you are experiencing slowness, you can
disable indexing by calling \c setItemIndexMethod(NoIndex).
\sa bspTreeDepth
*/
QGraphicsScene::ItemIndexMethod QGraphicsScene::itemIndexMethod() const
{
Q_D(const QGraphicsScene);
return d->indexMethod;
}
void QGraphicsScene::setItemIndexMethod(ItemIndexMethod method)
{
Q_D(QGraphicsScene);
d->resetIndex();
d->indexMethod = method;
}
/*!
\property QGraphicsScene::bspTreeDepth
\brief the depth of QGraphicsScene's BSP index tree
\since 4.3
This property has no effect when NoIndex is used.
This value determines the depth of QGraphicsScene's BSP tree. The depth
directly affects QGraphicsScene's performance and memory usage; the latter
growing exponentially with the depth of the tree. With an optimal tree
depth, QGraphicsScene can instantly determine the locality of items, even
for scenes with thousands or millions of items. This also greatly improves
rendering performance.
By default, the value is 0, in which case Qt will guess a reasonable
default depth based on the size, location and number of items in the
scene. If these parameters change frequently, however, you may experience
slowdowns as QGraphicsScene retunes the depth internally. You can avoid
potential slowdowns by fixating the tree depth through setting this
property.
The depth of the tree and the size of the scene rectangle decide the
granularity of the scene's partitioning. The size of each scene segment is
determined by the following algorithm:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 2
The BSP tree has an optimal size when each segment contains between 0 and
10 items.
\sa itemIndexMethod
*/
int QGraphicsScene::bspTreeDepth() const
{
Q_D(const QGraphicsScene);
return d->bspTreeDepth;
}
void QGraphicsScene::setBspTreeDepth(int depth)
{
Q_D(QGraphicsScene);
if (d->bspTreeDepth == depth)
return;
if (depth < 0) {
qWarning("QGraphicsScene::setBspTreeDepth: invalid depth %d ignored; must be >= 0", depth);
return;
}
d->bspTreeDepth = depth;
d->resetIndex();
}
/*!
\property QGraphicsScene::sortCacheEnabled
\brief whether sort caching is enabled
\since 4.5
When enabled, this property adds a cache that speeds up sorting and
transformations for scenes with deep hierarchies (i.e., items with many
levels of descendents), at the cost of using more memory (approx. 100 more
bytes of memory per item).
Items that are not part of a deep hierarchy suffer no penalty from this
cache.
*/
bool QGraphicsScene::isSortCacheEnabled() const
{
Q_D(const QGraphicsScene);
return d->sortCacheEnabled;
}
void QGraphicsScene::setSortCacheEnabled(bool enabled)
{
Q_D(QGraphicsScene);
if (enabled == d->sortCacheEnabled)
return;
if ((d->sortCacheEnabled = enabled))
d->invalidateSortCache();
}
/*!
Calculates and returns the bounding rect of all items on the scene. This
function works by iterating over all items, and because if this, it can
be slow for large scenes.
\sa sceneRect()
*/
QRectF QGraphicsScene::itemsBoundingRect() const
{
QRectF boundingRect;
foreach (QGraphicsItem *item, items())
boundingRect |= item->sceneBoundingRect();
return boundingRect;
}
/*!
Returns a list of all items on the scene, in no particular order.
\sa addItem(), removeItem()
*/
QList<QGraphicsItem *> QGraphicsScene::items() const
{
Q_D(const QGraphicsScene);
const_cast<QGraphicsScenePrivate *>(d)->purgeRemovedItems();
// If freeItemIndexes is empty, we know there are no holes in indexedItems and
// unindexedItems.
if (d->freeItemIndexes.isEmpty()) {
if (d->unindexedItems.isEmpty())
return d->indexedItems;
return d->indexedItems + d->unindexedItems;
}
// Rebuild the list of items to avoid holes. ### We could also just
// compress the item lists at this point.
QList<QGraphicsItem *> itemList;
foreach (QGraphicsItem *item, d->indexedItems + d->unindexedItems) {
if (item)
itemList << item;
}
return itemList;
}
/*!
Returns all visible items at position \a pos in the scene. The items are
listed in descending Z order (i.e., the first item in the list is the
top-most item, and the last item is the bottom-most item).
\sa itemAt()
*/
QList<QGraphicsItem *> QGraphicsScene::items(const QPointF &pos) const
{
QList<QGraphicsItem *> itemsAtPoint;
// Find all items within a 1x1 rect area starting at pos. This can be
// inefficient for scenes that use small coordinates (like unity
// coordinates), or for detailed graphs. ### The index should support
// fetching items at a pos to avoid this limitation.
foreach (QGraphicsItem *item, items(QRectF(pos, QSizeF(1, 1)), Qt::IntersectsItemBoundingRect)) {
if (item->contains(item->mapFromScene(pos)))
itemsAtPoint << item;
}
return itemsAtPoint;
}
/*!
\fn QList<QGraphicsItem *> QGraphicsScene::items(const QRectF &rectangle, Qt::ItemSelectionMode mode) const
\overload
Returns all visible items that, depending on \a mode, are either inside or
intersect with the specified \a rectangle.
The default value for \a mode is Qt::IntersectsItemShape; all items whose
exact shape intersects with or is contained by \a rectangle are returned.
\sa itemAt()
*/
QList<QGraphicsItem *> QGraphicsScene::items(const QRectF &rect, Qt::ItemSelectionMode mode) const
{
Q_D(const QGraphicsScene);
return d->items_helper(rect, mode, Qt::AscendingOrder);
}
/*!
\fn QList<QGraphicsItem *> QGraphicsScene::items(qreal x, qreal y, qreal w, qreal h, Qt::ItemSelectionMode mode) const
\since 4.3
This convenience function is equivalent to calling items(QRectF(\a x, \a y, \a w, \a h), \a mode).
*/
/*!
\overload
Returns all visible items that, depending on \a mode, are either inside or
intersect with the polygon \a polygon.
The default value for \a mode is Qt::IntersectsItemShape; all items whose
exact shape intersects with or is contained by \a polygon are returned.
\sa itemAt()
*/
QList<QGraphicsItem *> QGraphicsScene::items(const QPolygonF &polygon, Qt::ItemSelectionMode mode) const
{
Q_D(const QGraphicsScene);
return d->items_helper(polygon, mode, Qt::AscendingOrder);
}
/*!
\overload
Returns all visible items that, depending on \a path, are either inside or
intersect with the path \a path.
The default value for \a mode is Qt::IntersectsItemShape; all items whose
exact shape intersects with or is contained by \a path are returned.
\sa itemAt()
*/
QList<QGraphicsItem *> QGraphicsScene::items(const QPainterPath &path, Qt::ItemSelectionMode mode) const
{
Q_D(const QGraphicsScene);
return d->items_helper(path, mode, Qt::AscendingOrder);
}
/*!
Returns a list of all items that collide with \a item. Collisions are
determined by calling QGraphicsItem::collidesWithItem(); the collision
detection is determined by \a mode. By default, all items whose shape
intersects \a item or is contained inside \a item's shape are returned.
The items are returned in descending Z order (i.e., the first item in the
list is the top-most item, and the last item is the bottom-most item).
\sa items(), itemAt(), QGraphicsItem::collidesWithItem()
*/
QList<QGraphicsItem *> QGraphicsScene::collidingItems(const QGraphicsItem *item,
Qt::ItemSelectionMode mode) const
{
Q_D(const QGraphicsScene);
if (!item) {
qWarning("QGraphicsScene::collidingItems: cannot find collisions for null item");
return QList<QGraphicsItem *>();
}
QList<QGraphicsItem *> tmp;
foreach (QGraphicsItem *itemInVicinity, d->estimateItemsInRect(item->sceneBoundingRect())) {
if (item != itemInVicinity && item->collidesWithItem(itemInVicinity, mode))
tmp << itemInVicinity;
}
d->sortItems(&tmp, Qt::AscendingOrder, d->sortCacheEnabled);
return tmp;
}
/*!
\fn QGraphicsItem *QGraphicsScene::itemAt(const QPointF &position) const
Returns the topmost visible item at the specified \a position, or 0 if
there are no items at this position.
\note The topmost item is the one with the highest Z-value.
\sa items(), collidingItems(), QGraphicsItem::setZValue()
*/
QGraphicsItem *QGraphicsScene::itemAt(const QPointF &pos) const
{
QList<QGraphicsItem *> itemsAtPoint = items(pos);
return itemsAtPoint.isEmpty() ? 0 : itemsAtPoint.first();
}
/*!
\fn QGraphicsScene::itemAt(qreal x, qreal y) const
\overload
Returns the topmost item at the position specified by (\a x, \a
y), or 0 if there are no items at this position.
This convenience function is equivalent to calling \c
{itemAt(QPointF(x, y))}.
\note The topmost item is the one with the highest Z-value.
*/
/*!
Returns a list of all currently selected items. The items are
returned in no particular order.
\sa setSelectionArea()
*/
QList<QGraphicsItem *> QGraphicsScene::selectedItems() const
{
Q_D(const QGraphicsScene);
// Optimization: Lazily removes items that are not selected.
QGraphicsScene *that = const_cast<QGraphicsScene *>(this);
QSet<QGraphicsItem *> actuallySelectedSet;
foreach (QGraphicsItem *item, that->d_func()->selectedItems) {
if (item->isSelected())
actuallySelectedSet << item;
}
that->d_func()->selectedItems = actuallySelectedSet;
return d->selectedItems.values();
}
/*!
Returns the selection area that was previously set with
setSelectionArea(), or an empty QPainterPath if no selection area has been
set.
\sa setSelectionArea()
*/
QPainterPath QGraphicsScene::selectionArea() const
{
Q_D(const QGraphicsScene);
return d->selectionArea;
}
/*!
Sets the selection area to \a path. All items within this area are
immediately selected, and all items outside are unselected. You can get
the list of all selected items by calling selectedItems().
For an item to be selected, it must be marked as \e selectable
(QGraphicsItem::ItemIsSelectable).
\sa clearSelection(), selectionArea()
*/
void QGraphicsScene::setSelectionArea(const QPainterPath &path)
{
setSelectionArea(path, Qt::IntersectsItemShape);
}
/*!
\overload
\since 4.3
Sets the selection area to \a path using \a mode to determine if items are
included in the selection area.
\sa clearSelection(), selectionArea()
*/
void QGraphicsScene::setSelectionArea(const QPainterPath &path, Qt::ItemSelectionMode mode)
{
Q_D(QGraphicsScene);
// Note: with boolean path operations, we can improve performance here
// quite a lot by "growing" the old path instead of replacing it. That
// allows us to only check the intersect area for changes, instead of
// reevaluating the whole path over again.
d->selectionArea = path;
QSet<QGraphicsItem *> unselectItems = d->selectedItems;
// Disable emitting selectionChanged() for individual items.
++d->selectionChanging;
bool changed = false;
// Set all items in path to selected.
foreach (QGraphicsItem *item, items(path, mode)) {
if (item->flags() & QGraphicsItem::ItemIsSelectable) {
if (!item->isSelected())
changed = true;
unselectItems.remove(item);
item->setSelected(true);
}
}
// Unselect all items outside path.
foreach (QGraphicsItem *item, unselectItems) {
item->setSelected(false);
changed = true;
}
// Reenable emitting selectionChanged() for individual items.
--d->selectionChanging;
if (!d->selectionChanging && changed)
emit selectionChanged();
}
/*!
Clears the current selection.
\sa setSelectionArea(), selectedItems()
*/
void QGraphicsScene::clearSelection()
{
Q_D(QGraphicsScene);
// Disable emitting selectionChanged
++d->selectionChanging;
bool changed = !d->selectedItems.isEmpty();
foreach (QGraphicsItem *item, d->selectedItems)
item->setSelected(false);
d->selectedItems.clear();
// Reenable emitting selectionChanged() for individual items.
--d->selectionChanging;
if (!d->selectionChanging && changed)
emit selectionChanged();
}
/*!
\since 4.4
Removes and deletes all items from the scene, but otherwise leaves the
state of the scene unchanged.
\sa addItem()
*/
void QGraphicsScene::clear()
{
Q_D(QGraphicsScene);
// Recursive descent delete
for (int i = 0; i < d->indexedItems.size(); ++i) {
if (QGraphicsItem *item = d->indexedItems.at(i)) {
if (!item->parentItem())
delete item;
}
}
QList<QGraphicsItem *> unindexedParents;
for (int i = 0; i < d->unindexedItems.size(); ++i) {
QGraphicsItem *item = d->unindexedItems.at(i);
if (!item->parentItem())
unindexedParents << item;
}
d->unindexedItems.clear();
qDeleteAll(unindexedParents);
d->indexedItems.clear();
d->freeItemIndexes.clear();
d->lastItemCount = 0;
d->bspTree.clear();
d->largestUntransformableItem = QRectF();
}
/*!
Groups all items in \a items into a new QGraphicsItemGroup, and returns a
pointer to the group. The group is created with the common ancestor of \a
items as its parent, and with position (0, 0). The items are all
reparented to the group, and their positions and transformations are
mapped to the group. If \a items is empty, this function will return an
empty top-level QGraphicsItemGroup.
QGraphicsScene has ownership of the group item; you do not need to delete
it. To dismantle (ungroup) a group, call destroyItemGroup().
\sa destroyItemGroup(), QGraphicsItemGroup::addToGroup()
*/
QGraphicsItemGroup *QGraphicsScene::createItemGroup(const QList<QGraphicsItem *> &items)
{
// Build a list of the first item's ancestors
QList<QGraphicsItem *> ancestors;
int n = 0;
if (!items.isEmpty()) {
QGraphicsItem *parent = items.at(n++);
while ((parent = parent->parentItem()))
ancestors.append(parent);
}
// Find the common ancestor for all items
QGraphicsItem *commonAncestor = 0;
if (!ancestors.isEmpty()) {
while (n < items.size()) {
int commonIndex = -1;
QGraphicsItem *parent = items.at(n++);
do {
int index = ancestors.indexOf(parent, qMax(0, commonIndex));
if (index != -1) {
commonIndex = index;
break;
}
} while ((parent = parent->parentItem()));
if (commonIndex == -1) {
commonAncestor = 0;
break;
}
commonAncestor = ancestors.at(commonIndex);
}
}
// Create a new group at that level
QGraphicsItemGroup *group = new QGraphicsItemGroup(commonAncestor);
if (!commonAncestor)
addItem(group);
foreach (QGraphicsItem *item, items)
group->addToGroup(item);
return group;
}
/*!
Reparents all items in \a group to \a group's parent item, then removes \a
group from the scene, and finally deletes it. The items' positions and
transformations are mapped from the group to the group's parent.
\sa createItemGroup(), QGraphicsItemGroup::removeFromGroup()
*/
void QGraphicsScene::destroyItemGroup(QGraphicsItemGroup *group)
{
foreach (QGraphicsItem *item, group->children())
group->removeFromGroup(item);
removeItem(group);
delete group;
}
/*!
Adds or moves the item \a item and all its childen to the scene.
If the item is visible (i.e., QGraphicsItem::isVisible() returns
true), QGraphicsScene will emit changed() once control goes back
to the event loop.
If the item is already in a different scene, it will first be removed from
its old scene, and then added to this scene as a top-level.
QGraphicsScene will send ItemSceneChange notifications to \a item while
it is added to the scene. If item does not currently belong to a scene, only one
notification is sent. If it does belong to scene already (i.e., it is
moved to this scene), QGraphicsScene will send an addition notification as
the item is removed from its previous scene.
\sa removeItem(), addEllipse(), addLine(), addPath(), addPixmap(),
addRect(), addText(), addWidget()
*/
void QGraphicsScene::addItem(QGraphicsItem *item)
{
Q_D(QGraphicsScene);
if (!item) {
qWarning("QGraphicsScene::addItem: cannot add null item");
return;
}
if (item->scene() == this) {
qWarning("QGraphicsScene::addItem: item has already been added to this scene");
return;
}
// Remove this item from its existing scene
if (QGraphicsScene *oldScene = item->scene())
oldScene->removeItem(item);
// Notify the item that its scene is changing, and allow the item to
// react.
QGraphicsScene *targetScene = qVariantValue<QGraphicsScene *>(item->itemChange(QGraphicsItem::ItemSceneChange,
qVariantFromValue<QGraphicsScene *>(this)));
if (targetScene != this) {
if (targetScene && item->scene() != targetScene)
targetScene->addItem(item);
return;
}
// Prevent reusing a recently deleted pointer: purge all removed items
// from our lists.
d->purgeRemovedItems();
// Invalidate any sort caching; arrival of a new item means we need to
// resort.
d->invalidateSortCache();
// Detach this item from its parent if the parent's scene is different
// from this scene.
if (QGraphicsItem *itemParent = item->parentItem()) {
if (itemParent->scene() != this)
item->setParentItem(0);
}
// Add the item to this scene
item->d_func()->scene = targetScene;
// Indexing requires sceneBoundingRect(), but because \a item might
// not be completely constructed at this point, we need to store it in
// a temporary list and schedule an indexing for later.
d->unindexedItems << item;
item->d_func()->index = -1;
d->startIndexTimer();
// Update the scene's sort cache settings.
item->d_ptr->globalStackingOrder = -1;
d->invalidateSortCache();
// Add to list of items that require an update. We cannot assume that the
// item is fully constructed, so calling item->update() can lead to a pure
// virtual function call to boundingRect().
if (!d->updateAll) {
if (d->pendingUpdateItems.isEmpty())
QMetaObject::invokeMethod(this, "_q_updateLater", Qt::QueuedConnection);
d->pendingUpdateItems << item;
}
// Disable selectionChanged() for individual items
++d->selectionChanging;
int oldSelectedItemSize = d->selectedItems.size();
// Update selection lists
if (item->isSelected())
d->selectedItems << item;
if (item->isWidget() && item->isVisible() && static_cast<QGraphicsWidget *>(item)->windowType() == Qt::Popup)
d->addPopup(static_cast<QGraphicsWidget *>(item));
// Update creation order focus chain. Make sure to leave the widget's
// internal tab order intact.
if (item->isWidget()) {
QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
if (!d->tabFocusFirst) {
// No first tab focus widget - make this the first tab focus
// widget.
d->tabFocusFirst = widget;
} else if (!widget->parentWidget()) {
// Adding a widget that is not part of a tab focus chain.
QGraphicsWidget *last = d->tabFocusFirst->d_func()->focusPrev;
QGraphicsWidget *lastNew = widget->d_func()->focusPrev;
last->d_func()->focusNext = widget;
widget->d_func()->focusPrev = last;
d->tabFocusFirst->d_func()->focusPrev = lastNew;
lastNew->d_func()->focusNext = d->tabFocusFirst;
}
}
// Add all children recursively
foreach (QGraphicsItem *child, item->children())
addItem(child);
// Resolve font and palette.
item->d_ptr->resolveFont(d->font.resolve());
item->d_ptr->resolvePalette(d->palette.resolve());
if (!item->d_ptr->explicitlyHidden) {
if (d->unpolishedItems.isEmpty())
QMetaObject::invokeMethod(this, "_q_polishItems", Qt::QueuedConnection);
d->unpolishedItems << item;
}
// Reenable selectionChanged() for individual items
--d->selectionChanging;
if (!d->selectionChanging && d->selectedItems.size() != oldSelectedItemSize)
emit selectionChanged();
// Deliver post-change notification
item->itemChange(QGraphicsItem::ItemSceneHasChanged, qVariantFromValue<QGraphicsScene *>(this));
}
/*!
Creates and adds an ellipse item to the scene, and returns the item
pointer. The geometry of the ellipse is defined by \a rect, and its pen
and brush are initialized to \a pen and \a brush.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addLine(), addPath(), addPixmap(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsEllipseItem *QGraphicsScene::addEllipse(const QRectF &rect, const QPen &pen, const QBrush &brush)
{
QGraphicsEllipseItem *item = new QGraphicsEllipseItem(rect);
item->setPen(pen);
item->setBrush(brush);
addItem(item);
return item;
}
/*!
\fn QGraphicsEllipseItem *QGraphicsScene::addEllipse(qreal x, qreal y, qreal w, qreal h, const QPen &pen, const QBrush &brush)
\since 4.3
This convenience function is equivalent to calling addEllipse(QRectF(\a x,
\a y, \a w, \a h), \a pen, \a brush).
*/
/*!
Creates and adds a line item to the scene, and returns the item
pointer. The geometry of the line is defined by \a line, and its pen
is initialized to \a pen.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addPath(), addPixmap(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsLineItem *QGraphicsScene::addLine(const QLineF &line, const QPen &pen)
{
QGraphicsLineItem *item = new QGraphicsLineItem(line);
item->setPen(pen);
addItem(item);
return item;
}
/*!
\fn QGraphicsLineItem *QGraphicsScene::addLine(qreal x1, qreal y1, qreal x2, qreal y2, const QPen &pen)
\since 4.3
This convenience function is equivalent to calling addLine(QLineF(\a x1,
\a y1, \a x2, \a y2), \a pen).
*/
/*!
Creates and adds a path item to the scene, and returns the item
pointer. The geometry of the path is defined by \a path, and its pen and
brush are initialized to \a pen and \a brush.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPixmap(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsPathItem *QGraphicsScene::addPath(const QPainterPath &path, const QPen &pen, const QBrush &brush)
{
QGraphicsPathItem *item = new QGraphicsPathItem(path);
item->setPen(pen);
item->setBrush(brush);
addItem(item);
return item;
}
/*!
Creates and adds a pixmap item to the scene, and returns the item
pointer. The pixmap is defined by \a pixmap.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPath(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsPixmapItem *QGraphicsScene::addPixmap(const QPixmap &pixmap)
{
QGraphicsPixmapItem *item = new QGraphicsPixmapItem(pixmap);
addItem(item);
return item;
}
/*!
Creates and adds a polygon item to the scene, and returns the item
pointer. The polygon is defined by \a polygon, and its pen and
brush are initialized to \a pen and \a brush.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPath(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsPolygonItem *QGraphicsScene::addPolygon(const QPolygonF &polygon,
const QPen &pen, const QBrush &brush)
{
QGraphicsPolygonItem *item = new QGraphicsPolygonItem(polygon);
item->setPen(pen);
item->setBrush(brush);
addItem(item);
return item;
}
/*!
Creates and adds a rectangle item to the scene, and returns the item
pointer. The geometry of the rectangle is defined by \a rect, and its pen
and brush are initialized to \a pen and \a brush.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0). For example, if a QRect(50, 50, 100,
100) is added, its top-left corner will be at (50, 50) relative to the
origin in the items coordinate system.
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPixmap(), addPixmap(), addText(),
addItem(), addWidget()
*/
QGraphicsRectItem *QGraphicsScene::addRect(const QRectF &rect, const QPen &pen, const QBrush &brush)
{
QGraphicsRectItem *item = new QGraphicsRectItem(rect);
item->setPen(pen);
item->setBrush(brush);
addItem(item);
return item;
}
/*!
\fn QGraphicsRectItem *QGraphicsScene::addRect(qreal x, qreal y, qreal w, qreal h, const QPen &pen, const QBrush &brush)
\since 4.3
This convenience function is equivalent to calling addRect(QRectF(\a x,
\a y, \a w, \a h), \a pen, \a brush).
*/
/*!
Creates and adds a text item to the scene, and returns the item
pointer. The text string is initialized to \a text, and its font
is initialized to \a font.
The item's position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPixmap(), addPixmap(), addRect(),
addItem(), addWidget()
*/
QGraphicsTextItem *QGraphicsScene::addText(const QString &text, const QFont &font)
{
QGraphicsTextItem *item = new QGraphicsTextItem(text);
item->setFont(font);
addItem(item);
return item;
}
/*!
Creates and adds a QGraphicsSimpleTextItem to the scene, and returns the
item pointer. The text string is initialized to \a text, and its font is
initialized to \a font.
The item's position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPixmap(), addPixmap(), addRect(),
addItem(), addWidget()
*/
QGraphicsSimpleTextItem *QGraphicsScene::addSimpleText(const QString &text, const QFont &font)
{
QGraphicsSimpleTextItem *item = new QGraphicsSimpleTextItem(text);
item->setFont(font);
addItem(item);
return item;
}
/*!
Creates a new QGraphicsProxyWidget for \a widget, adds it to the scene,
and returns a pointer to the proxy. \a wFlags set the default window flags
for the embedding proxy widget.
The item's position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
Note that widgets with the Qt::WA_PaintOnScreen widget attribute
set and widgets that wrap an external application or controller
are not supported. Examples are QGLWidget and QAxWidget.
\sa addEllipse(), addLine(), addPixmap(), addPixmap(), addRect(),
addText(), addSimpleText(), addItem()
*/
QGraphicsProxyWidget *QGraphicsScene::addWidget(QWidget *widget, Qt::WindowFlags wFlags)
{
QGraphicsProxyWidget *proxy = new QGraphicsProxyWidget(0, wFlags);
proxy->setWidget(widget);
addItem(proxy);
return proxy;
}
/*!
Removes the item \a item and all its children from the scene. The
ownership of \a item is passed on to the caller (i.e.,
QGraphicsScene will no longer delete \a item when destroyed).
\sa addItem()
*/
void QGraphicsScene::removeItem(QGraphicsItem *item)
{
// ### Refactoring: This function shares much functionality with _q_removeItemLater()
Q_D(QGraphicsScene);
if (!item) {
qWarning("QGraphicsScene::removeItem: cannot remove 0-item");
return;
}
if (item->scene() != this) {
qWarning("QGraphicsScene::removeItem: item %p's scene (%p)"
" is different from this scene (%p)",
item, item->scene(), this);
return;
}
// Notify the item that it's scene is changing to 0, allowing the item to
// react.
QGraphicsScene *targetScene = qVariantValue<QGraphicsScene *>(item->itemChange(QGraphicsItem::ItemSceneChange,
qVariantFromValue<QGraphicsScene *>(0)));
if (targetScene != 0 && targetScene != this) {
targetScene->addItem(item);
return;
}
// If the item has focus, remove it (and any focusWidget reference).
item->clearFocus();
// Clear its background
item->update();
// Note: This will access item's sceneBoundingRect(), which (as this is
// C++) is why we cannot call removeItem() from QGraphicsItem's
// destructor.
d->removeFromIndex(item);
if (item == d->tabFocusFirst) {
QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
widget->d_func()->fixFocusChainBeforeReparenting(0, 0);
}
// Set the item's scene ptr to 0.
item->d_func()->scene = 0;
// Detach the item from its parent.
if (QGraphicsItem *parentItem = item->parentItem()) {
if (parentItem->scene()) {
Q_ASSERT_X(parentItem->scene() == this, "QGraphicsScene::removeItem",
"Parent item's scene is different from this item's scene");
item->setParentItem(0);
}
}
// Remove from our item lists.
int index = item->d_func()->index;
if (index != -1) {
d->freeItemIndexes << index;
d->indexedItems[index] = 0;
} else {
d->unindexedItems.removeAll(item);
}
// Remove from scene transform cache
int transformIndex = item->d_func()->sceneTransformIndex;
if (transformIndex != -1) {
d->validTransforms.setBit(transformIndex, 0);
d->freeSceneTransformSlots.append(transformIndex);
item->d_func()->sceneTransformIndex = -1;
}
if (item == d->focusItem)
d->focusItem = 0;
if (item == d->lastFocusItem)
d->lastFocusItem = 0;
if (item == d->activeWindow) {
// ### deactivate...
d->activeWindow = 0;
}
// Disable selectionChanged() for individual items
++d->selectionChanging;
int oldSelectedItemsSize = d->selectedItems.size();
// Update selected & hovered item bookkeeping
d->selectedItems.remove(item);
d->hoverItems.removeAll(item);
d->pendingUpdateItems.removeAll(item);
d->cachedItemsUnderMouse.removeAll(item);
d->unpolishedItems.removeAll(item);
d->dirtyItems.removeAll(item);
//We remove all references of item from the sceneEventFilter arrays
QMultiMap<QGraphicsItem*, QGraphicsItem*>::iterator iterator = d->sceneEventFilters.begin();
while (iterator != d->sceneEventFilters.end()) {
if (iterator.value() == item || iterator.key() == item)
iterator = d->sceneEventFilters.erase(iterator);
else
++iterator;
}
//Ensure dirty flag have the correct default value so the next time it will be added it will receive updates
item->d_func()->dirty = 0;
item->d_func()->dirtyChildren = 0;
// Remove all children recursively
foreach (QGraphicsItem *child, item->children())
removeItem(child);
// Reset the mouse grabber and focus item data.
if (d->mouseGrabberItems.contains(item))
d->ungrabMouse(item);
// Reset the keyboard grabber
if (d->keyboardGrabberItems.contains(item))
item->ungrabKeyboard();
// Reset the last mouse grabber item
if (item == d->lastMouseGrabberItem)
d->lastMouseGrabberItem = 0;
// Reenable selectionChanged() for individual items
--d->selectionChanging;
if (!d->selectionChanging && d->selectedItems.size() != oldSelectedItemsSize)
emit selectionChanged();
// Deliver post-change notification
item->itemChange(QGraphicsItem::ItemSceneHasChanged, qVariantFromValue<QGraphicsScene *>(0));
}
/*!
Returns the scene's current focus item, or 0 if no item currently has
focus.
The focus item receives keyboard input when the scene receives a
key event.
\sa setFocusItem(), QGraphicsItem::hasFocus()
*/
QGraphicsItem *QGraphicsScene::focusItem() const
{
Q_D(const QGraphicsScene);
return d->focusItem;
}
/*!
Sets the scene's focus item to \a item, with the focus reason \a
focusReason, after removing focus from any previous item that may have had
focus.
If \a item is 0, or if it either does not accept focus (i.e., it does not
have the QGraphicsItem::ItemIsFocusable flag enabled), or is not visible
or not enabled, this function only removes focus from any previous
focusitem.
If item is not 0, and the scene does not currently have focus (i.e.,
hasFocus() returns false), this function will call setFocus()
automatically.
\sa focusItem(), hasFocus(), setFocus()
*/
void QGraphicsScene::setFocusItem(QGraphicsItem *item, Qt::FocusReason focusReason)
{
Q_D(QGraphicsScene);
if (item == d->focusItem)
return;
if (item && (!(item->flags() & QGraphicsItem::ItemIsFocusable)
|| !item->isVisible() || !item->isEnabled())) {
item = 0;
}
if (item) {
setFocus(focusReason);
if (item == d->focusItem)
return;
}
if (d->focusItem) {
QFocusEvent event(QEvent::FocusOut, focusReason);
d->lastFocusItem = d->focusItem;
d->focusItem = 0;
d->sendEvent(d->lastFocusItem, &event);
}
if (item) {
if (item->isWidget()) {
// Update focus child chain.
static_cast<QGraphicsWidget *>(item)->d_func()->setFocusWidget();
}
d->focusItem = item;
QFocusEvent event(QEvent::FocusIn, focusReason);
d->sendEvent(item, &event);
}
}
/*!
Returns true if the scene has focus; otherwise returns false. If the scene
has focus, it will will forward key events from QKeyEvent to any item that
has focus.
\sa setFocus(), setFocusItem()
*/
bool QGraphicsScene::hasFocus() const
{
Q_D(const QGraphicsScene);
return d->hasFocus;
}
/*!
Sets focus on the scene by sending a QFocusEvent to the scene, passing \a
focusReason as the reason. If the scene regains focus after having
previously lost it while an item had focus, the last focus item will
receive focus with \a focusReason as the reason.
If the scene already has focus, this function does nothing.
\sa hasFocus(), clearFocus(), setFocusItem()
*/
void QGraphicsScene::setFocus(Qt::FocusReason focusReason)
{
Q_D(QGraphicsScene);
if (d->hasFocus)
return;
QFocusEvent event(QEvent::FocusIn, focusReason);
QCoreApplication::sendEvent(this, &event);
}
/*!
Clears focus from the scene. If any item has focus when this function is
called, it will lose focus, and regain focus again once the scene regains
focus.
A scene that does not have focus ignores key events.
\sa hasFocus(), setFocus(), setFocusItem()
*/
void QGraphicsScene::clearFocus()
{
Q_D(QGraphicsScene);
if (d->hasFocus) {
d->hasFocus = false;
setFocusItem(0, Qt::OtherFocusReason);
}
}
/*!
\property QGraphicsScene::stickyFocus
\brief whether or not clicking the scene will clear focus
If this property is false (the default), then clicking on the scene
background or on an item that does not accept focus, will clear
focus. Otherwise, focus will remain unchanged.
The focus change happens in response to a mouse press. You can reimplement
mousePressEvent() in a subclass of QGraphicsScene to toggle this property
based on where the user has clicked.
\sa clearFocus(), setFocusItem()
*/
void QGraphicsScene::setStickyFocus(bool enabled)
{
Q_D(QGraphicsScene);
d->stickyFocus = enabled;
}
bool QGraphicsScene::stickyFocus() const
{
Q_D(const QGraphicsScene);
return d->stickyFocus;
}
/*!
Returns the current mouse grabber item, or 0 if no item is currently
grabbing the mouse. The mouse grabber item is the item that receives all
mouse events sent to the scene.
An item becomes a mouse grabber when it receives and accepts a
mouse press event, and it stays the mouse grabber until either of
the following events occur:
\list
\o If the item receives a mouse release event when there are no other
buttons pressed, it loses the mouse grab.
\o If the item becomes invisible (i.e., someone calls \c {item->setVisible(false))},
or if it becomes disabled (i.e., someone calls \c {item->setEnabled(false))},
it loses the mouse grab.
\o If the item is removed from the scene, it loses the mouse grab.
\endlist
If the item loses its mouse grab, the scene will ignore all mouse events
until a new item grabs the mouse (i.e., until a new item receives a mouse
press event).
*/
QGraphicsItem *QGraphicsScene::mouseGrabberItem() const
{
Q_D(const QGraphicsScene);
return !d->mouseGrabberItems.isEmpty() ? d->mouseGrabberItems.last() : 0;
}
/*!
\property QGraphicsScene::backgroundBrush
\brief the background brush of the scene.
Set this property to changes the scene's background to a different color,
gradient or texture. The default background brush is Qt::NoBrush. The
background is drawn before (behind) the items.
Example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 3
QGraphicsScene::render() calls drawBackground() to draw the scene
background. For more detailed control over how the background is drawn,
you can reimplement drawBackground() in a subclass of QGraphicsScene.
*/
QBrush QGraphicsScene::backgroundBrush() const
{
Q_D(const QGraphicsScene);
return d->backgroundBrush;
}
void QGraphicsScene::setBackgroundBrush(const QBrush &brush)
{
Q_D(QGraphicsScene);
d->backgroundBrush = brush;
foreach (QGraphicsView *view, d->views) {
view->resetCachedContent();
view->viewport()->update();
}
update();
}
/*!
\property QGraphicsScene::foregroundBrush
\brief the foreground brush of the scene.
Change this property to set the scene's foreground to a different
color, gradient or texture.
The foreground is drawn after (on top of) the items. The default
foreground brush is Qt::NoBrush ( i.e. the foreground is not
drawn).
Example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 4
QGraphicsScene::render() calls drawForeground() to draw the scene
foreground. For more detailed control over how the foreground is
drawn, you can reimplement the drawForeground() function in a
QGraphicsScene subclass.
*/
QBrush QGraphicsScene::foregroundBrush() const
{
Q_D(const QGraphicsScene);
return d->foregroundBrush;
}
void QGraphicsScene::setForegroundBrush(const QBrush &brush)
{
Q_D(QGraphicsScene);
d->foregroundBrush = brush;
foreach (QGraphicsView *view, views())
view->viewport()->update();
update();
}
/*!
This method is used by input methods to query a set of properties of
the scene to be able to support complex input method operations as support
for surrounding text and reconversions.
The \a query parameter specifies which property is queried.
\sa QWidget::inputMethodQuery()
*/
QVariant QGraphicsScene::inputMethodQuery(Qt::InputMethodQuery query) const
{
Q_D(const QGraphicsScene);
if (!d->focusItem)
return QVariant();
const QTransform matrix = d->focusItem->sceneTransform();
QVariant value = d->focusItem->inputMethodQuery(query);
if (value.type() == QVariant::RectF)
value = matrix.mapRect(value.toRectF());
else if (value.type() == QVariant::PointF)
value = matrix.map(value.toPointF());
else if (value.type() == QVariant::Rect)
value = matrix.mapRect(value.toRect());
else if (value.type() == QVariant::Point)
value = matrix.map(value.toPoint());
return value;
}
/*!
\fn void QGraphicsScene::update(const QRectF &rect)
Schedules a redraw of the area \a rect on the scene.
\sa sceneRect(), changed()
*/
void QGraphicsScene::update(const QRectF &rect)
{
Q_D(QGraphicsScene);
if (d->updateAll || (rect.isEmpty() && !rect.isNull()))
return;
// Check if anyone's connected; if not, we can send updates directly to
// the views. Otherwise or if there are no views, use old behavior.
bool directUpdates = !(d->connectedSignals & d->changedSignalMask) && !d->views.isEmpty();
if (rect.isNull()) {
d->updateAll = true;
d->updatedRects.clear();
if (directUpdates) {
// Update all views.
for (int i = 0; i < d->views.size(); ++i)
d->views.at(i)->d_func()->updateAll();
}
} else {
if (directUpdates) {
// Update all views.
for (int i = 0; i < d->views.size(); ++i) {
QGraphicsView *view = d->views.at(i);
view->d_func()->updateRegion(QRegion(view->mapFromScene(rect).boundingRect()));
}
} else {
d->updatedRects << rect;
}
}
if (!directUpdates && !d->calledEmitUpdated) {
d->calledEmitUpdated = true;
QMetaObject::invokeMethod(this, "_q_emitUpdated", Qt::QueuedConnection);
}
}
/*!
\fn void QGraphicsScene::update(qreal x, qreal y, qreal w, qreal h)
\overload
\since 4.3
This function is equivalent to calling update(QRectF(\a x, \a y, \a w,
\a h));
*/
/*!
Invalidates and schedules a redraw of the \a layers in \a rect on the
scene. Any cached content in \a layers is unconditionally invalidated and
redrawn.
You can use this function overload to notify QGraphicsScene of changes to
the background or the foreground of the scene. This function is commonly
used for scenes with tile-based backgrounds to notify changes when
QGraphicsView has enabled
\l{QGraphicsView::CacheBackground}{CacheBackground}.
Example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 5
Note that QGraphicsView currently supports background caching only (see
QGraphicsView::CacheBackground). This function is equivalent to calling
update() if any layer but BackgroundLayer is passed.
\sa QGraphicsView::resetCachedContent()
*/
void QGraphicsScene::invalidate(const QRectF &rect, SceneLayers layers)
{
foreach (QGraphicsView *view, views())
view->invalidateScene(rect, layers);
update(rect);
}
/*!
\fn void QGraphicsScene::invalidate(qreal x, qreal y, qreal w, qreal h, SceneLayers layers)
\overload
\since 4.3
This convenience function is equivalent to calling invalidate(QRectF(\a x, \a
y, \a w, \a h), \a layers);
*/
/*!
Returns a list of all the views that display this scene.
\sa QGraphicsView::scene()
*/
QList <QGraphicsView *> QGraphicsScene::views() const
{
Q_D(const QGraphicsScene);
return d->views;
}
/*!
This slot \e advances the scene by one step, by calling
QGraphicsItem::advance() for all items on the scene. This is done in two
phases: in the first phase, all items are notified that the scene is about
to change, and in the second phase all items are notified that they can
move. In the first phase, QGraphicsItem::advance() is called passing a
value of 0 as an argument, and 1 is passed in the second phase.
\sa QGraphicsItem::advance(), QGraphicsItemAnimation, QTimeLine
*/
void QGraphicsScene::advance()
{
for (int i = 0; i < 2; ++i) {
foreach (QGraphicsItem *item, items())
item->advance(i);
}
}
/*!
Processes the event \a event, and dispatches it to the respective
event handlers.
In addition to calling the convenience event handlers, this
function is responsible for converting mouse move events to hover
events for when there is no mouse grabber item. Hover events are
delivered directly to items; there is no convenience function for
them.
Unlike QWidget, QGraphicsScene does not have the convenience functions
\l{QWidget::}{enterEvent()} and \l{QWidget::}{leaveEvent()}. Use this
function to obtain those events instead.
\sa contextMenuEvent(), keyPressEvent(), keyReleaseEvent(),
mousePressEvent(), mouseMoveEvent(), mouseReleaseEvent(),
mouseDoubleClickEvent(), focusInEvent(), focusOutEvent()
*/
bool QGraphicsScene::event(QEvent *event)
{
Q_D(QGraphicsScene);
switch (event->type()) {
case QEvent::GraphicsSceneMousePress:
case QEvent::GraphicsSceneMouseMove:
case QEvent::GraphicsSceneMouseRelease:
case QEvent::GraphicsSceneMouseDoubleClick:
case QEvent::GraphicsSceneHoverEnter:
case QEvent::GraphicsSceneHoverLeave:
case QEvent::GraphicsSceneHoverMove:
// Reset the under-mouse list to ensure that this event gets fresh
// item-under-mouse data. Be careful about this list; if people delete
// items from inside event handlers, this list can quickly end up
// having stale pointers in it. We need to clear it before dispatching
// events that use it.
d->cachedItemsUnderMouse.clear();
default:
break;
}
switch (event->type()) {
case QEvent::GraphicsSceneDragEnter:
dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
break;
case QEvent::GraphicsSceneDragMove:
dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
break;
case QEvent::GraphicsSceneDragLeave:
dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
break;
case QEvent::GraphicsSceneDrop:
dropEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
break;
case QEvent::GraphicsSceneContextMenu:
contextMenuEvent(static_cast<QGraphicsSceneContextMenuEvent *>(event));
break;
case QEvent::KeyPress:
if (!d->focusItem) {
QKeyEvent *k = static_cast<QKeyEvent *>(event);
if (k->key() == Qt::Key_Tab || k->key() == Qt::Key_Backtab) {
if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier?
bool res = false;
if (k->key() == Qt::Key_Backtab
|| (k->key() == Qt::Key_Tab && (k->modifiers() & Qt::ShiftModifier))) {
res = focusNextPrevChild(false);
} else if (k->key() == Qt::Key_Tab) {
res = focusNextPrevChild(true);
}
if (!res)
event->ignore();
return true;
}
}
}
keyPressEvent(static_cast<QKeyEvent *>(event));
break;
case QEvent::KeyRelease:
keyReleaseEvent(static_cast<QKeyEvent *>(event));
break;
case QEvent::ShortcutOverride: {
QGraphicsItem *parent = focusItem();
while (parent) {
d->sendEvent(parent, event);
if (event->isAccepted())
return true;
parent = parent->parentItem();
}
}
return false;
case QEvent::GraphicsSceneMouseMove:
mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
break;
case QEvent::GraphicsSceneMousePress:
mousePressEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
break;
case QEvent::GraphicsSceneMouseRelease:
mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
break;
case QEvent::GraphicsSceneMouseDoubleClick:
mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
break;
case QEvent::GraphicsSceneWheel:
wheelEvent(static_cast<QGraphicsSceneWheelEvent *>(event));
break;
case QEvent::FocusIn:
focusInEvent(static_cast<QFocusEvent *>(event));
break;
case QEvent::FocusOut:
focusOutEvent(static_cast<QFocusEvent *>(event));
break;
case QEvent::GraphicsSceneHoverEnter:
case QEvent::GraphicsSceneHoverLeave:
case QEvent::GraphicsSceneHoverMove:
d->dispatchHoverEvent(static_cast<QGraphicsSceneHoverEvent *>(event));
break;
case QEvent::Leave:
d->leaveScene();
break;
case QEvent::GraphicsSceneHelp:
helpEvent(static_cast<QGraphicsSceneHelpEvent *>(event));
break;
case QEvent::InputMethod:
inputMethodEvent(static_cast<QInputMethodEvent *>(event));
break;
case QEvent::WindowActivate: {
if (!d->activationRefCount++) {
// Notify all non-window widgets.
foreach (QGraphicsItem *item, items()) {
if (item->isWidget() && item->isVisible() && !item->isWindow() && !item->parentWidget()) {
QEvent event(QEvent::WindowActivate);
QApplication::sendEvent(static_cast<QGraphicsWidget *>(item), &event);
}
}
// Restore window activation.
QGraphicsItem *nextFocusItem = d->focusItem ? d->focusItem : d->lastFocusItem;
if (nextFocusItem && nextFocusItem->window())
setActiveWindow(static_cast<QGraphicsWidget *>(nextFocusItem));
else if (d->tabFocusFirst && d->tabFocusFirst->isWindow())
setActiveWindow(d->tabFocusFirst);
}
break;
}
case QEvent::WindowDeactivate: {
if (!--d->activationRefCount) {
// Remove window activation.
setActiveWindow(0);
// Notify all non-window widgets.
foreach (QGraphicsItem *item, items()) {
if (item->isWidget() && item->isVisible() && !item->isWindow() && !item->parentWidget()) {
QEvent event(QEvent::WindowDeactivate);
QApplication::sendEvent(static_cast<QGraphicsWidget *>(item), &event);
}
}
}
break;
}
case QEvent::ApplicationFontChange: {
// Resolve the existing scene font.
d->resolveFont();
break;
}
case QEvent::FontChange:
// Update the entire scene when the font changes.
update();
break;
case QEvent::ApplicationPaletteChange: {
// Resolve the existing scene palette.
d->resolvePalette();
break;
}
case QEvent::PaletteChange:
// Update the entire scene when the palette changes.
update();
break;
case QEvent::StyleChange:
// Reresolve all widgets' styles. Update all top-level widgets'
// geometries that do not have an explicit style set.
update();
break;
case QEvent::Timer:
if (d->indexTimerId && static_cast<QTimerEvent *>(event)->timerId() == d->indexTimerId) {
if (d->restartIndexTimer) {
d->restartIndexTimer = false;
} else {
// this call will kill the timer
d->_q_updateIndex();
}
}
// Fallthrough intended - support timers in subclasses.
default:
return QObject::event(event);
}
return true;
}
/*!
\reimp
QGraphicsScene filters QApplication's events to detect palette and font
changes.
*/
bool QGraphicsScene::eventFilter(QObject *watched, QEvent *event)
{
if (watched != qApp)
return false;
switch (event->type()) {
case QEvent::ApplicationPaletteChange:
qApp->postEvent(this, new QEvent(QEvent::ApplicationPaletteChange));
break;
case QEvent::ApplicationFontChange:
qApp->postEvent(this, new QEvent(QEvent::ApplicationFontChange));
break;
default:
break;
}
return false;
}
/*!
This event handler, for event \a contextMenuEvent, can be reimplemented in
a subclass to receive context menu events. The default implementation
forwards the event to the topmost item that accepts context menu events at
the position of the event. If no items accept context menu events at this
position, the event is ignored.
\sa QGraphicsItem::contextMenuEvent()
*/
void QGraphicsScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *contextMenuEvent)
{
Q_D(QGraphicsScene);
// Ignore by default.
contextMenuEvent->ignore();
// Send the event to all items at this position until one item accepts the
// event.
foreach (QGraphicsItem *item, d->itemsAtPosition(contextMenuEvent->screenPos(),
contextMenuEvent->scenePos(),
contextMenuEvent->widget())) {
contextMenuEvent->setPos(item->d_ptr->genericMapFromScene(contextMenuEvent->scenePos(),
contextMenuEvent->widget()));
contextMenuEvent->accept();
if (!d->sendEvent(item, contextMenuEvent))
break;
if (contextMenuEvent->isAccepted())
break;
}
}
/*!
This event handler, for event \a event, can be reimplemented in a subclass
to receive drag enter events for the scene.
The default implementation accepts the event and prepares the scene to
accept drag move events.
\sa QGraphicsItem::dragEnterEvent(), dragMoveEvent(), dragLeaveEvent(),
dropEvent()
*/
void QGraphicsScene::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
{
Q_D(QGraphicsScene);
d->dragDropItem = 0;
d->lastDropAction = Qt::IgnoreAction;
event->accept();
}
/*!
This event handler, for event \a event, can be reimplemented in a subclass
to receive drag move events for the scene.
\sa QGraphicsItem::dragMoveEvent(), dragEnterEvent(), dragLeaveEvent(),
dropEvent()
*/
void QGraphicsScene::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
{
Q_D(QGraphicsScene);
event->ignore();
if (!d->mouseGrabberItems.isEmpty()) {
// Mouse grabbers that start drag events lose the mouse grab.
d->clearMouseGrabber();
d->mouseGrabberButtonDownPos.clear();
d->mouseGrabberButtonDownScenePos.clear();
d->mouseGrabberButtonDownScreenPos.clear();
}
bool eventDelivered = false;
// Find the topmost enabled items under the cursor. They are all
// candidates for accepting drag & drop events.
foreach (QGraphicsItem *item, d->itemsAtPosition(event->screenPos(),
event->scenePos(),
event->widget())) {
if (!item->isEnabled() || !item->acceptDrops())
continue;
if (item != d->dragDropItem) {
// Enter the new drag drop item. If it accepts the event, we send
// the leave to the parent item.
QGraphicsSceneDragDropEvent dragEnter(QEvent::GraphicsSceneDragEnter);
d->cloneDragDropEvent(&dragEnter, event);
dragEnter.setDropAction(event->proposedAction());
d->sendDragDropEvent(item, &dragEnter);
event->setAccepted(dragEnter.isAccepted());
event->setDropAction(dragEnter.dropAction());
if (!event->isAccepted()) {
// Propagate to the item under
continue;
}
d->lastDropAction = event->dropAction();
if (d->dragDropItem) {
// Leave the last drag drop item. A perfect implementation
// would set the position of this event to the point where
// this event and the last event intersect with the item's
// shape, but that's not easy to do. :-)
QGraphicsSceneDragDropEvent dragLeave(QEvent::GraphicsSceneDragLeave);
d->cloneDragDropEvent(&dragLeave, event);
d->sendDragDropEvent(d->dragDropItem, &dragLeave);
}
// We've got a new drag & drop item
d->dragDropItem = item;
}
// Send the move event.
event->setDropAction(d->lastDropAction);
event->accept();
d->sendDragDropEvent(item, event);
if (event->isAccepted())
d->lastDropAction = event->dropAction();
eventDelivered = true;
break;
}
if (!eventDelivered) {
if (d->dragDropItem) {
// Leave the last drag drop item
QGraphicsSceneDragDropEvent dragLeave(QEvent::GraphicsSceneDragLeave);
d->cloneDragDropEvent(&dragLeave, event);
d->sendDragDropEvent(d->dragDropItem, &dragLeave);
d->dragDropItem = 0;
}
// Propagate
event->setDropAction(Qt::IgnoreAction);
}
}
/*!
This event handler, for event \a event, can be reimplemented in a subclass
to receive drag leave events for the scene.
\sa QGraphicsItem::dragLeaveEvent(), dragEnterEvent(), dragMoveEvent(),
dropEvent()
*/
void QGraphicsScene::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
{
Q_D(QGraphicsScene);
if (d->dragDropItem) {
// Leave the last drag drop item
d->sendDragDropEvent(d->dragDropItem, event);
d->dragDropItem = 0;
}
}
/*!
This event handler, for event \a event, can be reimplemented in a subclass
to receive drop events for the scene.
\sa QGraphicsItem::dropEvent(), dragEnterEvent(), dragMoveEvent(),
dragLeaveEvent()
*/
void QGraphicsScene::dropEvent(QGraphicsSceneDragDropEvent *event)
{
Q_UNUSED(event);
Q_D(QGraphicsScene);
if (d->dragDropItem) {
// Drop on the last drag drop item
d->sendDragDropEvent(d->dragDropItem, event);
d->dragDropItem = 0;
}
}
/*!
This event handler, for event \a focusEvent, can be reimplemented in a
subclass to receive focus in events.
The default implementation sets focus on the scene, and then on the last
focus item.
\sa QGraphicsItem::focusOutEvent()
*/
void QGraphicsScene::focusInEvent(QFocusEvent *focusEvent)
{
Q_D(QGraphicsScene);
d->hasFocus = true;
switch (focusEvent->reason()) {
case Qt::TabFocusReason:
if (!focusNextPrevChild(true))
focusEvent->ignore();
break;
case Qt::BacktabFocusReason:
if (!focusNextPrevChild(false))
focusEvent->ignore();
break;
default:
if (d->lastFocusItem) {
// Set focus on the last focus item
setFocusItem(d->lastFocusItem, focusEvent->reason());
}
break;
}
}
/*!
This event handler, for event \a focusEvent, can be reimplemented in a
subclass to receive focus out events.
The default implementation removes focus from any focus item, then removes
focus from the scene.
\sa QGraphicsItem::focusInEvent()
*/
void QGraphicsScene::focusOutEvent(QFocusEvent *focusEvent)
{
Q_D(QGraphicsScene);
d->hasFocus = false;
setFocusItem(0, focusEvent->reason());
// Remove all popups when the scene loses focus.
if (!d->popupWidgets.isEmpty())
d->removePopup(d->popupWidgets.first());
}
/*!
This event handler, for event \a helpEvent, can be
reimplemented in a subclass to receive help events. The events
are of type QEvent::ToolTip, which are created when a tooltip is
requested.
The default implementation shows the tooltip of the topmost
item, i.e., the item with the highest z-value, at the mouse
cursor position. If no item has a tooltip set, this function
does nothing.
\sa QGraphicsItem::toolTip(), QGraphicsSceneHelpEvent
*/
void QGraphicsScene::helpEvent(QGraphicsSceneHelpEvent *helpEvent)
{
#ifdef QT_NO_TOOLTIP
Q_UNUSED(helpEvent);
#else
// Find the first item that does tooltips
Q_D(QGraphicsScene);
QList<QGraphicsItem *> itemsAtPos = d->itemsAtPosition(helpEvent->screenPos(),
helpEvent->scenePos(),
helpEvent->widget());
QGraphicsItem *toolTipItem = 0;
for (int i = 0; i < itemsAtPos.size(); ++i) {
QGraphicsItem *tmp = itemsAtPos.at(i);
if (!tmp->toolTip().isEmpty()) {
toolTipItem = tmp;
break;
}
}
// Show or hide the tooltip
QString text;
QPoint point;
if (toolTipItem && !toolTipItem->toolTip().isEmpty()) {
text = toolTipItem->toolTip();
point = helpEvent->screenPos();
}
QToolTip::showText(point, text);
helpEvent->setAccepted(!text.isEmpty());
#endif
}
bool QGraphicsScenePrivate::itemAcceptsHoverEvents_helper(const QGraphicsItem *item) const
{
return item->acceptHoverEvents()
|| (item->isWidget() && static_cast<const QGraphicsWidget *>(item)->d_func()->hasDecoration());
}
/*!
This event handler, for event \a hoverEvent, can be reimplemented in a
subclass to receive hover enter events. The default implementation
forwards the event to the topmost item that accepts hover events at the
scene position from the event.
\sa QGraphicsItem::hoverEvent(), QGraphicsItem::setAcceptHoverEvents()
*/
bool QGraphicsScenePrivate::dispatchHoverEvent(QGraphicsSceneHoverEvent *hoverEvent)
{
// Find the first item that accepts hover events, reusing earlier
// calculated data is possible.
if (cachedItemsUnderMouse.isEmpty()) {
cachedItemsUnderMouse = itemsAtPosition(hoverEvent->screenPos(),
hoverEvent->scenePos(),
hoverEvent->widget());
}
QGraphicsItem *item = 0;
for (int i = 0; i < cachedItemsUnderMouse.size(); ++i) {
QGraphicsItem *tmp = cachedItemsUnderMouse.at(i);
if (itemAcceptsHoverEvents_helper(tmp)) {
item = tmp;
break;
}
}
// Find the common ancestor item for the new topmost hoverItem and the
// last item in the hoverItem list.
QGraphicsItem *commonAncestorItem = (item && !hoverItems.isEmpty()) ? item->commonAncestorItem(hoverItems.last()) : 0;
while (commonAncestorItem && !itemAcceptsHoverEvents_helper(commonAncestorItem))
commonAncestorItem = commonAncestorItem->parentItem();
if (commonAncestorItem && commonAncestorItem->window() != item->window()) {
// The common ancestor isn't in the same window as the two hovered
// items.
commonAncestorItem = 0;
}
// Check if the common ancestor item is known.
int index = commonAncestorItem ? hoverItems.indexOf(commonAncestorItem) : -1;
// Send hover leaves to any existing hovered children of the common
// ancestor item.
for (int i = hoverItems.size() - 1; i > index; --i) {
QGraphicsItem *lastItem = hoverItems.takeLast();
if (itemAcceptsHoverEvents_helper(lastItem))
sendHoverEvent(QEvent::GraphicsSceneHoverLeave, lastItem, hoverEvent);
}
// Item is a child of a known item. Generate enter events for the
// missing links.
QList<QGraphicsItem *> parents;
QGraphicsItem *parent = item;
while (parent && parent != commonAncestorItem) {
parents.prepend(parent);
if (parent->isWindow()) {
// Stop at the window - we don't deliver beyond this point.
break;
}
parent = parent->parentItem();
}
for (int i = 0; i < parents.size(); ++i) {
parent = parents.at(i);
hoverItems << parent;
if (itemAcceptsHoverEvents_helper(parent))
sendHoverEvent(QEvent::GraphicsSceneHoverEnter, parent, hoverEvent);
}
// Generate a move event for the item itself
if (item && !hoverItems.isEmpty() && item == hoverItems.last()) {
sendHoverEvent(QEvent::GraphicsSceneHoverMove, item, hoverEvent);
return true;
}
return false;
}
/*!
\internal
Handles all actions necessary to clean up the scene when the mouse leaves
the view.
*/
void QGraphicsScenePrivate::leaveScene()
{
Q_Q(QGraphicsScene);
#ifndef QT_NO_TOOLTIP
// Remove any tooltips
QToolTip::showText(QPoint(), QString());
#endif
// Send HoverLeave events to all existing hover items, topmost first.
QGraphicsView *senderWidget = qobject_cast<QGraphicsView *>(q->sender());
QGraphicsSceneHoverEvent hoverEvent;
hoverEvent.setWidget(senderWidget);
if (senderWidget) {
QPoint cursorPos = QCursor::pos();
hoverEvent.setScenePos(senderWidget->mapToScene(senderWidget->mapFromGlobal(cursorPos)));
hoverEvent.setLastScenePos(hoverEvent.scenePos());
hoverEvent.setScreenPos(cursorPos);
hoverEvent.setLastScreenPos(hoverEvent.screenPos());
}
while (!hoverItems.isEmpty()) {
QGraphicsItem *lastItem = hoverItems.takeLast();
if (lastItem->acceptHoverEvents()
|| (lastItem->isWidget() && static_cast<QGraphicsWidget*>(lastItem)->d_func()->hasDecoration()))
sendHoverEvent(QEvent::GraphicsSceneHoverLeave, lastItem, &hoverEvent);
}
}
/*!
This event handler, for event \a keyEvent, can be reimplemented in a
subclass to receive keypress events. The default implementation forwards
the event to current focus item.
\sa QGraphicsItem::keyPressEvent(), focusItem()
*/
void QGraphicsScene::keyPressEvent(QKeyEvent *keyEvent)
{
// ### Merge this function with keyReleaseEvent; they are identical
// ### (except this comment).
Q_D(QGraphicsScene);
QGraphicsItem *item = !d->keyboardGrabberItems.isEmpty() ? d->keyboardGrabberItems.last() : 0;
if (!item)
item = focusItem();
if (item) {
QGraphicsItem *p = item;
do {
// Accept the event by default
keyEvent->accept();
// Send it; QGraphicsItem::keyPressEvent ignores it. If the event
// is filtered out, stop propagating it.
if (!d->sendEvent(p, keyEvent))
break;
} while (!keyEvent->isAccepted() && !p->isWindow() && (p = p->parentItem()));
} else {
keyEvent->ignore();
}
}
/*!
This event handler, for event \a keyEvent, can be reimplemented in a
subclass to receive key release events. The default implementation
forwards the event to current focus item.
\sa QGraphicsItem::keyReleaseEvent(), focusItem()
*/
void QGraphicsScene::keyReleaseEvent(QKeyEvent *keyEvent)
{
// ### Merge this function with keyPressEvent; they are identical (except
// ### this comment).
Q_D(QGraphicsScene);
QGraphicsItem *item = !d->keyboardGrabberItems.isEmpty() ? d->keyboardGrabberItems.last() : 0;
if (!item)
item = focusItem();
if (item) {
QGraphicsItem *p = item;
do {
// Accept the event by default
keyEvent->accept();
// Send it; QGraphicsItem::keyPressEvent ignores it. If the event
// is filtered out, stop propagating it.
if (!d->sendEvent(p, keyEvent))
break;
} while (!keyEvent->isAccepted() && !p->isWindow() && (p = p->parentItem()));
} else {
keyEvent->ignore();
}
}
/*!
This event handler, for event \a mouseEvent, can be reimplemented
in a subclass to receive mouse press events for the scene.
The default implementation depends on the state of the scene. If
there is a mouse grabber item, then the event is sent to the mouse
grabber. Otherwise, it is forwarded to the topmost item that
accepts mouse events at the scene position from the event, and
that item promptly becomes the mouse grabber item.
If there is no item at the given position on the scene, the
selection area is reset, any focus item loses its input focus, and
the event is then ignored.
\sa QGraphicsItem::mousePressEvent(),
QGraphicsItem::setAcceptedMouseButtons()
*/
void QGraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_D(QGraphicsScene);
d->mousePressEventHandler(mouseEvent);
}
/*!
This event handler, for event \a mouseEvent, can be reimplemented
in a subclass to receive mouse move events for the scene.
The default implementation depends on the mouse grabber state. If there is
a mouse grabber item, the event is sent to the mouse grabber. If there
are any items that accept hover events at the current position, the event
is translated into a hover event and accepted; otherwise it's ignored.
\sa QGraphicsItem::mousePressEvent(), QGraphicsItem::mouseReleaseEvent(),
QGraphicsItem::mouseDoubleClickEvent(), QGraphicsItem::setAcceptedMouseButtons()
*/
void QGraphicsScene::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_D(QGraphicsScene);
if (d->mouseGrabberItems.isEmpty()) {
if (mouseEvent->buttons())
return;
QGraphicsSceneHoverEvent hover;
_q_hoverFromMouseEvent(&hover, mouseEvent);
mouseEvent->setAccepted(d->dispatchHoverEvent(&hover));
return;
}
// Forward the event to the mouse grabber
d->sendMouseEvent(mouseEvent);
mouseEvent->accept();
}
/*!
This event handler, for event \a mouseEvent, can be reimplemented
in a subclass to receive mouse release events for the scene.
The default implementation depends on the mouse grabber state. If
there is no mouse grabber, the event is ignored. Otherwise, if
there is a mouse grabber item, the event is sent to the mouse
grabber. If this mouse release represents the last pressed button
on the mouse, the mouse grabber item then loses the mouse grab.
\sa QGraphicsItem::mousePressEvent(), QGraphicsItem::mouseMoveEvent(),
QGraphicsItem::mouseDoubleClickEvent(), QGraphicsItem::setAcceptedMouseButtons()
*/
void QGraphicsScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_D(QGraphicsScene);
if (d->mouseGrabberItems.isEmpty()) {
mouseEvent->ignore();
return;
}
// Forward the event to the mouse grabber
d->sendMouseEvent(mouseEvent);
mouseEvent->accept();
// Reset the mouse grabber when the last mouse button has been released.
if (!mouseEvent->buttons()) {
if (!d->mouseGrabberItems.isEmpty()) {
d->lastMouseGrabberItem = d->mouseGrabberItems.last();
if (d->lastMouseGrabberItemHasImplicitMouseGrab)
d->mouseGrabberItems.last()->ungrabMouse();
} else {
d->lastMouseGrabberItem = 0;
}
// Generate a hoverevent
QGraphicsSceneHoverEvent hoverEvent;
_q_hoverFromMouseEvent(&hoverEvent, mouseEvent);
d->dispatchHoverEvent(&hoverEvent);
}
}
/*!
This event handler, for event \a mouseEvent, can be reimplemented
in a subclass to receive mouse doubleclick events for the scene.
If someone doubleclicks on the scene, the scene will first receive
a mouse press event, followed by a release event (i.e., a click),
then a doubleclick event, and finally a release event. If the
doubleclick event is delivered to a different item than the one
that received the first press and release, it will be delivered as
a press event. However, tripleclick events are not delivered as
doubleclick events in this case.
The default implementation is similar to mousePressEvent().
\sa QGraphicsItem::mousePressEvent(), QGraphicsItem::mouseMoveEvent(),
QGraphicsItem::mouseReleaseEvent(), QGraphicsItem::setAcceptedMouseButtons()
*/
void QGraphicsScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_D(QGraphicsScene);
d->mousePressEventHandler(mouseEvent);
}
/*!
This event handler, for event \a wheelEvent, can be reimplemented in a
subclass to receive mouse wheel events for the scene.
By default, the event is delivered to the topmost visible item under the
cursor. If ignored, the event propagates to the item beneath, and again
until the event is accepted, or it reaches the scene. If no items accept
the event, it is ignored.
\sa QGraphicsItem::wheelEvent()
*/
void QGraphicsScene::wheelEvent(QGraphicsSceneWheelEvent *wheelEvent)
{
Q_D(QGraphicsScene);
QList<QGraphicsItem *> wheelCandidates = d->itemsAtPosition(wheelEvent->screenPos(),
wheelEvent->scenePos(),
wheelEvent->widget());
bool hasSetFocus = false;
foreach (QGraphicsItem *item, wheelCandidates) {
if (!hasSetFocus && item->isEnabled() && (item->flags() & QGraphicsItem::ItemIsFocusable)) {
if (item->isWidget() && static_cast<QGraphicsWidget *>(item)->focusPolicy() == Qt::WheelFocus) {
hasSetFocus = true;
if (item != focusItem())
setFocusItem(item, Qt::MouseFocusReason);
}
}
wheelEvent->setPos(item->d_ptr->genericMapFromScene(wheelEvent->scenePos(),
wheelEvent->widget()));
wheelEvent->accept();
bool isWindow = item->isWindow();
d->sendEvent(item, wheelEvent);
if (isWindow || wheelEvent->isAccepted())
break;
}
}
/*!
This event handler, for event \a event, can be reimplemented in a
subclass to receive input method events for the scene.
The default implementation forwards the event to the focusItem().
If no item currently has focus, this function does nothing.
\sa QGraphicsItem::inputMethodEvent()
*/
void QGraphicsScene::inputMethodEvent(QInputMethodEvent *event)
{
Q_D(QGraphicsScene);
if (!d->focusItem)
return;
d->sendEvent(d->focusItem, event);
}
/*!
Draws the background of the scene using \a painter, before any items and
the foreground are drawn. Reimplement this function to provide a custom
background for the scene.
All painting is done in \e scene coordinates. The \a rect
parameter is the exposed rectangle.
If all you want is to define a color, texture, or gradient for the
background, you can call setBackgroundBrush() instead.
\sa drawForeground(), drawItems()
*/
void QGraphicsScene::drawBackground(QPainter *painter, const QRectF &rect)
{
Q_D(QGraphicsScene);
if (d->backgroundBrush.style() != Qt::NoBrush) {
if (d->painterStateProtection)
painter->save();
painter->setBrushOrigin(0, 0);
painter->fillRect(rect, backgroundBrush());
if (d->painterStateProtection)
painter->restore();
}
}
/*!
Draws the foreground of the scene using \a painter, after the background
and all items have been drawn. Reimplement this function to provide a
custom foreground for the scene.
All painting is done in \e scene coordinates. The \a rect
parameter is the exposed rectangle.
If all you want is to define a color, texture or gradient for the
foreground, you can call setForegroundBrush() instead.
\sa drawBackground(), drawItems()
*/
void QGraphicsScene::drawForeground(QPainter *painter, const QRectF &rect)
{
Q_D(QGraphicsScene);
if (d->foregroundBrush.style() != Qt::NoBrush) {
if (d->painterStateProtection)
painter->save();
painter->setBrushOrigin(0, 0);
painter->fillRect(rect, foregroundBrush());
if (d->painterStateProtection)
painter->restore();
}
}
static void _q_paintItem(QGraphicsItem *item, QPainter *painter,
const QStyleOptionGraphicsItem *option, QWidget *widget,
bool useWindowOpacity, bool painterStateProtection)
{
if (!item->isWidget()) {
item->paint(painter, option, widget);
return;
}
QGraphicsWidget *widgetItem = static_cast<QGraphicsWidget *>(item);
QGraphicsProxyWidget *proxy = qobject_cast<QGraphicsProxyWidget *>(widgetItem);
const qreal windowOpacity = (proxy && proxy->widget() && useWindowOpacity)
? proxy->widget()->windowOpacity() : 1.0;
const qreal oldPainterOpacity = painter->opacity();
if (qFuzzyCompare(windowOpacity + 1, qreal(1.0)))
return;
// Set new painter opacity.
if (windowOpacity < 1.0)
painter->setOpacity(oldPainterOpacity * windowOpacity);
// set layoutdirection on the painter
Qt::LayoutDirection oldLayoutDirection = painter->layoutDirection();
painter->setLayoutDirection(widgetItem->layoutDirection());
if (widgetItem->isWindow() && widgetItem->windowType() != Qt::Popup && widgetItem->windowType() != Qt::ToolTip
&& !(widgetItem->windowFlags() & Qt::FramelessWindowHint)) {
if (painterStateProtection)
painter->save();
widgetItem->paintWindowFrame(painter, option, widget);
if (painterStateProtection)
painter->restore();
}
widgetItem->paint(painter, option, widget);
// Restore layoutdirection on the painter.
painter->setLayoutDirection(oldLayoutDirection);
// Restore painter opacity.
if (windowOpacity < 1.0)
painter->setOpacity(oldPainterOpacity);
}
static void _q_paintIntoCache(QPixmap *pix, QGraphicsItem *item, const QRegion &pixmapExposed,
const QTransform &itemToPixmap, QPainter::RenderHints renderHints,
const QStyleOptionGraphicsItem *option, bool painterStateProtection)
{
QPixmap subPix;
QPainter pixmapPainter;
QRect br = pixmapExposed.boundingRect();
// Don't use subpixmap if we get a full update.
if (pixmapExposed.isEmpty() || (pixmapExposed.numRects() == 1 && br.contains(pix->rect()))) {
pix->fill(Qt::transparent);
pixmapPainter.begin(pix);
} else {
subPix = QPixmap(br.size());
subPix.fill(Qt::transparent);
pixmapPainter.begin(&subPix);
pixmapPainter.translate(-br.topLeft());
if (!pixmapExposed.isEmpty()) {
// Applied to subPix; paint is adjusted to the coordinate space is
// correct.
pixmapPainter.setClipRegion(pixmapExposed);
}
}
pixmapPainter.setRenderHints(pixmapPainter.renderHints(), false);
pixmapPainter.setRenderHints(renderHints, true);
pixmapPainter.setWorldTransform(itemToPixmap, true);
// Render.
_q_paintItem(item, &pixmapPainter, option, 0, false, painterStateProtection);
pixmapPainter.end();
if (!subPix.isNull()) {
// Blit the subpixmap into the main pixmap.
pixmapPainter.begin(pix);
pixmapPainter.setCompositionMode(QPainter::CompositionMode_Source);
pixmapPainter.setClipRegion(pixmapExposed);
pixmapPainter.drawPixmap(br.topLeft(), subPix);
pixmapPainter.end();
}
}
/*!
\internal
Draws items directly, or using cache.
*/
void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painter,
const QStyleOptionGraphicsItem *option, QWidget *widget,
bool painterStateProtection)
{
QGraphicsItemPrivate *itemd = item->d_ptr;
QGraphicsItem::CacheMode cacheMode = QGraphicsItem::CacheMode(itemd->cacheMode);
// Render directly, using no cache.
if (cacheMode == QGraphicsItem::NoCache
#ifdef Q_WS_X11
|| !X11->use_xrender
#endif
) {
_q_paintItem(static_cast<QGraphicsWidget *>(item), painter, option, widget, true, painterStateProtection);
return;
}
const qreal oldPainterOpacity = painter->opacity();
qreal newPainterOpacity = oldPainterOpacity;
QGraphicsProxyWidget *proxy = item->isWidget() ? qobject_cast<QGraphicsProxyWidget *>(static_cast<QGraphicsWidget *>(item)) : 0;
if (proxy && proxy->widget()) {
const qreal windowOpacity = proxy->widget()->windowOpacity();
if (windowOpacity < 1.0)
newPainterOpacity *= windowOpacity;
}
// Item's (local) bounding rect
QRectF brect = item->boundingRect();
if (_q_adjustedRect(brect).isEmpty())
return;
// Fetch the off-screen transparent buffer and exposed area info.
QString pixmapKey;
QPixmap pix;
QGraphicsItemCache *itemCache = itemd->extraItemCache();
if (cacheMode == QGraphicsItem::ItemCoordinateCache) {
if (itemCache->boundingRect != brect.toRect()) {
itemCache->boundingRect = brect.toRect();
itemCache->allExposed = true;
itemCache->exposed.clear();
}
pixmapKey = itemCache->key;
} else {
if ((pixmapKey = itemCache->deviceData.value(widget).key).isEmpty()) {
pixmapKey.sprintf("qgv-%p-%p", item, widget);
QGraphicsItemCache::DeviceData data;
data.key = pixmapKey;
itemCache->deviceData.insert(widget, data);
}
}
// Find pixmap in cache.
if (!itemCache->allExposed)
QPixmapCache::find(pixmapKey, pix);
// Render using item coordinate cache mode.
if (cacheMode == QGraphicsItem::ItemCoordinateCache) {
QSize pixmapSize;
bool fixedCacheSize = false;
QRectF brectAligned = brect.toAlignedRect();
if ((fixedCacheSize = itemCache->fixedSize.isValid())) {
pixmapSize = itemCache->fixedSize;
} else {
pixmapSize = brectAligned.size().toSize();
}
// Create or recreate the pixmap.
int adjust = itemCache->fixedSize.isValid() ? 0 : 2;
QSize adjustSize(adjust*2, adjust*2);
QRectF br = brectAligned.adjusted(-adjust, -adjust, adjust, adjust);
if (pix.isNull() || (!fixedCacheSize && (pixmapSize + adjustSize) != pix.size())) {
pix = QPixmap(pixmapSize + adjustSize);
itemCache->exposed.clear();
itemCache->allExposed = true;
}
// Redraw any newly exposed areas.
if (itemCache->allExposed || !itemCache->exposed.isEmpty()) {
// Fit the item's bounding rect into the pixmap's coordinates.
QTransform itemToPixmap;
if (fixedCacheSize) {
const QPointF scale(pixmapSize.width() / brect.width(), pixmapSize.height() / brect.height());
itemToPixmap.scale(scale.x(), scale.y());
}
itemToPixmap.translate(-br.x(), -br.y());
// Generate the item's exposedRect and map its list of expose
// rects to device coordinates.
QStyleOptionGraphicsItem cacheOption = *option;
QRegion pixmapExposed;
QRectF exposedRect;
if (!itemCache->allExposed) {
for (int i = 0; i < itemCache->exposed.size(); ++i) {
QRectF r = itemCache->exposed.at(i);
exposedRect |= r;
pixmapExposed += itemToPixmap.mapRect(r).toAlignedRect();
}
} else {
exposedRect = brect;
}
cacheOption.exposedRect = exposedRect;
// Render.
_q_paintIntoCache(&pix, item, pixmapExposed, itemToPixmap, painter->renderHints(),
&cacheOption, painterStateProtection);
// Reinsert this pixmap into the cache.
QPixmapCache::insert(pixmapKey, pix);
// Reset expose data.
itemCache->allExposed = false;
itemCache->exposed.clear();
}
// Redraw the exposed area using the transformed painter. Depending on
// the hardware, this may be a server-side operation, or an expensive
// qpixmap-image-transform-pixmap roundtrip.
if (newPainterOpacity != oldPainterOpacity) {
painter->setOpacity(newPainterOpacity);
painter->drawPixmap(br, pix, QRectF(QPointF(), pix.size()));
painter->setOpacity(oldPainterOpacity);
} else {
painter->drawPixmap(br, pix, QRectF(QPointF(), pix.size()));
}
return;
}
// Render using device coordinate cache mode.
if (cacheMode == QGraphicsItem::DeviceCoordinateCache) {
// Find the item's bounds in device coordinates.
QRectF deviceBounds = painter->worldTransform().mapRect(brect);
QRect deviceRect = deviceBounds.toRect().adjusted(-1, -1, 1, 1);
if (deviceRect.isEmpty())
return;
QRect viewRect = widget ? widget->rect() : QRect();
if (widget && !viewRect.intersects(deviceRect))
return;
// Resort to direct rendering if the device rect exceeds the
// (optional) maximum bounds. (QGraphicsSvgItem uses this).
QSize maximumCacheSize =
itemd->extra(QGraphicsItemPrivate::ExtraMaxDeviceCoordCacheSize).toSize();
if (!maximumCacheSize.isEmpty()
&& (deviceRect.width() > maximumCacheSize.width()
|| deviceRect.height() > maximumCacheSize.height())) {
_q_paintItem(static_cast<QGraphicsWidget *>(item), painter, option, widget,
oldPainterOpacity != newPainterOpacity, painterStateProtection);
return;
}
// Create or reuse offscreen pixmap, possibly scroll/blit from the old one.
bool pixModified = false;
QGraphicsItemCache::DeviceData *deviceData = &itemCache->deviceData[widget];
bool invertable = true;
QTransform diff = deviceData->lastTransform.inverted(&invertable);
if (invertable)
diff *= painter->worldTransform();
deviceData->lastTransform = painter->worldTransform();
if (!invertable || diff.type() > QTransform::TxTranslate) {
pixModified = true;
itemCache->allExposed = true;
itemCache->exposed.clear();
pix = QPixmap();
}
// ### This is a pretty bad way to determine when to start partial
// exposure for DeviceCoordinateCache but it's the least intrusive
// approach for now.
#if 0
// Only if the device rect isn't fully contained.
bool allowPartialCacheExposure = !viewRect.contains(deviceRect);
#else
// Only if deviceRect is 20% taller or wider than the desktop.
QRect desktopRect = qApp->desktop()->availableGeometry(widget);
bool allowPartialCacheExposure = (desktopRect.width() * 1.2 < deviceRect.width()
|| desktopRect.height() * 1.2 < deviceRect.height());
#endif
QRegion scrollExposure;
if (deviceData->cacheIndent != QPoint() || allowPartialCacheExposure) {
// Part of pixmap is drawn. Either device contains viewrect (big
// item covers whole screen) or parts of device are outside the
// viewport. In either case the device rect must be the intersect
// between the two.
int dx = deviceRect.left() < viewRect.left() ? viewRect.left() - deviceRect.left() : 0;
int dy = deviceRect.top() < viewRect.top() ? viewRect.top() - deviceRect.top() : 0;
QPoint newCacheIndent(dx, dy);
deviceRect &= viewRect;
if (pix.isNull()) {
deviceData->cacheIndent = QPoint();
itemCache->allExposed = true;
itemCache->exposed.clear();
pixModified = true;
}
// Copy / "scroll" the old pixmap onto the new ole and calculate
// scrolled exposure.
if (newCacheIndent != deviceData->cacheIndent || deviceRect.size() != pix.size()) {
QPoint diff = newCacheIndent - deviceData->cacheIndent;
QPixmap newPix(deviceRect.size());
// ### Investigate removing this fill (test with Plasma and
// graphicssystem raster).
newPix.fill(Qt::transparent);
if (!pix.isNull()) {
QPainter newPixPainter(&newPix);
newPixPainter.drawPixmap(-diff, pix);
newPixPainter.end();
}
QRegion exposed;
exposed += newPix.rect();
if (!pix.isNull())
exposed -= QRect(-diff, pix.size());
scrollExposure = exposed;
pix = newPix;
pixModified = true;
}
deviceData->cacheIndent = newCacheIndent;
} else {
// Full pixmap is drawn.
deviceData->cacheIndent = QPoint();
// Auto-adjust the pixmap size.
if (deviceRect.size() != pix.size()) {
// exposed needs to cover the whole pixmap
pix = QPixmap(deviceRect.size());
pixModified = true;
itemCache->allExposed = true;
itemCache->exposed.clear();
}
}
// Check for newly invalidated areas.
if (itemCache->allExposed || !itemCache->exposed.isEmpty() || !scrollExposure.isEmpty()) {
// Construct an item-to-pixmap transform.
QPointF p = deviceRect.topLeft();
QTransform itemToPixmap = painter->worldTransform();
if (!p.isNull())
itemToPixmap *= QTransform::fromTranslate(-p.x(), -p.y());
// Map the item's logical expose to pixmap coordinates.
QRegion pixmapExposed = scrollExposure;
if (!itemCache->allExposed) {
const QVector<QRectF> &exposed = itemCache->exposed;
for (int i = 0; i < exposed.size(); ++i)
pixmapExposed += itemToPixmap.mapRect(exposed.at(i)).toRect().adjusted(-1, -1, 1, 1);
}
// Calculate the style option's exposedRect.
QRectF br;
if (itemCache->allExposed) {
br = item->boundingRect();
} else {
const QVector<QRectF> &exposed = itemCache->exposed;
for (int i = 0; i < exposed.size(); ++i)
br |= exposed.at(i);
QTransform pixmapToItem = itemToPixmap.inverted();
foreach (QRect r, scrollExposure.rects())
br |= pixmapToItem.mapRect(r);
}
QStyleOptionGraphicsItem cacheOption = *option;
cacheOption.exposedRect = br.adjusted(-1, -1, 1, 1);
// Render the exposed areas.
_q_paintIntoCache(&pix, item, pixmapExposed, itemToPixmap, painter->renderHints(),
&cacheOption, painterStateProtection);
// Reset expose data.
pixModified = true;
itemCache->allExposed = false;
itemCache->exposed.clear();
}
if (pixModified) {
// Reinsert this pixmap into the cache
QPixmapCache::insert(pixmapKey, pix);
}
// Redraw the exposed area using an untransformed painter. This
// effectively becomes a bitblit that does not transform the cache.
QTransform restoreTransform = painter->worldTransform();
painter->setWorldTransform(QTransform());
if (newPainterOpacity != oldPainterOpacity) {
painter->setOpacity(newPainterOpacity);
painter->drawPixmap(deviceRect.topLeft(), pix);
painter->setOpacity(oldPainterOpacity);
} else {
painter->drawPixmap(deviceRect.topLeft(), pix);
}
painter->setWorldTransform(restoreTransform);
return;
}
}
/*!
Paints the given \a items using the provided \a painter, after the
background has been drawn, and before the foreground has been
drawn. All painting is done in \e scene coordinates. Before
drawing each item, the painter must be transformed using
QGraphicsItem::sceneMatrix().
The \a options parameter is the list of style option objects for
each item in \a items. The \a numItems parameter is the number of
items in \a items and options in \a options. The \a widget
parameter is optional; if specified, it should point to the widget
that is being painted on.
The default implementation prepares the painter matrix, and calls
QGraphicsItem::paint() on all items. Reimplement this function to
provide custom painting of all items for the scene; gaining
complete control over how each item is drawn. In some cases this
can increase drawing performance significantly.
Example:
\snippet doc/src/snippets/graphicssceneadditemsnippet.cpp 0
\sa drawBackground(), drawForeground()
*/
void QGraphicsScene::drawItems(QPainter *painter,
int numItems,
QGraphicsItem *items[],
const QStyleOptionGraphicsItem options[], QWidget *widget)
{
Q_D(QGraphicsScene);
// Detect if painter state protection is disabled.
QTransform viewTransform = painter->worldTransform();
QVarLengthArray<QGraphicsItem *, 16> childClippers;
for (int i = 0; i < numItems; ++i) {
QGraphicsItem *item = items[i];
if (!(item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)) {
if (!childClippers.isEmpty()) {
// Item is not clipped to any ancestor: pop all current clippers.
for (int i = 0; i < childClippers.size(); ++i)
painter->restore();
childClippers.clear();
}
} else {
// Item is clipped to an ancestor, which may or may not be in our
// child clipper list. Let's start by finding the item's closest
// clipping ancestor.
QGraphicsItem *clipParent = item->parentItem();
while (clipParent && !(clipParent->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape))
clipParent = clipParent->parentItem();
// Pop any in-between clippers. If the clipper is unknown, pop
// them all. ### QVarLengthArray::lastIndexOf().
int index = -1;
for (int n = childClippers.size() - 1; n >= 0; --n) {
if (childClippers[n] == clipParent) {
index = n;
break;
}
}
if (index != -1) {
int toPop = childClippers.size() - index - 1;
if (toPop > 0) {
for (int i = 0; i < toPop; ++i)
painter->restore();
childClippers.resize(index + 1);
}
}
// Sanity check
if (!childClippers.isEmpty())
Q_ASSERT(childClippers[childClippers.size() - 1] == clipParent);
// If the clipper list is empty at this point, but we're still
// clipped to an ancestor, then we need to build the clip chain
// ourselves. There is only one case that can produce this issue:
// This item is stacked behind an ancestor:
// ItemStacksBehindParent.
if (childClippers.isEmpty()) {
Q_ASSERT(clipParent != 0);
// Build a stack of clippers.
QVarLengthArray<QGraphicsItem *, 16> clippers;
QGraphicsItem *p = clipParent;
do {
if (p->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)
clippers.append(p);
} while ((p = p->parentItem()) && (p->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren));
// ### This code path can also use the itemTransform
// optimization, but it's hit very rarely.
for (int i = clippers.size() - 1; i >= 0; --i) {
QGraphicsItem *clipper = clippers[i];
if (clipper->d_ptr->itemIsUntransformable()) {
painter->setWorldTransform(clipper->deviceTransform(viewTransform), false);
} else {
painter->setWorldTransform(clipper->sceneTransform() * viewTransform, false);
}
childClippers.append(clipper);
painter->save();
painter->setClipPath(clipper->shape(), Qt::IntersectClip);
}
Q_ASSERT(childClippers[childClippers.size() - 1] == clipParent);
}
}
// Set up the painter transform
if (item->d_ptr->itemIsUntransformable()) {
painter->setWorldTransform(item->deviceTransform(viewTransform), false);
} else {
painter->setWorldTransform(item->sceneTransform() * viewTransform, false);
}
// Save painter
bool saveState = (d->painterStateProtection || (item->flags() & QGraphicsItem::ItemClipsToShape));
if (saveState)
painter->save();
// Set local clip
if (item->flags() & QGraphicsItem::ItemClipsToShape)
painter->setClipPath(item->shape(), Qt::IntersectClip);
// Setup opacity
painter->setOpacity(item->effectiveOpacity());
// Draw the item
d->drawItemHelper(item, painter, &options[i], widget, d->painterStateProtection);
if (saveState)
painter->restore();
if (item->flags() & QGraphicsItem::ItemClipsChildrenToShape) {
// Clip descendents to this item's shape, and keep the painter
// saved.
childClippers.append(item);
painter->save();
painter->setClipPath(item->shape(), Qt::IntersectClip);
}
}
for (int i = 0; i < childClippers.size(); ++i)
painter->restore();
painter->setWorldTransform(viewTransform);
}
/*!
\since 4.4
Finds a new widget to give the keyboard focus to, as appropriate for Tab
and Shift+Tab, and returns true if it can find a new widget, or false if
it cannot. If \a next is true, this function searches forward; if \a next
is false, it searches backward.
You can reimplement this function in a subclass of QGraphicsScene to
provide fine-grained control over how tab focus passes inside your
scene. The default implementation is based on the tab focus chain defined
by QGraphicsWidget::setTabOrder().
*/
bool QGraphicsScene::focusNextPrevChild(bool next)
{
Q_D(QGraphicsScene);
QGraphicsItem *item = focusItem();
if (item && !item->isWidget()) {
// Tab out of the scene.
return false;
}
if (!item) {
if (d->lastFocusItem && !d->lastFocusItem->isWidget()) {
// Restore focus to the last focusable non-widget item that had
// focus.
setFocusItem(d->lastFocusItem, next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
return true;
}
}
if (!d->tabFocusFirst) {
// No widgets...
return false;
}
// The item must be a widget.
QGraphicsWidget *widget = 0;
if (!item) {
widget = next ? d->tabFocusFirst : d->tabFocusFirst->d_func()->focusPrev;
} else {
QGraphicsWidget *test = static_cast<QGraphicsWidget *>(item);
widget = next ? test->d_func()->focusNext : test->d_func()->focusPrev;
if ((next && widget == d->tabFocusFirst) || (!next && widget == d->tabFocusFirst->d_func()->focusPrev))
return false;
}
QGraphicsWidget *widgetThatHadFocus = widget;
// Run around the focus chain until we find a widget that can take tab focus.
do {
if (widget->flags() & QGraphicsItem::ItemIsFocusable
&& widget->isEnabled() && widget->isVisibleTo(0)
&& (widget->focusPolicy() & Qt::TabFocus)
&& (!item || !item->isWindow() || item->isAncestorOf(widget))
) {
setFocusItem(widget, next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
return true;
}
widget = next ? widget->d_func()->focusNext : widget->d_func()->focusPrev;
if ((next && widget == d->tabFocusFirst) || (!next && widget == d->tabFocusFirst->d_func()->focusPrev))
return false;
} while (widget != widgetThatHadFocus);
return false;
}
/*!
\fn QGraphicsScene::changed(const QList<QRectF> ®ion)
This signal is emitted by QGraphicsScene when control reaches the
event loop, if the scene content changes. The \a region parameter
contains a list of scene rectangles that indicate the area that
has been changed.
\sa QGraphicsView::updateScene()
*/
/*!
\fn QGraphicsScene::sceneRectChanged(const QRectF &rect)
This signal is emitted by QGraphicsScene whenever the scene rect changes.
The \a rect parameter is the new scene rectangle.
\sa QGraphicsView::updateSceneRect()
*/
/*!
\fn QGraphicsScene::selectionChanged()
\since 4.3
This signal is emitted by QGraphicsScene whenever the selection
changes. You can call selectedItems() to get the new list of selected
items.
The selection changes whenever an item is selected or unselected, a
selection area is set, cleared or otherwise changed, if a preselected item
is added to the scene, or if a selected item is removed from the scene.
QGraphicsScene emits this signal only once for group selection operations.
For example, if you set a selection area, select or unselect a
QGraphicsItemGroup, or if you add or remove from the scene a parent item
that contains several selected items, selectionChanged() is emitted only
once after the operation has completed (instead of once for each item).
\sa setSelectionArea(), selectedItems(), QGraphicsItem::setSelected()
*/
/*!
\internal
This private function is called by QGraphicsItem, which is a friend of
QGraphicsScene. It is used by QGraphicsScene to record the rectangles that
need updating. It also launches a single-shot timer to ensure that
updated() will be emitted later.
The \a item parameter is the item that changed, and \a rect is the
area of the item that changed given in item coordinates.
*/
void QGraphicsScene::itemUpdated(QGraphicsItem *item, const QRectF &rect)
{
Q_D(QGraphicsScene);
// Deliver the actual update.
if (!d->updateAll) {
if (d->views.isEmpty() || ((d->connectedSignals & d->changedSignalMask) && !item->d_ptr->itemIsUntransformable()
&& qFuzzyCompare(item->boundingRegionGranularity(), qreal(0.0)))) {
// This block of code is kept for compatibility. Since 4.5, by default
// QGraphicsView does not connect the signal and we use the below
// method of delivering updates.
update(item->sceneBoundingRect());
} else {
// ### Remove _q_adjustedRects().
QRectF boundingRect = _q_adjustedRect(item->boundingRect());
if (!rect.isNull())
boundingRect &= _q_adjustedRect(rect);
// Update each view directly.
for (int i = 0; i < d->views.size(); ++i)
d->views.at(i)->d_func()->itemUpdated(item, boundingRect);
}
}
if (item->d_ptr->dirty) {
d->dirtyItems << item;
d->resetDirtyItemsLater();
}
// Update d->largestUntransformableItem by mapping this item's bounding
// rect back to the topmost untransformable item's untransformed
// coordinate system (which sort of equals the 1:1 coordinate system of an
// untransformed view).
if (item->d_ptr->itemIsUntransformable()) {
QGraphicsItem *parent = item;
while (parent && (parent->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorIgnoresTransformations))
parent = parent->parentItem();
d->largestUntransformableItem |= item->mapToItem(parent, item->boundingRect()).boundingRect();
}
// Only track the automatically growing scene rect if the scene has no
// defined scene rect.
if (!d->hasSceneRect) {
QRectF oldGrowingItemsBoundingRect = d->growingItemsBoundingRect;
d->growingItemsBoundingRect |= _q_adjustedRect(item->sceneBoundingRect());
if (d->growingItemsBoundingRect != oldGrowingItemsBoundingRect)
emit sceneRectChanged(d->growingItemsBoundingRect);
}
}
/*!
\since 4.4
Returns the scene's style, or the same as QApplication::style() if the
scene has not been explicitly assigned a style.
\sa setStyle()
*/
QStyle *QGraphicsScene::style() const
{
Q_D(const QGraphicsScene);
// ### This function, and the use of styles in general, is non-reentrant.
return d->style ? d->style : qApp->style();
}
/*!
\since 4.4
Sets or replaces the style of the scene to \a style, and reparents the
style to this scene. Any previously assigned style is deleted. The scene's
style defaults to QApplication::style(), and serves as the default for all
QGraphicsWidget items in the scene.
Changing the style, either directly by calling this function, or
indirectly by calling QApplication::setStyle(), will automatically update
the style for all widgets in the scene that do not have a style explicitly
assigned to them.
If \a style is 0, QGraphicsScene will revert to QApplication::style().
\sa style()
*/
void QGraphicsScene::setStyle(QStyle *style)
{
Q_D(QGraphicsScene);
// ### This function, and the use of styles in general, is non-reentrant.
if (style == d->style)
return;
// Delete the old style,
delete d->style;
if ((d->style = style))
d->style->setParent(this);
// Notify the scene.
QEvent event(QEvent::StyleChange);
QApplication::sendEvent(this, &event);
// Notify all widgets that don't have a style explicitly set.
foreach (QGraphicsItem *item, items()) {
if (item->isWidget()) {
QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
if (!widget->testAttribute(Qt::WA_SetStyle))
QApplication::sendEvent(widget, &event);
}
}
}
/*!
\property QGraphicsScene::font
\since 4.4
\brief the scene's default font
This property provides the scene's font. The scene font defaults to,
and resolves all its entries from, QApplication::font.
If the scene's font changes, either directly through setFont() or
indirectly when the application font changes, QGraphicsScene first
sends itself a \l{QEvent::FontChange}{FontChange} event, and it then
sends \l{QEvent::FontChange}{FontChange} events to all top-level
widget items in the scene. These items respond by resolving their own
fonts to the scene, and they then notify their children, who again
notify their children, and so on, until all widget items have updated
their fonts.
Changing the scene font, (directly or indirectly through
QApplication::setFont(),) automatically schedules a redraw the entire
scene.
\sa QWidget::font, QApplication::setFont(), palette, style()
*/
QFont QGraphicsScene::font() const
{
Q_D(const QGraphicsScene);
return d->font;
}
void QGraphicsScene::setFont(const QFont &font)
{
Q_D(QGraphicsScene);
QFont naturalFont = qApp->font();
naturalFont.resolve(0);
QFont resolvedFont = font.resolve(naturalFont);
d->setFont_helper(resolvedFont);
}
/*!
\property QGraphicsScene::palette
\since 4.4
\brief the scene's default palette
This property provides the scene's palette. The scene palette defaults to,
and resolves all its entries from, QApplication::palette.
If the scene's palette changes, either directly through setPalette() or
indirectly when the application palette changes, QGraphicsScene first
sends itself a \l{QEvent::PaletteChange}{PaletteChange} event, and it then
sends \l{QEvent::PaletteChange}{PaletteChange} events to all top-level
widget items in the scene. These items respond by resolving their own
palettes to the scene, and they then notify their children, who again
notify their children, and so on, until all widget items have updated
their palettes.
Changing the scene palette, (directly or indirectly through
QApplication::setPalette(),) automatically schedules a redraw the entire
scene.
\sa QWidget::palette, QApplication::setPalette(), font, style()
*/
QPalette QGraphicsScene::palette() const
{
Q_D(const QGraphicsScene);
return d->palette;
}
void QGraphicsScene::setPalette(const QPalette &palette)
{
Q_D(QGraphicsScene);
QPalette naturalPalette = qApp->palette();
naturalPalette.resolve(0);
QPalette resolvedPalette = palette.resolve(naturalPalette);
d->setPalette_helper(resolvedPalette);
}
/*!
\since 4.4
Returns the current active window, or 0 if there is no window is currently
active.
\sa QGraphicsScene::setActiveWindow()
*/
QGraphicsWidget *QGraphicsScene::activeWindow() const
{
Q_D(const QGraphicsScene);
return d->activeWindow;
}
/*!
\since 4.4
Activates \a widget, which must be a widget in this scene. You can also
pass 0 for \a widget, in which case QGraphicsScene will deactivate any
currently active window.
\sa activeWindow(), QGraphicsWidget::isActiveWindow()
*/
void QGraphicsScene::setActiveWindow(QGraphicsWidget *widget)
{
Q_D(QGraphicsScene);
if (widget && widget->scene() != this) {
qWarning("QGraphicsScene::setActiveWindow: widget %p must be part of this scene",
widget);
return;
}
// Activate the widget's window.
QGraphicsWidget *window = widget ? widget->window() : 0;
if (window == d->activeWindow)
return;
// Deactivate the last active window.
if (d->activeWindow) {
if (QGraphicsWidget *fw = d->activeWindow->focusWidget()) {
// Remove focus from the current focus item.
if (fw == focusItem())
setFocusItem(0, Qt::ActiveWindowFocusReason);
}
QEvent event(QEvent::WindowDeactivate);
QApplication::sendEvent(d->activeWindow, &event);
}
// Update activate state.
d->activeWindow = window;
QEvent event(QEvent::ActivationChange);
QApplication::sendEvent(this, &event);
// Activate
if (window) {
QEvent event(QEvent::WindowActivate);
QApplication::sendEvent(window, &event);
QList<QGraphicsItem *> siblingWindows;
QGraphicsItem *parent = window->parentItem();
// Raise ### inefficient for toplevels
foreach (QGraphicsItem *sibling, parent ? parent->children() : items()) {
if (sibling != window && sibling->isWidget()
&& static_cast<QGraphicsWidget *>(sibling)->isWindow()) {
siblingWindows << sibling;
}
}
// Find the highest z value.
qreal z = window->zValue();
for (int i = 0; i < siblingWindows.size(); ++i)
z = qMax(z, siblingWindows.at(i)->zValue());
// This will probably never overflow.
const qreal litt = qreal(0.001);
window->setZValue(z + litt);
if (QGraphicsWidget *focusChild = window->focusWidget())
focusChild->setFocus(Qt::ActiveWindowFocusReason);
}
}
QT_END_NAMESPACE
#include "moc_qgraphicsscene.cpp"
#endif // QT_NO_GRAPHICSVIEW
Fixes: Don't fill the pixmap because we will copy the cache into it.
RevBy: bnilsen
AutoTest: All pass + plasma ok
(cherry picked from commit 0985805ab3c7de5b15c115a98afb15944b6d93b9)
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
static const int QGRAPHICSSCENE_INDEXTIMER_TIMEOUT = 2000;
/*!
\class QGraphicsScene
\brief The QGraphicsScene class provides a surface for managing a large
number of 2D graphical items.
\since 4.2
\ingroup multimedia
\ingroup graphicsview-api
\mainclass
The class serves as a container for QGraphicsItems. It is used together
with QGraphicsView for visualizing graphical items, such as lines,
rectangles, text, or even custom items, on a 2D surface. QGraphicsScene is
part of \l{The Graphics View Framework}.
QGraphicsScene also provides functionality that lets you efficiently
determine both the location of items, and for determining what items are
visible within an arbitrary area on the scene. With the QGraphicsView
widget, you can either visualize the whole scene, or zoom in and view only
parts of the scene.
Example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 0
Note that QGraphicsScene has no visual appearance of its own; it only
manages the items. You need to create a QGraphicsView widget to visualize
the scene.
To add items to a scene, you start off by constructing a QGraphicsScene
object. Then, you have two options: either add your existing QGraphicsItem
objects by calling addItem(), or you can call one of the convenience
functions addEllipse(), addLine(), addPath(), addPixmap(), addPolygon(),
addRect(), or addText(), which all return a pointer to the newly added item.
The dimensions of the items added with these functions are relative to the
item's coordinate system, and the items position is initialized to (0,
0) in the scene.
You can then visualize the scene using QGraphicsView. When the scene
changes, (e.g., when an item moves or is transformed) QGraphicsScene
emits the changed() signal. To remove an item, call removeItem().
QGraphicsScene uses an indexing algorithm to manage the location of items
efficiently. By default, a BSP (Binary Space Partitioning) tree is used; an
algorithm suitable for large scenes where most items remain static (i.e.,
do not move around). You can choose to disable this index by calling
setItemIndexMethod(). For more information about the available indexing
algorithms, see the itemIndexMethod property.
The scene's bounding rect is set by calling setSceneRect(). Items can be
placed at any position on the scene, and the size of the scene is by
default unlimited. The scene rect is used only for internal bookkeeping,
maintaining the scene's item index. If the scene rect is unset,
QGraphicsScene will use the bounding area of all items, as returned by
itemsBoundingRect(), as the scene rect. However, itemsBoundingRect() is a
relatively time consuming function, as it operates by collecting
positional information for every item on the scene. Because of this, you
should always set the scene rect when operating on large scenes.
One of QGraphicsScene's greatest strengths is its ability to efficiently
determine the location of items. Even with millions of items on the scene,
the items() functions can determine the location of an item within few
milliseconds. There are several overloads to items(): one that finds items
at a certain position, one that finds items inside or intersecting with a
polygon or a rectangle, and more. The list of returned items is sorted by
stacking order, with the topmost item being the first item in the list.
For convenience, there is also an itemAt() function that returns the
topmost item at a given position.
QGraphicsScene maintains selection information for the scene. To select
items, call setSelectionArea(), and to clear the current selection, call
clearSelection(). Call selectedItems() to get the list of all selected
items.
\section1 Event Handling and Propagation
Another responsibility that QGraphicsScene has, is to propagate events
from QGraphicsView. To send an event to a scene, you construct an event
that inherits QEvent, and then send it using, for example,
QApplication::sendEvent(). event() is responsible for dispatching
the event to the individual items. Some common events are handled by
convenience event handlers. For example, key press events are handled by
keyPressEvent(), and mouse press events are handled by mousePressEvent().
Key events are delivered to the \e {focus item}. To set the focus item,
you can either call setFocusItem(), passing an item that accepts focus, or
the item itself can call QGraphicsItem::setFocus(). Call focusItem() to
get the current focus item. For compatibility with widgets, the scene also
maintains its own focus information. By default, the scene does not have
focus, and all key events are discarded. If setFocus() is called, or if an
item on the scene gains focus, the scene automatically gains focus. If the
scene has focus, hasFocus() will return true, and key events will be
forwarded to the focus item, if any. If the scene loses focus, (i.e.,
someone calls clearFocus(),) while an item has focus, the scene will
maintain its item focus information, and once the scene regains focus, it
will make sure the last focus item regains focus.
For mouse-over effects, QGraphicsScene dispatches \e {hover
events}. If an item accepts hover events (see
QGraphicsItem::acceptHoverEvents()), it will receive a \l
{QEvent::}{GraphicsSceneHoverEnter} event when the mouse enters
its area. As the mouse continues moving inside the item's area,
QGraphicsScene will send it \l {QEvent::}{GraphicsSceneHoverMove}
events. When the mouse leaves the item's area, the item will
receive a \l {QEvent::}{GraphicsSceneHoverLeave} event.
All mouse events are delivered to the current \e {mouse grabber}
item. An item becomes the scene's mouse grabber if it accepts
mouse events (see QGraphicsItem::acceptedMouseButtons()) and it
receives a mouse press. It stays the mouse grabber until it
receives a mouse release when no other mouse buttons are
pressed. You can call mouseGrabberItem() to determine what item is
currently grabbing the mouse.
\sa QGraphicsItem, QGraphicsView
*/
/*!
\enum QGraphicsScene::SceneLayer
\since 4.3
This enum describes the rendering layers in a QGraphicsScene. When
QGraphicsScene draws the scene contents, it renders each of these layers
separately, in order.
Each layer represents a flag that can be OR'ed together when calling
functions such as invalidate() or QGraphicsView::invalidateScene().
\value ItemLayer The item layer. QGraphicsScene renders all items are in
this layer by calling the virtual function drawItems(). The item layer is
drawn after the background layer, but before the foreground layer.
\value BackgroundLayer The background layer. QGraphicsScene renders the
scene's background in this layer by calling the virtual function
drawBackground(). The background layer is drawn first of all layers.
\value ForegroundLayer The foreground layer. QGraphicsScene renders the
scene's foreground in this layer by calling the virtual function
drawForeground(). The foreground layer is drawn last of all layers.
\value AllLayers All layers; this value represents a combination of all
three layers.
\sa invalidate(), QGraphicsView::invalidateScene()
*/
/*!
\enum QGraphicsScene::ItemIndexMethod
This enum describes the indexing algorithms QGraphicsScene provides for
managing positional information about items on the scene.
\value BspTreeIndex A Binary Space Partitioning tree is applied. All
QGraphicsScene's item location algorithms are of an order close to
logarithmic complexity, by making use of binary search. Adding, moving and
removing items is logarithmic. This approach is best for static scenes
(i.e., scenes where most items do not move).
\value NoIndex No index is applied. Item location is of linear complexity,
as all items on the scene are searched. Adding, moving and removing items,
however, is done in constant time. This approach is ideal for dynamic
scenes, where many items are added, moved or removed continuously.
\sa setItemIndexMethod(), bspTreeDepth
*/
#include "qgraphicsscene.h"
#ifndef QT_NO_GRAPHICSVIEW
#include "qgraphicsitem.h"
#include "qgraphicsitem_p.h"
#include "qgraphicslayout.h"
#include "qgraphicsscene_p.h"
#include "qgraphicssceneevent.h"
#include "qgraphicsview.h"
#include "qgraphicsview_p.h"
#include "qgraphicswidget.h"
#include "qgraphicswidget_p.h"
#include <QtCore/qdebug.h>
#include <QtCore/qlist.h>
#include <QtCore/qmath.h>
#include <QtCore/qrect.h>
#include <QtCore/qset.h>
#include <QtCore/qstack.h>
#include <QtCore/qtimer.h>
#include <QtCore/qvarlengtharray.h>
#include <QtGui/qapplication.h>
#include <QtGui/qdesktopwidget.h>
#include <QtGui/qevent.h>
#include <QtGui/qgraphicslayout.h>
#include <QtGui/qgraphicsproxywidget.h>
#include <QtGui/qgraphicswidget.h>
#include <QtGui/qmatrix.h>
#include <QtGui/qpaintengine.h>
#include <QtGui/qpainter.h>
#include <QtGui/qpixmapcache.h>
#include <QtGui/qpolygon.h>
#include <QtGui/qstyleoption.h>
#include <QtGui/qtooltip.h>
#include <QtGui/qtransform.h>
#include <private/qapplication_p.h>
#include <private/qobject_p.h>
#ifdef Q_WS_X11
#include <private/qt_x11_p.h>
#endif
QT_BEGIN_NAMESPACE
static inline bool QRectF_intersects(const QRectF &s, const QRectF &r)
{
qreal xp = s.left();
qreal yp = s.top();
qreal w = s.width();
qreal h = s.height();
qreal l1 = xp;
qreal r1 = xp;
if (w < 0)
l1 += w;
else
r1 += w;
qreal l2 = r.left();
qreal r2 = r.left();
if (w < 0)
l2 += r.width();
else
r2 += r.width();
if (l1 >= r2 || l2 >= r1)
return false;
qreal t1 = yp;
qreal b1 = yp;
if (h < 0)
t1 += h;
else
b1 += h;
qreal t2 = r.top();
qreal b2 = r.top();
if (r.height() < 0)
t2 += r.height();
else
b2 += r.height();
return !(t1 >= b2 || t2 >= b1);
}
// QRectF::intersects() returns false always if either the source or target
// rectangle's width or height are 0. This works around that problem.
static QRectF _q_adjustedRect(const QRectF &rect)
{
static const qreal p = (qreal)0.00001;
QRectF r = rect;
if (!r.width())
r.adjust(-p, 0, p, 0);
if (!r.height())
r.adjust(0, -p, 0, p);
return r;
}
static void _q_hoverFromMouseEvent(QGraphicsSceneHoverEvent *hover, const QGraphicsSceneMouseEvent *mouseEvent)
{
hover->setWidget(mouseEvent->widget());
hover->setPos(mouseEvent->pos());
hover->setScenePos(mouseEvent->scenePos());
hover->setScreenPos(mouseEvent->screenPos());
hover->setLastPos(mouseEvent->lastPos());
hover->setLastScenePos(mouseEvent->lastScenePos());
hover->setLastScreenPos(mouseEvent->lastScreenPos());
hover->setModifiers(mouseEvent->modifiers());
hover->setAccepted(mouseEvent->isAccepted());
}
/*!
\internal
*/
QGraphicsScenePrivate::QGraphicsScenePrivate()
: changedSignalMask(0),
indexMethod(QGraphicsScene::BspTreeIndex),
bspTreeDepth(0),
lastItemCount(0),
hasSceneRect(false),
updateAll(false),
calledEmitUpdated(false),
selectionChanging(0),
dirtyItemResetPending(false),
regenerateIndex(true),
purgePending(false),
indexTimerId(0),
restartIndexTimer(false),
stickyFocus(false),
hasFocus(false),
focusItem(0),
lastFocusItem(0),
tabFocusFirst(0),
activeWindow(0),
activationRefCount(0),
lastMouseGrabberItem(0),
lastMouseGrabberItemHasImplicitMouseGrab(false),
dragDropItem(0),
enterWidget(0),
lastDropAction(Qt::IgnoreAction),
painterStateProtection(true),
sortCacheEnabled(false),
updatingSortCache(false),
style(0)
{
}
/*!
\internal
*/
void QGraphicsScenePrivate::init()
{
Q_Q(QGraphicsScene);
// Keep this index so we can check for connected slots later on.
changedSignalMask = (1 << q->metaObject()->indexOfSignal("changed(QList<QRectF>)"));
qApp->d_func()->scene_list.append(q);
q->update();
}
/*!
\internal
*/
QList<QGraphicsItem *> QGraphicsScenePrivate::estimateItemsInRect(const QRectF &rect) const
{
const_cast<QGraphicsScenePrivate *>(this)->purgeRemovedItems();
const_cast<QGraphicsScenePrivate *>(this)->_q_updateSortCache();
if (indexMethod == QGraphicsScene::BspTreeIndex) {
// ### Only do this once in a while.
QGraphicsScenePrivate *that = const_cast<QGraphicsScenePrivate *>(this);
// Get items from BSP tree
QList<QGraphicsItem *> items = that->bspTree.items(rect);
// Fill in with any unindexed items
for (int i = 0; i < unindexedItems.size(); ++i) {
if (QGraphicsItem *item = unindexedItems.at(i)) {
if (!item->d_ptr->itemDiscovered && item->d_ptr->visible && !(item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)) {
QRectF boundingRect = item->sceneBoundingRect();
if (QRectF_intersects(boundingRect, rect)) {
item->d_ptr->itemDiscovered = 1;
items << item;
}
}
}
}
// Reset the discovered state of all discovered items
for (int i = 0; i < items.size(); ++i)
items.at(i)->d_func()->itemDiscovered = 0;
return items;
}
QList<QGraphicsItem *> itemsInRect;
for (int i = 0; i < unindexedItems.size(); ++i) {
if (QGraphicsItem *item = unindexedItems.at(i)) {
if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)
continue;
if (item->d_ptr->visible && item->effectiveOpacity() > qreal(0.0))
itemsInRect << item;
}
}
for (int i = 0; i < indexedItems.size(); ++i) {
if (QGraphicsItem *item = indexedItems.at(i)) {
if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)
continue;
if (item->d_ptr->visible && item->effectiveOpacity() > qreal(0.0))
itemsInRect << item;
}
}
return itemsInRect;
}
/*!
\internal
*/
void QGraphicsScenePrivate::addToIndex(QGraphicsItem *item)
{
if (indexMethod == QGraphicsScene::BspTreeIndex) {
if (item->d_func()->index != -1) {
bspTree.insertItem(item, item->sceneBoundingRect());
foreach (QGraphicsItem *child, item->children())
child->addToIndex();
} else {
// The BSP tree is regenerated if the number of items grows to a
// certain threshold, or if the bounding rect of the graph doubles in
// size.
startIndexTimer();
}
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::removeFromIndex(QGraphicsItem *item)
{
if (indexMethod == QGraphicsScene::BspTreeIndex) {
int index = item->d_func()->index;
if (index != -1) {
bspTree.removeItem(item, item->sceneBoundingRect());
freeItemIndexes << index;
indexedItems[index] = 0;
item->d_func()->index = -1;
unindexedItems << item;
foreach (QGraphicsItem *child, item->children())
child->removeFromIndex();
}
startIndexTimer();
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::resetIndex()
{
purgeRemovedItems();
if (indexMethod == QGraphicsScene::BspTreeIndex) {
for (int i = 0; i < indexedItems.size(); ++i) {
if (QGraphicsItem *item = indexedItems.at(i)) {
item->d_ptr->index = -1;
unindexedItems << item;
}
}
indexedItems.clear();
freeItemIndexes.clear();
regenerateIndex = true;
startIndexTimer();
}
}
static inline int intmaxlog(int n)
{
return (n > 0 ? qMax(qCeil(qLn(qreal(n)) / qLn(qreal(2))), 5) : 0);
}
/*!
\internal
*/
void QGraphicsScenePrivate::_q_updateIndex()
{
if (!indexTimerId)
return;
Q_Q(QGraphicsScene);
q->killTimer(indexTimerId);
indexTimerId = 0;
purgeRemovedItems();
// Add unindexedItems to indexedItems
QRectF unindexedItemsBoundingRect;
for (int i = 0; i < unindexedItems.size(); ++i) {
if (QGraphicsItem *item = unindexedItems.at(i)) {
unindexedItemsBoundingRect |= item->sceneBoundingRect();
if (!freeItemIndexes.isEmpty()) {
int freeIndex = freeItemIndexes.takeFirst();
item->d_func()->index = freeIndex;
indexedItems[freeIndex] = item;
} else {
item->d_func()->index = indexedItems.size();
indexedItems << item;
}
}
}
// Update growing scene rect.
QRectF oldGrowingItemsBoundingRect = growingItemsBoundingRect;
growingItemsBoundingRect |= unindexedItemsBoundingRect;
// Determine whether we should regenerate the BSP tree.
if (indexMethod == QGraphicsScene::BspTreeIndex) {
int depth = bspTreeDepth;
if (depth == 0) {
int oldDepth = intmaxlog(lastItemCount);
depth = intmaxlog(indexedItems.size());
static const int slack = 100;
if (bspTree.leafCount() == 0 || (oldDepth != depth && qAbs(lastItemCount - indexedItems.size()) > slack)) {
// ### Crude algorithm.
regenerateIndex = true;
}
}
// Regenerate the tree.
if (regenerateIndex) {
regenerateIndex = false;
bspTree.initialize(q->sceneRect(), depth);
unindexedItems = indexedItems;
lastItemCount = indexedItems.size();
q->update();
// Take this opportunity to reset our largest-item counter for
// untransformable items. When the items are inserted into the BSP
// tree, we'll get an accurate calculation.
largestUntransformableItem = QRectF();
}
}
// Insert all unindexed items into the tree.
for (int i = 0; i < unindexedItems.size(); ++i) {
if (QGraphicsItem *item = unindexedItems.at(i)) {
QRectF rect = item->sceneBoundingRect();
if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)
continue;
if (indexMethod == QGraphicsScene::BspTreeIndex)
bspTree.insertItem(item, rect);
// If the item ignores view transformations, update our
// largest-item-counter to ensure that the view can accurately
// discover untransformable items when drawing.
if (item->d_ptr->itemIsUntransformable()) {
QGraphicsItem *topmostUntransformable = item;
while (topmostUntransformable && (topmostUntransformable->d_ptr->ancestorFlags
& QGraphicsItemPrivate::AncestorIgnoresTransformations)) {
topmostUntransformable = topmostUntransformable->parentItem();
}
// ### Verify that this is the correct largest untransformable rectangle.
largestUntransformableItem |= item->mapToItem(topmostUntransformable, item->boundingRect()).boundingRect();
}
}
}
unindexedItems.clear();
// Notify scene rect changes.
if (!hasSceneRect && growingItemsBoundingRect != oldGrowingItemsBoundingRect)
emit q->sceneRectChanged(growingItemsBoundingRect);
}
/*!
\internal
*/
void QGraphicsScenePrivate::_q_emitUpdated()
{
Q_Q(QGraphicsScene);
calledEmitUpdated = false;
// Ensure all views are connected if anything is connected. This disables
// the optimization that items send updates directly to the views, but it
// needs to happen in order to keep compatibility with the behavior from
// Qt 4.4 and backward.
if (!views.isEmpty() && (connectedSignals & changedSignalMask)) {
for (int i = 0; i < views.size(); ++i) {
QGraphicsView *view = views.at(i);
if (!view->d_func()->connectedToScene) {
view->d_func()->connectedToScene = true;
q->connect(q, SIGNAL(changed(QList<QRectF>)),
views.at(i), SLOT(updateScene(QList<QRectF>)));
}
}
}
// Ensure all dirty items's current positions are recorded in the list of
// updated rects.
for (int i = 0; i < dirtyItems.size(); ++i)
updatedRects += dirtyItems.at(i)->sceneBoundingRect();
// Notify the changes to anybody interested.
QList<QRectF> oldUpdatedRects;
oldUpdatedRects = updateAll ? (QList<QRectF>() << q->sceneRect()) : updatedRects;
updateAll = false;
updatedRects.clear();
emit q->changed(oldUpdatedRects);
}
/*!
\internal
Updates all items in the pending update list. At this point, the list is
unlikely to contain partially constructed items.
*/
void QGraphicsScenePrivate::_q_updateLater()
{
foreach (QGraphicsItem *item, pendingUpdateItems)
item->update();
pendingUpdateItems.clear();
}
/*!
\internal
*/
void QGraphicsScenePrivate::_q_polishItems()
{
foreach (QGraphicsItem *item, unpolishedItems) {
if (!item->d_ptr->explicitlyHidden) {
item->itemChange(QGraphicsItem::ItemVisibleChange, true);
item->itemChange(QGraphicsItem::ItemVisibleHasChanged, true);
}
if (item->isWidget()) {
QEvent event(QEvent::Polish);
QApplication::sendEvent((QGraphicsWidget *)item, &event);
}
}
unpolishedItems.clear();
}
/*!
\internal
*/
void QGraphicsScenePrivate::_q_resetDirtyItems()
{
for (int i = 0; i < dirtyItems.size(); ++i) {
QGraphicsItem *item = dirtyItems.at(i);
item->d_ptr->dirty = 0;
item->d_ptr->dirtyChildren = 0;
}
dirtyItems.clear();
dirtyItemResetPending = false;
}
/*!
\internal
*/
void QGraphicsScenePrivate::resetDirtyItemsLater()
{
Q_Q(QGraphicsScene);
if (dirtyItemResetPending)
return;
// dirtyItems.reserve(indexedItems.size() + unindexedItems.size());
dirtyItemResetPending = true;
QMetaObject::invokeMethod(q, "_q_resetDirtyItems", Qt::QueuedConnection);
}
/*!
\internal
Schedules an item for removal. This function leaves some stale indexes
around in the BSP tree; these will be cleaned up the next time someone
triggers purgeRemovedItems().
Note: This function is called from QGraphicsItem's destructor. \a item is
being destroyed, so we cannot call any pure virtual functions on it (such
as boundingRect()). Also, it is unnecessary to update the item's own state
in any way.
### Refactoring: This function shares much functionality with removeItem()
*/
void QGraphicsScenePrivate::_q_removeItemLater(QGraphicsItem *item)
{
Q_Q(QGraphicsScene);
if (QGraphicsItem *parent = item->d_func()->parent) {
QVariant variant;
qVariantSetValue<QGraphicsItem *>(variant, item);
parent->itemChange(QGraphicsItem::ItemChildRemovedChange, variant);
parent->d_func()->children.removeAll(item);
}
// Clear focus on the item to remove any reference in the focusWidget
// chain.
item->clearFocus();
int index = item->d_func()->index;
if (index != -1) {
// Important: The index is useless until purgeRemovedItems() is
// called.
indexedItems[index] = (QGraphicsItem *)0;
if (!purgePending) {
purgePending = true;
q->update();
}
removedItems << item;
} else {
// Recently added items are purged immediately. unindexedItems() never
// contains stale items.
unindexedItems.removeAll(item);
q->update();
}
// Reset the mouse grabber and focus item data.
if (item == focusItem)
focusItem = 0;
if (item == lastFocusItem)
lastFocusItem = 0;
if (item == activeWindow) {
// ### deactivate...
activeWindow = 0;
}
// Disable selectionChanged() for individual items
++selectionChanging;
int oldSelectedItemsSize = selectedItems.size();
// Update selected & hovered item bookkeeping
selectedItems.remove(item);
hoverItems.removeAll(item);
pendingUpdateItems.removeAll(item);
cachedItemsUnderMouse.removeAll(item);
unpolishedItems.removeAll(item);
dirtyItems.removeAll(item);
//We remove all references of item from the sceneEventFilter arrays
QMultiMap<QGraphicsItem*, QGraphicsItem*>::iterator iterator = sceneEventFilters.begin();
while (iterator != sceneEventFilters.end()) {
if (iterator.value() == item || iterator.key() == item)
iterator = sceneEventFilters.erase(iterator);
else
++iterator;
}
// Remove from scene transform cache
int transformIndex = item->d_func()->sceneTransformIndex;
if (transformIndex != -1) {
validTransforms.setBit(transformIndex, 0);
freeSceneTransformSlots.append(transformIndex);
}
// Remove all children recursively.
foreach (QGraphicsItem *child, item->children())
_q_removeItemLater(child);
// Reset the mouse grabber
if (mouseGrabberItems.contains(item))
ungrabMouse(item, /* item is dying */ true);
// Reset the keyboard grabber
if (keyboardGrabberItems.contains(item))
ungrabKeyboard(item, /* item is dying */ true);
// Reset the last mouse grabber item
if (item == lastMouseGrabberItem)
lastMouseGrabberItem = 0;
// Reenable selectionChanged() for individual items
--selectionChanging;
if (!selectionChanging && selectedItems.size() != oldSelectedItemsSize)
emit q->selectionChanged();
}
/*!
\internal
Removes stale pointers from all data structures.
*/
void QGraphicsScenePrivate::purgeRemovedItems()
{
Q_Q(QGraphicsScene);
if (!purgePending && removedItems.isEmpty())
return;
// Remove stale items from the BSP tree.
if (indexMethod != QGraphicsScene::NoIndex)
bspTree.removeItems(removedItems);
// Purge this list.
removedItems.clear();
freeItemIndexes.clear();
for (int i = 0; i < indexedItems.size(); ++i) {
if (!indexedItems.at(i))
freeItemIndexes << i;
}
purgePending = false;
// No locality info for the items; update the whole scene.
q->update();
}
/*!
\internal
Starts or restarts the timer used for reindexing unindexed items.
*/
void QGraphicsScenePrivate::startIndexTimer()
{
Q_Q(QGraphicsScene);
if (indexTimerId) {
restartIndexTimer = true;
} else {
indexTimerId = q->startTimer(QGRAPHICSSCENE_INDEXTIMER_TIMEOUT);
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::addPopup(QGraphicsWidget *widget)
{
Q_ASSERT(widget);
Q_ASSERT(!popupWidgets.contains(widget));
popupWidgets << widget;
if (QGraphicsWidget *focusWidget = widget->focusWidget()) {
focusWidget->setFocus(Qt::PopupFocusReason);
} else {
grabKeyboard((QGraphicsItem *)widget);
if (focusItem && popupWidgets.size() == 1) {
QFocusEvent event(QEvent::FocusOut, Qt::PopupFocusReason);
sendEvent(focusItem, &event);
}
}
grabMouse((QGraphicsItem *)widget);
}
/*!
\internal
Remove \a widget from the popup list. Important notes:
\a widget is guaranteed to be in the list of popups, but it might not be
the last entry; you can hide any item in the pop list before the others,
and this must cause all later mouse grabbers to lose the grab.
*/
void QGraphicsScenePrivate::removePopup(QGraphicsWidget *widget, bool itemIsDying)
{
Q_ASSERT(widget);
int index = popupWidgets.indexOf(widget);
Q_ASSERT(index != -1);
for (int i = popupWidgets.size() - 1; i >= index; --i) {
QGraphicsWidget *widget = popupWidgets.takeLast();
ungrabMouse(widget, itemIsDying);
if (focusItem && popupWidgets.isEmpty()) {
QFocusEvent event(QEvent::FocusIn, Qt::PopupFocusReason);
sendEvent(focusItem, &event);
} else {
ungrabKeyboard((QGraphicsItem *)widget, itemIsDying);
}
if (!itemIsDying && widget->isVisible()) {
widget->hide();
widget->QGraphicsItem::d_ptr->explicitlyHidden = 0;
}
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::grabMouse(QGraphicsItem *item, bool implicit)
{
// Append to list of mouse grabber items, and send a mouse grab event.
if (mouseGrabberItems.contains(item)) {
if (mouseGrabberItems.last() == item)
qWarning("QGraphicsItem::grabMouse: already a mouse grabber");
else
qWarning("QGraphicsItem::grabMouse: already blocked by mouse grabber: %p",
mouseGrabberItems.last());
return;
}
// Send ungrab event to the last grabber.
if (!mouseGrabberItems.isEmpty()) {
QGraphicsItem *last = mouseGrabberItems.last();
if (lastMouseGrabberItemHasImplicitMouseGrab) {
// Implicit mouse grab is immediately lost.
last->ungrabMouse();
} else {
// Just send ungrab event to current grabber.
QEvent ungrabEvent(QEvent::UngrabMouse);
sendEvent(last, &ungrabEvent);
}
}
mouseGrabberItems << item;
lastMouseGrabberItemHasImplicitMouseGrab = implicit;
// Send grab event to current grabber.
QEvent grabEvent(QEvent::GrabMouse);
sendEvent(item, &grabEvent);
}
/*!
\internal
*/
void QGraphicsScenePrivate::ungrabMouse(QGraphicsItem *item, bool itemIsDying)
{
int index = mouseGrabberItems.indexOf(item);
if (index == -1) {
qWarning("QGraphicsItem::ungrabMouse: not a mouse grabber");
return;
}
if (item != mouseGrabberItems.last()) {
// Recursively ungrab the next mouse grabber until we reach this item
// to ensure state consistency.
ungrabMouse(mouseGrabberItems.at(index + 1), itemIsDying);
}
if (!popupWidgets.isEmpty() && item == popupWidgets.last()) {
// If the item is a popup, go via removePopup to ensure state
// consistency and that it gets hidden correctly - beware that
// removePopup() reenters this function to continue removing the grab.
removePopup((QGraphicsWidget *)item, itemIsDying);
return;
}
// Send notification about mouse ungrab.
if (!itemIsDying) {
QEvent event(QEvent::UngrabMouse);
sendEvent(item, &event);
}
// Remove the item from the list of grabbers. Whenever this happens, we
// reset the implicitGrab (there can be only ever be one implicit grabber
// in a scene, and it is always the latest grabber; if the implicit grab
// is lost, it is not automatically regained.
mouseGrabberItems.takeLast();
lastMouseGrabberItemHasImplicitMouseGrab = false;
// Send notification about mouse regrab. ### It's unfortunate that all the
// items get a GrabMouse event, but this is a rare case with a simple
// implementation and it does ensure a consistent state.
if (!itemIsDying && !mouseGrabberItems.isEmpty()) {
QGraphicsItem *last = mouseGrabberItems.last();
QEvent event(QEvent::GrabMouse);
sendEvent(last, &event);
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::clearMouseGrabber()
{
if (!mouseGrabberItems.isEmpty())
mouseGrabberItems.first()->ungrabMouse();
lastMouseGrabberItem = 0;
}
/*!
\internal
*/
void QGraphicsScenePrivate::grabKeyboard(QGraphicsItem *item)
{
if (keyboardGrabberItems.contains(item)) {
if (keyboardGrabberItems.last() == item)
qWarning("QGraphicsItem::grabKeyboard: already a keyboard grabber");
else
qWarning("QGraphicsItem::grabKeyboard: already blocked by keyboard grabber: %p",
keyboardGrabberItems.last());
return;
}
// Send ungrab event to the last grabber.
if (!keyboardGrabberItems.isEmpty()) {
// Just send ungrab event to current grabber.
QEvent ungrabEvent(QEvent::UngrabKeyboard);
sendEvent(keyboardGrabberItems.last(), &ungrabEvent);
}
keyboardGrabberItems << item;
// Send grab event to current grabber.
QEvent grabEvent(QEvent::GrabKeyboard);
sendEvent(item, &grabEvent);
}
/*!
\internal
*/
void QGraphicsScenePrivate::ungrabKeyboard(QGraphicsItem *item, bool itemIsDying)
{
int index = keyboardGrabberItems.lastIndexOf(item);
if (index == -1) {
qWarning("QGraphicsItem::ungrabKeyboard: not a keyboard grabber");
return;
}
if (item != keyboardGrabberItems.last()) {
// Recursively ungrab the topmost keyboard grabber until we reach this
// item to ensure state consistency.
ungrabKeyboard(keyboardGrabberItems.at(index + 1), itemIsDying);
}
// Send notification about keyboard ungrab.
if (!itemIsDying) {
QEvent event(QEvent::UngrabKeyboard);
sendEvent(item, &event);
}
// Remove the item from the list of grabbers.
keyboardGrabberItems.takeLast();
// Send notification about mouse regrab.
if (!itemIsDying && !keyboardGrabberItems.isEmpty()) {
QGraphicsItem *last = keyboardGrabberItems.last();
QEvent event(QEvent::GrabKeyboard);
sendEvent(last, &event);
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::clearKeyboardGrabber()
{
if (!keyboardGrabberItems.isEmpty())
ungrabKeyboard(keyboardGrabberItems.first());
}
/*!
Returns all items for the screen position in \a event.
*/
QList<QGraphicsItem *> QGraphicsScenePrivate::itemsAtPosition(const QPoint &screenPos,
const QPointF &scenePos,
QWidget *widget) const
{
Q_Q(const QGraphicsScene);
QGraphicsView *view = widget ? qobject_cast<QGraphicsView *>(widget->parentWidget()) : 0;
QList<QGraphicsItem *> items;
if (view)
items = view->items(view->viewport()->mapFromGlobal(screenPos));
else
items = q->items(scenePos);
return items;
}
/*!
\internal
Checks if item collides with the path and mode, but also checks that if it
doesn't collide, maybe its frame rect will.
*/
bool QGraphicsScenePrivate::itemCollidesWithPath(QGraphicsItem *item,
const QPainterPath &path,
Qt::ItemSelectionMode mode)
{
if (item->collidesWithPath(path, mode))
return true;
if (item->isWidget()) {
// Check if this is a window, and if its frame rect collides.
QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
if (widget->isWindow()) {
QRectF frameRect = widget->windowFrameRect();
QPainterPath framePath;
framePath.addRect(frameRect);
bool intersects = path.intersects(frameRect);
if (mode == Qt::IntersectsItemShape || mode == Qt::IntersectsItemBoundingRect)
return intersects || path.contains(frameRect.topLeft())
|| framePath.contains(path.elementAt(0));
return !intersects && path.contains(frameRect.topLeft());
}
}
return false;
}
/*!
\internal
*/
void QGraphicsScenePrivate::storeMouseButtonsForMouseGrabber(QGraphicsSceneMouseEvent *event)
{
for (int i = 0x1; i <= 0x10; i <<= 1) {
if (event->buttons() & i) {
mouseGrabberButtonDownPos.insert(Qt::MouseButton(i),
mouseGrabberItems.last()->d_ptr->genericMapFromScene(event->scenePos(),
event->widget()));
mouseGrabberButtonDownScenePos.insert(Qt::MouseButton(i), event->scenePos());
mouseGrabberButtonDownScreenPos.insert(Qt::MouseButton(i), event->screenPos());
}
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::installSceneEventFilter(QGraphicsItem *watched, QGraphicsItem *filter)
{
sceneEventFilters.insert(watched, filter);
}
/*!
\internal
*/
void QGraphicsScenePrivate::removeSceneEventFilter(QGraphicsItem *watched, QGraphicsItem *filter)
{
if (!sceneEventFilters.contains(watched))
return;
QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator it = sceneEventFilters.lowerBound(watched);
QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator end = sceneEventFilters.upperBound(watched);
do {
if (it.value() == filter)
it = sceneEventFilters.erase(it);
else
++it;
} while (it != end);
}
/*!
\internal
*/
bool QGraphicsScenePrivate::filterEvent(QGraphicsItem *item, QEvent *event)
{
if (item && !sceneEventFilters.contains(item))
return false;
QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator it = sceneEventFilters.lowerBound(item);
QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator end = sceneEventFilters.upperBound(item);
while (it != end) {
// ### The filterer and filteree might both be deleted.
if (it.value()->sceneEventFilter(it.key(), event))
return true;
++it;
}
return false;
}
/*!
\internal
This is the final dispatch point for any events from the scene to the
item. It filters the event first - if the filter returns true, the event
is considered to have been eaten by the filter, and is therefore stopped
(the default filter returns false). Then/otherwise, if the item is
enabled, the event is sent; otherwise it is stopped.
*/
bool QGraphicsScenePrivate::sendEvent(QGraphicsItem *item, QEvent *event)
{
if (filterEvent(item, event))
return false;
return (item && item->isEnabled()) ? item->sceneEvent(event) : false;
}
/*!
\internal
*/
void QGraphicsScenePrivate::cloneDragDropEvent(QGraphicsSceneDragDropEvent *dest,
QGraphicsSceneDragDropEvent *source)
{
dest->setWidget(source->widget());
dest->setPos(source->pos());
dest->setScenePos(source->scenePos());
dest->setScreenPos(source->screenPos());
dest->setButtons(source->buttons());
dest->setModifiers(source->modifiers());
dest->setPossibleActions(source->possibleActions());
dest->setProposedAction(source->proposedAction());
dest->setDropAction(source->dropAction());
dest->setSource(source->source());
dest->setMimeData(source->mimeData());
}
/*!
\internal
*/
void QGraphicsScenePrivate::sendDragDropEvent(QGraphicsItem *item,
QGraphicsSceneDragDropEvent *dragDropEvent)
{
dragDropEvent->setPos(item->d_ptr->genericMapFromScene(dragDropEvent->scenePos(), dragDropEvent->widget()));
sendEvent(item, dragDropEvent);
}
/*!
\internal
*/
void QGraphicsScenePrivate::sendHoverEvent(QEvent::Type type, QGraphicsItem *item,
QGraphicsSceneHoverEvent *hoverEvent)
{
QGraphicsSceneHoverEvent event(type);
event.setWidget(hoverEvent->widget());
event.setPos(item->d_ptr->genericMapFromScene(hoverEvent->scenePos(), hoverEvent->widget()));
event.setScenePos(hoverEvent->scenePos());
event.setScreenPos(hoverEvent->screenPos());
event.setLastPos(item->d_ptr->genericMapFromScene(hoverEvent->lastScenePos(), hoverEvent->widget()));
event.setLastScenePos(hoverEvent->lastScenePos());
event.setLastScreenPos(hoverEvent->lastScreenPos());
event.setModifiers(hoverEvent->modifiers());
sendEvent(item, &event);
}
/*!
\internal
*/
void QGraphicsScenePrivate::sendMouseEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
if (mouseEvent->button() == 0 && mouseEvent->buttons() == 0 && lastMouseGrabberItemHasImplicitMouseGrab) {
// ### This is a temporary fix for until we get proper mouse
// grab events.
clearMouseGrabber();
return;
}
QGraphicsItem *item = mouseGrabberItems.last();
for (int i = 0x1; i <= 0x10; i <<= 1) {
Qt::MouseButton button = Qt::MouseButton(i);
mouseEvent->setButtonDownPos(button, mouseGrabberButtonDownPos.value(button, item->d_ptr->genericMapFromScene(mouseEvent->scenePos(), mouseEvent->widget())));
mouseEvent->setButtonDownScenePos(button, mouseGrabberButtonDownScenePos.value(button, mouseEvent->scenePos()));
mouseEvent->setButtonDownScreenPos(button, mouseGrabberButtonDownScreenPos.value(button, mouseEvent->screenPos()));
}
mouseEvent->setPos(item->d_ptr->genericMapFromScene(mouseEvent->scenePos(), mouseEvent->widget()));
mouseEvent->setLastPos(item->d_ptr->genericMapFromScene(mouseEvent->lastScenePos(), mouseEvent->widget()));
sendEvent(item, mouseEvent);
}
/*!
\internal
*/
void QGraphicsScenePrivate::mousePressEventHandler(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_Q(QGraphicsScene);
// Ignore by default, unless we find a mouse grabber that accepts it.
mouseEvent->ignore();
// Deliver to any existing mouse grabber.
if (!mouseGrabberItems.isEmpty()) {
// The event is ignored by default, but we disregard the event's
// accepted state after delivery; the mouse is grabbed, after all.
sendMouseEvent(mouseEvent);
return;
}
// Start by determining the number of items at the current position.
// Reuse value from earlier calculations if possible.
if (cachedItemsUnderMouse.isEmpty()) {
cachedItemsUnderMouse = itemsAtPosition(mouseEvent->screenPos(),
mouseEvent->scenePos(),
mouseEvent->widget());
}
// Update window activation.
QGraphicsWidget *newActiveWindow = windowForItem(cachedItemsUnderMouse.value(0));
if (newActiveWindow != activeWindow)
q->setActiveWindow(newActiveWindow);
// Set focus on the topmost enabled item that can take focus.
bool setFocus = false;
foreach (QGraphicsItem *item, cachedItemsUnderMouse) {
if (item->isEnabled() && (item->flags() & QGraphicsItem::ItemIsFocusable)) {
if (!item->isWidget() || ((QGraphicsWidget *)item)->focusPolicy() & Qt::ClickFocus) {
setFocus = true;
if (item != q->focusItem())
q->setFocusItem(item, Qt::MouseFocusReason);
break;
}
}
}
// If nobody could take focus, clear it.
if (!stickyFocus && !setFocus)
q->setFocusItem(0, Qt::MouseFocusReason);
// Find a mouse grabber by sending mouse press events to all mouse grabber
// candidates one at a time, until the event is accepted. It's accepted by
// default, so the receiver has to explicitly ignore it for it to pass
// through.
foreach (QGraphicsItem *item, cachedItemsUnderMouse) {
if (!(item->acceptedMouseButtons() & mouseEvent->button())) {
// Skip items that don't accept the event's mouse button.
continue;
}
grabMouse(item, /* implicit = */ true);
mouseEvent->accept();
// check if the item we are sending to are disabled (before we send the event)
bool disabled = !item->isEnabled();
bool isWindow = item->isWindow();
if (mouseEvent->type() == QEvent::GraphicsSceneMouseDoubleClick && item != lastMouseGrabberItem) {
// If this item is different from the item that received the last
// mouse event, and mouseEvent is a doubleclick event, then the
// event is converted to a press. Known limitation:
// Triple-clicking will not generate a doubleclick, though.
QGraphicsSceneMouseEvent mousePress(QEvent::GraphicsSceneMousePress);
mousePress.accept();
mousePress.setButton(mouseEvent->button());
mousePress.setButtons(mouseEvent->buttons());
mousePress.setScreenPos(mouseEvent->screenPos());
mousePress.setScenePos(mouseEvent->scenePos());
mousePress.setModifiers(mouseEvent->modifiers());
mousePress.setWidget(mouseEvent->widget());
mousePress.setButtonDownPos(mouseEvent->button(),
mouseEvent->buttonDownPos(mouseEvent->button()));
mousePress.setButtonDownScenePos(mouseEvent->button(),
mouseEvent->buttonDownScenePos(mouseEvent->button()));
mousePress.setButtonDownScreenPos(mouseEvent->button(),
mouseEvent->buttonDownScreenPos(mouseEvent->button()));
sendMouseEvent(&mousePress);
mouseEvent->setAccepted(mousePress.isAccepted());
} else {
sendMouseEvent(mouseEvent);
}
bool dontSendUngrabEvents = mouseGrabberItems.isEmpty() || mouseGrabberItems.last() != item;
if (disabled) {
ungrabMouse(item, /* itemIsDying = */ dontSendUngrabEvents);
break;
}
if (mouseEvent->isAccepted()) {
if (!mouseGrabberItems.isEmpty())
storeMouseButtonsForMouseGrabber(mouseEvent);
lastMouseGrabberItem = item;
return;
}
ungrabMouse(item, /* itemIsDying = */ dontSendUngrabEvents);
// Don't propagate through windows.
if (isWindow)
break;
}
// Is the event still ignored? Then the mouse press goes to the scene.
// Reset the mouse grabber, clear the selection, clear focus, and leave
// the event ignored so that it can propagate through the originating
// view.
if (!mouseEvent->isAccepted()) {
clearMouseGrabber();
QGraphicsView *view = mouseEvent->widget() ? qobject_cast<QGraphicsView *>(mouseEvent->widget()->parentWidget()) : 0;
bool dontClearSelection = view && view->dragMode() == QGraphicsView::ScrollHandDrag;
if (!dontClearSelection) {
// Clear the selection if the originating view isn't in scroll
// hand drag mode. The view will clear the selection if no drag
// happened.
q->clearSelection();
}
}
}
QGraphicsWidget *QGraphicsScenePrivate::windowForItem(const QGraphicsItem *item) const
{
if (!item)
return 0;
do {
if (item->isWidget())
return static_cast<const QGraphicsWidget *>(item)->window();
item = item->parentItem();
} while (item);
return 0;
}
QList<QGraphicsItem *> QGraphicsScenePrivate::items_helper(const QRectF &rect,
Qt::ItemSelectionMode mode,
Qt::SortOrder order) const
{
QList<QGraphicsItem *> items;
QPainterPath path;
// The index returns a rough estimate of what items are inside the rect.
// Refine it by iterating through all returned items.
QRectF adjustedRect = _q_adjustedRect(rect);
foreach (QGraphicsItem *item, estimateItemsInRect(adjustedRect)) {
// Find the item's scene transform in a clever way.
QTransform x = item->sceneTransform();
bool keep = false;
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
QRectF br = _q_adjustedRect(item->boundingRect());
if (mode >= Qt::ContainsItemBoundingRect) {
// Rect intersects/contains item's bounding rect
QRectF mbr = x.mapRect(br);
if ((mode == Qt::IntersectsItemBoundingRect && QRectF_intersects(rect, mbr))
|| (mode == Qt::ContainsItemBoundingRect && rect != mbr && rect.contains(mbr))) {
items << item;
keep = true;
}
} else {
// Rect intersects/contains item's shape
if (QRectF_intersects(adjustedRect, x.mapRect(br))) {
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
if (path == QPainterPath())
path.addRect(rect);
if (itemCollidesWithPath(item, xinv.map(path), mode)) {
items << item;
keep = true;
}
}
}
}
if (keep && (item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) {
// Recurse into children that clip children.
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
if (x.type() <= QTransform::TxScale) {
// Rect
childItems_helper(&items, item, xinv.mapRect(rect), mode);
} else {
// Polygon
childItems_helper(&items, item, xinv.map(rect), mode);
}
}
}
}
if (order != Qt::SortOrder(-1))
sortItems(&items, order, sortCacheEnabled);
return items;
}
QList<QGraphicsItem *> QGraphicsScenePrivate::items_helper(const QPolygonF &polygon,
Qt::ItemSelectionMode mode,
Qt::SortOrder order) const
{
QList<QGraphicsItem *> items;
QRectF polyRect = _q_adjustedRect(polygon.boundingRect());
QPainterPath path;
// The index returns a rough estimate of what items are inside the rect.
// Refine it by iterating through all returned items.
foreach (QGraphicsItem *item, estimateItemsInRect(polyRect)) {
// Find the item's scene transform in a clever way.
QTransform x = item->sceneTransform();
bool keep = false;
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
QRectF br = _q_adjustedRect(item->boundingRect());
if (mode >= Qt::ContainsItemBoundingRect) {
// Polygon contains/intersects item's bounding rect
if (path == QPainterPath())
path.addPolygon(polygon);
if ((mode == Qt::IntersectsItemBoundingRect && path.intersects(x.mapRect(br)))
|| (mode == Qt::ContainsItemBoundingRect && path.contains(x.mapRect(br)))) {
items << item;
keep = true;
}
} else {
// Polygon contains/intersects item's shape
if (QRectF_intersects(polyRect, x.mapRect(br))) {
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
if (path == QPainterPath())
path.addPolygon(polygon);
if (itemCollidesWithPath(item, xinv.map(path), mode)) {
items << item;
keep = true;
}
}
}
}
if (keep && (item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) {
// Recurse into children that clip children.
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok)
childItems_helper(&items, item, xinv.map(polygon), mode);
}
}
if (order != Qt::SortOrder(-1))
sortItems(&items, order, sortCacheEnabled);
return items;
}
QList<QGraphicsItem *> QGraphicsScenePrivate::items_helper(const QPainterPath &path,
Qt::ItemSelectionMode mode,
Qt::SortOrder order) const
{
QList<QGraphicsItem *> items;
// The index returns a rough estimate of what items are inside the rect.
// Refine it by iterating through all returned items.
foreach (QGraphicsItem *item, estimateItemsInRect(_q_adjustedRect(path.controlPointRect()))) {
// Find the item's scene transform in a clever way.
QTransform x = item->sceneTransform();
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
QPainterPath mappedPath = xinv.map(path);
if (itemCollidesWithPath(item, mappedPath, mode)) {
items << item;
if (item->flags() & QGraphicsItem::ItemClipsChildrenToShape)
childItems_helper(&items, item, mappedPath, mode);
}
}
}
if (order != Qt::SortOrder(-1))
sortItems(&items, order, sortCacheEnabled);
return items;
}
void QGraphicsScenePrivate::childItems_helper(QList<QGraphicsItem *> *items,
const QGraphicsItem *parent,
const QRectF &rect,
Qt::ItemSelectionMode mode) const
{
QPainterPath path;
bool parentClip = (parent->flags() & QGraphicsItem::ItemClipsChildrenToShape);
QRectF r = !parentClip ? _q_adjustedRect(rect) : _q_adjustedRect(rect).intersected(_q_adjustedRect(parent->boundingRect()));
if (r.isEmpty())
return;
QList<QGraphicsItem *> &children = parent->d_ptr->children;
for (int i = 0; i < children.size(); ++i) {
QGraphicsItem *item = children.at(i);
if (item->d_ptr->hasTransform && !item->transform().isInvertible())
continue;
// Skip invisible items and all their children.
if (!item->d_ptr->visible || qFuzzyCompare(item->effectiveOpacity(), qreal(0.0)))
continue;
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
QRectF br = _q_adjustedRect(item->boundingRect());
QRectF mbr = item->mapRectToParent(br);
bool keep = false;
if (mode >= Qt::ContainsItemBoundingRect) {
// Rect intersects/contains item's bounding rect
if ((mode == Qt::IntersectsItemBoundingRect && QRectF_intersects(rect, mbr))
|| (mode == Qt::ContainsItemBoundingRect && rect != mbr && rect.contains(br))) {
items->append(item);
keep = true;
}
} else {
// Rect intersects/contains item's shape
if (QRectF_intersects(rect, mbr)) {
if (path == QPainterPath())
path.addRect(rect);
if (itemCollidesWithPath(item, item->mapFromParent(path), mode)) {
items->append(item);
keep = true;
}
}
}
if ((keep || !(item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) && !item->d_ptr->children.isEmpty()) {
// Recurse into children.
if (!item->d_ptr->hasTransform || item->transform().type() <= QTransform::TxScale) {
// Rect
childItems_helper(items, item, item->mapRectFromParent(rect), mode);
} else {
// Polygon
childItems_helper(items, item, item->mapFromParent(rect), mode);
}
}
}
}
void QGraphicsScenePrivate::childItems_helper(QList<QGraphicsItem *> *items,
const QGraphicsItem *parent,
const QPolygonF &polygon,
Qt::ItemSelectionMode mode) const
{
QPainterPath path;
bool parentClip = (parent->flags() & QGraphicsItem::ItemClipsChildrenToShape);
QRectF polyRect = _q_adjustedRect(polygon.boundingRect());
QRectF r = !parentClip ? polyRect : polyRect.intersected(_q_adjustedRect(parent->boundingRect()));
if (r.isEmpty())
return;
QList<QGraphicsItem *> &children = parent->d_ptr->children;
for (int i = 0; i < children.size(); ++i) {
QGraphicsItem *item = children.at(i);
if (item->d_ptr->hasTransform && !item->transform().isInvertible())
continue;
// Skip invisible items.
if (!item->d_ptr->visible || qFuzzyCompare(item->effectiveOpacity() + 1, qreal(1.0)))
continue;
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
QRectF br = _q_adjustedRect(item->boundingRect());
bool keep = false;
if (mode >= Qt::ContainsItemBoundingRect) {
// Polygon contains/intersects item's bounding rect
if (path == QPainterPath())
path.addPolygon(polygon);
if ((mode == Qt::IntersectsItemBoundingRect && path.intersects(item->mapRectToParent(br)))
|| (mode == Qt::ContainsItemBoundingRect && path.contains(item->mapRectToParent(br)))) {
items->append(item);
keep = true;
}
} else {
// Polygon contains/intersects item's shape
if (QRectF_intersects(polyRect, item->mapRectToParent(br))) {
if (path == QPainterPath())
path.addPolygon(polygon);
if (itemCollidesWithPath(item, item->mapFromParent(path), mode)) {
items->append(item);
keep = true;
}
}
}
if ((keep || !(item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) && !item->d_ptr->children.isEmpty()) {
// Recurse into children that clip children.
childItems_helper(items, item, item->mapFromParent(polygon), mode);
}
}
}
void QGraphicsScenePrivate::childItems_helper(QList<QGraphicsItem *> *items,
const QGraphicsItem *parent,
const QPainterPath &path,
Qt::ItemSelectionMode mode) const
{
bool parentClip = (parent->flags() & QGraphicsItem::ItemClipsChildrenToShape);
QPainterPath intersectedPath = !parentClip ? path : path.intersected(parent->shape());
if (intersectedPath.isEmpty())
return;
QList<QGraphicsItem *> &children = parent->d_ptr->children;
for (int i = 0; i < children.size(); ++i) {
QGraphicsItem *item = children.at(i);
// Skip invisible items.
if (!item->d_ptr->visible || qFuzzyCompare(item->effectiveOpacity(), qreal(0.0)))
continue;
QTransform x = item->sceneTransform();
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
QPainterPath mappedPath = xinv.map(path);
if (itemCollidesWithPath(item, mappedPath, mode)) {
items->append(item);
if (!item->d_ptr->children.isEmpty())
childItems_helper(items, item, mappedPath, mode);
}
}
}
}
void QGraphicsScenePrivate::invalidateSortCache()
{
Q_Q(QGraphicsScene);
if (!sortCacheEnabled || updatingSortCache)
return;
updatingSortCache = true;
QMetaObject::invokeMethod(q, "_q_updateSortCache", Qt::QueuedConnection);
}
/*!
\internal
Should not be exported, but we can't change that now.
### Qt 5: Remove symbol / make static
*/
inline bool qt_closestLeaf(const QGraphicsItem *item1, const QGraphicsItem *item2)
{
// Return true if sibling item1 is on top of item2.
const QGraphicsItemPrivate *d1 = item1->d_ptr;
const QGraphicsItemPrivate *d2 = item2->d_ptr;
bool f1 = d1->flags & QGraphicsItem::ItemStacksBehindParent;
bool f2 = d2->flags & QGraphicsItem::ItemStacksBehindParent;
if (f1 != f2) return f2;
qreal z1 = d1->z;
qreal z2 = d2->z;
return z1 != z2 ? z1 > z2 : item1 > item2;
}
/*!
\internal
Should not be exported, but we can't change that now.
*/
inline bool qt_closestItemFirst(const QGraphicsItem *item1, const QGraphicsItem *item2)
{
return QGraphicsScenePrivate::closestItemFirst_withoutCache(item1, item2);
}
/*!
Returns true if \a item1 is on top of \a item2.
\internal
*/
bool QGraphicsScenePrivate::closestItemFirst_withoutCache(const QGraphicsItem *item1, const QGraphicsItem *item2)
{
// Siblings? Just check their z-values.
const QGraphicsItemPrivate *d1 = item1->d_ptr;
const QGraphicsItemPrivate *d2 = item2->d_ptr;
if (d1->parent == d2->parent)
return qt_closestLeaf(item1, item2);
// Find common ancestor, and each item's ancestor closest to the common
// ancestor.
int item1Depth = d1->depth;
int item2Depth = d2->depth;
const QGraphicsItem *p = item1;
const QGraphicsItem *t1 = item1;
while (item1Depth > item2Depth && (p = p->d_ptr->parent)) {
if (p == item2) {
// item2 is one of item1's ancestors; item1 is on top
return !(t1->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent);
}
t1 = p;
--item1Depth;
}
p = item2;
const QGraphicsItem *t2 = item2;
while (item2Depth > item1Depth && (p = p->d_ptr->parent)) {
if (p == item1) {
// item1 is one of item2's ancestors; item1 is not on top
return (t2->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent);
}
t2 = p;
--item2Depth;
}
// item1Ancestor is now at the same level as item2Ancestor, but not the same.
const QGraphicsItem *a1 = t1;
const QGraphicsItem *a2 = t2;
while (a1) {
const QGraphicsItem *p1 = a1;
const QGraphicsItem *p2 = a2;
a1 = a1->parentItem();
a2 = a2->parentItem();
if (a1 && a1 == a2)
return qt_closestLeaf(p1, p2);
}
// No common ancestor? Then just compare the items' toplevels directly.
return qt_closestLeaf(t1->topLevelItem(), t2->topLevelItem());
}
/*!
Returns true if \a item2 is on top of \a item1.
\internal
*/
bool QGraphicsScenePrivate::closestItemLast_withoutCache(const QGraphicsItem *item1, const QGraphicsItem *item2)
{
return closestItemFirst_withoutCache(item2, item1);
}
void QGraphicsScenePrivate::climbTree(QGraphicsItem *item, int *stackingOrder)
{
if (!item->d_ptr->children.isEmpty()) {
QList<QGraphicsItem *> childList = item->d_ptr->children;
qSort(childList.begin(), childList.end(), qt_closestLeaf);
for (int i = 0; i < childList.size(); ++i) {
QGraphicsItem *item = childList.at(i);
if (!(item->flags() & QGraphicsItem::ItemStacksBehindParent))
climbTree(childList.at(i), stackingOrder);
}
item->d_ptr->globalStackingOrder = (*stackingOrder)++;
for (int i = 0; i < childList.size(); ++i) {
QGraphicsItem *item = childList.at(i);
if (item->flags() & QGraphicsItem::ItemStacksBehindParent)
climbTree(childList.at(i), stackingOrder);
}
} else {
item->d_ptr->globalStackingOrder = (*stackingOrder)++;
}
}
void QGraphicsScenePrivate::_q_updateSortCache()
{
_q_updateIndex();
if (!sortCacheEnabled || !updatingSortCache)
return;
updatingSortCache = false;
int stackingOrder = 0;
QList<QGraphicsItem *> topLevels;
for (int i = 0; i < indexedItems.size(); ++i) {
QGraphicsItem *item = indexedItems.at(i);
if (item && item->parentItem() == 0)
topLevels << item;
}
for (int i = 0; i < unindexedItems.size(); ++i) {
QGraphicsItem *item = unindexedItems.at(i);
if (item->parentItem() == 0)
topLevels << item;
}
qSort(topLevels.begin(), topLevels.end(), qt_closestLeaf);
for (int i = 0; i < topLevels.size(); ++i)
climbTree(topLevels.at(i), &stackingOrder);
}
void QGraphicsScenePrivate::sortItems(QList<QGraphicsItem *> *itemList, Qt::SortOrder order,
bool sortCacheEnabled)
{
if (sortCacheEnabled) {
if (order == Qt::AscendingOrder) {
qSort(itemList->begin(), itemList->end(), closestItemFirst_withCache);
} else if (order == Qt::DescendingOrder) {
qSort(itemList->begin(), itemList->end(), closestItemLast_withCache);
}
} else {
if (order == Qt::AscendingOrder) {
qSort(itemList->begin(), itemList->end(), closestItemFirst_withoutCache);
} else if (order == Qt::DescendingOrder) {
qSort(itemList->begin(), itemList->end(), closestItemLast_withoutCache);
}
}
}
/*!
\internal
Set the font and propagate the changes if the font is different from the
current font.
*/
void QGraphicsScenePrivate::setFont_helper(const QFont &font)
{
if (this->font == font && this->font.resolve() == font.resolve())
return;
updateFont(font);
}
/*!
\internal
Resolve the scene's font against the application font, and propagate the
changes too all items in the scene.
*/
void QGraphicsScenePrivate::resolveFont()
{
QFont naturalFont = qApp->font();
naturalFont.resolve(0);
QFont resolvedFont = font.resolve(naturalFont);
updateFont(resolvedFont);
}
/*!
\internal
Update the font, and whether or not it has changed, reresolve all fonts in
the scene.
*/
void QGraphicsScenePrivate::updateFont(const QFont &font)
{
Q_Q(QGraphicsScene);
// Update local font setting.
this->font = font;
// Resolve the fonts of all top-level widget items, or widget items
// whose parent is not a widget.
foreach (QGraphicsItem *item, q->items()) {
if (!item->parentItem()) {
// Resolvefont for an item is a noop operation, but
// every item can be a widget, or can have a widget
// childre.
item->d_ptr->resolveFont(font.resolve());
}
}
// Send the scene a FontChange event.
QEvent event(QEvent::FontChange);
QApplication::sendEvent(q, &event);
}
/*!
\internal
Set the palette and propagate the changes if the palette is different from
the current palette.
*/
void QGraphicsScenePrivate::setPalette_helper(const QPalette &palette)
{
if (this->palette == palette && this->palette.resolve() == palette.resolve())
return;
updatePalette(palette);
}
/*!
\internal
Resolve the scene's palette against the application palette, and propagate
the changes too all items in the scene.
*/
void QGraphicsScenePrivate::resolvePalette()
{
QPalette naturalPalette = qApp->palette();
naturalPalette.resolve(0);
QPalette resolvedPalette = palette.resolve(naturalPalette);
updatePalette(resolvedPalette);
}
/*!
\internal
Update the palette, and whether or not it has changed, reresolve all
palettes in the scene.
*/
void QGraphicsScenePrivate::updatePalette(const QPalette &palette)
{
Q_Q(QGraphicsScene);
// Update local palette setting.
this->palette = palette;
// Resolve the palettes of all top-level widget items, or widget items
// whose parent is not a widget.
foreach (QGraphicsItem *item, q->items()) {
if (!item->parentItem()) {
// Resolvefont for an item is a noop operation, but
// every item can be a widget, or can have a widget
// childre.
item->d_ptr->resolvePalette(palette.resolve());
}
}
// Send the scene a PaletteChange event.
QEvent event(QEvent::PaletteChange);
QApplication::sendEvent(q, &event);
}
/*!
Constructs a QGraphicsScene object. The \a parent parameter is
passed to QObject's constructor.
*/
QGraphicsScene::QGraphicsScene(QObject *parent)
: QObject(*new QGraphicsScenePrivate, parent)
{
d_func()->init();
}
/*!
Constructs a QGraphicsScene object, using \a sceneRect for its
scene rectangle. The \a parent parameter is passed to QObject's
constructor.
\sa sceneRect
*/
QGraphicsScene::QGraphicsScene(const QRectF &sceneRect, QObject *parent)
: QObject(*new QGraphicsScenePrivate, parent)
{
setSceneRect(sceneRect);
d_func()->init();
}
/*!
Constructs a QGraphicsScene object, using the rectangle specified
by (\a x, \a y), and the given \a width and \a height for its
scene rectangle. The \a parent parameter is passed to QObject's
constructor.
\sa sceneRect
*/
QGraphicsScene::QGraphicsScene(qreal x, qreal y, qreal width, qreal height, QObject *parent)
: QObject(*new QGraphicsScenePrivate, parent)
{
setSceneRect(x, y, width, height);
d_func()->init();
}
/*!
Destroys the QGraphicsScene object.
*/
QGraphicsScene::~QGraphicsScene()
{
Q_D(QGraphicsScene);
// Remove this scene from qApp's global scene list.
qApp->d_func()->scene_list.removeAll(this);
clear();
// Remove this scene from all associated views.
for (int j = 0; j < d->views.size(); ++j)
d->views.at(j)->setScene(0);
}
/*!
\property QGraphicsScene::sceneRect
\brief the scene rectangle; the bounding rectangle of the scene
The scene rectangle defines the extent of the scene. It is
primarily used by QGraphicsView to determine the view's default
scrollable area, and by QGraphicsScene to manage item indexing.
If unset, or if set to a null QRectF, sceneRect() will return the largest
bounding rect of all items on the scene since the scene was created (i.e.,
a rectangle that grows when items are added to or moved in the scene, but
never shrinks).
\sa width(), height(), QGraphicsView::sceneRect
*/
QRectF QGraphicsScene::sceneRect() const
{
Q_D(const QGraphicsScene);
const_cast<QGraphicsScenePrivate *>(d)->_q_updateIndex();
return d->hasSceneRect ? d->sceneRect : d->growingItemsBoundingRect;
}
void QGraphicsScene::setSceneRect(const QRectF &rect)
{
Q_D(QGraphicsScene);
if (rect != d->sceneRect) {
d->hasSceneRect = !rect.isNull();
d->sceneRect = rect;
d->resetIndex();
emit sceneRectChanged(rect);
}
}
/*!
\fn qreal QGraphicsScene::width() const
This convenience function is equivalent to calling sceneRect().width().
\sa height()
*/
/*!
\fn qreal QGraphicsScene::height() const
This convenience function is equivalent to calling \c sceneRect().height().
\sa width()
*/
/*!
Renders the \a source rect from scene into \a target, using \a painter. This
function is useful for capturing the contents of the scene onto a paint
device, such as a QImage (e.g., to take a screenshot), or for printing
with QPrinter. For example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 1
If \a source is a null rect, this function will use sceneRect() to
determine what to render. If \a target is a null rect, the dimensions of \a
painter's paint device will be used.
The source rect contents will be transformed according to \a
aspectRatioMode to fit into the target rect. By default, the aspect ratio
is kept, and \a source is scaled to fit in \a target.
\sa QGraphicsView::render()
*/
void QGraphicsScene::render(QPainter *painter, const QRectF &target, const QRectF &source,
Qt::AspectRatioMode aspectRatioMode)
{
Q_D(QGraphicsScene);
// Default source rect = scene rect
QRectF sourceRect = source;
if (sourceRect.isNull())
sourceRect = sceneRect();
// Default target rect = device rect
QRectF targetRect = target;
if (targetRect.isNull()) {
if (painter->device()->devType() == QInternal::Picture)
targetRect = sourceRect;
else
targetRect.setRect(0, 0, painter->device()->width(), painter->device()->height());
}
// Find the ideal x / y scaling ratio to fit \a source into \a target.
qreal xratio = targetRect.width() / sourceRect.width();
qreal yratio = targetRect.height() / sourceRect.height();
// Scale according to the aspect ratio mode.
switch (aspectRatioMode) {
case Qt::KeepAspectRatio:
xratio = yratio = qMin(xratio, yratio);
break;
case Qt::KeepAspectRatioByExpanding:
xratio = yratio = qMax(xratio, yratio);
break;
case Qt::IgnoreAspectRatio:
break;
}
// Find all items to draw, and reverse the list (we want to draw
// in reverse order).
QList<QGraphicsItem *> itemList = items(sourceRect, Qt::IntersectsItemBoundingRect);
QGraphicsItem **itemArray = new QGraphicsItem *[itemList.size()];
int numItems = itemList.size();
for (int i = 0; i < numItems; ++i)
itemArray[numItems - i - 1] = itemList.at(i);
itemList.clear();
painter->save();
// Transform the painter.
painter->setClipRect(targetRect);
QTransform painterTransform;
painterTransform *= QTransform()
.translate(targetRect.left(), targetRect.top())
.scale(xratio, yratio)
.translate(-sourceRect.left(), -sourceRect.top());
painter->setWorldTransform(painterTransform, true);
// Two unit vectors.
QLineF v1(0, 0, 1, 0);
QLineF v2(0, 0, 0, 1);
// Generate the style options
QStyleOptionGraphicsItem *styleOptionArray = new QStyleOptionGraphicsItem[numItems];
for (int i = 0; i < numItems; ++i) {
QGraphicsItem *item = itemArray[i];
QStyleOptionGraphicsItem option;
option.state = QStyle::State_None;
option.rect = item->boundingRect().toRect();
if (item->isSelected())
option.state |= QStyle::State_Selected;
if (item->isEnabled())
option.state |= QStyle::State_Enabled;
if (item->hasFocus())
option.state |= QStyle::State_HasFocus;
if (d->hoverItems.contains(item))
option.state |= QStyle::State_MouseOver;
if (item == mouseGrabberItem())
option.state |= QStyle::State_Sunken;
// Calculate a simple level-of-detail metric.
// ### almost identical code in QGraphicsView::paintEvent()
// and QGraphicsView::render() - consider refactoring
QTransform itemToDeviceTransform;
if (item->d_ptr->itemIsUntransformable()) {
itemToDeviceTransform = item->deviceTransform(painterTransform);
} else {
itemToDeviceTransform = item->sceneTransform() * painterTransform;
}
option.levelOfDetail = qSqrt(itemToDeviceTransform.map(v1).length() * itemToDeviceTransform.map(v2).length());
option.matrix = itemToDeviceTransform.toAffine(); //### discards perspective
option.exposedRect = item->boundingRect();
option.exposedRect &= itemToDeviceTransform.inverted().mapRect(targetRect);
styleOptionArray[i] = option;
}
// Render the scene.
drawBackground(painter, sourceRect);
drawItems(painter, numItems, itemArray, styleOptionArray);
drawForeground(painter, sourceRect);
delete [] itemArray;
delete [] styleOptionArray;
painter->restore();
}
/*!
\property QGraphicsScene::itemIndexMethod
\brief the item indexing method.
QGraphicsScene applies an indexing algorithm to the scene, to speed up
item discovery functions like items() and itemAt(). Indexing is most
efficient for static scenes (i.e., where items don't move around). For
dynamic scenes, or scenes with many animated items, the index bookkeeping
can outweight the fast lookup speeds.
For the common case, the default index method BspTreeIndex works fine. If
your scene uses many animations and you are experiencing slowness, you can
disable indexing by calling \c setItemIndexMethod(NoIndex).
\sa bspTreeDepth
*/
QGraphicsScene::ItemIndexMethod QGraphicsScene::itemIndexMethod() const
{
Q_D(const QGraphicsScene);
return d->indexMethod;
}
void QGraphicsScene::setItemIndexMethod(ItemIndexMethod method)
{
Q_D(QGraphicsScene);
d->resetIndex();
d->indexMethod = method;
}
/*!
\property QGraphicsScene::bspTreeDepth
\brief the depth of QGraphicsScene's BSP index tree
\since 4.3
This property has no effect when NoIndex is used.
This value determines the depth of QGraphicsScene's BSP tree. The depth
directly affects QGraphicsScene's performance and memory usage; the latter
growing exponentially with the depth of the tree. With an optimal tree
depth, QGraphicsScene can instantly determine the locality of items, even
for scenes with thousands or millions of items. This also greatly improves
rendering performance.
By default, the value is 0, in which case Qt will guess a reasonable
default depth based on the size, location and number of items in the
scene. If these parameters change frequently, however, you may experience
slowdowns as QGraphicsScene retunes the depth internally. You can avoid
potential slowdowns by fixating the tree depth through setting this
property.
The depth of the tree and the size of the scene rectangle decide the
granularity of the scene's partitioning. The size of each scene segment is
determined by the following algorithm:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 2
The BSP tree has an optimal size when each segment contains between 0 and
10 items.
\sa itemIndexMethod
*/
int QGraphicsScene::bspTreeDepth() const
{
Q_D(const QGraphicsScene);
return d->bspTreeDepth;
}
void QGraphicsScene::setBspTreeDepth(int depth)
{
Q_D(QGraphicsScene);
if (d->bspTreeDepth == depth)
return;
if (depth < 0) {
qWarning("QGraphicsScene::setBspTreeDepth: invalid depth %d ignored; must be >= 0", depth);
return;
}
d->bspTreeDepth = depth;
d->resetIndex();
}
/*!
\property QGraphicsScene::sortCacheEnabled
\brief whether sort caching is enabled
\since 4.5
When enabled, this property adds a cache that speeds up sorting and
transformations for scenes with deep hierarchies (i.e., items with many
levels of descendents), at the cost of using more memory (approx. 100 more
bytes of memory per item).
Items that are not part of a deep hierarchy suffer no penalty from this
cache.
*/
bool QGraphicsScene::isSortCacheEnabled() const
{
Q_D(const QGraphicsScene);
return d->sortCacheEnabled;
}
void QGraphicsScene::setSortCacheEnabled(bool enabled)
{
Q_D(QGraphicsScene);
if (enabled == d->sortCacheEnabled)
return;
if ((d->sortCacheEnabled = enabled))
d->invalidateSortCache();
}
/*!
Calculates and returns the bounding rect of all items on the scene. This
function works by iterating over all items, and because if this, it can
be slow for large scenes.
\sa sceneRect()
*/
QRectF QGraphicsScene::itemsBoundingRect() const
{
QRectF boundingRect;
foreach (QGraphicsItem *item, items())
boundingRect |= item->sceneBoundingRect();
return boundingRect;
}
/*!
Returns a list of all items on the scene, in no particular order.
\sa addItem(), removeItem()
*/
QList<QGraphicsItem *> QGraphicsScene::items() const
{
Q_D(const QGraphicsScene);
const_cast<QGraphicsScenePrivate *>(d)->purgeRemovedItems();
// If freeItemIndexes is empty, we know there are no holes in indexedItems and
// unindexedItems.
if (d->freeItemIndexes.isEmpty()) {
if (d->unindexedItems.isEmpty())
return d->indexedItems;
return d->indexedItems + d->unindexedItems;
}
// Rebuild the list of items to avoid holes. ### We could also just
// compress the item lists at this point.
QList<QGraphicsItem *> itemList;
foreach (QGraphicsItem *item, d->indexedItems + d->unindexedItems) {
if (item)
itemList << item;
}
return itemList;
}
/*!
Returns all visible items at position \a pos in the scene. The items are
listed in descending Z order (i.e., the first item in the list is the
top-most item, and the last item is the bottom-most item).
\sa itemAt()
*/
QList<QGraphicsItem *> QGraphicsScene::items(const QPointF &pos) const
{
QList<QGraphicsItem *> itemsAtPoint;
// Find all items within a 1x1 rect area starting at pos. This can be
// inefficient for scenes that use small coordinates (like unity
// coordinates), or for detailed graphs. ### The index should support
// fetching items at a pos to avoid this limitation.
foreach (QGraphicsItem *item, items(QRectF(pos, QSizeF(1, 1)), Qt::IntersectsItemBoundingRect)) {
if (item->contains(item->mapFromScene(pos)))
itemsAtPoint << item;
}
return itemsAtPoint;
}
/*!
\fn QList<QGraphicsItem *> QGraphicsScene::items(const QRectF &rectangle, Qt::ItemSelectionMode mode) const
\overload
Returns all visible items that, depending on \a mode, are either inside or
intersect with the specified \a rectangle.
The default value for \a mode is Qt::IntersectsItemShape; all items whose
exact shape intersects with or is contained by \a rectangle are returned.
\sa itemAt()
*/
QList<QGraphicsItem *> QGraphicsScene::items(const QRectF &rect, Qt::ItemSelectionMode mode) const
{
Q_D(const QGraphicsScene);
return d->items_helper(rect, mode, Qt::AscendingOrder);
}
/*!
\fn QList<QGraphicsItem *> QGraphicsScene::items(qreal x, qreal y, qreal w, qreal h, Qt::ItemSelectionMode mode) const
\since 4.3
This convenience function is equivalent to calling items(QRectF(\a x, \a y, \a w, \a h), \a mode).
*/
/*!
\overload
Returns all visible items that, depending on \a mode, are either inside or
intersect with the polygon \a polygon.
The default value for \a mode is Qt::IntersectsItemShape; all items whose
exact shape intersects with or is contained by \a polygon are returned.
\sa itemAt()
*/
QList<QGraphicsItem *> QGraphicsScene::items(const QPolygonF &polygon, Qt::ItemSelectionMode mode) const
{
Q_D(const QGraphicsScene);
return d->items_helper(polygon, mode, Qt::AscendingOrder);
}
/*!
\overload
Returns all visible items that, depending on \a path, are either inside or
intersect with the path \a path.
The default value for \a mode is Qt::IntersectsItemShape; all items whose
exact shape intersects with or is contained by \a path are returned.
\sa itemAt()
*/
QList<QGraphicsItem *> QGraphicsScene::items(const QPainterPath &path, Qt::ItemSelectionMode mode) const
{
Q_D(const QGraphicsScene);
return d->items_helper(path, mode, Qt::AscendingOrder);
}
/*!
Returns a list of all items that collide with \a item. Collisions are
determined by calling QGraphicsItem::collidesWithItem(); the collision
detection is determined by \a mode. By default, all items whose shape
intersects \a item or is contained inside \a item's shape are returned.
The items are returned in descending Z order (i.e., the first item in the
list is the top-most item, and the last item is the bottom-most item).
\sa items(), itemAt(), QGraphicsItem::collidesWithItem()
*/
QList<QGraphicsItem *> QGraphicsScene::collidingItems(const QGraphicsItem *item,
Qt::ItemSelectionMode mode) const
{
Q_D(const QGraphicsScene);
if (!item) {
qWarning("QGraphicsScene::collidingItems: cannot find collisions for null item");
return QList<QGraphicsItem *>();
}
QList<QGraphicsItem *> tmp;
foreach (QGraphicsItem *itemInVicinity, d->estimateItemsInRect(item->sceneBoundingRect())) {
if (item != itemInVicinity && item->collidesWithItem(itemInVicinity, mode))
tmp << itemInVicinity;
}
d->sortItems(&tmp, Qt::AscendingOrder, d->sortCacheEnabled);
return tmp;
}
/*!
\fn QGraphicsItem *QGraphicsScene::itemAt(const QPointF &position) const
Returns the topmost visible item at the specified \a position, or 0 if
there are no items at this position.
\note The topmost item is the one with the highest Z-value.
\sa items(), collidingItems(), QGraphicsItem::setZValue()
*/
QGraphicsItem *QGraphicsScene::itemAt(const QPointF &pos) const
{
QList<QGraphicsItem *> itemsAtPoint = items(pos);
return itemsAtPoint.isEmpty() ? 0 : itemsAtPoint.first();
}
/*!
\fn QGraphicsScene::itemAt(qreal x, qreal y) const
\overload
Returns the topmost item at the position specified by (\a x, \a
y), or 0 if there are no items at this position.
This convenience function is equivalent to calling \c
{itemAt(QPointF(x, y))}.
\note The topmost item is the one with the highest Z-value.
*/
/*!
Returns a list of all currently selected items. The items are
returned in no particular order.
\sa setSelectionArea()
*/
QList<QGraphicsItem *> QGraphicsScene::selectedItems() const
{
Q_D(const QGraphicsScene);
// Optimization: Lazily removes items that are not selected.
QGraphicsScene *that = const_cast<QGraphicsScene *>(this);
QSet<QGraphicsItem *> actuallySelectedSet;
foreach (QGraphicsItem *item, that->d_func()->selectedItems) {
if (item->isSelected())
actuallySelectedSet << item;
}
that->d_func()->selectedItems = actuallySelectedSet;
return d->selectedItems.values();
}
/*!
Returns the selection area that was previously set with
setSelectionArea(), or an empty QPainterPath if no selection area has been
set.
\sa setSelectionArea()
*/
QPainterPath QGraphicsScene::selectionArea() const
{
Q_D(const QGraphicsScene);
return d->selectionArea;
}
/*!
Sets the selection area to \a path. All items within this area are
immediately selected, and all items outside are unselected. You can get
the list of all selected items by calling selectedItems().
For an item to be selected, it must be marked as \e selectable
(QGraphicsItem::ItemIsSelectable).
\sa clearSelection(), selectionArea()
*/
void QGraphicsScene::setSelectionArea(const QPainterPath &path)
{
setSelectionArea(path, Qt::IntersectsItemShape);
}
/*!
\overload
\since 4.3
Sets the selection area to \a path using \a mode to determine if items are
included in the selection area.
\sa clearSelection(), selectionArea()
*/
void QGraphicsScene::setSelectionArea(const QPainterPath &path, Qt::ItemSelectionMode mode)
{
Q_D(QGraphicsScene);
// Note: with boolean path operations, we can improve performance here
// quite a lot by "growing" the old path instead of replacing it. That
// allows us to only check the intersect area for changes, instead of
// reevaluating the whole path over again.
d->selectionArea = path;
QSet<QGraphicsItem *> unselectItems = d->selectedItems;
// Disable emitting selectionChanged() for individual items.
++d->selectionChanging;
bool changed = false;
// Set all items in path to selected.
foreach (QGraphicsItem *item, items(path, mode)) {
if (item->flags() & QGraphicsItem::ItemIsSelectable) {
if (!item->isSelected())
changed = true;
unselectItems.remove(item);
item->setSelected(true);
}
}
// Unselect all items outside path.
foreach (QGraphicsItem *item, unselectItems) {
item->setSelected(false);
changed = true;
}
// Reenable emitting selectionChanged() for individual items.
--d->selectionChanging;
if (!d->selectionChanging && changed)
emit selectionChanged();
}
/*!
Clears the current selection.
\sa setSelectionArea(), selectedItems()
*/
void QGraphicsScene::clearSelection()
{
Q_D(QGraphicsScene);
// Disable emitting selectionChanged
++d->selectionChanging;
bool changed = !d->selectedItems.isEmpty();
foreach (QGraphicsItem *item, d->selectedItems)
item->setSelected(false);
d->selectedItems.clear();
// Reenable emitting selectionChanged() for individual items.
--d->selectionChanging;
if (!d->selectionChanging && changed)
emit selectionChanged();
}
/*!
\since 4.4
Removes and deletes all items from the scene, but otherwise leaves the
state of the scene unchanged.
\sa addItem()
*/
void QGraphicsScene::clear()
{
Q_D(QGraphicsScene);
// Recursive descent delete
for (int i = 0; i < d->indexedItems.size(); ++i) {
if (QGraphicsItem *item = d->indexedItems.at(i)) {
if (!item->parentItem())
delete item;
}
}
QList<QGraphicsItem *> unindexedParents;
for (int i = 0; i < d->unindexedItems.size(); ++i) {
QGraphicsItem *item = d->unindexedItems.at(i);
if (!item->parentItem())
unindexedParents << item;
}
d->unindexedItems.clear();
qDeleteAll(unindexedParents);
d->indexedItems.clear();
d->freeItemIndexes.clear();
d->lastItemCount = 0;
d->bspTree.clear();
d->largestUntransformableItem = QRectF();
}
/*!
Groups all items in \a items into a new QGraphicsItemGroup, and returns a
pointer to the group. The group is created with the common ancestor of \a
items as its parent, and with position (0, 0). The items are all
reparented to the group, and their positions and transformations are
mapped to the group. If \a items is empty, this function will return an
empty top-level QGraphicsItemGroup.
QGraphicsScene has ownership of the group item; you do not need to delete
it. To dismantle (ungroup) a group, call destroyItemGroup().
\sa destroyItemGroup(), QGraphicsItemGroup::addToGroup()
*/
QGraphicsItemGroup *QGraphicsScene::createItemGroup(const QList<QGraphicsItem *> &items)
{
// Build a list of the first item's ancestors
QList<QGraphicsItem *> ancestors;
int n = 0;
if (!items.isEmpty()) {
QGraphicsItem *parent = items.at(n++);
while ((parent = parent->parentItem()))
ancestors.append(parent);
}
// Find the common ancestor for all items
QGraphicsItem *commonAncestor = 0;
if (!ancestors.isEmpty()) {
while (n < items.size()) {
int commonIndex = -1;
QGraphicsItem *parent = items.at(n++);
do {
int index = ancestors.indexOf(parent, qMax(0, commonIndex));
if (index != -1) {
commonIndex = index;
break;
}
} while ((parent = parent->parentItem()));
if (commonIndex == -1) {
commonAncestor = 0;
break;
}
commonAncestor = ancestors.at(commonIndex);
}
}
// Create a new group at that level
QGraphicsItemGroup *group = new QGraphicsItemGroup(commonAncestor);
if (!commonAncestor)
addItem(group);
foreach (QGraphicsItem *item, items)
group->addToGroup(item);
return group;
}
/*!
Reparents all items in \a group to \a group's parent item, then removes \a
group from the scene, and finally deletes it. The items' positions and
transformations are mapped from the group to the group's parent.
\sa createItemGroup(), QGraphicsItemGroup::removeFromGroup()
*/
void QGraphicsScene::destroyItemGroup(QGraphicsItemGroup *group)
{
foreach (QGraphicsItem *item, group->children())
group->removeFromGroup(item);
removeItem(group);
delete group;
}
/*!
Adds or moves the item \a item and all its childen to the scene.
If the item is visible (i.e., QGraphicsItem::isVisible() returns
true), QGraphicsScene will emit changed() once control goes back
to the event loop.
If the item is already in a different scene, it will first be removed from
its old scene, and then added to this scene as a top-level.
QGraphicsScene will send ItemSceneChange notifications to \a item while
it is added to the scene. If item does not currently belong to a scene, only one
notification is sent. If it does belong to scene already (i.e., it is
moved to this scene), QGraphicsScene will send an addition notification as
the item is removed from its previous scene.
\sa removeItem(), addEllipse(), addLine(), addPath(), addPixmap(),
addRect(), addText(), addWidget()
*/
void QGraphicsScene::addItem(QGraphicsItem *item)
{
Q_D(QGraphicsScene);
if (!item) {
qWarning("QGraphicsScene::addItem: cannot add null item");
return;
}
if (item->scene() == this) {
qWarning("QGraphicsScene::addItem: item has already been added to this scene");
return;
}
// Remove this item from its existing scene
if (QGraphicsScene *oldScene = item->scene())
oldScene->removeItem(item);
// Notify the item that its scene is changing, and allow the item to
// react.
QGraphicsScene *targetScene = qVariantValue<QGraphicsScene *>(item->itemChange(QGraphicsItem::ItemSceneChange,
qVariantFromValue<QGraphicsScene *>(this)));
if (targetScene != this) {
if (targetScene && item->scene() != targetScene)
targetScene->addItem(item);
return;
}
// Prevent reusing a recently deleted pointer: purge all removed items
// from our lists.
d->purgeRemovedItems();
// Invalidate any sort caching; arrival of a new item means we need to
// resort.
d->invalidateSortCache();
// Detach this item from its parent if the parent's scene is different
// from this scene.
if (QGraphicsItem *itemParent = item->parentItem()) {
if (itemParent->scene() != this)
item->setParentItem(0);
}
// Add the item to this scene
item->d_func()->scene = targetScene;
// Indexing requires sceneBoundingRect(), but because \a item might
// not be completely constructed at this point, we need to store it in
// a temporary list and schedule an indexing for later.
d->unindexedItems << item;
item->d_func()->index = -1;
d->startIndexTimer();
// Update the scene's sort cache settings.
item->d_ptr->globalStackingOrder = -1;
d->invalidateSortCache();
// Add to list of items that require an update. We cannot assume that the
// item is fully constructed, so calling item->update() can lead to a pure
// virtual function call to boundingRect().
if (!d->updateAll) {
if (d->pendingUpdateItems.isEmpty())
QMetaObject::invokeMethod(this, "_q_updateLater", Qt::QueuedConnection);
d->pendingUpdateItems << item;
}
// Disable selectionChanged() for individual items
++d->selectionChanging;
int oldSelectedItemSize = d->selectedItems.size();
// Update selection lists
if (item->isSelected())
d->selectedItems << item;
if (item->isWidget() && item->isVisible() && static_cast<QGraphicsWidget *>(item)->windowType() == Qt::Popup)
d->addPopup(static_cast<QGraphicsWidget *>(item));
// Update creation order focus chain. Make sure to leave the widget's
// internal tab order intact.
if (item->isWidget()) {
QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
if (!d->tabFocusFirst) {
// No first tab focus widget - make this the first tab focus
// widget.
d->tabFocusFirst = widget;
} else if (!widget->parentWidget()) {
// Adding a widget that is not part of a tab focus chain.
QGraphicsWidget *last = d->tabFocusFirst->d_func()->focusPrev;
QGraphicsWidget *lastNew = widget->d_func()->focusPrev;
last->d_func()->focusNext = widget;
widget->d_func()->focusPrev = last;
d->tabFocusFirst->d_func()->focusPrev = lastNew;
lastNew->d_func()->focusNext = d->tabFocusFirst;
}
}
// Add all children recursively
foreach (QGraphicsItem *child, item->children())
addItem(child);
// Resolve font and palette.
item->d_ptr->resolveFont(d->font.resolve());
item->d_ptr->resolvePalette(d->palette.resolve());
if (!item->d_ptr->explicitlyHidden) {
if (d->unpolishedItems.isEmpty())
QMetaObject::invokeMethod(this, "_q_polishItems", Qt::QueuedConnection);
d->unpolishedItems << item;
}
// Reenable selectionChanged() for individual items
--d->selectionChanging;
if (!d->selectionChanging && d->selectedItems.size() != oldSelectedItemSize)
emit selectionChanged();
// Deliver post-change notification
item->itemChange(QGraphicsItem::ItemSceneHasChanged, qVariantFromValue<QGraphicsScene *>(this));
}
/*!
Creates and adds an ellipse item to the scene, and returns the item
pointer. The geometry of the ellipse is defined by \a rect, and its pen
and brush are initialized to \a pen and \a brush.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addLine(), addPath(), addPixmap(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsEllipseItem *QGraphicsScene::addEllipse(const QRectF &rect, const QPen &pen, const QBrush &brush)
{
QGraphicsEllipseItem *item = new QGraphicsEllipseItem(rect);
item->setPen(pen);
item->setBrush(brush);
addItem(item);
return item;
}
/*!
\fn QGraphicsEllipseItem *QGraphicsScene::addEllipse(qreal x, qreal y, qreal w, qreal h, const QPen &pen, const QBrush &brush)
\since 4.3
This convenience function is equivalent to calling addEllipse(QRectF(\a x,
\a y, \a w, \a h), \a pen, \a brush).
*/
/*!
Creates and adds a line item to the scene, and returns the item
pointer. The geometry of the line is defined by \a line, and its pen
is initialized to \a pen.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addPath(), addPixmap(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsLineItem *QGraphicsScene::addLine(const QLineF &line, const QPen &pen)
{
QGraphicsLineItem *item = new QGraphicsLineItem(line);
item->setPen(pen);
addItem(item);
return item;
}
/*!
\fn QGraphicsLineItem *QGraphicsScene::addLine(qreal x1, qreal y1, qreal x2, qreal y2, const QPen &pen)
\since 4.3
This convenience function is equivalent to calling addLine(QLineF(\a x1,
\a y1, \a x2, \a y2), \a pen).
*/
/*!
Creates and adds a path item to the scene, and returns the item
pointer. The geometry of the path is defined by \a path, and its pen and
brush are initialized to \a pen and \a brush.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPixmap(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsPathItem *QGraphicsScene::addPath(const QPainterPath &path, const QPen &pen, const QBrush &brush)
{
QGraphicsPathItem *item = new QGraphicsPathItem(path);
item->setPen(pen);
item->setBrush(brush);
addItem(item);
return item;
}
/*!
Creates and adds a pixmap item to the scene, and returns the item
pointer. The pixmap is defined by \a pixmap.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPath(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsPixmapItem *QGraphicsScene::addPixmap(const QPixmap &pixmap)
{
QGraphicsPixmapItem *item = new QGraphicsPixmapItem(pixmap);
addItem(item);
return item;
}
/*!
Creates and adds a polygon item to the scene, and returns the item
pointer. The polygon is defined by \a polygon, and its pen and
brush are initialized to \a pen and \a brush.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPath(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsPolygonItem *QGraphicsScene::addPolygon(const QPolygonF &polygon,
const QPen &pen, const QBrush &brush)
{
QGraphicsPolygonItem *item = new QGraphicsPolygonItem(polygon);
item->setPen(pen);
item->setBrush(brush);
addItem(item);
return item;
}
/*!
Creates and adds a rectangle item to the scene, and returns the item
pointer. The geometry of the rectangle is defined by \a rect, and its pen
and brush are initialized to \a pen and \a brush.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0). For example, if a QRect(50, 50, 100,
100) is added, its top-left corner will be at (50, 50) relative to the
origin in the items coordinate system.
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPixmap(), addPixmap(), addText(),
addItem(), addWidget()
*/
QGraphicsRectItem *QGraphicsScene::addRect(const QRectF &rect, const QPen &pen, const QBrush &brush)
{
QGraphicsRectItem *item = new QGraphicsRectItem(rect);
item->setPen(pen);
item->setBrush(brush);
addItem(item);
return item;
}
/*!
\fn QGraphicsRectItem *QGraphicsScene::addRect(qreal x, qreal y, qreal w, qreal h, const QPen &pen, const QBrush &brush)
\since 4.3
This convenience function is equivalent to calling addRect(QRectF(\a x,
\a y, \a w, \a h), \a pen, \a brush).
*/
/*!
Creates and adds a text item to the scene, and returns the item
pointer. The text string is initialized to \a text, and its font
is initialized to \a font.
The item's position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPixmap(), addPixmap(), addRect(),
addItem(), addWidget()
*/
QGraphicsTextItem *QGraphicsScene::addText(const QString &text, const QFont &font)
{
QGraphicsTextItem *item = new QGraphicsTextItem(text);
item->setFont(font);
addItem(item);
return item;
}
/*!
Creates and adds a QGraphicsSimpleTextItem to the scene, and returns the
item pointer. The text string is initialized to \a text, and its font is
initialized to \a font.
The item's position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPixmap(), addPixmap(), addRect(),
addItem(), addWidget()
*/
QGraphicsSimpleTextItem *QGraphicsScene::addSimpleText(const QString &text, const QFont &font)
{
QGraphicsSimpleTextItem *item = new QGraphicsSimpleTextItem(text);
item->setFont(font);
addItem(item);
return item;
}
/*!
Creates a new QGraphicsProxyWidget for \a widget, adds it to the scene,
and returns a pointer to the proxy. \a wFlags set the default window flags
for the embedding proxy widget.
The item's position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
Note that widgets with the Qt::WA_PaintOnScreen widget attribute
set and widgets that wrap an external application or controller
are not supported. Examples are QGLWidget and QAxWidget.
\sa addEllipse(), addLine(), addPixmap(), addPixmap(), addRect(),
addText(), addSimpleText(), addItem()
*/
QGraphicsProxyWidget *QGraphicsScene::addWidget(QWidget *widget, Qt::WindowFlags wFlags)
{
QGraphicsProxyWidget *proxy = new QGraphicsProxyWidget(0, wFlags);
proxy->setWidget(widget);
addItem(proxy);
return proxy;
}
/*!
Removes the item \a item and all its children from the scene. The
ownership of \a item is passed on to the caller (i.e.,
QGraphicsScene will no longer delete \a item when destroyed).
\sa addItem()
*/
void QGraphicsScene::removeItem(QGraphicsItem *item)
{
// ### Refactoring: This function shares much functionality with _q_removeItemLater()
Q_D(QGraphicsScene);
if (!item) {
qWarning("QGraphicsScene::removeItem: cannot remove 0-item");
return;
}
if (item->scene() != this) {
qWarning("QGraphicsScene::removeItem: item %p's scene (%p)"
" is different from this scene (%p)",
item, item->scene(), this);
return;
}
// Notify the item that it's scene is changing to 0, allowing the item to
// react.
QGraphicsScene *targetScene = qVariantValue<QGraphicsScene *>(item->itemChange(QGraphicsItem::ItemSceneChange,
qVariantFromValue<QGraphicsScene *>(0)));
if (targetScene != 0 && targetScene != this) {
targetScene->addItem(item);
return;
}
// If the item has focus, remove it (and any focusWidget reference).
item->clearFocus();
// Clear its background
item->update();
// Note: This will access item's sceneBoundingRect(), which (as this is
// C++) is why we cannot call removeItem() from QGraphicsItem's
// destructor.
d->removeFromIndex(item);
if (item == d->tabFocusFirst) {
QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
widget->d_func()->fixFocusChainBeforeReparenting(0, 0);
}
// Set the item's scene ptr to 0.
item->d_func()->scene = 0;
// Detach the item from its parent.
if (QGraphicsItem *parentItem = item->parentItem()) {
if (parentItem->scene()) {
Q_ASSERT_X(parentItem->scene() == this, "QGraphicsScene::removeItem",
"Parent item's scene is different from this item's scene");
item->setParentItem(0);
}
}
// Remove from our item lists.
int index = item->d_func()->index;
if (index != -1) {
d->freeItemIndexes << index;
d->indexedItems[index] = 0;
} else {
d->unindexedItems.removeAll(item);
}
// Remove from scene transform cache
int transformIndex = item->d_func()->sceneTransformIndex;
if (transformIndex != -1) {
d->validTransforms.setBit(transformIndex, 0);
d->freeSceneTransformSlots.append(transformIndex);
item->d_func()->sceneTransformIndex = -1;
}
if (item == d->focusItem)
d->focusItem = 0;
if (item == d->lastFocusItem)
d->lastFocusItem = 0;
if (item == d->activeWindow) {
// ### deactivate...
d->activeWindow = 0;
}
// Disable selectionChanged() for individual items
++d->selectionChanging;
int oldSelectedItemsSize = d->selectedItems.size();
// Update selected & hovered item bookkeeping
d->selectedItems.remove(item);
d->hoverItems.removeAll(item);
d->pendingUpdateItems.removeAll(item);
d->cachedItemsUnderMouse.removeAll(item);
d->unpolishedItems.removeAll(item);
d->dirtyItems.removeAll(item);
//We remove all references of item from the sceneEventFilter arrays
QMultiMap<QGraphicsItem*, QGraphicsItem*>::iterator iterator = d->sceneEventFilters.begin();
while (iterator != d->sceneEventFilters.end()) {
if (iterator.value() == item || iterator.key() == item)
iterator = d->sceneEventFilters.erase(iterator);
else
++iterator;
}
//Ensure dirty flag have the correct default value so the next time it will be added it will receive updates
item->d_func()->dirty = 0;
item->d_func()->dirtyChildren = 0;
// Remove all children recursively
foreach (QGraphicsItem *child, item->children())
removeItem(child);
// Reset the mouse grabber and focus item data.
if (d->mouseGrabberItems.contains(item))
d->ungrabMouse(item);
// Reset the keyboard grabber
if (d->keyboardGrabberItems.contains(item))
item->ungrabKeyboard();
// Reset the last mouse grabber item
if (item == d->lastMouseGrabberItem)
d->lastMouseGrabberItem = 0;
// Reenable selectionChanged() for individual items
--d->selectionChanging;
if (!d->selectionChanging && d->selectedItems.size() != oldSelectedItemsSize)
emit selectionChanged();
// Deliver post-change notification
item->itemChange(QGraphicsItem::ItemSceneHasChanged, qVariantFromValue<QGraphicsScene *>(0));
}
/*!
Returns the scene's current focus item, or 0 if no item currently has
focus.
The focus item receives keyboard input when the scene receives a
key event.
\sa setFocusItem(), QGraphicsItem::hasFocus()
*/
QGraphicsItem *QGraphicsScene::focusItem() const
{
Q_D(const QGraphicsScene);
return d->focusItem;
}
/*!
Sets the scene's focus item to \a item, with the focus reason \a
focusReason, after removing focus from any previous item that may have had
focus.
If \a item is 0, or if it either does not accept focus (i.e., it does not
have the QGraphicsItem::ItemIsFocusable flag enabled), or is not visible
or not enabled, this function only removes focus from any previous
focusitem.
If item is not 0, and the scene does not currently have focus (i.e.,
hasFocus() returns false), this function will call setFocus()
automatically.
\sa focusItem(), hasFocus(), setFocus()
*/
void QGraphicsScene::setFocusItem(QGraphicsItem *item, Qt::FocusReason focusReason)
{
Q_D(QGraphicsScene);
if (item == d->focusItem)
return;
if (item && (!(item->flags() & QGraphicsItem::ItemIsFocusable)
|| !item->isVisible() || !item->isEnabled())) {
item = 0;
}
if (item) {
setFocus(focusReason);
if (item == d->focusItem)
return;
}
if (d->focusItem) {
QFocusEvent event(QEvent::FocusOut, focusReason);
d->lastFocusItem = d->focusItem;
d->focusItem = 0;
d->sendEvent(d->lastFocusItem, &event);
}
if (item) {
if (item->isWidget()) {
// Update focus child chain.
static_cast<QGraphicsWidget *>(item)->d_func()->setFocusWidget();
}
d->focusItem = item;
QFocusEvent event(QEvent::FocusIn, focusReason);
d->sendEvent(item, &event);
}
}
/*!
Returns true if the scene has focus; otherwise returns false. If the scene
has focus, it will will forward key events from QKeyEvent to any item that
has focus.
\sa setFocus(), setFocusItem()
*/
bool QGraphicsScene::hasFocus() const
{
Q_D(const QGraphicsScene);
return d->hasFocus;
}
/*!
Sets focus on the scene by sending a QFocusEvent to the scene, passing \a
focusReason as the reason. If the scene regains focus after having
previously lost it while an item had focus, the last focus item will
receive focus with \a focusReason as the reason.
If the scene already has focus, this function does nothing.
\sa hasFocus(), clearFocus(), setFocusItem()
*/
void QGraphicsScene::setFocus(Qt::FocusReason focusReason)
{
Q_D(QGraphicsScene);
if (d->hasFocus)
return;
QFocusEvent event(QEvent::FocusIn, focusReason);
QCoreApplication::sendEvent(this, &event);
}
/*!
Clears focus from the scene. If any item has focus when this function is
called, it will lose focus, and regain focus again once the scene regains
focus.
A scene that does not have focus ignores key events.
\sa hasFocus(), setFocus(), setFocusItem()
*/
void QGraphicsScene::clearFocus()
{
Q_D(QGraphicsScene);
if (d->hasFocus) {
d->hasFocus = false;
setFocusItem(0, Qt::OtherFocusReason);
}
}
/*!
\property QGraphicsScene::stickyFocus
\brief whether or not clicking the scene will clear focus
If this property is false (the default), then clicking on the scene
background or on an item that does not accept focus, will clear
focus. Otherwise, focus will remain unchanged.
The focus change happens in response to a mouse press. You can reimplement
mousePressEvent() in a subclass of QGraphicsScene to toggle this property
based on where the user has clicked.
\sa clearFocus(), setFocusItem()
*/
void QGraphicsScene::setStickyFocus(bool enabled)
{
Q_D(QGraphicsScene);
d->stickyFocus = enabled;
}
bool QGraphicsScene::stickyFocus() const
{
Q_D(const QGraphicsScene);
return d->stickyFocus;
}
/*!
Returns the current mouse grabber item, or 0 if no item is currently
grabbing the mouse. The mouse grabber item is the item that receives all
mouse events sent to the scene.
An item becomes a mouse grabber when it receives and accepts a
mouse press event, and it stays the mouse grabber until either of
the following events occur:
\list
\o If the item receives a mouse release event when there are no other
buttons pressed, it loses the mouse grab.
\o If the item becomes invisible (i.e., someone calls \c {item->setVisible(false))},
or if it becomes disabled (i.e., someone calls \c {item->setEnabled(false))},
it loses the mouse grab.
\o If the item is removed from the scene, it loses the mouse grab.
\endlist
If the item loses its mouse grab, the scene will ignore all mouse events
until a new item grabs the mouse (i.e., until a new item receives a mouse
press event).
*/
QGraphicsItem *QGraphicsScene::mouseGrabberItem() const
{
Q_D(const QGraphicsScene);
return !d->mouseGrabberItems.isEmpty() ? d->mouseGrabberItems.last() : 0;
}
/*!
\property QGraphicsScene::backgroundBrush
\brief the background brush of the scene.
Set this property to changes the scene's background to a different color,
gradient or texture. The default background brush is Qt::NoBrush. The
background is drawn before (behind) the items.
Example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 3
QGraphicsScene::render() calls drawBackground() to draw the scene
background. For more detailed control over how the background is drawn,
you can reimplement drawBackground() in a subclass of QGraphicsScene.
*/
QBrush QGraphicsScene::backgroundBrush() const
{
Q_D(const QGraphicsScene);
return d->backgroundBrush;
}
void QGraphicsScene::setBackgroundBrush(const QBrush &brush)
{
Q_D(QGraphicsScene);
d->backgroundBrush = brush;
foreach (QGraphicsView *view, d->views) {
view->resetCachedContent();
view->viewport()->update();
}
update();
}
/*!
\property QGraphicsScene::foregroundBrush
\brief the foreground brush of the scene.
Change this property to set the scene's foreground to a different
color, gradient or texture.
The foreground is drawn after (on top of) the items. The default
foreground brush is Qt::NoBrush ( i.e. the foreground is not
drawn).
Example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 4
QGraphicsScene::render() calls drawForeground() to draw the scene
foreground. For more detailed control over how the foreground is
drawn, you can reimplement the drawForeground() function in a
QGraphicsScene subclass.
*/
QBrush QGraphicsScene::foregroundBrush() const
{
Q_D(const QGraphicsScene);
return d->foregroundBrush;
}
void QGraphicsScene::setForegroundBrush(const QBrush &brush)
{
Q_D(QGraphicsScene);
d->foregroundBrush = brush;
foreach (QGraphicsView *view, views())
view->viewport()->update();
update();
}
/*!
This method is used by input methods to query a set of properties of
the scene to be able to support complex input method operations as support
for surrounding text and reconversions.
The \a query parameter specifies which property is queried.
\sa QWidget::inputMethodQuery()
*/
QVariant QGraphicsScene::inputMethodQuery(Qt::InputMethodQuery query) const
{
Q_D(const QGraphicsScene);
if (!d->focusItem)
return QVariant();
const QTransform matrix = d->focusItem->sceneTransform();
QVariant value = d->focusItem->inputMethodQuery(query);
if (value.type() == QVariant::RectF)
value = matrix.mapRect(value.toRectF());
else if (value.type() == QVariant::PointF)
value = matrix.map(value.toPointF());
else if (value.type() == QVariant::Rect)
value = matrix.mapRect(value.toRect());
else if (value.type() == QVariant::Point)
value = matrix.map(value.toPoint());
return value;
}
/*!
\fn void QGraphicsScene::update(const QRectF &rect)
Schedules a redraw of the area \a rect on the scene.
\sa sceneRect(), changed()
*/
void QGraphicsScene::update(const QRectF &rect)
{
Q_D(QGraphicsScene);
if (d->updateAll || (rect.isEmpty() && !rect.isNull()))
return;
// Check if anyone's connected; if not, we can send updates directly to
// the views. Otherwise or if there are no views, use old behavior.
bool directUpdates = !(d->connectedSignals & d->changedSignalMask) && !d->views.isEmpty();
if (rect.isNull()) {
d->updateAll = true;
d->updatedRects.clear();
if (directUpdates) {
// Update all views.
for (int i = 0; i < d->views.size(); ++i)
d->views.at(i)->d_func()->updateAll();
}
} else {
if (directUpdates) {
// Update all views.
for (int i = 0; i < d->views.size(); ++i) {
QGraphicsView *view = d->views.at(i);
view->d_func()->updateRegion(QRegion(view->mapFromScene(rect).boundingRect()));
}
} else {
d->updatedRects << rect;
}
}
if (!directUpdates && !d->calledEmitUpdated) {
d->calledEmitUpdated = true;
QMetaObject::invokeMethod(this, "_q_emitUpdated", Qt::QueuedConnection);
}
}
/*!
\fn void QGraphicsScene::update(qreal x, qreal y, qreal w, qreal h)
\overload
\since 4.3
This function is equivalent to calling update(QRectF(\a x, \a y, \a w,
\a h));
*/
/*!
Invalidates and schedules a redraw of the \a layers in \a rect on the
scene. Any cached content in \a layers is unconditionally invalidated and
redrawn.
You can use this function overload to notify QGraphicsScene of changes to
the background or the foreground of the scene. This function is commonly
used for scenes with tile-based backgrounds to notify changes when
QGraphicsView has enabled
\l{QGraphicsView::CacheBackground}{CacheBackground}.
Example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 5
Note that QGraphicsView currently supports background caching only (see
QGraphicsView::CacheBackground). This function is equivalent to calling
update() if any layer but BackgroundLayer is passed.
\sa QGraphicsView::resetCachedContent()
*/
void QGraphicsScene::invalidate(const QRectF &rect, SceneLayers layers)
{
foreach (QGraphicsView *view, views())
view->invalidateScene(rect, layers);
update(rect);
}
/*!
\fn void QGraphicsScene::invalidate(qreal x, qreal y, qreal w, qreal h, SceneLayers layers)
\overload
\since 4.3
This convenience function is equivalent to calling invalidate(QRectF(\a x, \a
y, \a w, \a h), \a layers);
*/
/*!
Returns a list of all the views that display this scene.
\sa QGraphicsView::scene()
*/
QList <QGraphicsView *> QGraphicsScene::views() const
{
Q_D(const QGraphicsScene);
return d->views;
}
/*!
This slot \e advances the scene by one step, by calling
QGraphicsItem::advance() for all items on the scene. This is done in two
phases: in the first phase, all items are notified that the scene is about
to change, and in the second phase all items are notified that they can
move. In the first phase, QGraphicsItem::advance() is called passing a
value of 0 as an argument, and 1 is passed in the second phase.
\sa QGraphicsItem::advance(), QGraphicsItemAnimation, QTimeLine
*/
void QGraphicsScene::advance()
{
for (int i = 0; i < 2; ++i) {
foreach (QGraphicsItem *item, items())
item->advance(i);
}
}
/*!
Processes the event \a event, and dispatches it to the respective
event handlers.
In addition to calling the convenience event handlers, this
function is responsible for converting mouse move events to hover
events for when there is no mouse grabber item. Hover events are
delivered directly to items; there is no convenience function for
them.
Unlike QWidget, QGraphicsScene does not have the convenience functions
\l{QWidget::}{enterEvent()} and \l{QWidget::}{leaveEvent()}. Use this
function to obtain those events instead.
\sa contextMenuEvent(), keyPressEvent(), keyReleaseEvent(),
mousePressEvent(), mouseMoveEvent(), mouseReleaseEvent(),
mouseDoubleClickEvent(), focusInEvent(), focusOutEvent()
*/
bool QGraphicsScene::event(QEvent *event)
{
Q_D(QGraphicsScene);
switch (event->type()) {
case QEvent::GraphicsSceneMousePress:
case QEvent::GraphicsSceneMouseMove:
case QEvent::GraphicsSceneMouseRelease:
case QEvent::GraphicsSceneMouseDoubleClick:
case QEvent::GraphicsSceneHoverEnter:
case QEvent::GraphicsSceneHoverLeave:
case QEvent::GraphicsSceneHoverMove:
// Reset the under-mouse list to ensure that this event gets fresh
// item-under-mouse data. Be careful about this list; if people delete
// items from inside event handlers, this list can quickly end up
// having stale pointers in it. We need to clear it before dispatching
// events that use it.
d->cachedItemsUnderMouse.clear();
default:
break;
}
switch (event->type()) {
case QEvent::GraphicsSceneDragEnter:
dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
break;
case QEvent::GraphicsSceneDragMove:
dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
break;
case QEvent::GraphicsSceneDragLeave:
dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
break;
case QEvent::GraphicsSceneDrop:
dropEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
break;
case QEvent::GraphicsSceneContextMenu:
contextMenuEvent(static_cast<QGraphicsSceneContextMenuEvent *>(event));
break;
case QEvent::KeyPress:
if (!d->focusItem) {
QKeyEvent *k = static_cast<QKeyEvent *>(event);
if (k->key() == Qt::Key_Tab || k->key() == Qt::Key_Backtab) {
if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier?
bool res = false;
if (k->key() == Qt::Key_Backtab
|| (k->key() == Qt::Key_Tab && (k->modifiers() & Qt::ShiftModifier))) {
res = focusNextPrevChild(false);
} else if (k->key() == Qt::Key_Tab) {
res = focusNextPrevChild(true);
}
if (!res)
event->ignore();
return true;
}
}
}
keyPressEvent(static_cast<QKeyEvent *>(event));
break;
case QEvent::KeyRelease:
keyReleaseEvent(static_cast<QKeyEvent *>(event));
break;
case QEvent::ShortcutOverride: {
QGraphicsItem *parent = focusItem();
while (parent) {
d->sendEvent(parent, event);
if (event->isAccepted())
return true;
parent = parent->parentItem();
}
}
return false;
case QEvent::GraphicsSceneMouseMove:
mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
break;
case QEvent::GraphicsSceneMousePress:
mousePressEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
break;
case QEvent::GraphicsSceneMouseRelease:
mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
break;
case QEvent::GraphicsSceneMouseDoubleClick:
mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
break;
case QEvent::GraphicsSceneWheel:
wheelEvent(static_cast<QGraphicsSceneWheelEvent *>(event));
break;
case QEvent::FocusIn:
focusInEvent(static_cast<QFocusEvent *>(event));
break;
case QEvent::FocusOut:
focusOutEvent(static_cast<QFocusEvent *>(event));
break;
case QEvent::GraphicsSceneHoverEnter:
case QEvent::GraphicsSceneHoverLeave:
case QEvent::GraphicsSceneHoverMove:
d->dispatchHoverEvent(static_cast<QGraphicsSceneHoverEvent *>(event));
break;
case QEvent::Leave:
d->leaveScene();
break;
case QEvent::GraphicsSceneHelp:
helpEvent(static_cast<QGraphicsSceneHelpEvent *>(event));
break;
case QEvent::InputMethod:
inputMethodEvent(static_cast<QInputMethodEvent *>(event));
break;
case QEvent::WindowActivate: {
if (!d->activationRefCount++) {
// Notify all non-window widgets.
foreach (QGraphicsItem *item, items()) {
if (item->isWidget() && item->isVisible() && !item->isWindow() && !item->parentWidget()) {
QEvent event(QEvent::WindowActivate);
QApplication::sendEvent(static_cast<QGraphicsWidget *>(item), &event);
}
}
// Restore window activation.
QGraphicsItem *nextFocusItem = d->focusItem ? d->focusItem : d->lastFocusItem;
if (nextFocusItem && nextFocusItem->window())
setActiveWindow(static_cast<QGraphicsWidget *>(nextFocusItem));
else if (d->tabFocusFirst && d->tabFocusFirst->isWindow())
setActiveWindow(d->tabFocusFirst);
}
break;
}
case QEvent::WindowDeactivate: {
if (!--d->activationRefCount) {
// Remove window activation.
setActiveWindow(0);
// Notify all non-window widgets.
foreach (QGraphicsItem *item, items()) {
if (item->isWidget() && item->isVisible() && !item->isWindow() && !item->parentWidget()) {
QEvent event(QEvent::WindowDeactivate);
QApplication::sendEvent(static_cast<QGraphicsWidget *>(item), &event);
}
}
}
break;
}
case QEvent::ApplicationFontChange: {
// Resolve the existing scene font.
d->resolveFont();
break;
}
case QEvent::FontChange:
// Update the entire scene when the font changes.
update();
break;
case QEvent::ApplicationPaletteChange: {
// Resolve the existing scene palette.
d->resolvePalette();
break;
}
case QEvent::PaletteChange:
// Update the entire scene when the palette changes.
update();
break;
case QEvent::StyleChange:
// Reresolve all widgets' styles. Update all top-level widgets'
// geometries that do not have an explicit style set.
update();
break;
case QEvent::Timer:
if (d->indexTimerId && static_cast<QTimerEvent *>(event)->timerId() == d->indexTimerId) {
if (d->restartIndexTimer) {
d->restartIndexTimer = false;
} else {
// this call will kill the timer
d->_q_updateIndex();
}
}
// Fallthrough intended - support timers in subclasses.
default:
return QObject::event(event);
}
return true;
}
/*!
\reimp
QGraphicsScene filters QApplication's events to detect palette and font
changes.
*/
bool QGraphicsScene::eventFilter(QObject *watched, QEvent *event)
{
if (watched != qApp)
return false;
switch (event->type()) {
case QEvent::ApplicationPaletteChange:
qApp->postEvent(this, new QEvent(QEvent::ApplicationPaletteChange));
break;
case QEvent::ApplicationFontChange:
qApp->postEvent(this, new QEvent(QEvent::ApplicationFontChange));
break;
default:
break;
}
return false;
}
/*!
This event handler, for event \a contextMenuEvent, can be reimplemented in
a subclass to receive context menu events. The default implementation
forwards the event to the topmost item that accepts context menu events at
the position of the event. If no items accept context menu events at this
position, the event is ignored.
\sa QGraphicsItem::contextMenuEvent()
*/
void QGraphicsScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *contextMenuEvent)
{
Q_D(QGraphicsScene);
// Ignore by default.
contextMenuEvent->ignore();
// Send the event to all items at this position until one item accepts the
// event.
foreach (QGraphicsItem *item, d->itemsAtPosition(contextMenuEvent->screenPos(),
contextMenuEvent->scenePos(),
contextMenuEvent->widget())) {
contextMenuEvent->setPos(item->d_ptr->genericMapFromScene(contextMenuEvent->scenePos(),
contextMenuEvent->widget()));
contextMenuEvent->accept();
if (!d->sendEvent(item, contextMenuEvent))
break;
if (contextMenuEvent->isAccepted())
break;
}
}
/*!
This event handler, for event \a event, can be reimplemented in a subclass
to receive drag enter events for the scene.
The default implementation accepts the event and prepares the scene to
accept drag move events.
\sa QGraphicsItem::dragEnterEvent(), dragMoveEvent(), dragLeaveEvent(),
dropEvent()
*/
void QGraphicsScene::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
{
Q_D(QGraphicsScene);
d->dragDropItem = 0;
d->lastDropAction = Qt::IgnoreAction;
event->accept();
}
/*!
This event handler, for event \a event, can be reimplemented in a subclass
to receive drag move events for the scene.
\sa QGraphicsItem::dragMoveEvent(), dragEnterEvent(), dragLeaveEvent(),
dropEvent()
*/
void QGraphicsScene::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
{
Q_D(QGraphicsScene);
event->ignore();
if (!d->mouseGrabberItems.isEmpty()) {
// Mouse grabbers that start drag events lose the mouse grab.
d->clearMouseGrabber();
d->mouseGrabberButtonDownPos.clear();
d->mouseGrabberButtonDownScenePos.clear();
d->mouseGrabberButtonDownScreenPos.clear();
}
bool eventDelivered = false;
// Find the topmost enabled items under the cursor. They are all
// candidates for accepting drag & drop events.
foreach (QGraphicsItem *item, d->itemsAtPosition(event->screenPos(),
event->scenePos(),
event->widget())) {
if (!item->isEnabled() || !item->acceptDrops())
continue;
if (item != d->dragDropItem) {
// Enter the new drag drop item. If it accepts the event, we send
// the leave to the parent item.
QGraphicsSceneDragDropEvent dragEnter(QEvent::GraphicsSceneDragEnter);
d->cloneDragDropEvent(&dragEnter, event);
dragEnter.setDropAction(event->proposedAction());
d->sendDragDropEvent(item, &dragEnter);
event->setAccepted(dragEnter.isAccepted());
event->setDropAction(dragEnter.dropAction());
if (!event->isAccepted()) {
// Propagate to the item under
continue;
}
d->lastDropAction = event->dropAction();
if (d->dragDropItem) {
// Leave the last drag drop item. A perfect implementation
// would set the position of this event to the point where
// this event and the last event intersect with the item's
// shape, but that's not easy to do. :-)
QGraphicsSceneDragDropEvent dragLeave(QEvent::GraphicsSceneDragLeave);
d->cloneDragDropEvent(&dragLeave, event);
d->sendDragDropEvent(d->dragDropItem, &dragLeave);
}
// We've got a new drag & drop item
d->dragDropItem = item;
}
// Send the move event.
event->setDropAction(d->lastDropAction);
event->accept();
d->sendDragDropEvent(item, event);
if (event->isAccepted())
d->lastDropAction = event->dropAction();
eventDelivered = true;
break;
}
if (!eventDelivered) {
if (d->dragDropItem) {
// Leave the last drag drop item
QGraphicsSceneDragDropEvent dragLeave(QEvent::GraphicsSceneDragLeave);
d->cloneDragDropEvent(&dragLeave, event);
d->sendDragDropEvent(d->dragDropItem, &dragLeave);
d->dragDropItem = 0;
}
// Propagate
event->setDropAction(Qt::IgnoreAction);
}
}
/*!
This event handler, for event \a event, can be reimplemented in a subclass
to receive drag leave events for the scene.
\sa QGraphicsItem::dragLeaveEvent(), dragEnterEvent(), dragMoveEvent(),
dropEvent()
*/
void QGraphicsScene::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
{
Q_D(QGraphicsScene);
if (d->dragDropItem) {
// Leave the last drag drop item
d->sendDragDropEvent(d->dragDropItem, event);
d->dragDropItem = 0;
}
}
/*!
This event handler, for event \a event, can be reimplemented in a subclass
to receive drop events for the scene.
\sa QGraphicsItem::dropEvent(), dragEnterEvent(), dragMoveEvent(),
dragLeaveEvent()
*/
void QGraphicsScene::dropEvent(QGraphicsSceneDragDropEvent *event)
{
Q_UNUSED(event);
Q_D(QGraphicsScene);
if (d->dragDropItem) {
// Drop on the last drag drop item
d->sendDragDropEvent(d->dragDropItem, event);
d->dragDropItem = 0;
}
}
/*!
This event handler, for event \a focusEvent, can be reimplemented in a
subclass to receive focus in events.
The default implementation sets focus on the scene, and then on the last
focus item.
\sa QGraphicsItem::focusOutEvent()
*/
void QGraphicsScene::focusInEvent(QFocusEvent *focusEvent)
{
Q_D(QGraphicsScene);
d->hasFocus = true;
switch (focusEvent->reason()) {
case Qt::TabFocusReason:
if (!focusNextPrevChild(true))
focusEvent->ignore();
break;
case Qt::BacktabFocusReason:
if (!focusNextPrevChild(false))
focusEvent->ignore();
break;
default:
if (d->lastFocusItem) {
// Set focus on the last focus item
setFocusItem(d->lastFocusItem, focusEvent->reason());
}
break;
}
}
/*!
This event handler, for event \a focusEvent, can be reimplemented in a
subclass to receive focus out events.
The default implementation removes focus from any focus item, then removes
focus from the scene.
\sa QGraphicsItem::focusInEvent()
*/
void QGraphicsScene::focusOutEvent(QFocusEvent *focusEvent)
{
Q_D(QGraphicsScene);
d->hasFocus = false;
setFocusItem(0, focusEvent->reason());
// Remove all popups when the scene loses focus.
if (!d->popupWidgets.isEmpty())
d->removePopup(d->popupWidgets.first());
}
/*!
This event handler, for event \a helpEvent, can be
reimplemented in a subclass to receive help events. The events
are of type QEvent::ToolTip, which are created when a tooltip is
requested.
The default implementation shows the tooltip of the topmost
item, i.e., the item with the highest z-value, at the mouse
cursor position. If no item has a tooltip set, this function
does nothing.
\sa QGraphicsItem::toolTip(), QGraphicsSceneHelpEvent
*/
void QGraphicsScene::helpEvent(QGraphicsSceneHelpEvent *helpEvent)
{
#ifdef QT_NO_TOOLTIP
Q_UNUSED(helpEvent);
#else
// Find the first item that does tooltips
Q_D(QGraphicsScene);
QList<QGraphicsItem *> itemsAtPos = d->itemsAtPosition(helpEvent->screenPos(),
helpEvent->scenePos(),
helpEvent->widget());
QGraphicsItem *toolTipItem = 0;
for (int i = 0; i < itemsAtPos.size(); ++i) {
QGraphicsItem *tmp = itemsAtPos.at(i);
if (!tmp->toolTip().isEmpty()) {
toolTipItem = tmp;
break;
}
}
// Show or hide the tooltip
QString text;
QPoint point;
if (toolTipItem && !toolTipItem->toolTip().isEmpty()) {
text = toolTipItem->toolTip();
point = helpEvent->screenPos();
}
QToolTip::showText(point, text);
helpEvent->setAccepted(!text.isEmpty());
#endif
}
bool QGraphicsScenePrivate::itemAcceptsHoverEvents_helper(const QGraphicsItem *item) const
{
return item->acceptHoverEvents()
|| (item->isWidget() && static_cast<const QGraphicsWidget *>(item)->d_func()->hasDecoration());
}
/*!
This event handler, for event \a hoverEvent, can be reimplemented in a
subclass to receive hover enter events. The default implementation
forwards the event to the topmost item that accepts hover events at the
scene position from the event.
\sa QGraphicsItem::hoverEvent(), QGraphicsItem::setAcceptHoverEvents()
*/
bool QGraphicsScenePrivate::dispatchHoverEvent(QGraphicsSceneHoverEvent *hoverEvent)
{
// Find the first item that accepts hover events, reusing earlier
// calculated data is possible.
if (cachedItemsUnderMouse.isEmpty()) {
cachedItemsUnderMouse = itemsAtPosition(hoverEvent->screenPos(),
hoverEvent->scenePos(),
hoverEvent->widget());
}
QGraphicsItem *item = 0;
for (int i = 0; i < cachedItemsUnderMouse.size(); ++i) {
QGraphicsItem *tmp = cachedItemsUnderMouse.at(i);
if (itemAcceptsHoverEvents_helper(tmp)) {
item = tmp;
break;
}
}
// Find the common ancestor item for the new topmost hoverItem and the
// last item in the hoverItem list.
QGraphicsItem *commonAncestorItem = (item && !hoverItems.isEmpty()) ? item->commonAncestorItem(hoverItems.last()) : 0;
while (commonAncestorItem && !itemAcceptsHoverEvents_helper(commonAncestorItem))
commonAncestorItem = commonAncestorItem->parentItem();
if (commonAncestorItem && commonAncestorItem->window() != item->window()) {
// The common ancestor isn't in the same window as the two hovered
// items.
commonAncestorItem = 0;
}
// Check if the common ancestor item is known.
int index = commonAncestorItem ? hoverItems.indexOf(commonAncestorItem) : -1;
// Send hover leaves to any existing hovered children of the common
// ancestor item.
for (int i = hoverItems.size() - 1; i > index; --i) {
QGraphicsItem *lastItem = hoverItems.takeLast();
if (itemAcceptsHoverEvents_helper(lastItem))
sendHoverEvent(QEvent::GraphicsSceneHoverLeave, lastItem, hoverEvent);
}
// Item is a child of a known item. Generate enter events for the
// missing links.
QList<QGraphicsItem *> parents;
QGraphicsItem *parent = item;
while (parent && parent != commonAncestorItem) {
parents.prepend(parent);
if (parent->isWindow()) {
// Stop at the window - we don't deliver beyond this point.
break;
}
parent = parent->parentItem();
}
for (int i = 0; i < parents.size(); ++i) {
parent = parents.at(i);
hoverItems << parent;
if (itemAcceptsHoverEvents_helper(parent))
sendHoverEvent(QEvent::GraphicsSceneHoverEnter, parent, hoverEvent);
}
// Generate a move event for the item itself
if (item && !hoverItems.isEmpty() && item == hoverItems.last()) {
sendHoverEvent(QEvent::GraphicsSceneHoverMove, item, hoverEvent);
return true;
}
return false;
}
/*!
\internal
Handles all actions necessary to clean up the scene when the mouse leaves
the view.
*/
void QGraphicsScenePrivate::leaveScene()
{
Q_Q(QGraphicsScene);
#ifndef QT_NO_TOOLTIP
// Remove any tooltips
QToolTip::showText(QPoint(), QString());
#endif
// Send HoverLeave events to all existing hover items, topmost first.
QGraphicsView *senderWidget = qobject_cast<QGraphicsView *>(q->sender());
QGraphicsSceneHoverEvent hoverEvent;
hoverEvent.setWidget(senderWidget);
if (senderWidget) {
QPoint cursorPos = QCursor::pos();
hoverEvent.setScenePos(senderWidget->mapToScene(senderWidget->mapFromGlobal(cursorPos)));
hoverEvent.setLastScenePos(hoverEvent.scenePos());
hoverEvent.setScreenPos(cursorPos);
hoverEvent.setLastScreenPos(hoverEvent.screenPos());
}
while (!hoverItems.isEmpty()) {
QGraphicsItem *lastItem = hoverItems.takeLast();
if (lastItem->acceptHoverEvents()
|| (lastItem->isWidget() && static_cast<QGraphicsWidget*>(lastItem)->d_func()->hasDecoration()))
sendHoverEvent(QEvent::GraphicsSceneHoverLeave, lastItem, &hoverEvent);
}
}
/*!
This event handler, for event \a keyEvent, can be reimplemented in a
subclass to receive keypress events. The default implementation forwards
the event to current focus item.
\sa QGraphicsItem::keyPressEvent(), focusItem()
*/
void QGraphicsScene::keyPressEvent(QKeyEvent *keyEvent)
{
// ### Merge this function with keyReleaseEvent; they are identical
// ### (except this comment).
Q_D(QGraphicsScene);
QGraphicsItem *item = !d->keyboardGrabberItems.isEmpty() ? d->keyboardGrabberItems.last() : 0;
if (!item)
item = focusItem();
if (item) {
QGraphicsItem *p = item;
do {
// Accept the event by default
keyEvent->accept();
// Send it; QGraphicsItem::keyPressEvent ignores it. If the event
// is filtered out, stop propagating it.
if (!d->sendEvent(p, keyEvent))
break;
} while (!keyEvent->isAccepted() && !p->isWindow() && (p = p->parentItem()));
} else {
keyEvent->ignore();
}
}
/*!
This event handler, for event \a keyEvent, can be reimplemented in a
subclass to receive key release events. The default implementation
forwards the event to current focus item.
\sa QGraphicsItem::keyReleaseEvent(), focusItem()
*/
void QGraphicsScene::keyReleaseEvent(QKeyEvent *keyEvent)
{
// ### Merge this function with keyPressEvent; they are identical (except
// ### this comment).
Q_D(QGraphicsScene);
QGraphicsItem *item = !d->keyboardGrabberItems.isEmpty() ? d->keyboardGrabberItems.last() : 0;
if (!item)
item = focusItem();
if (item) {
QGraphicsItem *p = item;
do {
// Accept the event by default
keyEvent->accept();
// Send it; QGraphicsItem::keyPressEvent ignores it. If the event
// is filtered out, stop propagating it.
if (!d->sendEvent(p, keyEvent))
break;
} while (!keyEvent->isAccepted() && !p->isWindow() && (p = p->parentItem()));
} else {
keyEvent->ignore();
}
}
/*!
This event handler, for event \a mouseEvent, can be reimplemented
in a subclass to receive mouse press events for the scene.
The default implementation depends on the state of the scene. If
there is a mouse grabber item, then the event is sent to the mouse
grabber. Otherwise, it is forwarded to the topmost item that
accepts mouse events at the scene position from the event, and
that item promptly becomes the mouse grabber item.
If there is no item at the given position on the scene, the
selection area is reset, any focus item loses its input focus, and
the event is then ignored.
\sa QGraphicsItem::mousePressEvent(),
QGraphicsItem::setAcceptedMouseButtons()
*/
void QGraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_D(QGraphicsScene);
d->mousePressEventHandler(mouseEvent);
}
/*!
This event handler, for event \a mouseEvent, can be reimplemented
in a subclass to receive mouse move events for the scene.
The default implementation depends on the mouse grabber state. If there is
a mouse grabber item, the event is sent to the mouse grabber. If there
are any items that accept hover events at the current position, the event
is translated into a hover event and accepted; otherwise it's ignored.
\sa QGraphicsItem::mousePressEvent(), QGraphicsItem::mouseReleaseEvent(),
QGraphicsItem::mouseDoubleClickEvent(), QGraphicsItem::setAcceptedMouseButtons()
*/
void QGraphicsScene::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_D(QGraphicsScene);
if (d->mouseGrabberItems.isEmpty()) {
if (mouseEvent->buttons())
return;
QGraphicsSceneHoverEvent hover;
_q_hoverFromMouseEvent(&hover, mouseEvent);
mouseEvent->setAccepted(d->dispatchHoverEvent(&hover));
return;
}
// Forward the event to the mouse grabber
d->sendMouseEvent(mouseEvent);
mouseEvent->accept();
}
/*!
This event handler, for event \a mouseEvent, can be reimplemented
in a subclass to receive mouse release events for the scene.
The default implementation depends on the mouse grabber state. If
there is no mouse grabber, the event is ignored. Otherwise, if
there is a mouse grabber item, the event is sent to the mouse
grabber. If this mouse release represents the last pressed button
on the mouse, the mouse grabber item then loses the mouse grab.
\sa QGraphicsItem::mousePressEvent(), QGraphicsItem::mouseMoveEvent(),
QGraphicsItem::mouseDoubleClickEvent(), QGraphicsItem::setAcceptedMouseButtons()
*/
void QGraphicsScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_D(QGraphicsScene);
if (d->mouseGrabberItems.isEmpty()) {
mouseEvent->ignore();
return;
}
// Forward the event to the mouse grabber
d->sendMouseEvent(mouseEvent);
mouseEvent->accept();
// Reset the mouse grabber when the last mouse button has been released.
if (!mouseEvent->buttons()) {
if (!d->mouseGrabberItems.isEmpty()) {
d->lastMouseGrabberItem = d->mouseGrabberItems.last();
if (d->lastMouseGrabberItemHasImplicitMouseGrab)
d->mouseGrabberItems.last()->ungrabMouse();
} else {
d->lastMouseGrabberItem = 0;
}
// Generate a hoverevent
QGraphicsSceneHoverEvent hoverEvent;
_q_hoverFromMouseEvent(&hoverEvent, mouseEvent);
d->dispatchHoverEvent(&hoverEvent);
}
}
/*!
This event handler, for event \a mouseEvent, can be reimplemented
in a subclass to receive mouse doubleclick events for the scene.
If someone doubleclicks on the scene, the scene will first receive
a mouse press event, followed by a release event (i.e., a click),
then a doubleclick event, and finally a release event. If the
doubleclick event is delivered to a different item than the one
that received the first press and release, it will be delivered as
a press event. However, tripleclick events are not delivered as
doubleclick events in this case.
The default implementation is similar to mousePressEvent().
\sa QGraphicsItem::mousePressEvent(), QGraphicsItem::mouseMoveEvent(),
QGraphicsItem::mouseReleaseEvent(), QGraphicsItem::setAcceptedMouseButtons()
*/
void QGraphicsScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_D(QGraphicsScene);
d->mousePressEventHandler(mouseEvent);
}
/*!
This event handler, for event \a wheelEvent, can be reimplemented in a
subclass to receive mouse wheel events for the scene.
By default, the event is delivered to the topmost visible item under the
cursor. If ignored, the event propagates to the item beneath, and again
until the event is accepted, or it reaches the scene. If no items accept
the event, it is ignored.
\sa QGraphicsItem::wheelEvent()
*/
void QGraphicsScene::wheelEvent(QGraphicsSceneWheelEvent *wheelEvent)
{
Q_D(QGraphicsScene);
QList<QGraphicsItem *> wheelCandidates = d->itemsAtPosition(wheelEvent->screenPos(),
wheelEvent->scenePos(),
wheelEvent->widget());
bool hasSetFocus = false;
foreach (QGraphicsItem *item, wheelCandidates) {
if (!hasSetFocus && item->isEnabled() && (item->flags() & QGraphicsItem::ItemIsFocusable)) {
if (item->isWidget() && static_cast<QGraphicsWidget *>(item)->focusPolicy() == Qt::WheelFocus) {
hasSetFocus = true;
if (item != focusItem())
setFocusItem(item, Qt::MouseFocusReason);
}
}
wheelEvent->setPos(item->d_ptr->genericMapFromScene(wheelEvent->scenePos(),
wheelEvent->widget()));
wheelEvent->accept();
bool isWindow = item->isWindow();
d->sendEvent(item, wheelEvent);
if (isWindow || wheelEvent->isAccepted())
break;
}
}
/*!
This event handler, for event \a event, can be reimplemented in a
subclass to receive input method events for the scene.
The default implementation forwards the event to the focusItem().
If no item currently has focus, this function does nothing.
\sa QGraphicsItem::inputMethodEvent()
*/
void QGraphicsScene::inputMethodEvent(QInputMethodEvent *event)
{
Q_D(QGraphicsScene);
if (!d->focusItem)
return;
d->sendEvent(d->focusItem, event);
}
/*!
Draws the background of the scene using \a painter, before any items and
the foreground are drawn. Reimplement this function to provide a custom
background for the scene.
All painting is done in \e scene coordinates. The \a rect
parameter is the exposed rectangle.
If all you want is to define a color, texture, or gradient for the
background, you can call setBackgroundBrush() instead.
\sa drawForeground(), drawItems()
*/
void QGraphicsScene::drawBackground(QPainter *painter, const QRectF &rect)
{
Q_D(QGraphicsScene);
if (d->backgroundBrush.style() != Qt::NoBrush) {
if (d->painterStateProtection)
painter->save();
painter->setBrushOrigin(0, 0);
painter->fillRect(rect, backgroundBrush());
if (d->painterStateProtection)
painter->restore();
}
}
/*!
Draws the foreground of the scene using \a painter, after the background
and all items have been drawn. Reimplement this function to provide a
custom foreground for the scene.
All painting is done in \e scene coordinates. The \a rect
parameter is the exposed rectangle.
If all you want is to define a color, texture or gradient for the
foreground, you can call setForegroundBrush() instead.
\sa drawBackground(), drawItems()
*/
void QGraphicsScene::drawForeground(QPainter *painter, const QRectF &rect)
{
Q_D(QGraphicsScene);
if (d->foregroundBrush.style() != Qt::NoBrush) {
if (d->painterStateProtection)
painter->save();
painter->setBrushOrigin(0, 0);
painter->fillRect(rect, foregroundBrush());
if (d->painterStateProtection)
painter->restore();
}
}
static void _q_paintItem(QGraphicsItem *item, QPainter *painter,
const QStyleOptionGraphicsItem *option, QWidget *widget,
bool useWindowOpacity, bool painterStateProtection)
{
if (!item->isWidget()) {
item->paint(painter, option, widget);
return;
}
QGraphicsWidget *widgetItem = static_cast<QGraphicsWidget *>(item);
QGraphicsProxyWidget *proxy = qobject_cast<QGraphicsProxyWidget *>(widgetItem);
const qreal windowOpacity = (proxy && proxy->widget() && useWindowOpacity)
? proxy->widget()->windowOpacity() : 1.0;
const qreal oldPainterOpacity = painter->opacity();
if (qFuzzyCompare(windowOpacity + 1, qreal(1.0)))
return;
// Set new painter opacity.
if (windowOpacity < 1.0)
painter->setOpacity(oldPainterOpacity * windowOpacity);
// set layoutdirection on the painter
Qt::LayoutDirection oldLayoutDirection = painter->layoutDirection();
painter->setLayoutDirection(widgetItem->layoutDirection());
if (widgetItem->isWindow() && widgetItem->windowType() != Qt::Popup && widgetItem->windowType() != Qt::ToolTip
&& !(widgetItem->windowFlags() & Qt::FramelessWindowHint)) {
if (painterStateProtection)
painter->save();
widgetItem->paintWindowFrame(painter, option, widget);
if (painterStateProtection)
painter->restore();
}
widgetItem->paint(painter, option, widget);
// Restore layoutdirection on the painter.
painter->setLayoutDirection(oldLayoutDirection);
// Restore painter opacity.
if (windowOpacity < 1.0)
painter->setOpacity(oldPainterOpacity);
}
static void _q_paintIntoCache(QPixmap *pix, QGraphicsItem *item, const QRegion &pixmapExposed,
const QTransform &itemToPixmap, QPainter::RenderHints renderHints,
const QStyleOptionGraphicsItem *option, bool painterStateProtection)
{
QPixmap subPix;
QPainter pixmapPainter;
QRect br = pixmapExposed.boundingRect();
// Don't use subpixmap if we get a full update.
if (pixmapExposed.isEmpty() || (pixmapExposed.numRects() == 1 && br.contains(pix->rect()))) {
pix->fill(Qt::transparent);
pixmapPainter.begin(pix);
} else {
subPix = QPixmap(br.size());
subPix.fill(Qt::transparent);
pixmapPainter.begin(&subPix);
pixmapPainter.translate(-br.topLeft());
if (!pixmapExposed.isEmpty()) {
// Applied to subPix; paint is adjusted to the coordinate space is
// correct.
pixmapPainter.setClipRegion(pixmapExposed);
}
}
pixmapPainter.setRenderHints(pixmapPainter.renderHints(), false);
pixmapPainter.setRenderHints(renderHints, true);
pixmapPainter.setWorldTransform(itemToPixmap, true);
// Render.
_q_paintItem(item, &pixmapPainter, option, 0, false, painterStateProtection);
pixmapPainter.end();
if (!subPix.isNull()) {
// Blit the subpixmap into the main pixmap.
pixmapPainter.begin(pix);
pixmapPainter.setCompositionMode(QPainter::CompositionMode_Source);
pixmapPainter.setClipRegion(pixmapExposed);
pixmapPainter.drawPixmap(br.topLeft(), subPix);
pixmapPainter.end();
}
}
/*!
\internal
Draws items directly, or using cache.
*/
void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painter,
const QStyleOptionGraphicsItem *option, QWidget *widget,
bool painterStateProtection)
{
QGraphicsItemPrivate *itemd = item->d_ptr;
QGraphicsItem::CacheMode cacheMode = QGraphicsItem::CacheMode(itemd->cacheMode);
// Render directly, using no cache.
if (cacheMode == QGraphicsItem::NoCache
#ifdef Q_WS_X11
|| !X11->use_xrender
#endif
) {
_q_paintItem(static_cast<QGraphicsWidget *>(item), painter, option, widget, true, painterStateProtection);
return;
}
const qreal oldPainterOpacity = painter->opacity();
qreal newPainterOpacity = oldPainterOpacity;
QGraphicsProxyWidget *proxy = item->isWidget() ? qobject_cast<QGraphicsProxyWidget *>(static_cast<QGraphicsWidget *>(item)) : 0;
if (proxy && proxy->widget()) {
const qreal windowOpacity = proxy->widget()->windowOpacity();
if (windowOpacity < 1.0)
newPainterOpacity *= windowOpacity;
}
// Item's (local) bounding rect
QRectF brect = item->boundingRect();
if (_q_adjustedRect(brect).isEmpty())
return;
// Fetch the off-screen transparent buffer and exposed area info.
QString pixmapKey;
QPixmap pix;
QGraphicsItemCache *itemCache = itemd->extraItemCache();
if (cacheMode == QGraphicsItem::ItemCoordinateCache) {
if (itemCache->boundingRect != brect.toRect()) {
itemCache->boundingRect = brect.toRect();
itemCache->allExposed = true;
itemCache->exposed.clear();
}
pixmapKey = itemCache->key;
} else {
if ((pixmapKey = itemCache->deviceData.value(widget).key).isEmpty()) {
pixmapKey.sprintf("qgv-%p-%p", item, widget);
QGraphicsItemCache::DeviceData data;
data.key = pixmapKey;
itemCache->deviceData.insert(widget, data);
}
}
// Find pixmap in cache.
if (!itemCache->allExposed)
QPixmapCache::find(pixmapKey, pix);
// Render using item coordinate cache mode.
if (cacheMode == QGraphicsItem::ItemCoordinateCache) {
QSize pixmapSize;
bool fixedCacheSize = false;
QRectF brectAligned = brect.toAlignedRect();
if ((fixedCacheSize = itemCache->fixedSize.isValid())) {
pixmapSize = itemCache->fixedSize;
} else {
pixmapSize = brectAligned.size().toSize();
}
// Create or recreate the pixmap.
int adjust = itemCache->fixedSize.isValid() ? 0 : 2;
QSize adjustSize(adjust*2, adjust*2);
QRectF br = brectAligned.adjusted(-adjust, -adjust, adjust, adjust);
if (pix.isNull() || (!fixedCacheSize && (pixmapSize + adjustSize) != pix.size())) {
pix = QPixmap(pixmapSize + adjustSize);
itemCache->exposed.clear();
itemCache->allExposed = true;
}
// Redraw any newly exposed areas.
if (itemCache->allExposed || !itemCache->exposed.isEmpty()) {
// Fit the item's bounding rect into the pixmap's coordinates.
QTransform itemToPixmap;
if (fixedCacheSize) {
const QPointF scale(pixmapSize.width() / brect.width(), pixmapSize.height() / brect.height());
itemToPixmap.scale(scale.x(), scale.y());
}
itemToPixmap.translate(-br.x(), -br.y());
// Generate the item's exposedRect and map its list of expose
// rects to device coordinates.
QStyleOptionGraphicsItem cacheOption = *option;
QRegion pixmapExposed;
QRectF exposedRect;
if (!itemCache->allExposed) {
for (int i = 0; i < itemCache->exposed.size(); ++i) {
QRectF r = itemCache->exposed.at(i);
exposedRect |= r;
pixmapExposed += itemToPixmap.mapRect(r).toAlignedRect();
}
} else {
exposedRect = brect;
}
cacheOption.exposedRect = exposedRect;
// Render.
_q_paintIntoCache(&pix, item, pixmapExposed, itemToPixmap, painter->renderHints(),
&cacheOption, painterStateProtection);
// Reinsert this pixmap into the cache.
QPixmapCache::insert(pixmapKey, pix);
// Reset expose data.
itemCache->allExposed = false;
itemCache->exposed.clear();
}
// Redraw the exposed area using the transformed painter. Depending on
// the hardware, this may be a server-side operation, or an expensive
// qpixmap-image-transform-pixmap roundtrip.
if (newPainterOpacity != oldPainterOpacity) {
painter->setOpacity(newPainterOpacity);
painter->drawPixmap(br, pix, QRectF(QPointF(), pix.size()));
painter->setOpacity(oldPainterOpacity);
} else {
painter->drawPixmap(br, pix, QRectF(QPointF(), pix.size()));
}
return;
}
// Render using device coordinate cache mode.
if (cacheMode == QGraphicsItem::DeviceCoordinateCache) {
// Find the item's bounds in device coordinates.
QRectF deviceBounds = painter->worldTransform().mapRect(brect);
QRect deviceRect = deviceBounds.toRect().adjusted(-1, -1, 1, 1);
if (deviceRect.isEmpty())
return;
QRect viewRect = widget ? widget->rect() : QRect();
if (widget && !viewRect.intersects(deviceRect))
return;
// Resort to direct rendering if the device rect exceeds the
// (optional) maximum bounds. (QGraphicsSvgItem uses this).
QSize maximumCacheSize =
itemd->extra(QGraphicsItemPrivate::ExtraMaxDeviceCoordCacheSize).toSize();
if (!maximumCacheSize.isEmpty()
&& (deviceRect.width() > maximumCacheSize.width()
|| deviceRect.height() > maximumCacheSize.height())) {
_q_paintItem(static_cast<QGraphicsWidget *>(item), painter, option, widget,
oldPainterOpacity != newPainterOpacity, painterStateProtection);
return;
}
// Create or reuse offscreen pixmap, possibly scroll/blit from the old one.
bool pixModified = false;
QGraphicsItemCache::DeviceData *deviceData = &itemCache->deviceData[widget];
bool invertable = true;
QTransform diff = deviceData->lastTransform.inverted(&invertable);
if (invertable)
diff *= painter->worldTransform();
deviceData->lastTransform = painter->worldTransform();
if (!invertable || diff.type() > QTransform::TxTranslate) {
pixModified = true;
itemCache->allExposed = true;
itemCache->exposed.clear();
pix = QPixmap();
}
// ### This is a pretty bad way to determine when to start partial
// exposure for DeviceCoordinateCache but it's the least intrusive
// approach for now.
#if 0
// Only if the device rect isn't fully contained.
bool allowPartialCacheExposure = !viewRect.contains(deviceRect);
#else
// Only if deviceRect is 20% taller or wider than the desktop.
QRect desktopRect = qApp->desktop()->availableGeometry(widget);
bool allowPartialCacheExposure = (desktopRect.width() * 1.2 < deviceRect.width()
|| desktopRect.height() * 1.2 < deviceRect.height());
#endif
QRegion scrollExposure;
if (deviceData->cacheIndent != QPoint() || allowPartialCacheExposure) {
// Part of pixmap is drawn. Either device contains viewrect (big
// item covers whole screen) or parts of device are outside the
// viewport. In either case the device rect must be the intersect
// between the two.
int dx = deviceRect.left() < viewRect.left() ? viewRect.left() - deviceRect.left() : 0;
int dy = deviceRect.top() < viewRect.top() ? viewRect.top() - deviceRect.top() : 0;
QPoint newCacheIndent(dx, dy);
deviceRect &= viewRect;
if (pix.isNull()) {
deviceData->cacheIndent = QPoint();
itemCache->allExposed = true;
itemCache->exposed.clear();
pixModified = true;
}
// Copy / "scroll" the old pixmap onto the new ole and calculate
// scrolled exposure.
if (newCacheIndent != deviceData->cacheIndent || deviceRect.size() != pix.size()) {
QPoint diff = newCacheIndent - deviceData->cacheIndent;
QPixmap newPix(deviceRect.size());
if (!pix.isNull()) {
QPainter newPixPainter(&newPix);
newPixPainter.setCompositionMode(QPainter::CompositionMode_Source);
newPixPainter.drawPixmap(-diff, pix);
newPixPainter.end();
}
QRegion exposed;
exposed += newPix.rect();
if (!pix.isNull())
exposed -= QRect(-diff, pix.size());
scrollExposure = exposed;
pix = newPix;
pixModified = true;
}
deviceData->cacheIndent = newCacheIndent;
} else {
// Full pixmap is drawn.
deviceData->cacheIndent = QPoint();
// Auto-adjust the pixmap size.
if (deviceRect.size() != pix.size()) {
// exposed needs to cover the whole pixmap
pix = QPixmap(deviceRect.size());
pixModified = true;
itemCache->allExposed = true;
itemCache->exposed.clear();
}
}
// Check for newly invalidated areas.
if (itemCache->allExposed || !itemCache->exposed.isEmpty() || !scrollExposure.isEmpty()) {
// Construct an item-to-pixmap transform.
QPointF p = deviceRect.topLeft();
QTransform itemToPixmap = painter->worldTransform();
if (!p.isNull())
itemToPixmap *= QTransform::fromTranslate(-p.x(), -p.y());
// Map the item's logical expose to pixmap coordinates.
QRegion pixmapExposed = scrollExposure;
if (!itemCache->allExposed) {
const QVector<QRectF> &exposed = itemCache->exposed;
for (int i = 0; i < exposed.size(); ++i)
pixmapExposed += itemToPixmap.mapRect(exposed.at(i)).toRect().adjusted(-1, -1, 1, 1);
}
// Calculate the style option's exposedRect.
QRectF br;
if (itemCache->allExposed) {
br = item->boundingRect();
} else {
const QVector<QRectF> &exposed = itemCache->exposed;
for (int i = 0; i < exposed.size(); ++i)
br |= exposed.at(i);
QTransform pixmapToItem = itemToPixmap.inverted();
foreach (QRect r, scrollExposure.rects())
br |= pixmapToItem.mapRect(r);
}
QStyleOptionGraphicsItem cacheOption = *option;
cacheOption.exposedRect = br.adjusted(-1, -1, 1, 1);
// Render the exposed areas.
_q_paintIntoCache(&pix, item, pixmapExposed, itemToPixmap, painter->renderHints(),
&cacheOption, painterStateProtection);
// Reset expose data.
pixModified = true;
itemCache->allExposed = false;
itemCache->exposed.clear();
}
if (pixModified) {
// Reinsert this pixmap into the cache
QPixmapCache::insert(pixmapKey, pix);
}
// Redraw the exposed area using an untransformed painter. This
// effectively becomes a bitblit that does not transform the cache.
QTransform restoreTransform = painter->worldTransform();
painter->setWorldTransform(QTransform());
if (newPainterOpacity != oldPainterOpacity) {
painter->setOpacity(newPainterOpacity);
painter->drawPixmap(deviceRect.topLeft(), pix);
painter->setOpacity(oldPainterOpacity);
} else {
painter->drawPixmap(deviceRect.topLeft(), pix);
}
painter->setWorldTransform(restoreTransform);
return;
}
}
/*!
Paints the given \a items using the provided \a painter, after the
background has been drawn, and before the foreground has been
drawn. All painting is done in \e scene coordinates. Before
drawing each item, the painter must be transformed using
QGraphicsItem::sceneMatrix().
The \a options parameter is the list of style option objects for
each item in \a items. The \a numItems parameter is the number of
items in \a items and options in \a options. The \a widget
parameter is optional; if specified, it should point to the widget
that is being painted on.
The default implementation prepares the painter matrix, and calls
QGraphicsItem::paint() on all items. Reimplement this function to
provide custom painting of all items for the scene; gaining
complete control over how each item is drawn. In some cases this
can increase drawing performance significantly.
Example:
\snippet doc/src/snippets/graphicssceneadditemsnippet.cpp 0
\sa drawBackground(), drawForeground()
*/
void QGraphicsScene::drawItems(QPainter *painter,
int numItems,
QGraphicsItem *items[],
const QStyleOptionGraphicsItem options[], QWidget *widget)
{
Q_D(QGraphicsScene);
// Detect if painter state protection is disabled.
QTransform viewTransform = painter->worldTransform();
QVarLengthArray<QGraphicsItem *, 16> childClippers;
for (int i = 0; i < numItems; ++i) {
QGraphicsItem *item = items[i];
if (!(item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)) {
if (!childClippers.isEmpty()) {
// Item is not clipped to any ancestor: pop all current clippers.
for (int i = 0; i < childClippers.size(); ++i)
painter->restore();
childClippers.clear();
}
} else {
// Item is clipped to an ancestor, which may or may not be in our
// child clipper list. Let's start by finding the item's closest
// clipping ancestor.
QGraphicsItem *clipParent = item->parentItem();
while (clipParent && !(clipParent->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape))
clipParent = clipParent->parentItem();
// Pop any in-between clippers. If the clipper is unknown, pop
// them all. ### QVarLengthArray::lastIndexOf().
int index = -1;
for (int n = childClippers.size() - 1; n >= 0; --n) {
if (childClippers[n] == clipParent) {
index = n;
break;
}
}
if (index != -1) {
int toPop = childClippers.size() - index - 1;
if (toPop > 0) {
for (int i = 0; i < toPop; ++i)
painter->restore();
childClippers.resize(index + 1);
}
}
// Sanity check
if (!childClippers.isEmpty())
Q_ASSERT(childClippers[childClippers.size() - 1] == clipParent);
// If the clipper list is empty at this point, but we're still
// clipped to an ancestor, then we need to build the clip chain
// ourselves. There is only one case that can produce this issue:
// This item is stacked behind an ancestor:
// ItemStacksBehindParent.
if (childClippers.isEmpty()) {
Q_ASSERT(clipParent != 0);
// Build a stack of clippers.
QVarLengthArray<QGraphicsItem *, 16> clippers;
QGraphicsItem *p = clipParent;
do {
if (p->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)
clippers.append(p);
} while ((p = p->parentItem()) && (p->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren));
// ### This code path can also use the itemTransform
// optimization, but it's hit very rarely.
for (int i = clippers.size() - 1; i >= 0; --i) {
QGraphicsItem *clipper = clippers[i];
if (clipper->d_ptr->itemIsUntransformable()) {
painter->setWorldTransform(clipper->deviceTransform(viewTransform), false);
} else {
painter->setWorldTransform(clipper->sceneTransform() * viewTransform, false);
}
childClippers.append(clipper);
painter->save();
painter->setClipPath(clipper->shape(), Qt::IntersectClip);
}
Q_ASSERT(childClippers[childClippers.size() - 1] == clipParent);
}
}
// Set up the painter transform
if (item->d_ptr->itemIsUntransformable()) {
painter->setWorldTransform(item->deviceTransform(viewTransform), false);
} else {
painter->setWorldTransform(item->sceneTransform() * viewTransform, false);
}
// Save painter
bool saveState = (d->painterStateProtection || (item->flags() & QGraphicsItem::ItemClipsToShape));
if (saveState)
painter->save();
// Set local clip
if (item->flags() & QGraphicsItem::ItemClipsToShape)
painter->setClipPath(item->shape(), Qt::IntersectClip);
// Setup opacity
painter->setOpacity(item->effectiveOpacity());
// Draw the item
d->drawItemHelper(item, painter, &options[i], widget, d->painterStateProtection);
if (saveState)
painter->restore();
if (item->flags() & QGraphicsItem::ItemClipsChildrenToShape) {
// Clip descendents to this item's shape, and keep the painter
// saved.
childClippers.append(item);
painter->save();
painter->setClipPath(item->shape(), Qt::IntersectClip);
}
}
for (int i = 0; i < childClippers.size(); ++i)
painter->restore();
painter->setWorldTransform(viewTransform);
}
/*!
\since 4.4
Finds a new widget to give the keyboard focus to, as appropriate for Tab
and Shift+Tab, and returns true if it can find a new widget, or false if
it cannot. If \a next is true, this function searches forward; if \a next
is false, it searches backward.
You can reimplement this function in a subclass of QGraphicsScene to
provide fine-grained control over how tab focus passes inside your
scene. The default implementation is based on the tab focus chain defined
by QGraphicsWidget::setTabOrder().
*/
bool QGraphicsScene::focusNextPrevChild(bool next)
{
Q_D(QGraphicsScene);
QGraphicsItem *item = focusItem();
if (item && !item->isWidget()) {
// Tab out of the scene.
return false;
}
if (!item) {
if (d->lastFocusItem && !d->lastFocusItem->isWidget()) {
// Restore focus to the last focusable non-widget item that had
// focus.
setFocusItem(d->lastFocusItem, next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
return true;
}
}
if (!d->tabFocusFirst) {
// No widgets...
return false;
}
// The item must be a widget.
QGraphicsWidget *widget = 0;
if (!item) {
widget = next ? d->tabFocusFirst : d->tabFocusFirst->d_func()->focusPrev;
} else {
QGraphicsWidget *test = static_cast<QGraphicsWidget *>(item);
widget = next ? test->d_func()->focusNext : test->d_func()->focusPrev;
if ((next && widget == d->tabFocusFirst) || (!next && widget == d->tabFocusFirst->d_func()->focusPrev))
return false;
}
QGraphicsWidget *widgetThatHadFocus = widget;
// Run around the focus chain until we find a widget that can take tab focus.
do {
if (widget->flags() & QGraphicsItem::ItemIsFocusable
&& widget->isEnabled() && widget->isVisibleTo(0)
&& (widget->focusPolicy() & Qt::TabFocus)
&& (!item || !item->isWindow() || item->isAncestorOf(widget))
) {
setFocusItem(widget, next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
return true;
}
widget = next ? widget->d_func()->focusNext : widget->d_func()->focusPrev;
if ((next && widget == d->tabFocusFirst) || (!next && widget == d->tabFocusFirst->d_func()->focusPrev))
return false;
} while (widget != widgetThatHadFocus);
return false;
}
/*!
\fn QGraphicsScene::changed(const QList<QRectF> ®ion)
This signal is emitted by QGraphicsScene when control reaches the
event loop, if the scene content changes. The \a region parameter
contains a list of scene rectangles that indicate the area that
has been changed.
\sa QGraphicsView::updateScene()
*/
/*!
\fn QGraphicsScene::sceneRectChanged(const QRectF &rect)
This signal is emitted by QGraphicsScene whenever the scene rect changes.
The \a rect parameter is the new scene rectangle.
\sa QGraphicsView::updateSceneRect()
*/
/*!
\fn QGraphicsScene::selectionChanged()
\since 4.3
This signal is emitted by QGraphicsScene whenever the selection
changes. You can call selectedItems() to get the new list of selected
items.
The selection changes whenever an item is selected or unselected, a
selection area is set, cleared or otherwise changed, if a preselected item
is added to the scene, or if a selected item is removed from the scene.
QGraphicsScene emits this signal only once for group selection operations.
For example, if you set a selection area, select or unselect a
QGraphicsItemGroup, or if you add or remove from the scene a parent item
that contains several selected items, selectionChanged() is emitted only
once after the operation has completed (instead of once for each item).
\sa setSelectionArea(), selectedItems(), QGraphicsItem::setSelected()
*/
/*!
\internal
This private function is called by QGraphicsItem, which is a friend of
QGraphicsScene. It is used by QGraphicsScene to record the rectangles that
need updating. It also launches a single-shot timer to ensure that
updated() will be emitted later.
The \a item parameter is the item that changed, and \a rect is the
area of the item that changed given in item coordinates.
*/
void QGraphicsScene::itemUpdated(QGraphicsItem *item, const QRectF &rect)
{
Q_D(QGraphicsScene);
// Deliver the actual update.
if (!d->updateAll) {
if (d->views.isEmpty() || ((d->connectedSignals & d->changedSignalMask) && !item->d_ptr->itemIsUntransformable()
&& qFuzzyCompare(item->boundingRegionGranularity(), qreal(0.0)))) {
// This block of code is kept for compatibility. Since 4.5, by default
// QGraphicsView does not connect the signal and we use the below
// method of delivering updates.
update(item->sceneBoundingRect());
} else {
// ### Remove _q_adjustedRects().
QRectF boundingRect = _q_adjustedRect(item->boundingRect());
if (!rect.isNull())
boundingRect &= _q_adjustedRect(rect);
// Update each view directly.
for (int i = 0; i < d->views.size(); ++i)
d->views.at(i)->d_func()->itemUpdated(item, boundingRect);
}
}
if (item->d_ptr->dirty) {
d->dirtyItems << item;
d->resetDirtyItemsLater();
}
// Update d->largestUntransformableItem by mapping this item's bounding
// rect back to the topmost untransformable item's untransformed
// coordinate system (which sort of equals the 1:1 coordinate system of an
// untransformed view).
if (item->d_ptr->itemIsUntransformable()) {
QGraphicsItem *parent = item;
while (parent && (parent->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorIgnoresTransformations))
parent = parent->parentItem();
d->largestUntransformableItem |= item->mapToItem(parent, item->boundingRect()).boundingRect();
}
// Only track the automatically growing scene rect if the scene has no
// defined scene rect.
if (!d->hasSceneRect) {
QRectF oldGrowingItemsBoundingRect = d->growingItemsBoundingRect;
d->growingItemsBoundingRect |= _q_adjustedRect(item->sceneBoundingRect());
if (d->growingItemsBoundingRect != oldGrowingItemsBoundingRect)
emit sceneRectChanged(d->growingItemsBoundingRect);
}
}
/*!
\since 4.4
Returns the scene's style, or the same as QApplication::style() if the
scene has not been explicitly assigned a style.
\sa setStyle()
*/
QStyle *QGraphicsScene::style() const
{
Q_D(const QGraphicsScene);
// ### This function, and the use of styles in general, is non-reentrant.
return d->style ? d->style : qApp->style();
}
/*!
\since 4.4
Sets or replaces the style of the scene to \a style, and reparents the
style to this scene. Any previously assigned style is deleted. The scene's
style defaults to QApplication::style(), and serves as the default for all
QGraphicsWidget items in the scene.
Changing the style, either directly by calling this function, or
indirectly by calling QApplication::setStyle(), will automatically update
the style for all widgets in the scene that do not have a style explicitly
assigned to them.
If \a style is 0, QGraphicsScene will revert to QApplication::style().
\sa style()
*/
void QGraphicsScene::setStyle(QStyle *style)
{
Q_D(QGraphicsScene);
// ### This function, and the use of styles in general, is non-reentrant.
if (style == d->style)
return;
// Delete the old style,
delete d->style;
if ((d->style = style))
d->style->setParent(this);
// Notify the scene.
QEvent event(QEvent::StyleChange);
QApplication::sendEvent(this, &event);
// Notify all widgets that don't have a style explicitly set.
foreach (QGraphicsItem *item, items()) {
if (item->isWidget()) {
QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
if (!widget->testAttribute(Qt::WA_SetStyle))
QApplication::sendEvent(widget, &event);
}
}
}
/*!
\property QGraphicsScene::font
\since 4.4
\brief the scene's default font
This property provides the scene's font. The scene font defaults to,
and resolves all its entries from, QApplication::font.
If the scene's font changes, either directly through setFont() or
indirectly when the application font changes, QGraphicsScene first
sends itself a \l{QEvent::FontChange}{FontChange} event, and it then
sends \l{QEvent::FontChange}{FontChange} events to all top-level
widget items in the scene. These items respond by resolving their own
fonts to the scene, and they then notify their children, who again
notify their children, and so on, until all widget items have updated
their fonts.
Changing the scene font, (directly or indirectly through
QApplication::setFont(),) automatically schedules a redraw the entire
scene.
\sa QWidget::font, QApplication::setFont(), palette, style()
*/
QFont QGraphicsScene::font() const
{
Q_D(const QGraphicsScene);
return d->font;
}
void QGraphicsScene::setFont(const QFont &font)
{
Q_D(QGraphicsScene);
QFont naturalFont = qApp->font();
naturalFont.resolve(0);
QFont resolvedFont = font.resolve(naturalFont);
d->setFont_helper(resolvedFont);
}
/*!
\property QGraphicsScene::palette
\since 4.4
\brief the scene's default palette
This property provides the scene's palette. The scene palette defaults to,
and resolves all its entries from, QApplication::palette.
If the scene's palette changes, either directly through setPalette() or
indirectly when the application palette changes, QGraphicsScene first
sends itself a \l{QEvent::PaletteChange}{PaletteChange} event, and it then
sends \l{QEvent::PaletteChange}{PaletteChange} events to all top-level
widget items in the scene. These items respond by resolving their own
palettes to the scene, and they then notify their children, who again
notify their children, and so on, until all widget items have updated
their palettes.
Changing the scene palette, (directly or indirectly through
QApplication::setPalette(),) automatically schedules a redraw the entire
scene.
\sa QWidget::palette, QApplication::setPalette(), font, style()
*/
QPalette QGraphicsScene::palette() const
{
Q_D(const QGraphicsScene);
return d->palette;
}
void QGraphicsScene::setPalette(const QPalette &palette)
{
Q_D(QGraphicsScene);
QPalette naturalPalette = qApp->palette();
naturalPalette.resolve(0);
QPalette resolvedPalette = palette.resolve(naturalPalette);
d->setPalette_helper(resolvedPalette);
}
/*!
\since 4.4
Returns the current active window, or 0 if there is no window is currently
active.
\sa QGraphicsScene::setActiveWindow()
*/
QGraphicsWidget *QGraphicsScene::activeWindow() const
{
Q_D(const QGraphicsScene);
return d->activeWindow;
}
/*!
\since 4.4
Activates \a widget, which must be a widget in this scene. You can also
pass 0 for \a widget, in which case QGraphicsScene will deactivate any
currently active window.
\sa activeWindow(), QGraphicsWidget::isActiveWindow()
*/
void QGraphicsScene::setActiveWindow(QGraphicsWidget *widget)
{
Q_D(QGraphicsScene);
if (widget && widget->scene() != this) {
qWarning("QGraphicsScene::setActiveWindow: widget %p must be part of this scene",
widget);
return;
}
// Activate the widget's window.
QGraphicsWidget *window = widget ? widget->window() : 0;
if (window == d->activeWindow)
return;
// Deactivate the last active window.
if (d->activeWindow) {
if (QGraphicsWidget *fw = d->activeWindow->focusWidget()) {
// Remove focus from the current focus item.
if (fw == focusItem())
setFocusItem(0, Qt::ActiveWindowFocusReason);
}
QEvent event(QEvent::WindowDeactivate);
QApplication::sendEvent(d->activeWindow, &event);
}
// Update activate state.
d->activeWindow = window;
QEvent event(QEvent::ActivationChange);
QApplication::sendEvent(this, &event);
// Activate
if (window) {
QEvent event(QEvent::WindowActivate);
QApplication::sendEvent(window, &event);
QList<QGraphicsItem *> siblingWindows;
QGraphicsItem *parent = window->parentItem();
// Raise ### inefficient for toplevels
foreach (QGraphicsItem *sibling, parent ? parent->children() : items()) {
if (sibling != window && sibling->isWidget()
&& static_cast<QGraphicsWidget *>(sibling)->isWindow()) {
siblingWindows << sibling;
}
}
// Find the highest z value.
qreal z = window->zValue();
for (int i = 0; i < siblingWindows.size(); ++i)
z = qMax(z, siblingWindows.at(i)->zValue());
// This will probably never overflow.
const qreal litt = qreal(0.001);
window->setZValue(z + litt);
if (QGraphicsWidget *focusChild = window->focusWidget())
focusChild->setFocus(Qt::ActiveWindowFocusReason);
}
}
QT_END_NAMESPACE
#include "moc_qgraphicsscene.cpp"
#endif // QT_NO_GRAPHICSVIEW
|
//******************************************************************************
// FILE : function_variable.hpp
//
// LAST MODIFIED : 23 January 2005
//
// DESCRIPTION :
// An abstract class for specifying input/independent and output/dependent
// variables of a function.
//
// Function_variables can be evaluated, differentiated or set to another value.
//==============================================================================
#if !defined (__FUNCTION_VARIABLE_HPP__)
#define __FUNCTION_VARIABLE_HPP__
#include <iterator>
#include <list>
#include "computed_variable/function_base.hpp"
#include "computed_variable/function_variable_value.hpp"
//#define USE_FUNCTION_VARIABLE__EVALUATE_DERIVATIVE
class Function_variable_iterator_representation
//******************************************************************************
// LAST MODIFIED : 2 March 2004
//
// DESCRIPTION :
//
// NOTES:
// To get iterators for a sub-class of Function_variable, derive a represenation
// class from this one.
//==============================================================================
{
friend class Function_variable_iterator;
public:
// a "virtual" constructor
virtual Function_variable_iterator_representation *clone()=0;
protected:
// destructor. Virtual for proper destruction of derived classes
virtual ~Function_variable_iterator_representation();
private:
// increment. Do not want to return an object derived from
// Function_variable_iterator_representation. Used by
// Function_variable_iterator::operator++() and ++(int)
virtual void increment()=0;
// decrement. Do not want to return an object derived from
// Function_variable_iterator_representation. Needs to be able to step
// from one past the last to the last. Used by
// Function_variable_iterator::operator--() and --(int)
virtual void decrement()=0;
// equality. Used by Function_variable_iterator::operator==() and !=()
virtual bool equality(const Function_variable_iterator_representation*)=0;
// dereference. Used by Function_variable_iterator::operator*()
virtual Function_variable_handle dereference() const=0;
protected:
// constructor. Protected so that can't create "plain"
// Function_variable_iterator_representations
Function_variable_iterator_representation();
private:
// copy operations are private and undefined to prevent copying
Function_variable_iterator_representation(
const Function_variable_iterator_representation&);
Function_variable_iterator_representation& operator=(
const Function_variable_iterator_representation&);
};
class Function_variable_iterator:
public std::iterator<std::bidirectional_iterator_tag,Function_variable_handle,
ptrdiff_t,Function_variable_handle*,Function_variable_handle>
//******************************************************************************
// LAST MODIFIED : 2 March 2004
//
// DESCRIPTION :
//
// NOTES:
// Do not derive from this class. Derive from
// Function_variable_iterator_representation.
//
// The reference is Function_variable_handle rather the
// Function_variable_handle& (the default for std::iterator<>) because using
// smart pointers and because the objects in the pool being iterated are created
// by the iterator as required.
//==============================================================================
{
public:
// constructors
Function_variable_iterator();
Function_variable_iterator(Function_variable_iterator_representation *);
// copy constructor
Function_variable_iterator(const Function_variable_iterator&);
// assignment
Function_variable_iterator& operator=(const Function_variable_iterator&);
// destructor
~Function_variable_iterator();
// increment (prefix)
Function_variable_iterator& operator++();
// increment (postfix)
Function_variable_iterator operator++(int);
// decrement (prefix)
Function_variable_iterator& operator--();
// decrement (postfix)
Function_variable_iterator operator--(int);
// equality
bool operator==(const Function_variable_iterator&) const;
// inequality
bool operator!=(const Function_variable_iterator&) const;
// dereference
Function_variable_handle operator*() const;
// don't have a operator-> because its not needed and it would return a
// Function_variable_handle*
private:
Function_variable_iterator_representation *representation;
};
class Function_variable
//******************************************************************************
// LAST MODIFIED : 23 January 2005
//
// DESCRIPTION :
// A specification for an input/independent and/or output/dependent variable of
// a Function.
//==============================================================================
{
template<class Value_type_1,class Value_type_2>
friend bool equivalent(boost::intrusive_ptr<Value_type_1> const &,
boost::intrusive_ptr<Value_type_2> const &);
public:
virtual Function_variable_handle clone() const=0;
// if the variable is for a single function, the function is returned,
// otherwise a zero handle is returned
virtual Function_handle function() const;
// returns a specification for the type of variable's value
virtual Function_variable_value_handle value();
#if defined (EVALUATE_RETURNS_VALUE)
// evaluate creates a new Function which is the variable's value with the
// specified <input> replaced by the given <value>. For a dependent
// variable, this will involve evaluating the variable's function
virtual Function_handle evaluate();
virtual Function_handle evaluate(Function_variable_handle input,
Function_handle value);
#else // defined (EVALUATE_RETURNS_VALUE)
// for a dependent variable, the variable's function will be evaluated. For
// an independent variable, nothing will happen
virtual bool evaluate();
#endif // defined (EVALUATE_RETURNS_VALUE)
#if defined (USE_FUNCTION_VARIABLE__EVALUATE_DERIVATIVE)
// evaluate_derivative creates a new Function which is the value of the
// variable differentiated with respect to the <independent_variables>
// and the specified <input> replaced with given the <value>
virtual Function_handle evaluate_derivative(
std::list<Function_variable_handle>& independent_variables);
virtual Function_handle evaluate_derivative(
std::list<Function_variable_handle>& independent_variables,
Function_variable_handle input,Function_handle value);
#else // defined (USE_FUNCTION_VARIABLE__EVALUATE_DERIVATIVE)
// derivative creates a new Function which calculates the value of this
// variable differentiated with respect to the <independent_variables>
virtual Function_handle derivative(
const std::list<Function_variable_handle>& independent_variables);
#endif // defined (USE_FUNCTION_VARIABLE__EVALUATE_DERIVATIVE)
// set_value changes the variable to have the <value> in the same order as
// evaluate. Returns true if the variable is changed and false otherwise
virtual bool set_value(Function_handle value);
// rset_value changes the variable to have the <value> in the opposite order
// to evaluate (back to front). Returns true if the variable is changed
// and false otherwise
virtual bool rset_value(Function_handle value);
// get_value creates a new Function which is the variable's value. The
// variable's function is not evaluated
virtual Function_handle get_value() const;
// returns a string the represents the variable
virtual string_handle get_string_representation()=0;
// for stepping through the atomic variables that make up the variable.
// Atomic variables are indivisible, that is, two atomic variables are
// either the same or disjoint. This is needed for determining the
// overlap between variables. Atomic variables are for a single function
virtual Function_variable_iterator begin_atomic() const=0;
virtual Function_variable_iterator end_atomic() const=0;
virtual std::reverse_iterator<Function_variable_iterator>
rbegin_atomic() const=0;
virtual std::reverse_iterator<Function_variable_iterator>
rend_atomic() const=0;
// returns the number of atomic variables that it makes sense to
// differentiate (output/dependent) or differentiate with respect to
// (input/independent)
virtual Function_size_type number_differentiable();
// the norm of the variable. A negative result means that the norm is not
// defined
virtual Scalar norm() const;
// a zero handle indicates an error. -= and += work in place. - and +
// create new Functions and return their output variables
virtual Function_variable_handle operator-(const Function_variable&) const;
virtual Function_variable_handle operator-=(const Function_variable&);
virtual Function_variable_handle operator+(const Function_variable&) const;
virtual Function_variable_handle operator+=(const Function_variable&);
public:
// for caching function evaluations:
// adds <dependent_function> to the list of functions that have to be
// re-evaluated if this variable's function(s) has/have to be re-evaluated
#if defined (CIRCULAR_SMART_POINTERS)
virtual void add_dependent_function(
const Function_handle dependent_function);
#else // defined (CIRCULAR_SMART_POINTERS)
virtual void add_dependent_function(
Function *dependent_function);
#endif // defined (CIRCULAR_SMART_POINTERS)
// removes <dependent_function> to the list of functions that have to be
// re-evaluated if this variable's function(s) has/have to be re-evaluated
#if defined (CIRCULAR_SMART_POINTERS)
virtual void remove_dependent_function(
const Function_handle dependent_function);
#else // defined (CIRCULAR_SMART_POINTERS)
virtual void remove_dependent_function(
Function *dependent_function);
#endif // defined (CIRCULAR_SMART_POINTERS)
private:
virtual bool equality_atomic(const Function_variable_handle&) const=0;
// equality operator. To be used in equivalent
virtual bool operator==(const Function_variable&) const;
protected:
// constructors. Protected so that can't create "plain" Function_variables
Function_variable(const Function_handle& function);
// copy constructor
Function_variable(const Function_variable&);
// destructor. Virtual for proper destruction of derived classes
virtual ~Function_variable();
private:
// copy operations are private and undefined to prevent copying
void operator=(const Function_variable&);
protected:
Function_handle function_private;
Function_variable_value_handle value_private;
private:
mutable int reference_count;
friend void intrusive_ptr_add_ref(Function_variable *);
friend void intrusive_ptr_release(Function_variable *);
};
#endif /* !defined (__FUNCTION_VARIABLE_HPP__) */
Changed back to USE_FUNCTION_VARIABLE__EVALUATE_DERIVATIVE
git-svn-id: 4705079bc6b8aadf675e3696f5c015a6aa4916e3@3794 3c1deb5b-d424-0410-962d-aba41a686d42
//******************************************************************************
// FILE : function_variable.hpp
//
// LAST MODIFIED : 23 January 2005
//
// DESCRIPTION :
// An abstract class for specifying input/independent and output/dependent
// variables of a function.
//
// Function_variables can be evaluated, differentiated or set to another value.
//==============================================================================
#if !defined (__FUNCTION_VARIABLE_HPP__)
#define __FUNCTION_VARIABLE_HPP__
#include <iterator>
#include <list>
#include "computed_variable/function_base.hpp"
#include "computed_variable/function_variable_value.hpp"
#define USE_FUNCTION_VARIABLE__EVALUATE_DERIVATIVE
class Function_variable_iterator_representation
//******************************************************************************
// LAST MODIFIED : 2 March 2004
//
// DESCRIPTION :
//
// NOTES:
// To get iterators for a sub-class of Function_variable, derive a represenation
// class from this one.
//==============================================================================
{
friend class Function_variable_iterator;
public:
// a "virtual" constructor
virtual Function_variable_iterator_representation *clone()=0;
protected:
// destructor. Virtual for proper destruction of derived classes
virtual ~Function_variable_iterator_representation();
private:
// increment. Do not want to return an object derived from
// Function_variable_iterator_representation. Used by
// Function_variable_iterator::operator++() and ++(int)
virtual void increment()=0;
// decrement. Do not want to return an object derived from
// Function_variable_iterator_representation. Needs to be able to step
// from one past the last to the last. Used by
// Function_variable_iterator::operator--() and --(int)
virtual void decrement()=0;
// equality. Used by Function_variable_iterator::operator==() and !=()
virtual bool equality(const Function_variable_iterator_representation*)=0;
// dereference. Used by Function_variable_iterator::operator*()
virtual Function_variable_handle dereference() const=0;
protected:
// constructor. Protected so that can't create "plain"
// Function_variable_iterator_representations
Function_variable_iterator_representation();
private:
// copy operations are private and undefined to prevent copying
Function_variable_iterator_representation(
const Function_variable_iterator_representation&);
Function_variable_iterator_representation& operator=(
const Function_variable_iterator_representation&);
};
class Function_variable_iterator:
public std::iterator<std::bidirectional_iterator_tag,Function_variable_handle,
ptrdiff_t,Function_variable_handle*,Function_variable_handle>
//******************************************************************************
// LAST MODIFIED : 2 March 2004
//
// DESCRIPTION :
//
// NOTES:
// Do not derive from this class. Derive from
// Function_variable_iterator_representation.
//
// The reference is Function_variable_handle rather the
// Function_variable_handle& (the default for std::iterator<>) because using
// smart pointers and because the objects in the pool being iterated are created
// by the iterator as required.
//==============================================================================
{
public:
// constructors
Function_variable_iterator();
Function_variable_iterator(Function_variable_iterator_representation *);
// copy constructor
Function_variable_iterator(const Function_variable_iterator&);
// assignment
Function_variable_iterator& operator=(const Function_variable_iterator&);
// destructor
~Function_variable_iterator();
// increment (prefix)
Function_variable_iterator& operator++();
// increment (postfix)
Function_variable_iterator operator++(int);
// decrement (prefix)
Function_variable_iterator& operator--();
// decrement (postfix)
Function_variable_iterator operator--(int);
// equality
bool operator==(const Function_variable_iterator&) const;
// inequality
bool operator!=(const Function_variable_iterator&) const;
// dereference
Function_variable_handle operator*() const;
// don't have a operator-> because its not needed and it would return a
// Function_variable_handle*
private:
Function_variable_iterator_representation *representation;
};
class Function_variable
//******************************************************************************
// LAST MODIFIED : 23 January 2005
//
// DESCRIPTION :
// A specification for an input/independent and/or output/dependent variable of
// a Function.
//==============================================================================
{
template<class Value_type_1,class Value_type_2>
friend bool equivalent(boost::intrusive_ptr<Value_type_1> const &,
boost::intrusive_ptr<Value_type_2> const &);
public:
virtual Function_variable_handle clone() const=0;
// if the variable is for a single function, the function is returned,
// otherwise a zero handle is returned
virtual Function_handle function() const;
// returns a specification for the type of variable's value
virtual Function_variable_value_handle value();
#if defined (EVALUATE_RETURNS_VALUE)
// evaluate creates a new Function which is the variable's value with the
// specified <input> replaced by the given <value>. For a dependent
// variable, this will involve evaluating the variable's function
virtual Function_handle evaluate();
virtual Function_handle evaluate(Function_variable_handle input,
Function_handle value);
#else // defined (EVALUATE_RETURNS_VALUE)
// for a dependent variable, the variable's function will be evaluated. For
// an independent variable, nothing will happen
virtual bool evaluate();
#endif // defined (EVALUATE_RETURNS_VALUE)
#if defined (USE_FUNCTION_VARIABLE__EVALUATE_DERIVATIVE)
// evaluate_derivative creates a new Function which is the value of the
// variable differentiated with respect to the <independent_variables>
// and the specified <input> replaced with given the <value>
virtual Function_handle evaluate_derivative(
std::list<Function_variable_handle>& independent_variables);
virtual Function_handle evaluate_derivative(
std::list<Function_variable_handle>& independent_variables,
Function_variable_handle input,Function_handle value);
#else // defined (USE_FUNCTION_VARIABLE__EVALUATE_DERIVATIVE)
// derivative creates a new Function which calculates the value of this
// variable differentiated with respect to the <independent_variables>
virtual Function_handle derivative(
const std::list<Function_variable_handle>& independent_variables);
#endif // defined (USE_FUNCTION_VARIABLE__EVALUATE_DERIVATIVE)
// set_value changes the variable to have the <value> in the same order as
// evaluate. Returns true if the variable is changed and false otherwise
virtual bool set_value(Function_handle value);
// rset_value changes the variable to have the <value> in the opposite order
// to evaluate (back to front). Returns true if the variable is changed
// and false otherwise
virtual bool rset_value(Function_handle value);
// get_value creates a new Function which is the variable's value. The
// variable's function is not evaluated
virtual Function_handle get_value() const;
// returns a string the represents the variable
virtual string_handle get_string_representation()=0;
// for stepping through the atomic variables that make up the variable.
// Atomic variables are indivisible, that is, two atomic variables are
// either the same or disjoint. This is needed for determining the
// overlap between variables. Atomic variables are for a single function
virtual Function_variable_iterator begin_atomic() const=0;
virtual Function_variable_iterator end_atomic() const=0;
virtual std::reverse_iterator<Function_variable_iterator>
rbegin_atomic() const=0;
virtual std::reverse_iterator<Function_variable_iterator>
rend_atomic() const=0;
// returns the number of atomic variables that it makes sense to
// differentiate (output/dependent) or differentiate with respect to
// (input/independent)
virtual Function_size_type number_differentiable();
// the norm of the variable. A negative result means that the norm is not
// defined
virtual Scalar norm() const;
// a zero handle indicates an error. -= and += work in place. - and +
// create new Functions and return their output variables
virtual Function_variable_handle operator-(const Function_variable&) const;
virtual Function_variable_handle operator-=(const Function_variable&);
virtual Function_variable_handle operator+(const Function_variable&) const;
virtual Function_variable_handle operator+=(const Function_variable&);
public:
// for caching function evaluations:
// adds <dependent_function> to the list of functions that have to be
// re-evaluated if this variable's function(s) has/have to be re-evaluated
#if defined (CIRCULAR_SMART_POINTERS)
virtual void add_dependent_function(
const Function_handle dependent_function);
#else // defined (CIRCULAR_SMART_POINTERS)
virtual void add_dependent_function(
Function *dependent_function);
#endif // defined (CIRCULAR_SMART_POINTERS)
// removes <dependent_function> to the list of functions that have to be
// re-evaluated if this variable's function(s) has/have to be re-evaluated
#if defined (CIRCULAR_SMART_POINTERS)
virtual void remove_dependent_function(
const Function_handle dependent_function);
#else // defined (CIRCULAR_SMART_POINTERS)
virtual void remove_dependent_function(
Function *dependent_function);
#endif // defined (CIRCULAR_SMART_POINTERS)
private:
virtual bool equality_atomic(const Function_variable_handle&) const=0;
// equality operator. To be used in equivalent
virtual bool operator==(const Function_variable&) const;
protected:
// constructors. Protected so that can't create "plain" Function_variables
Function_variable(const Function_handle& function);
// copy constructor
Function_variable(const Function_variable&);
// destructor. Virtual for proper destruction of derived classes
virtual ~Function_variable();
private:
// copy operations are private and undefined to prevent copying
void operator=(const Function_variable&);
protected:
Function_handle function_private;
Function_variable_value_handle value_private;
private:
mutable int reference_count;
friend void intrusive_ptr_add_ref(Function_variable *);
friend void intrusive_ptr_release(Function_variable *);
};
#endif /* !defined (__FUNCTION_VARIABLE_HPP__) */
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* 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. *
**************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// Check basic detector results at ESD level //
// - Geometrical efficiency //
// - Tracking efficiency //
// - PID efficiency //
// - Refit efficiency //
// //
// Author //
// Alex Bercuci <A.Bercuci@gsi.de> //
// Ionut Arsene <i.c.arsene@gsi.de> //
// //
// The analysis task fills AliCFContainer objects defined in the //
// configuration macro using the AddCFContainer() method. //
// The CF containers can be filled with any of the variables defined //
// in ETrdCfVariables and at any of the steps defined in ETrdCfSteps. //
// To define a new variable one needs to: //
// 1. Add an entry in the ETrdCfVariables enumeration //
// 2. Add the corresponding variable name (and in the correct order) //
// in fgkVarNames //
// 3. Define how the variable is filled in one of the Fill functions: //
// FillEventInfo(), FillTrackInfo(), FillTrackletInfo(), //
// FillTrackletSliceInfo(). //
// To define a new step one needs to: //
// 1. Add an entry in the ETrdCfSteps //
// 2. Add the corresponding name in fgkStepNames //
// 3. Define the track level cuts for this step in IsTrackSelected() //
// //
//////////////////////////////////////////////////////////////////////////
#include <TClonesArray.h>
#include <TCanvas.h>
#include <TObjArray.h>
#include <TPad.h>
#include <TLegend.h>
#include <TLatex.h>
#include <TLine.h>
#include <TF1.h>
#include <TH1D.h>
#include <TH2D.h>
#include <TH3D.h>
#include <TH2I.h>
#include <TH2F.h>
#include <TH3S.h>
#include <TH3F.h>
#include <TProfile2D.h>
#include <TProfile.h>
#include <TGraphErrors.h>
#include <TGraphAsymmErrors.h>
#include <TFile.h>
#include <TTree.h>
#include <TROOT.h>
#include <TChain.h>
#include <TParticle.h>
#include <TTimeStamp.h>
#include <TRandom.h>
#include <TString.h>
#include "AliLog.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisCuts.h"
#include "AliPhysicsSelection.h"
#include "AliESDEvent.h"
#include "AliESDkink.h"
#include "AliMCEvent.h"
#include "AliESDInputHandler.h"
#include "AliMCEventHandler.h"
#include "AliESDpid.h"
#include "AliExternalTrackParam.h"
#include "AliESDtrack.h"
#include "AliMCParticle.h"
#include "AliPID.h"
#include "AliStack.h"
#include "AliTrackReference.h"
#include "AliMultiplicity.h"
#include "AliCFContainer.h"
#include "AliTRDcheckESD.h"
#include <iostream>
using std::cout;
using std::endl;
ClassImp(AliTRDcheckESD)
const Float_t AliTRDcheckESD::fgkxTPC = 290.;
const Float_t AliTRDcheckESD::fgkxTOF = 365.;
const Char_t* AliTRDcheckESD::fgkVarNames[AliTRDcheckESD::kNTrdCfVariables] = {
"vtxZ", "multiplicity", "trigger", "BC", "TOFBC", "DCAxy", "DCAz", "charge", "OuterParam rad.", "phiVtx", "phi",
"etaVtx", "eta", "pt", "ptTRD", "P", "PTRD", "TRDchi2", "tracklets", "clusters", "TrdQuality",
"TrdBudget", "TOFchi2", "Qtot0", "ClustersPerRows", "Clusters/tracklet", "TrdP", "TrdPloss", "layer", "slice", "PH0"
};
const Char_t* AliTRDcheckESD::fgkStepNames[AliTRDcheckESD::kNSteps] = {"TPC", "TRD", "TOF", "TOFin", "TOFout"};
FILE* AliTRDcheckESD::fgFile = NULL;
//____________________________________________________________________
AliTRDcheckESD::AliTRDcheckESD():
AliAnalysisTaskSE()
,fStatus(0)
,fNRefFigures(0)
,fESD(NULL)
,fMC(NULL)
,fESDpid(new AliESDpid)
,fHistos(NULL)
,fReferenceTrackFilter(NULL)
,fPhysSelTriggersEnabled(kFALSE)
,fUserEnabledTriggers("")
,fNAssignedTriggers(0)
{
//
// Default constructor
//
SetNameTitle("TRDcheckESD", "Check TRD @ ESD level");
SetMC(kTRUE);
}
//____________________________________________________________________
AliTRDcheckESD::AliTRDcheckESD(char* name):
AliAnalysisTaskSE(name)
,fStatus(0)
,fNRefFigures(0)
,fESD(NULL)
,fMC(NULL)
,fESDpid(new AliESDpid)
,fHistos(NULL)
,fReferenceTrackFilter(NULL)
,fPhysSelTriggersEnabled(kFALSE)
,fUserEnabledTriggers("")
,fNAssignedTriggers(0)
{
//
// Default constructor
//
SetMC(kTRUE);
SetTitle("Check TRD @ ESD level");
DefineOutput(1, TObjArray::Class());
}
//____________________________________________________________________
AliTRDcheckESD::~AliTRDcheckESD()
{
// Destructor
if(fHistos && !(AliAnalysisManager::GetAnalysisManager() && AliAnalysisManager::GetAnalysisManager()->IsProofMode())){
if(fHistos->IsOwner()) fHistos->Delete();
delete fHistos;
fHistos = NULL;
}
}
//____________________________________________________________________
void AliTRDcheckESD::FillEventInfo(Double_t* values) {
//
// Fill event information
//
values[kEventVtxZ] = fESD->GetPrimaryVertex()->GetZ();
values[kEventBC] = fESD->GetBunchCrossNumber();
const AliMultiplicity* mult=fESD->GetMultiplicity();
Double_t itsNTracklets = mult->GetNumberOfTracklets();
values[kEventMult] = itsNTracklets;
}
//____________________________________________________________________
void AliTRDcheckESD::FillTrackInfo(Double_t* values, AliESDtrack* esdTrack) {
//
// Fill track information
//
Float_t dcaxy,dcaz;
esdTrack->GetImpactParameters(dcaxy,dcaz);
values[kTrackDCAxy] = dcaxy;
values[kTrackDCAz] = dcaz;
values[kTrackCharge] = esdTrack->Charge();
values[kTrackPt] = esdTrack->Pt();
values[kTrackPhi] = esdTrack->Phi();
values[kTrackEta] = esdTrack->Eta();
values[kTrackP] = esdTrack->P();
values[kTrackTrdTracklets] = esdTrack->GetTRDntracklets();
values[kTrackTrdClusters] = esdTrack->GetTRDncls();
values[kTrackTrdChi2] = esdTrack->GetTRDchi2()/(esdTrack->GetTRDntracklets()>0 ? esdTrack->GetTRDntracklets() : 1.0);
values[kTrackTrdQuality] = esdTrack->GetTRDQuality();
values[kTrackTRDBudget] = -1.0*esdTrack->GetTRDBudget();
values[kTrackTOFBC] = esdTrack->GetTOFBunchCrossing(fESD->GetMagneticField());
values[kTrackTOFchi2] = esdTrack->GetTOFchi2();
const AliExternalTrackParam *out=esdTrack->GetOuterParam();
Double_t p[3];
if(out->GetXYZ(p))
values[kTrackOuterParamRadius] = TMath::Sqrt(p[0]*p[0]+p[1]*p[1]);
else
values[kTrackOuterParamRadius] = 0.0;
}
//____________________________________________________________________
void AliTRDcheckESD::FillTrackletInfo(Double_t* values, AliESDtrack* esdTrack, Int_t iPlane,
Double_t* localSagitaPhi, Double_t localMom[][3], Bool_t* localMomGood) {
//
// Fill TRD tracklet info
//
values[kTrackletClustersVsRows] = esdTrack->GetTRDtrkltClCross(iPlane);
values[kTrackletClusters] = esdTrack->GetTRDtrkltOccupancy(iPlane);
values[kTrackletQtot] = esdTrack->GetTRDslice(iPlane, 0);
values[kTrackletP] = esdTrack->GetTRDmomentum(iPlane);
values[kTrackPlossTRDlayer] = 1000.0*(esdTrack->P() - values[kTrackletP]); // p loss in MeV
values[kTrackletLayer] = iPlane;
values[kTrackPhiTRD] = localSagitaPhi[iPlane];
values[kTrackPtTRD] = (localMomGood[iPlane] ? TMath::Sqrt(localMom[iPlane][0]*localMom[iPlane][0]+
localMom[iPlane][1]*localMom[iPlane][1]) : values[kTrackPt]);
values[kTrackPTRD] = (localMomGood[iPlane] ? TMath::Sqrt(values[kTrackPtTRD]*values[kTrackPtTRD]+
localMom[iPlane][2]*localMom[iPlane][2]) : values[kTrackP]);
values[kTrackEtaTRD] = values[kTrackPTRD]-(localMomGood[iPlane] ? localMom[iPlane][2] : esdTrack->Pz());
values[kTrackEtaTRD] = (TMath::Abs(values[kTrackPTRD])>1.0e-8 ? (values[kTrackPTRD]+(localMomGood[iPlane] ? localMom[iPlane][2] : esdTrack->Pz()))/values[kTrackEtaTRD] : 0.0);
values[kTrackEtaTRD] = (values[kTrackEtaTRD]>1.0e-8 ? 0.5*TMath::Log(values[kTrackEtaTRD]) : -999.);
}
//____________________________________________________________________
void AliTRDcheckESD::FillTrackletSliceInfo(Double_t* values, AliESDtrack* esdTrack, Int_t iSlice) {
//
// Fill TRD tracklet info
//
values[kTrackletPHslice] = esdTrack->GetTRDslice(Int_t(values[kTrackletLayer]), iSlice);
values[kTrackletSlice] = iSlice;
}
//____________________________________________________________________
Bool_t AliTRDcheckESD::IsTrackSelected(AliESDtrack* track, Double_t* /*values*/, Int_t step) {
//
// Select tracks at each step
//
Bool_t referenceFilter = fReferenceTrackFilter->IsSelected(track);
if(step==kTPCreference) { // reference track filter
return referenceFilter;
}
if(step==kTRD) { // TRD reference track filter
return (referenceFilter && Int_t(track->GetTRDntracklets()>0));
}
if(step==kTOF) { // TRD+(TOFout || TOFpid) request
return (referenceFilter && Int_t(track->GetTRDntracklets())>0 &&
((track->GetStatus() & AliESDtrack::kTOFout) || (track->GetStatus() & AliESDtrack::kTOFpid)));
}
if(step==kTOFin) { // TOFin request
return (referenceFilter && (track->GetStatus() & AliESDtrack::kTOFin));
}
if(step==kTOFout) { // TOFout request
return (referenceFilter && (track->GetStatus() & AliESDtrack::kTOFout));
}
return kFALSE;
}
//____________________________________________________________________
void AliTRDcheckESD::UserCreateOutputObjects()
{
//
// Create Output Containers (TObjectArray containing 1D histograms)
//
Histos();
PostData(1, fHistos);
}
//____________________________________________________________________
void AliTRDcheckESD::MakeSummaryFromCF(Double_t* trendValues, const Char_t* /*triggerName*/, Bool_t /*useIsolatedBC*/, Bool_t /*cutTOFbc*/){
//
// Draw summary plots for the ESDcheck task using the CF container
//
cout << "Make summary from CF" << endl;
TCanvas *cOut=0x0;
if(gROOT->FindObject("trackingSummary")) delete gROOT->FindObject("trackingSummary");
cOut = new TCanvas("trackingSummary", "Tracking summary for the ESD task", 1600, 1200);
cOut->cd();
//PlotTrackingSummaryFromCF(trendValues, triggerName, useIsolatedBC, cutTOFbc);
PlotTrackingSummaryFromCF(trendValues);
cOut->SaveAs("trackingSummary.gif");
if(gROOT->FindObject("pidSummary")) delete gROOT->FindObject("pidSummary");
cOut = new TCanvas("pidSummary", "PID summary for the ESD task", 1600, 1200);
cOut->cd();
//PlotPidSummaryFromCF(trendValues, triggerName, useIsolatedBC, cutTOFbc);
PlotPidSummaryFromCF(trendValues);
cOut->SaveAs("pidSummary.gif");
if(gROOT->FindObject("centSummary")) delete gROOT->FindObject("centSummary");
cOut = new TCanvas("centSummary", "Centrality summary for the ESD task", 1600, 1200);
cOut->cd();
//PlotCentSummaryFromCF(trendValues, triggerName, useIsolatedBC, cutTOFbc);
PlotCentSummaryFromCF(trendValues);
cOut->SaveAs("centSummary.gif");
PlotOtherSummaryFromCF(trendValues);
if(trendValues)
for(Int_t i=0;i<50;++i) cout << "trend #" << i << " :: " << trendValues[i] << endl;
}
//____________________________________________________________________
void AliTRDcheckESD::UserExec(Option_t *){
//
// Run the Analysis
//
fESD = dynamic_cast<AliESDEvent*>(InputEvent());
fMC = MCEvent();
if(!fESD){
AliError("ESD event missing.");
return;
}
AliAnalysisManager *man=AliAnalysisManager::GetAnalysisManager();
AliInputEventHandler* inputHandler = (AliInputEventHandler*) (man->GetInputEventHandler());
if(!inputHandler) return;
if(!fPhysSelTriggersEnabled) {
InitializeCFContainers();
fPhysSelTriggersEnabled = kTRUE;
}
UInt_t isSelected = AliVEvent::kAny;
if(inputHandler){
if(inputHandler->GetEventSelection()) {
isSelected = inputHandler->IsEventSelected();
}
}
if(!isSelected) return;
TString triggerClasses = fESD->GetFiredTriggerClasses();
//cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++triggers fired: " << triggerClasses.Data() << endl;
TObjArray* triggers = triggerClasses.Tokenize(" ");
TObjArray* userTriggers = fUserEnabledTriggers.Tokenize(";");
if(triggers->GetEntries()<1) {delete triggers; delete userTriggers; return;}
Bool_t hasGoodTriggers = kFALSE;
Int_t triggerIndices[kNMaxAssignedTriggers] = {0};
Int_t nTrigFired=0;
Bool_t trigAlreadyChecked = kFALSE;
Bool_t trigSelected = kFALSE;
Int_t trigIdx = 0;
for(Int_t i=0; i<triggers->GetEntries(); ++i) {
TString trigStr=triggers->At(i)->GetName();
if(!trigStr.Contains("NOTRD") && !trigStr.Contains("MUON")) hasGoodTriggers = kTRUE; // check wheter TRD was read out in this event
if(trigStr.Contains("NOTRD")) continue;
if(trigStr.Contains("MUON")) continue;
if(i>=kNMaxAssignedTriggers) continue;
hasGoodTriggers = kTRUE;
// enable the "All triggers" bit
trigIdx = 1;
trigAlreadyChecked = kFALSE;
for(Int_t k=0;k<nTrigFired;++k)
if(triggerIndices[k]==trigIdx) {
trigAlreadyChecked = kTRUE;
break;
}
if(!trigAlreadyChecked) triggerIndices[nTrigFired++] = trigIdx;
trigSelected = kFALSE;
// check whether this trigger matches any of the user defined trigger families
for(Int_t j=0;j<userTriggers->GetEntries();++j) {
TString userTrigStr=userTriggers->At(j)->GetName();
if(trigStr.Contains(userTrigStr.Data())) {
trigSelected = kTRUE;
trigIdx = GetTriggerIndex(userTrigStr.Data(), kFALSE);
trigAlreadyChecked = kFALSE;
for(Int_t k=0;k<nTrigFired;++k)
if(triggerIndices[k]==trigIdx) {
trigAlreadyChecked = kTRUE;
break;
}
if(!trigAlreadyChecked) { // add trigger to the list of enabled triggers only if it was not added already
triggerIndices[nTrigFired++] = trigIdx;
}
}
}
trigIdx = GetTriggerIndex(trigStr.Data(), kFALSE);
if(trigIdx>0) trigSelected = kTRUE;
if(trigIdx==-1) trigIdx=1;
trigAlreadyChecked = kFALSE;
for(Int_t k=0;k<nTrigFired;++k)
if(triggerIndices[k]==trigIdx) {
trigAlreadyChecked = kTRUE;
break;
}
if(!trigAlreadyChecked) {
triggerIndices[nTrigFired++]=1; // 0-assigned to all other triggers
}
} // end loop over triggers
if(!trigSelected && hasGoodTriggers) {
triggerIndices[nTrigFired++]=2;
}
TH1F* hTrig = (TH1F*)fHistos->FindObject("hTriggerDefs");
for(Int_t i=0; i<nTrigFired; ++i)
hTrig->Fill(triggerIndices[i]);
if(!hasGoodTriggers) {
PostData(1, fHistos);
delete triggers;
delete userTriggers;
return;
}
Int_t* trigFiredIdx=new Int_t[nTrigFired];
for(Int_t i=0;i<nTrigFired;++i) trigFiredIdx[i] = triggerIndices[i];
// Get MC information if available
//AliStack * fStack = NULL;
if(HasMC()){
if(!fMC){
AliWarning("MC event missing");
SetMC(kFALSE);
} else {
if(!fMC->Stack()){
AliWarning("MC stack missing");
SetMC(kFALSE);
}
}
}
Double_t values[kNTrdCfVariables]; // array where the CF container variables are stored
for(Int_t i=0;i<kNTrdCfVariables; ++i) values[i] = -999.;
FillEventInfo(values);
Int_t multLimits[6] = {0, 700, 1400, 2100, 2800, 3500};
Int_t centralityClass = 0;
for(Int_t iCent=0; iCent<5; ++iCent) {
if(values[kEventMult]>=multLimits[iCent] && values[kEventMult]<multLimits[iCent+1])
centralityClass=iCent+1;
}
if(centralityClass == 0) return;
// radius of TRD entrance plane in each layer
Double_t rTRD[6] = {298.0, 311.0, 324.0, 337.0, 350.0, 363.0};
AliESDtrack *esdTrack(NULL);
for(Int_t itrk = 0; itrk < fESD->GetNumberOfTracks(); itrk++){
esdTrack = fESD->GetTrack(itrk);
Bool_t stepSelections[kNSteps];
for(Int_t is=0;is<kNSteps;++is) {
stepSelections[is] = IsTrackSelected(esdTrack, values, is);
}
if(!stepSelections[0]) continue;
FillTrackInfo(values, esdTrack);
// find position and momentum of the track at entrance in TRD
const AliExternalTrackParam *outerParam = esdTrack->GetOuterParam();
Double_t localCoord[6][3] = {{0.0}};
Bool_t localCoordGood[6];
for(Int_t il=0;il<6;++il)
localCoordGood[il] = (outerParam ? outerParam : esdTrack)->GetXYZAt(rTRD[il], fESD->GetMagneticField(), localCoord[il]);
Double_t localMom[6][3] = {{0.0}};
Bool_t localMomGood[6];
for(Int_t il=0; il<6; ++il)
localMomGood[il] = (outerParam ? outerParam : esdTrack)->GetPxPyPzAt(rTRD[il], fESD->GetMagneticField(), localMom[il]);
Double_t localSagitaPhi[6] = {-999.};
for(Int_t il=0; il<6; ++il)
localSagitaPhi[il] = (localCoordGood[il] ? TMath::ATan2(localCoord[il][1], localCoord[il][0]) : -999.);
if(!localMomGood[0]) continue;
// fill tracklet values such that the TRD local coordinates are filled
FillTrackletInfo(values, esdTrack, 0, localSagitaPhi, localMom, localMomGood);
for(Int_t itrig=0; itrig<nTrigFired; ++itrig) {
values[kEventTrigger] = Double_t(trigFiredIdx[itrig]);
// check if cf needs tracklet or slice info
FillGlobalTrackContainers(values, stepSelections, itrig);
for(Int_t iPlane=0; iPlane<6; iPlane++) {
FillTrackletInfo(values, esdTrack, iPlane, localSagitaPhi, localMom, localMomGood);
if(values[kTrackletQtot]>20.0) FillTrdTrackletContainers(values, stepSelections, itrig);
for(Int_t iSlice=0; iSlice<8; iSlice++) {
FillTrackletSliceInfo(values, esdTrack, iSlice);
if(values[kTrackletPHslice]>20.0) FillTrdSliceContainers(values, stepSelections, itrig);
} // end loop over slices
} // end loop over TRD layers
} // end loop over triggers
} // end loop over tracks
delete triggers;
delete userTriggers;
delete [] trigFiredIdx;
PostData(1, fHistos);
}
//____________________________________________________________________
TObjArray* AliTRDcheckESD::Histos()
{
// Retrieve histograms array if already build or build it
if(!fHistos) {
fHistos = new TObjArray();
fHistos->SetOwner(kTRUE);
}
TH1* h = 0x0;
// Trigger definitions
if(!(h=(TH1F*)gROOT->FindObject("hTriggerDefs"))) {
h = new TH1F("hTriggerDefs", "Trigger definitions", kNMaxAssignedTriggers, 0.5, 0.5+Float_t(kNMaxAssignedTriggers));
}
else h->Reset();
fHistos->Add(h);
return fHistos;
}
//__________________________________________________________________________________________________________
void AliTRDcheckESD::InitializeCFContainers() {
//
// Initialize the CF container
//
AliAnalysisManager* man=AliAnalysisManager::GetAnalysisManager();
AliInputEventHandler* inputHandler = (AliInputEventHandler*) (man->GetInputEventHandler());
if(!inputHandler) return;
GetTriggerIndex("All triggers", kTRUE);
GetTriggerIndex("Not specified triggers", kTRUE);
AliPhysicsSelection* physSel = (AliPhysicsSelection*)inputHandler->GetEventSelection();
const TList* trigList = (physSel ? physSel->GetCollisionTriggerClasses() : 0x0);
const TList* bgTrigList = (physSel ? physSel->GetBGTriggerClasses() : 0x0);
// Add collision triggers from PhysicsSelection
if(trigList) {
for(Int_t it=0; it<trigList->GetEntries(); ++it) {
TString trigName = trigList->At(it)->GetName();
TObjArray* arr = trigName.Tokenize(" ");
trigName = arr->At(0)->GetName();
trigName.Remove(0,1);
TObjArray* arr2 = trigName.Tokenize(",");
for(Int_t jt=0; jt<arr2->GetEntries(); ++jt) {
// Assign an index into the trigger histogram and the CF container for this trigger
GetTriggerIndex(arr2->At(jt)->GetName(), kTRUE);
}
delete arr;
}
}
// Add background triggers from PhysicsSelection
if(bgTrigList) {
for(Int_t it=0; it<bgTrigList->GetEntries(); ++it) {
TString trigName = bgTrigList->At(it)->GetName();
TObjArray* arr = trigName.Tokenize(" ");
trigName = arr->At(0)->GetName();
trigName.Remove(0,1);
TObjArray* arr2 = trigName.Tokenize(",");
for(Int_t jt=0; jt<arr2->GetEntries(); ++jt) {
// Assign an index into the trigger histogram and the CF container for this trigger
GetTriggerIndex(arr2->At(jt)->GetName(), kTRUE);
}
delete arr;
}
}
// Add user enabled triggers
TObjArray* arr = fUserEnabledTriggers.Tokenize(";");
for(Int_t it=0; it<arr->GetEntries(); ++it) {
GetTriggerIndex(arr->At(it)->GetName(), kTRUE);
}
delete arr;
}
//__________________________________________________________________________________________________________
void AliTRDcheckESD::AddCFContainer(const Char_t* name, const Char_t* title,
Int_t nSteps, Int_t* steps,
Int_t nVars, UInt_t* vars, TArrayD* binLimits) {
//
// Add a CF container
//
if(!fHistos) {
fHistos = new TObjArray();
fHistos->SetOwner(kTRUE);
}
// get number of bins for each variable
Int_t* nBins = new Int_t[nVars];
for(Int_t iv=0;iv<nVars;++iv)
nBins[iv] = binLimits[iv].GetSize()-1;
// create the CF container
AliCFContainer* cf = new AliCFContainer(name, title, nSteps, nVars, nBins);
// set CF container variable binning and name
for(Int_t iv=0;iv<nVars;++iv) {
cf->SetBinLimits(iv, binLimits[iv].GetArray());
cf->SetVarTitle(iv, fgkVarNames[vars[iv]]);
}
// set the step names
for(Int_t is=0; is<nSteps; ++is) {
cf->SetStepTitle(is, fgkStepNames[steps[is]]);
for(Int_t iv=0;iv<nVars;++iv) cf->GetAxis(iv, is)->SetUniqueID(vars[iv]);
}
fHistos->Add(cf);
}
//__________________________________________________________________________________________________
void AliTRDcheckESD::FillTrdSliceContainers(Double_t* values, Bool_t* stepSelections, Int_t itrig) {
//
// fill TRD slice info
//
if(!fHistos) return;
for(Int_t i=0;i<fHistos->GetEntries();++i) {
TString objType = fHistos->At(i)->IsA()->GetName();
if(!objType.Contains("AliCFContainer")) continue;
AliCFContainer* cf = (AliCFContainer*)fHistos->At(i);
TString varNames="";
for(Int_t ivar=0;ivar<cf->GetNVar();++ivar) {
varNames += cf->GetVarTitle(ivar); varNames += ";";
}
//if(cf->GetVar(fgkVarNames[kTrackletSlice])<0 && cf->GetVar(fgkVarNames[kTrackletPHslice])<0) continue;
if(!varNames.Contains(fgkVarNames[kTrackletSlice]) && !varNames.Contains(fgkVarNames[kTrackletPHslice])) continue;
//if((cf->GetVar(fgkVarNames[kEventTrigger])<0 && itrig==0) || (cf->GetVar(fgkVarNames[kEventTrigger])>=0))
if((!varNames.Contains(fgkVarNames[kEventTrigger]) && itrig==0) || varNames.Contains(fgkVarNames[kEventTrigger]))
FillCFContainer(cf, values, stepSelections);
}
}
//__________________________________________________________________________________________________
void AliTRDcheckESD::FillTrdTrackletContainers(Double_t* values, Bool_t* stepSelections, Int_t itrig) {
//
// fill global track info
//
if(!fHistos) return;
for(Int_t i=0;i<fHistos->GetEntries();++i) {
TString objType = fHistos->At(i)->IsA()->GetName();
if(!objType.Contains("AliCFContainer")) continue;
AliCFContainer* cf = (AliCFContainer*)fHistos->At(i);
TString varNames="";
for(Int_t ivar=0;ivar<cf->GetNVar();++ivar) {
varNames += cf->GetVarTitle(ivar); varNames += ";";
}
//if(cf->GetVar(fgkVarNames[kTrackletSlice])>=0 || cf->GetVar(fgkVarNames[kTrackletPHslice])>=0) continue;
if(varNames.Contains(fgkVarNames[kTrackletSlice]) || varNames.Contains(fgkVarNames[kTrackletPHslice])) continue;
//if(cf->GetVar(fgkVarNames[kTrackletLayer])<0 && cf->GetVar(fgkVarNames[kTrackletQtot])<0) continue;
if(!varNames.Contains(fgkVarNames[kTrackletLayer]) && !varNames.Contains(fgkVarNames[kTrackletQtot])) continue;
//if((cf->GetVar(fgkVarNames[kEventTrigger])<0 && itrig==0) || (cf->GetVar(fgkVarNames[kEventTrigger])>=0))
if((!varNames.Contains(fgkVarNames[kEventTrigger]) && itrig==0) || varNames.Contains(fgkVarNames[kEventTrigger]))
FillCFContainer(cf, values, stepSelections);
}
}
//__________________________________________________________________________________________________
void AliTRDcheckESD::FillGlobalTrackContainers(Double_t* values, Bool_t* stepSelections, Int_t itrig) {
//
// fill global track info
//
if(!fHistos) return;
for(Int_t i=0;i<fHistos->GetEntries();++i) {
TString objType = fHistos->At(i)->IsA()->GetName();
if(!objType.Contains("AliCFContainer")) continue;
AliCFContainer* cf = (AliCFContainer*)fHistos->At(i);
TString varNames="";
for(Int_t ivar=0;ivar<cf->GetNVar();++ivar) {
varNames += cf->GetVarTitle(ivar); varNames += ";";
}
/*if(cf->GetVar(fgkVarNames[kTrackletLayer])>=0 ||
cf->GetVar(fgkVarNames[kTrackletSlice])>=0 ||
cf->GetVar(fgkVarNames[kTrackletQtot])>=0 ||
cf->GetVar(fgkVarNames[kTrackletPHslice])>=0) continue;*/
if(varNames.Contains(fgkVarNames[kTrackletLayer]) ||
varNames.Contains(fgkVarNames[kTrackletSlice]) ||
varNames.Contains(fgkVarNames[kTrackletQtot]) ||
varNames.Contains(fgkVarNames[kTrackletPHslice])) continue;
/*if((cf->GetVar(fgkVarNames[kEventTrigger])<0 && itrig==0) ||
(cf->GetVar(fgkVarNames[kEventTrigger])>=0))*/
if((!varNames.Contains(fgkVarNames[kEventTrigger]) && itrig==0) ||
varNames.Contains(fgkVarNames[kEventTrigger]))
FillCFContainer(cf, values, stepSelections);
}
}
//__________________________________________________________________________________________________
void AliTRDcheckESD::FillCFContainer(AliCFContainer* cf, Double_t* values, Bool_t* stepSelections) {
//
// Fill CF container
//
Double_t* cfValues=new Double_t[cf->GetNVar()];
for(Int_t iv=0;iv<cf->GetNVar();++iv)
cfValues[iv] = values[cf->GetAxis(iv,0)->GetUniqueID()];
for(Int_t istep=0; istep<cf->GetNStep(); ++istep) {
TString stepTitle = cf->GetStepTitle(istep);
Int_t stepNo = -1;
for(Int_t is=0;is<kNSteps;++is)
if(!stepTitle.CompareTo(fgkStepNames[is])) {
stepNo = is;
break;
}
if(stepSelections[stepNo]) cf->Fill(cfValues, istep);
} // end loop over steps
delete [] cfValues;
}
//____________________________________________________________________
Bool_t AliTRDcheckESD::Load(const Char_t *file, const Char_t *dir, const Char_t *name)
{
//
// Load data from performance file
//
if(!TFile::Open(file)){
AliWarning(Form("Couldn't open file %s.", file));
return kFALSE;
}
if(dir){
if(!gFile->cd(dir)){
AliWarning(Form("Couldn't cd to %s in %s.", dir, file));
return kFALSE;
}
}
TObjArray *o(NULL);
const Char_t *tn=(name ? name : GetName());
if(!(o = (TObjArray*)gDirectory->Get(tn))){
AliWarning(Form("Missing histogram container %s.", tn));
return kFALSE;
}
fHistos = (TObjArray*)o->Clone(GetName());
TH1F* trigHist = (TH1F*)fHistos->FindObject("hTriggerDefs");
for(Int_t i=1;i<=trigHist->GetXaxis()->GetNbins();++i) {
if(trigHist->GetXaxis()->GetBinLabel(i)[0]!='\0') ++fNAssignedTriggers;
}
gFile->Close();
return kTRUE;
}
//_______________________________________________________
Bool_t AliTRDcheckESD::PutTrendValue(const Char_t *name, Double_t val)
{
// Dump trending value to default file
if(!fgFile){
fgFile = fopen("TRD.Performance.txt", "at");
}
fprintf(fgFile, "%s_%s %f\n", GetName(), name, val);
return kTRUE;
}
//____________________________________________________________________
void AliTRDcheckESD::Terminate(Option_t *)
{
// Steer post-processing
if(!fHistos){
fHistos = dynamic_cast<TObjArray *>(GetOutputData(1));
if(!fHistos){
AliError("Histogram container not found in output");
return;
}
}
}
//____________________________________________________________________
Int_t AliTRDcheckESD::Pdg2Idx(Int_t pdg) const
{
//
// Helper function converting PDG code into AliPID index
//
switch(pdg){
case kElectron:
case kPositron: return AliPID::kElectron;
case kMuonPlus:
case kMuonMinus: return AliPID::kMuon;
case kPiPlus:
case kPiMinus: return AliPID::kPion;
case kKPlus:
case kKMinus: return AliPID::kKaon;
case kProton:
case kProtonBar: return AliPID::kProton;
}
return -1;
}
//________________________________________________________
void AliTRDcheckESD::Process2D(TH2 * const h2, TGraphErrors **g)
{
//
// Do the processing
//
Int_t n = 0;
if((n=g[0]->GetN())) for(;n--;) g[0]->RemovePoint(n);
if((n=g[1]->GetN())) for(;n--;) g[1]->RemovePoint(n);
TF1 f("fg", "gaus", -3.,3.);
for(Int_t ibin = 1; ibin <= h2->GetNbinsX(); ibin++){
Double_t x = h2->GetXaxis()->GetBinCenter(ibin);
TH1D *h = h2->ProjectionY("py", ibin, ibin);
if(h->GetEntries()<100) continue;
//AdjustF1(h, f);
h->Fit(&f, "QN");
Int_t ip = g[0]->GetN();
g[0]->SetPoint(ip, x, f.GetParameter(1));
g[0]->SetPointError(ip, 0., f.GetParError(1));
g[1]->SetPoint(ip, x, f.GetParameter(2));
g[1]->SetPointError(ip, 0., f.GetParError(2));
}
return;
}
//____________________________________________________________________
void AliTRDcheckESD::PrintStatus(ULong_t status)
{
// Dump track status to stdout
printf("ITS[i(%d) o(%d) r(%d)] TPC[i(%d) o(%d) r(%d) p(%d)] TRD[i(%d) o(%d) r(%d) p(%d) s(%d)] HMPID[o(%d) p(%d)]\n"
,Bool_t(status & AliESDtrack::kITSin)
,Bool_t(status & AliESDtrack::kITSout)
,Bool_t(status & AliESDtrack::kITSrefit)
,Bool_t(status & AliESDtrack::kTPCin)
,Bool_t(status & AliESDtrack::kTPCout)
,Bool_t(status & AliESDtrack::kTPCrefit)
,Bool_t(status & AliESDtrack::kTPCpid)
,Bool_t(status & AliESDtrack::kTRDin)
,Bool_t(status & AliESDtrack::kTRDout)
,Bool_t(status & AliESDtrack::kTRDrefit)
,Bool_t(status & AliESDtrack::kTRDpid)
,Bool_t(status & AliESDtrack::kTRDStop)
,Bool_t(status & AliESDtrack::kHMPIDout)
,Bool_t(status & AliESDtrack::kHMPIDpid)
);
}
//____________________________________________________________________
TH1D* AliTRDcheckESD::Proj2D(TH2* hist, TH1* mpvErr, TH1* widthErr, TH1* chi2) {
//
// project the PH vs Slice 2D-histo into a 1D histo with Landau MPV and widths
//
TH1D* hProjection = (TH1D*)hist->ProjectionX(Form("hProjection_%f", gRandom->Rndm()));
hProjection->Reset();
TF1* fitLandau = new TF1("landauFunc","landau",20.,3000.);
TH1D *hD;
for(Int_t iBin=1;iBin<=hist->GetXaxis()->GetNbins();iBin++) {
if(gROOT->FindObject("projection"))
delete gROOT->FindObject("projection");
hD = (TH1D*)hist->ProjectionY("projection",iBin,iBin);
//hD->Rebin(4);
if(hD->Integral()>10) {
fitLandau->SetParameter(1, hD->GetBinCenter(hD->GetMaximumBin()));
fitLandau->SetParLimits(1, 0.2*hD->GetBinCenter(hD->GetMaximumBin()), 3.0*hD->GetBinCenter(hD->GetMaximumBin()));
fitLandau->SetParameter(0, 1000.);
fitLandau->SetParLimits(0, 1., 10000000.);
fitLandau->SetParameter(2, 0.5*hD->GetBinCenter(hD->GetMaximumBin()));
fitLandau->SetParLimits(2, 0.01*hD->GetBinCenter(hD->GetMaximumBin()), 1.0*hD->GetRMS());
hD->Fit(fitLandau, "Q0", "", hD->GetXaxis()->GetXmin(), hD->GetXaxis()->GetXmax());
hD->Fit(fitLandau, "Q0", "", hD->GetXaxis()->GetXmin(), hD->GetXaxis()->GetXmax());
hProjection->SetBinContent(iBin, fitLandau->GetParameter(1));
hProjection->SetBinError(iBin, fitLandau->GetParameter(2));
if(mpvErr) {
mpvErr->SetBinContent(iBin, fitLandau->GetParameter(1));
mpvErr->SetBinError(iBin, fitLandau->GetParError(1));
}
if(widthErr) {
widthErr->SetBinContent(iBin, fitLandau->GetParameter(2));
widthErr->SetBinError(iBin, fitLandau->GetParError(2));
}
if(chi2) {
chi2->SetBinContent(iBin, (fitLandau->GetNDF()>0 ? fitLandau->GetChisquare()/Double_t(fitLandau->GetNDF()) : 0.0));
}
}
else{
hProjection->SetBinContent(iBin, 0);
hProjection->SetBinError(iBin, 0);
}
}
return hProjection;
}
//____________________________________________________________________
TH2F* AliTRDcheckESD::Proj3D(TH3* hist, TH2* accMap, Int_t zbinLow, Int_t zbinHigh, Float_t &entries) {
//
// Project a 3D histogram to a 2D histogram in the Z axis interval [zbinLow,zbinHigh]
// Return the 2D histogram and also the number of entries into this projection (entries)
Int_t nBinsX = hist->GetXaxis()->GetNbins(); // X and Y axis bins are assumed to be all equal
Float_t minX = hist->GetXaxis()->GetXmin();
Float_t maxX = hist->GetXaxis()->GetXmax();
Int_t nBinsY = hist->GetYaxis()->GetNbins();
Float_t minY = hist->GetYaxis()->GetXmin();
Float_t maxY = hist->GetYaxis()->GetXmax();
Int_t nBinsZ = hist->GetZaxis()->GetNbins(); // Z axis bins (pt) might have different widths
TH2F* projHisto = (TH2F*)gROOT->FindObject("projHisto");
if(projHisto)
projHisto->Reset();
else
projHisto = new TH2F("projHisto", "projection", nBinsX, minX, maxX, nBinsY, minY, maxY);
for(Int_t iZ=1; iZ<=nBinsZ; iZ++) {
if(iZ<zbinLow) continue;
if(iZ>zbinHigh) continue;
for(Int_t iX=1; iX<=nBinsX; iX++) {
for(Int_t iY=1; iY<=nBinsY; iY++) {
if(accMap) {
if(accMap->GetBinContent(iX,iY)>0.1)
projHisto->SetBinContent(iX, iY, projHisto->GetBinContent(iX, iY)+hist->GetBinContent(iX,iY,iZ));
}
else // no acc. cut
projHisto->SetBinContent(iX, iY, projHisto->GetBinContent(iX, iY)+hist->GetBinContent(iX,iY,iZ));
// count only the entries which are inside the acceptance map
if(accMap) {
if(accMap->GetBinContent(iX,iY)>0.1)
entries+=hist->GetBinContent(iX,iY,iZ);
}
else // no acc. cut
entries+=hist->GetBinContent(iX,iY,iZ);
}
}
}
return projHisto;
}
//____________________________________________________________________
void AliTRDcheckESD::CheckActiveSM(TH1D* phiProj, Bool_t activeSM[18]) {
//
// Check the active super-modules
//
Double_t entries[18] = {0.0};
Double_t smPhiLimits[19];
for(Int_t ism=0; ism<=18; ++ism) smPhiLimits[ism] = -TMath::Pi() + (2.0*TMath::Pi()/18.0)*ism;
for(Int_t phiBin=1; phiBin<=phiProj->GetXaxis()->GetNbins(); ++phiBin) {
Double_t phi = phiProj->GetBinCenter(phiBin);
Int_t sm = -1;
for(Int_t ism=0; ism<18; ++ism)
if(phi>=smPhiLimits[ism] && phi<smPhiLimits[ism+1]) sm = ism;
if(sm==-1) continue;
entries[sm] += phiProj->GetBinContent(phiBin);
}
Double_t avEntries = Double_t(phiProj->Integral())/18.0;
for(Int_t ism=0; ism<18; ++ism)
if(entries[ism]>0.5*avEntries) activeSM[ism] = kTRUE;
}
//__________________________________________________________________________________________________
TH1F* AliTRDcheckESD::EfficiencyFromPhiPt(AliCFContainer* cf, Int_t minNtrkl, Int_t maxNtrkl,
Int_t stepNom, Int_t stepDenom, Int_t var) {
//
// Use the CF container to extract the efficiency vs pt (other variables beside pt also posible)
//
Int_t varTrackPhi = cf->GetVar(fgkVarNames[kTrackPhiTRD]);
Int_t otherVar = cf->GetVar(fgkVarNames[var]);
Int_t trdStepNumber = cf->GetStep(fgkStepNames[kTRD]);
Int_t tpcStepNumber = cf->GetStep(fgkStepNames[kTPCreference]);
TH1D* phiProj = (TH1D*)cf->Project(trdStepNumber, varTrackPhi);
Bool_t activeSM[18] = {kFALSE};
CheckActiveSM(phiProj, activeSM); delete phiProj;
Double_t smPhiLimits[19];
for(Int_t ism=0; ism<=18; ++ism) smPhiLimits[ism] = -TMath::Pi() + (2.0*TMath::Pi()/18.0)*ism;
TH2D* hNomPhiVar=0x0;
TH2D* hDenomPhiVar=0x0;
if((stepNom!=tpcStepNumber) &&
(minNtrkl>-1 && minNtrkl<7 && maxNtrkl>-1 && maxNtrkl<7)) {
cf->SetRangeUser(cf->GetVar(fgkVarNames[kTrackTrdTracklets]), Double_t(minNtrkl), Double_t(maxNtrkl));
hNomPhiVar = (TH2D*)cf->Project(stepNom, otherVar, varTrackPhi);
cf->SetRangeUser(cf->GetVar(fgkVarNames[kTrackTrdTracklets]), 0.0,6.0);
}
else
hNomPhiVar = (TH2D*)cf->Project(stepNom, otherVar, varTrackPhi);
if((stepDenom!=tpcStepNumber) &&
(minNtrkl>-1 && minNtrkl<7 && maxNtrkl>-1 && maxNtrkl<7)) {
cf->SetRangeUser(cf->GetVar(fgkVarNames[kTrackTrdTracklets]), Double_t(minNtrkl), Double_t(maxNtrkl));
hDenomPhiVar = (TH2D*)cf->Project(stepDenom, otherVar, varTrackPhi);
cf->SetRangeUser(cf->GetVar(fgkVarNames[kTrackTrdTracklets]), 0.0,6.0);
}
else
hDenomPhiVar = (TH2D*)cf->Project(stepDenom, otherVar, varTrackPhi);
TH1F* hEff = new TH1F(Form("hEff%s_%d_%d_%f", fgkVarNames[var], stepNom, stepDenom, gRandom->Rndm()), "",
hNomPhiVar->GetXaxis()->GetNbins(), hNomPhiVar->GetXaxis()->GetXbins()->GetArray());
for(Int_t ib=1;ib<=hNomPhiVar->GetXaxis()->GetNbins();++ib)
hEff->GetXaxis()->SetBinLabel(ib, hNomPhiVar->GetXaxis()->GetBinLabel(ib));
for(Int_t ivar=1; ivar<=hEff->GetXaxis()->GetNbins(); ++ivar) {
Double_t nom = 0.0; Double_t denom = 0.0;
Double_t eff = 0.0; Double_t err = 0.0;
for(Int_t iphi=1; iphi<=hNomPhiVar->GetYaxis()->GetNbins(); ++iphi) {
Double_t phi = hNomPhiVar->GetYaxis()->GetBinCenter(iphi);
Bool_t isActive = kFALSE;
for(Int_t ism=0; ism<18; ++ism)
if(phi>=smPhiLimits[ism] && phi<smPhiLimits[ism+1] && activeSM[ism])
isActive = kTRUE;
if(!isActive) continue;
nom += hNomPhiVar->GetBinContent(ivar, iphi);
denom += hDenomPhiVar->GetBinContent(ivar, iphi);
}
eff = (denom>0.001 ? nom/denom : 0.0);
err = (denom>0.001 && (denom-nom)>0.001 && nom>0.001 ? (TMath::Sqrt(nom*(denom-nom)/denom/denom/denom)) : 0.0);
hEff->SetBinContent(ivar, eff);
hEff->SetBinError(ivar, err);
} // end loop over pt bins
delete hNomPhiVar; delete hDenomPhiVar;
return hEff;
}
//____________________________________________________________________
TH1F* AliTRDcheckESD::EfficiencyTRD(TH3* tpc3D, TH3* trd3D, Bool_t useAcceptance) {
//
// Calculate the TRD-TPC matching efficiency as function of pt
//
if(!tpc3D || !trd3D) return NULL;
Int_t nBinsZ = trd3D->GetZaxis()->GetNbins();
// project everything on the eta-phi map to obtain an acceptance map
Float_t nada = 0.;
TH2F *trdAcc = (useAcceptance ? (TH2F*)Proj3D(trd3D, 0x0, 1, nBinsZ, nada)->Clone(Form("trdAcc%f", gRandom->Rndm())) : 0x0);
TH1D *phiProj = (trdAcc ? trdAcc->ProjectionY(Form("phiProj%f", gRandom->Rndm())) : 0x0);
// prepare the acceptance map
Bool_t activeSM[18] = {kFALSE};
Double_t smPhiLimits[19];
for(Int_t ism=0; ism<=18; ++ism) smPhiLimits[ism] = -TMath::Pi() + (2.0*TMath::Pi()/18.0)*ism;
if(phiProj) {
CheckActiveSM(phiProj, activeSM); // get the active SMs
trdAcc->Reset();
// Put 1 entry in every bin which belongs to an active SM
for(Int_t iY=1; iY<=trdAcc->GetYaxis()->GetNbins(); ++iY) {
Double_t phi = trdAcc->GetYaxis()->GetBinCenter(iY);
Bool_t isActive = kFALSE;
for(Int_t ism=0; ism<18; ++ism) {
if(phi>=smPhiLimits[ism] && phi<smPhiLimits[ism+1] && activeSM[ism]) {
isActive = kTRUE;
}
}
if(!isActive) continue;
for(Int_t iX=1; iX<=trdAcc->GetXaxis()->GetNbins(); ++iX)
if(trdAcc->GetXaxis()->GetBinCenter(iX)>=-0.85 && trdAcc->GetXaxis()->GetBinCenter(iX)<=0.85) trdAcc->SetBinContent(iX, iY, 1.0);
} // end for over Y(phi) bins
} // end if phiProj
// get the bin limits from the Z axis of 3D histos
Float_t *ptBinLimits = new Float_t[nBinsZ+1];
for(Int_t i=1; i<=nBinsZ; i++) {
ptBinLimits[i-1] = trd3D->GetZaxis()->GetBinLowEdge(i);
}
ptBinLimits[nBinsZ] = trd3D->GetZaxis()->GetBinUpEdge(nBinsZ);
TH1F *efficiency = new TH1F(Form("eff%d", Int_t(1000000.0*gRandom->Rndm())), "TRD-TPC matching efficiency", nBinsZ, ptBinLimits);
// loop over Z bins
Bool_t effGood = kFALSE;
for(Int_t i=1; i<=nBinsZ; i++) {
Float_t tpcEntries = 0.0; Float_t trdEntries = 0.0;
Proj3D(tpc3D, trdAcc, i, i, tpcEntries);
Proj3D(trd3D, trdAcc, i, i, trdEntries);
Float_t ratio = 0;
if(tpcEntries>0) ratio = trdEntries/tpcEntries;
Float_t error = 0;
if(tpcEntries>0 && trdEntries>0 && (tpcEntries-trdEntries)>=0.0)
error = TMath::Sqrt(trdEntries*(tpcEntries-trdEntries)/tpcEntries/tpcEntries/tpcEntries);
if(ratio>0.001) {
efficiency->SetBinContent(i,ratio);
efficiency->SetBinError(i,error);
effGood = kTRUE;
}
} // end loop over Z bins
if(!effGood) return 0x0;
return efficiency;
}
//__________________________________________________________________________________________________
void AliTRDcheckESD::PlotCentSummaryFromCF(Double_t* /*trendValues*/, const Char_t* /*triggerName*/, Bool_t /*useIsolatedBC*/, Bool_t /*cutTOFbc*/) {
//
// Make the centrality summary figure from the CF container
//
if(!fHistos) return;
AliCFContainer* matchPt=(AliCFContainer*)fHistos->FindObject("MatchingPt");
if(!matchPt) return;
AliCFContainer* centCF=(AliCFContainer*)fHistos->FindObject("CentralityCF");
if(!centCF) return;
AliCFContainer* clustersCF=(AliCFContainer*)fHistos->FindObject("ClustersCF");
if(!clustersCF) return;
TLatex* lat=new TLatex();
lat->SetTextSize(0.06);
lat->SetTextColor(2);
gPad->SetTopMargin(0.05); gPad->SetBottomMargin(0.001); gPad->SetLeftMargin(0.001); gPad->SetRightMargin(0.001);
gPad->Divide(3,3,0.,0.);
TList* l=gPad->GetListOfPrimitives();
TVirtualPad* pad=0x0;
if(gROOT->FindObject("rangeEffPt")) delete gROOT->FindObject("rangeEffPt");
TH2F* rangeEffPt=new TH2F("rangeEffPt", "",10,0.,10.,10,0.,1.3);
rangeEffPt->SetStats(kFALSE);
SetStyle(rangeEffPt->GetXaxis(), "p_{T} [GeV/c]", 0.07, 0.8, kTRUE, 0.05);
SetStyle(rangeEffPt->GetYaxis(), "efficiency", 0.07, 0.8, kTRUE, 0.05);
Int_t padsForEffs[5] = {0,3,6,1,4};
for(Int_t iCent=1; iCent<6; ++iCent) {
pad = ((TVirtualPad*)l->At(padsForEffs[iCent-1])); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.02); pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
rangeEffPt->Draw();
TLine line;
line.SetLineStyle(2);
line.SetLineWidth(2);
line.DrawLine(rangeEffPt->GetXaxis()->GetXmin(), 0.7, rangeEffPt->GetXaxis()->GetXmax(), 0.7);
line.DrawLine(rangeEffPt->GetXaxis()->GetXmin(), 0.9, rangeEffPt->GetXaxis()->GetXmax(), 0.9);
matchPt->SetRangeUser(matchPt->GetVar(fgkVarNames[kEventMult]), Double_t(iCent), Double_t(iCent), kTRUE);
matchPt->SetRangeUser(matchPt->GetVar(fgkVarNames[kTrackCharge]), +1.0, +1.0);
TH1F* hEffPosAll = EfficiencyFromPhiPt(matchPt, 0, 6, 1, 0);
TH1F* hEffPosTrk4 = EfficiencyFromPhiPt(matchPt, 4, 4, 1, 0);
TH1F* hEffPosTrk5 = EfficiencyFromPhiPt(matchPt, 5, 5, 1, 0);
TH1F* hEffPosTrk6 = EfficiencyFromPhiPt(matchPt, 6, 6, 1, 0);
matchPt->SetRangeUser(matchPt->GetVar(fgkVarNames[kTrackCharge]), -1.0, -1.0);
TH1F* hEffNegAll = EfficiencyFromPhiPt(matchPt, 0, 6, 1, 0);
TH1F* hEffNegTrk4 = EfficiencyFromPhiPt(matchPt, 4, 4, 1, 0);
TH1F* hEffNegTrk5 = EfficiencyFromPhiPt(matchPt, 5, 5, 1, 0);
TH1F* hEffNegTrk6 = EfficiencyFromPhiPt(matchPt, 6, 6, 1, 0);
matchPt->SetRangeUser(matchPt->GetVar(fgkVarNames[kTrackTrdTracklets]), 0.0, 6.0);
matchPt->SetRangeUser(matchPt->GetVar(fgkVarNames[kTrackCharge]), -1.0, +1.0);
SetStyle(hEffPosAll, 1, kRed, 1, 24, kRed, 1);
SetStyle(hEffPosTrk4, 1, kRed, 1, 25, kRed, 1);
SetStyle(hEffPosTrk5, 1, kRed, 1, 26, kRed, 1);
SetStyle(hEffPosTrk6, 1, kRed, 1, 27, kRed, 1);
SetStyle(hEffNegAll, 1, kBlue, 1, 24, kBlue, 1);
SetStyle(hEffNegTrk4, 1, kBlue, 1, 25, kBlue, 1);
SetStyle(hEffNegTrk5, 1, kBlue, 1, 26, kBlue, 1);
SetStyle(hEffNegTrk6, 1, kBlue, 1, 27, kBlue, 1);
hEffPosAll->Draw("same");
hEffNegAll->Draw("same");
hEffPosTrk4->Draw("same");
hEffNegTrk4->Draw("same");
hEffPosTrk5->Draw("same");
hEffNegTrk5->Draw("same");
hEffPosTrk6->Draw("same");
hEffNegTrk6->Draw("same");
TLegend* leg=new TLegend(0.18, 0.7, 0.77, 0.89);
if(iCent==1) {
leg->SetFillColor(0);
leg->SetNColumns(2);
leg->SetMargin(0.1);
leg->SetBorderSize(0);
leg->AddEntry(hEffPosAll, "pos. (#geq 1 tracklet)", "p");
leg->AddEntry(hEffNegAll, "neg. (#geq 1 tracklet)", "p");
leg->AddEntry(hEffPosTrk4, "pos. (4 tracklets)", "p");
leg->AddEntry(hEffNegTrk4, "neg. (4 tracklets)", "p");
leg->AddEntry(hEffPosTrk5, "pos. (5 tracklets)", "p");
leg->AddEntry(hEffNegTrk5, "neg. (5 tracklets)", "p");
leg->AddEntry(hEffPosTrk6, "pos. (6 tracklets)", "p");
leg->AddEntry(hEffNegTrk6, "neg. (6 tracklets)", "p");
leg->Draw();
}
lat->DrawLatex(0.2, 1.32, Form("%.0f < SPD tracklets < %.0f", matchPt->GetAxis(matchPt->GetVar(fgkVarNames[kEventMult]),0)->GetBinLowEdge(iCent), matchPt->GetAxis(matchPt->GetVar(fgkVarNames[kEventMult]),0)->GetBinUpEdge(iCent)));
} // end for loop over multiplicity classes
// Reset the modified user ranges of the CF container
matchPt->SetRangeUser(matchPt->GetVar(fgkVarNames[kEventMult]), 0., 3500.);
// Cluster distributions in all multiplicity classes
pad = ((TVirtualPad*)l->At(2)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.02);
pad->SetTopMargin(0.02); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
if(gROOT->FindObject("rangeNcls")) delete gROOT->FindObject("rangeNcls");
TH2F* rangeNcls = new TH2F("rangeNcls", "", 10, 0.0, 199.9, 10, 0.0, 1.199);
SetStyle(rangeNcls->GetXaxis(), "# TRD clusters", 0.07, 0.8, kTRUE, 0.05);
SetStyle(rangeNcls->GetYaxis(), "entries (a.u.)", 0.07, 0.8, kTRUE, 0.05);
rangeNcls->SetStats(kFALSE);
rangeNcls->Draw();
TH1D* hNcls[6]={0x0};
TLegend* legCls=new TLegend(0.7, 0.75, 0.97, 0.97);
legCls->SetBorderSize(0);
legCls->SetFillColor(0);
legCls->SetMargin(0.15);
for(Int_t iCent=0; iCent<6; ++iCent) {
if(iCent>0)
clustersCF->SetRangeUser(clustersCF->GetVar(fgkVarNames[kEventMult]), Double_t(iCent), Double_t(iCent), kTRUE);
hNcls[iCent] = (TH1D*)clustersCF->Project(0, clustersCF->GetVar(fgkVarNames[kTrackTrdClusters]));
if(!hNcls[iCent]) continue;
hNcls[iCent]->SetLineColor(iCent<4 ? iCent+1 : iCent+2);
Double_t maximum = hNcls[iCent]->GetMaximum();
if(maximum>1.0)
hNcls[iCent]->Scale(1.0/maximum);
hNcls[iCent]->SetStats(kFALSE);
hNcls[iCent]->SetTitle("");
hNcls[iCent]->SetLineWidth(2);
if(hNcls[iCent]->Integral()>0.01) {
hNcls[iCent]->Draw("same");
legCls->AddEntry(hNcls[iCent], (iCent==0 ? "all centralities" : Form("%.0f < SPD tracklets < %.0f", clustersCF->GetAxis(clustersCF->GetVar(fgkVarNames[kEventMult]),0)->GetBinLowEdge(iCent),
clustersCF->GetAxis(clustersCF->GetVar(fgkVarNames[kEventMult]),0)->GetBinUpEdge(iCent))), "l");
}
}
legCls->Draw();
clustersCF->SetRangeUser(clustersCF->GetVar(fgkVarNames[kEventMult]), 0.0, 6.0, kTRUE);
// Qtot distributions
pad = ((TVirtualPad*)l->At(5)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.02);
pad->SetTopMargin(0.02); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
if(gROOT->FindObject("rangeQtot")) delete gROOT->FindObject("rangeQtot");
TH2F* rangeQtot = new TH2F("rangeQtot", "", 10, 0.0, 9.999, 10, 0.0, 1.199);
SetStyle(rangeQtot->GetXaxis(), "Q_{tot} (a.u.)", 0.07, 0.8, kTRUE, 0.05);
SetStyle(rangeQtot->GetYaxis(), "entries (a.u.)", 0.07, 0.8, kTRUE, 0.05);
rangeQtot->SetStats(kFALSE);
rangeQtot->Draw();
TH1D* hQtot[6+1]={0x0};
TLegend* leg2=new TLegend(0.6, 0.7, 0.9, 0.97);
leg2->SetFillColor(0);
leg2->SetBorderSize(0);
for(Int_t iCent=0; iCent<6; ++iCent) {
if(iCent>0)
centCF->SetRangeUser(centCF->GetVar(fgkVarNames[kEventMult]), Double_t(iCent), Double_t(iCent), kTRUE);
hQtot[iCent] = (TH1D*)centCF->Project(0, centCF->GetVar(fgkVarNames[kTrackletQtot]));
if(!hQtot[iCent]) continue;
hQtot[iCent]->SetBinContent(1, 0);
Double_t maximum = hQtot[iCent]->GetMaximum();
if(maximum>1.0)
hQtot[iCent]->Scale(1.0/maximum);
hQtot[iCent]->SetLineColor(iCent<4 ? iCent+1 : iCent+2);
hQtot[iCent]->SetStats(kFALSE);
hQtot[iCent]->SetTitle("");
hQtot[iCent]->SetLineWidth(2);
if(hQtot[iCent]->Integral()>0.01) {
hQtot[iCent]->Draw(iCent==0 ? "" : "same");
leg2->AddEntry(hQtot[iCent], (iCent==0 ? "all centralities" : Form("%.0f < SPD tracklets < %.0f", centCF->GetAxis(centCF->GetVar(fgkVarNames[kEventMult]),0)->GetBinLowEdge(iCent),
centCF->GetAxis(centCF->GetVar(fgkVarNames[kEventMult]),0)->GetBinUpEdge(iCent))), "l");
}
}
leg2->Draw();
centCF->SetRangeUser(centCF->GetVar(fgkVarNames[kEventMult]), 0.0, 5.0, kTRUE);
}
//_________________________________________________________________
void AliTRDcheckESD::PlotTrackingSummaryFromCF(Double_t* trendValues, const Char_t* /*triggerName*/, Bool_t /*useIsolatedBC*/, Bool_t /*cutTOFbc*/) {
//
// Plot tracking summary
//
// trendValues will be filled with trending variables
// trendValues[0] : TPC-TRD matching efficiency for positive tracks in the range 1.0<pt<3.0 GeV/c
// trendValues[1] : statistical error of trendValues[0]
// trendValues[2] : TPC-TRD matching efficiency for negative tracks in the range 1.0<pt<3.0 GeV/c
// trendValues[3] : statistical error of trendValues[2]
// trendValues[4] : TRD-TOF matching efficiency for positive tracks in the range 1.0<pt<3.0 GeV/c
// trendValues[5] : statistical error of trendValues[4]
// trendValues[6] : TRD-TOF matching efficiency for negative tracks in the range 1.0<pt<3.0 GeV/c
// trendValues[7] : statistical error of trendValues[6]
// trendValues[8] : Average number of TRD tracklets per track in the range 1.0<pt<3.0 GeV/c
// trendValues[9] : statistical error of trendValues[8]
// trendValues[10]: Average number of TRD clusters per track in the range 1.0<p<3.0 GeV/c
// trendValues[11]: statistical error of trendValues[10]
//
if(!fHistos) return;
AliCFContainer* matchPhiEta=(AliCFContainer*)fHistos->FindObject("MatchingPhiEta");
if(!matchPhiEta) return;
AliCFContainer* matchPt=(AliCFContainer*)fHistos->FindObject("MatchingPt");
if(!matchPt) return;
AliCFContainer* clustersCF=(AliCFContainer*)fHistos->FindObject("ClustersCF");
if(!clustersCF) return;
AliCFContainer* bcCF=(AliCFContainer*)fHistos->FindObject("BunchCrossingsCF");
if(!bcCF) return;
TLatex *lat=new TLatex();
lat->SetTextSize(0.06);
lat->SetTextColor(2);
lat->SetTextFont(42);
gPad->SetTopMargin(0.05); gPad->SetBottomMargin(0.001);
gPad->SetLeftMargin(0.001); gPad->SetRightMargin(0.001);
gPad->Divide(3,3,0.,0.);
TList* l=gPad->GetListOfPrimitives();
// eta-phi distr. for positive TPC tracks
TVirtualPad* pad = ((TVirtualPad*)l->At(0)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
TH2D* hTPCrefPos = 0x0; TH2D* hTRDrefPos = 0x0; TH2D* hTOFrefPos = 0x0;
TH2D* hTPCrefNeg = 0x0; TH2D* hTRDrefNeg = 0x0; TH2D* hTOFrefNeg = 0x0;
matchPhiEta->SetRangeUser(matchPhiEta->GetVar(fgkVarNames[kTrackTrdTracklets]), 0.0, 6.0);
matchPhiEta->SetRangeUser(matchPhiEta->GetVar(fgkVarNames[kTrackCharge]), +1.0, +1.0); // positive charges
hTPCrefPos = (TH2D*)matchPhiEta->Project(0, matchPhiEta->GetVar(fgkVarNames[kTrackEtaTRD]), matchPhiEta->GetVar(fgkVarNames[kTrackPhiTRD]));
hTRDrefPos = (TH2D*)matchPhiEta->Project(1, matchPhiEta->GetVar(fgkVarNames[kTrackEtaTRD]), matchPhiEta->GetVar(fgkVarNames[kTrackPhiTRD]));
hTOFrefPos = (TH2D*)matchPhiEta->Project(2, matchPhiEta->GetVar(fgkVarNames[kTrackEtaTRD]), matchPhiEta->GetVar(fgkVarNames[kTrackPhiTRD]));
matchPhiEta->SetRangeUser(matchPhiEta->GetVar(fgkVarNames[kTrackCharge]), -1.0, -1.0); // negative charges
hTPCrefNeg = (TH2D*)matchPhiEta->Project(0, matchPhiEta->GetVar(fgkVarNames[kTrackEtaTRD]), matchPhiEta->GetVar(fgkVarNames[kTrackPhiTRD]));
hTRDrefNeg = (TH2D*)matchPhiEta->Project(1, matchPhiEta->GetVar(fgkVarNames[kTrackEtaTRD]), matchPhiEta->GetVar(fgkVarNames[kTrackPhiTRD]));
hTOFrefNeg = (TH2D*)matchPhiEta->Project(2, matchPhiEta->GetVar(fgkVarNames[kTrackEtaTRD]), matchPhiEta->GetVar(fgkVarNames[kTrackPhiTRD]));
matchPhiEta->SetRangeUser(matchPhiEta->GetVar(fgkVarNames[kTrackCharge]), -1.0, +1.0); // reset charge cut
if(gROOT->FindObject("rangeEtaPhi")) delete gROOT->FindObject("rangeEtaPhi");
TH2F* rangeEtaPhi = new TH2F("rangeEtaPhi", "", 10, -0.99, +0.99, 10, -3.15, 3.15);
SetStyle(rangeEtaPhi->GetXaxis(), "#eta", 0.07, 0.8, kTRUE, 0.05);
SetStyle(rangeEtaPhi->GetYaxis(), "detector #varphi", 0.07, 0.8, kTRUE, 0.05);
rangeEtaPhi->SetStats(kFALSE);
//----------------------------------------------
// eta-phi efficiency for positive TRD tracks
pad = ((TVirtualPad*)l->At(0)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
rangeEtaPhi->Draw();
TH2D* hTRDeffPos = (hTRDrefPos ? (TH2D*)hTRDrefPos->Clone("hTRDeffPos") : 0x0);
if(hTRDeffPos) {
hTRDeffPos->Reset();
hTRDeffPos->SetStats(kFALSE);
hTRDeffPos->Divide(hTRDrefPos, hTPCrefPos);
hTRDeffPos->SetMaximum(1.0);
hTRDeffPos->Draw("samecolz");
lat->DrawLatex(-0.9, 3.3, "TPC-TRD matching for positive tracks");
DrawTRDGrid();
}
//----------------------------------------------
// eta-phi efficiency for negative TRD tracks
pad = ((TVirtualPad*)l->At(3)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
rangeEtaPhi->Draw();
TH2D* hTRDeffNeg = (hTRDrefNeg ? (TH2D*)hTRDrefNeg->Clone("hTRDeffNeg") : 0x0);
if(hTRDeffNeg) {
hTRDeffNeg->Reset();
hTRDeffNeg->SetStats(kFALSE);
hTRDeffNeg->Divide(hTRDrefNeg, hTPCrefNeg);
hTRDeffNeg->SetMaximum(1.0);
hTRDeffNeg->Draw("samecolz");
lat->DrawLatex(-0.9, 3.3, "TPC-TRD matching for negative tracks");
DrawTRDGrid();
}
//----------------------------------------------
// eta-phi TRD-TOF matching efficiency for positive tracks
pad = ((TVirtualPad*)l->At(1)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
rangeEtaPhi->Draw();
TH2D* hTOFeffPos = (hTOFrefPos ? (TH2D*)hTOFrefPos->Clone("hTOFeffPos") : 0x0);
if(hTOFeffPos) {
hTOFeffPos->Reset();
hTOFeffPos->SetStats(kFALSE);
hTOFeffPos->Divide(hTOFrefPos, hTRDrefPos);
hTOFeffPos->SetMaximum(1.0);
hTOFeffPos->Draw("samecolz");
lat->DrawLatex(-0.9, 3.3, "TRD-TOF matching for positive tracks");
DrawTRDGrid();
}
//----------------------------------------------
// eta-phi TRD-TOF matching efficiency for negative tracks
pad = ((TVirtualPad*)l->At(4)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
rangeEtaPhi->Draw();
TH2D* hTOFeffNeg = (hTOFrefNeg ? (TH2D*)hTOFrefNeg->Clone("hTOFeffNeg") : 0x0);
if(hTOFeffNeg) {
hTOFeffNeg->Reset();
hTOFeffNeg->SetStats(kFALSE);
hTOFeffNeg->Divide(hTOFrefNeg, hTRDrefNeg);
hTOFeffNeg->SetMaximum(1.0);
hTOFeffNeg->Draw("samecolz");
lat->DrawLatex(-0.9, 3.3, "TRD-TOF matching for negative tracks");
DrawTRDGrid();
}
if(hTRDrefPos) delete hTRDrefPos; if(hTPCrefPos) delete hTPCrefPos; if(hTOFrefPos) delete hTOFrefPos;
if(hTRDrefNeg) delete hTRDrefNeg; if(hTPCrefNeg) delete hTPCrefNeg; if(hTOFrefNeg) delete hTOFrefNeg;
// switch to the Pt cf container
matchPt->SetRangeUser(matchPt->GetVar(fgkVarNames[kTrackCharge]), +1.0, +1.0);
TH1F* hTRDEffPtPosAll = EfficiencyFromPhiPt(matchPt, 0, 6, 1, 0);
TH1F* hTOFEffPtPosAll = EfficiencyFromPhiPt(matchPt, 0, 6, 2, 1);
TH1F* hTRDEffPtPosTrk4 = EfficiencyFromPhiPt(matchPt, 4, 4, 1, 0);
TH1F* hTOFEffPtPosTrk4 = EfficiencyFromPhiPt(matchPt, 4, 4, 2, 1);
TH1F* hTRDEffPtPosTrk5 = EfficiencyFromPhiPt(matchPt, 5, 5, 1, 0);
TH1F* hTOFEffPtPosTrk5 = EfficiencyFromPhiPt(matchPt, 5, 5, 2, 1);
TH1F* hTRDEffPtPosTrk6 = EfficiencyFromPhiPt(matchPt, 6, 6, 1, 0);
TH1F* hTOFEffPtPosTrk6 = EfficiencyFromPhiPt(matchPt, 6, 6, 2, 1);
matchPt->SetRangeUser(matchPt->GetVar(fgkVarNames[kTrackCharge]), -1.0, -1.0);
TH1F* hTRDEffPtNegAll = EfficiencyFromPhiPt(matchPt, 0, 6, 1, 0);
TH1F* hTOFEffPtNegAll = EfficiencyFromPhiPt(matchPt, 0, 6, 2, 1);
TH1F* hTRDEffPtNegTrk4 = EfficiencyFromPhiPt(matchPt, 4, 4, 1, 0);
TH1F* hTOFEffPtNegTrk4 = EfficiencyFromPhiPt(matchPt, 4, 4, 2, 1);
TH1F* hTRDEffPtNegTrk5 = EfficiencyFromPhiPt(matchPt, 5, 5, 1, 0);
TH1F* hTOFEffPtNegTrk5 = EfficiencyFromPhiPt(matchPt, 5, 5, 2, 1);
TH1F* hTRDEffPtNegTrk6 = EfficiencyFromPhiPt(matchPt, 6, 6, 1, 0);
TH1F* hTOFEffPtNegTrk6 = EfficiencyFromPhiPt(matchPt, 6, 6, 2, 1);
matchPt->SetRangeUser(matchPt->GetVar(fgkVarNames[kTrackCharge]), -1.0, +1.0);
TF1* funcConst = new TF1("constFunc", "[0]", 1.0, 3.0);
if(trendValues) {
if(hTRDEffPtPosAll && hTRDEffPtPosAll->Integral()>0.1) {
hTRDEffPtPosAll->Fit(funcConst, "Q0ME", "goff", 1.0, 3.0);
trendValues[0] = funcConst->GetParameter(0);
trendValues[1] = funcConst->GetParError(0);
}
}
if(trendValues) {
if(hTRDEffPtNegAll && hTRDEffPtNegAll->Integral()>0.1) {
hTRDEffPtNegAll->Fit(funcConst, "Q0ME", "goff", 1.0, 3.0);
trendValues[2] = funcConst->GetParameter(0);
trendValues[3] = funcConst->GetParError(0);
}
}
if(trendValues) {
if(hTOFEffPtPosAll && hTOFEffPtPosAll->Integral()>0.1) {
hTOFEffPtPosAll->Fit(funcConst, "Q0ME", "goff", 1.0, 3.0);
trendValues[4] = funcConst->GetParameter(0);
trendValues[5] = funcConst->GetParError(0);
}
}
if(trendValues) {
if(hTOFEffPtNegAll && hTOFEffPtNegAll->Integral()>0.1) {
hTOFEffPtNegAll->Fit(funcConst, "Q0ME", "goff", 1.0, 3.0);
trendValues[6] = funcConst->GetParameter(0);
trendValues[7] = funcConst->GetParError(0);
}
}
//---------------------------------------------------------
// TPC-TRD matching efficiency vs pt
pad = ((TVirtualPad*)l->At(6)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.02);
pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
if(gROOT->FindObject("rangeEffPt2")) delete gROOT->FindObject("rangeEffPt2");
TH2F* rangeEffPt=new TH2F("rangeEffPt2", "",10,0.,10.,10,0.,1.4);
rangeEffPt->SetStats(kFALSE);
SetStyle(rangeEffPt->GetXaxis(), "p_{T} [GeV/c]", 0.07, 0.8, kTRUE, 0.05);
SetStyle(rangeEffPt->GetYaxis(), "efficiency", 0.07, 0.8, kTRUE, 0.05);
rangeEffPt->Draw();
lat->DrawLatex(0.2, 1.44, "TPC-TRD matching efficiency");
//++++++++++++++++++
TLine line;
line.SetLineStyle(2);
line.SetLineWidth(2);
line.DrawLine(rangeEffPt->GetXaxis()->GetXmin(), 0.7, rangeEffPt->GetXaxis()->GetXmax(), 0.7);
line.DrawLine(rangeEffPt->GetXaxis()->GetXmin(), 0.9, rangeEffPt->GetXaxis()->GetXmax(), 0.9);
TLegend* leg=new TLegend(0.2, 0.7, 0.7, 0.89);
leg->SetNColumns(2);
leg->SetMargin(0.15);
leg->SetBorderSize(0);
leg->SetFillColor(0);
SetStyle(hTRDEffPtPosAll, 1, kRed, 1, 24, kRed, 1);
SetStyle(hTRDEffPtNegAll, 1, kBlue, 1, 24, kBlue, 1);
SetStyle(hTRDEffPtPosTrk4, 1, kRed, 1, 25, kRed, 1);
SetStyle(hTRDEffPtNegTrk4, 1, kBlue, 1, 25, kBlue, 1);
SetStyle(hTRDEffPtPosTrk5, 1, kRed, 1, 26, kRed, 1);
SetStyle(hTRDEffPtNegTrk5, 1, kBlue, 1, 26, kBlue, 1);
SetStyle(hTRDEffPtPosTrk6, 1, kRed, 1, 27, kRed, 1);
SetStyle(hTRDEffPtNegTrk6, 1, kBlue, 1, 27, kBlue, 1);
if(hTRDEffPtPosAll) {hTRDEffPtPosAll->Draw("same"); leg->AddEntry(hTRDEffPtPosAll, "pos. (#geq 1 tracklet)", "p");}
if(hTRDEffPtNegAll) {hTRDEffPtNegAll->Draw("same"); leg->AddEntry(hTRDEffPtNegAll, "neg. (#geq 1 tracklet)", "p");}
hTRDEffPtPosTrk4->Draw("same"); leg->AddEntry(hTRDEffPtPosTrk4, "pos. (4 tracklets)", "p");
hTRDEffPtNegTrk4->Draw("same"); leg->AddEntry(hTRDEffPtNegTrk4, "neg. (4 tracklets)", "p");
hTRDEffPtPosTrk5->Draw("same"); leg->AddEntry(hTRDEffPtPosTrk5, "pos. (5 tracklets)", "p");
hTRDEffPtNegTrk5->Draw("same"); leg->AddEntry(hTRDEffPtNegTrk5, "neg. (5 tracklets)", "p");
hTRDEffPtPosTrk6->Draw("same"); leg->AddEntry(hTRDEffPtPosTrk6, "pos. (6 tracklets)", "p");
hTRDEffPtNegTrk6->Draw("same"); leg->AddEntry(hTRDEffPtNegTrk6, "neg. (6 tracklets)", "p");
leg->Draw();
//---------------------------------------------------------
// TRD-TOF matching efficiency vs pt
pad = ((TVirtualPad*)l->At(7)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.02);
pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
rangeEffPt->Draw();
lat->DrawLatex(0.2, 1.44, "TRD-TOF matching efficiency");
SetStyle(hTOFEffPtPosAll, 1, kRed, 1, 24, kRed, 1);
SetStyle(hTOFEffPtPosTrk4, 1, kRed, 1, 25, kRed, 1);
SetStyle(hTOFEffPtPosTrk5, 1, kRed, 1, 26, kRed, 1);
SetStyle(hTOFEffPtPosTrk6, 1, kRed, 1, 27, kRed, 1);
SetStyle(hTOFEffPtNegAll, 1, kBlue, 1, 24, kBlue, 1);
SetStyle(hTOFEffPtNegTrk4, 1, kBlue, 1, 25, kBlue, 1);
SetStyle(hTOFEffPtNegTrk5, 1, kBlue, 1, 26, kBlue, 1);
SetStyle(hTOFEffPtNegTrk6, 1, kBlue, 1, 27, kBlue, 1);
if(hTOFEffPtPosAll) hTOFEffPtPosAll->Draw("same");
hTOFEffPtPosTrk4->Draw("same");
hTOFEffPtPosTrk5->Draw("same");
hTOFEffPtPosTrk6->Draw("same");
if(hTOFEffPtNegAll) hTOFEffPtNegAll->Draw("same");
hTOFEffPtNegTrk4->Draw("same");
hTOFEffPtNegTrk5->Draw("same");
hTOFEffPtNegTrk6->Draw("same");
//-----------------------------------------------------
// <ntracklets> vs (phi,eta)
pad = ((TVirtualPad*)l->At(2)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
rangeEtaPhi->Draw();
lat->DrawLatex(-0.9, 3.3, "TRD <N_{tracklets}>");
TH3D* hNtracklets = (TH3D*)matchPhiEta->Project(kTRD, matchPhiEta->GetVar(fgkVarNames[kTrackPhiTRD]), matchPhiEta->GetVar(fgkVarNames[kTrackEtaTRD]), matchPhiEta->GetVar(fgkVarNames[kTrackTrdTracklets]));
TProfile2D* hNtrackletsProf = hNtracklets->Project3DProfile();
delete hNtracklets;
if(hNtrackletsProf) {
hNtrackletsProf->SetStats(kFALSE);
hNtrackletsProf->SetMinimum(0.);
hNtrackletsProf->SetMaximum(6.);
hNtrackletsProf->Draw("samecolz");
DrawTRDGrid();
}
// calculate the trend value for tracklets/track
TH2D* hNtrackletsVsP = (TH2D*)matchPt->Project(kTRD, matchPt->GetVar(fgkVarNames[kTrackPt]), matchPt->GetVar(fgkVarNames[kTrackTrdTracklets]));
if(trendValues && hNtrackletsVsP && hNtrackletsVsP->GetEntries()>0.1) {
TProfile* hNtrackletsVsPprof = hNtrackletsVsP->ProfileX("hNtrackletsVsPprof");
hNtrackletsVsPprof->Fit(funcConst, "QME0", "goff", 1.0, 3.0);
trendValues[8] = funcConst->GetParameter(0);
trendValues[9] = funcConst->GetParError(0);
delete hNtrackletsVsP;
}
//--------------------------------------------------------------
// Nclusters per TRD track vs momentum
pad = ((TVirtualPad*)l->At(5)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.12);
pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
pad->SetLogz();
if(gROOT->FindObject("rangeNclsP")) delete gROOT->FindObject("rangeNclsP");
TH2F* rangeNclsP = new TH2F("rangeNclsP", "", 10, 0.0, 11.99, 10, 0.0, 199.0);
SetStyle(rangeNclsP->GetXaxis(), "p [GeV/c]", 0.07, 0.8, kTRUE, 0.05);
SetStyle(rangeNclsP->GetYaxis(), "#clusters", 0.07, 0.8, kTRUE, 0.05);
rangeNclsP->SetStats(kFALSE);
rangeNclsP->Draw();
lat->DrawLatex(1.0, 205., "TRD Clusters / track");
TH2D* hNclsVsP = (TH2D*)clustersCF->Project(0, clustersCF->GetVar(fgkVarNames[kTrackP]), clustersCF->GetVar(fgkVarNames[kTrackTrdClusters]));
if(hNclsVsP) {
hNclsVsP->SetStats(kFALSE);
hNclsVsP->Draw("samecolz");
}
if(trendValues && hNclsVsP && hNclsVsP->GetEntries()>10) {
TProfile* hNclsVsPprof = hNclsVsP->ProfileX("hNclsVsPprof");
hNclsVsPprof->Fit(funcConst, "QME0", "goff", 1.0, 3.0);
trendValues[10] = funcConst->GetParameter(0);
trendValues[11] = funcConst->GetParError(0);
}
//--------------------------------------------------------------
// TRD-TPC and TOF-TRD matching efficiency vs bunch crossing
pad = ((TVirtualPad*)l->At(8)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.02);
pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
TH1F* hTRDEffBC = EfficiencyFromPhiPt(bcCF, -1, -1, 1, 0, kEventBC);
TH1F* hTOFEffBC = EfficiencyFromPhiPt(bcCF, -1, -1, 2, 1, kEventBC);
if(gROOT->FindObject("rangeBC")) delete gROOT->FindObject("rangeBC");
TH2F* rangeBC = new TH2F("rangeBC", "", 10, -0.5, 3499.5, 10, 0.0, 1.4);
rangeBC->SetStats(kFALSE);
SetStyle(rangeBC->GetXaxis(), "Bunch crossing", 0.07, 0.8, kTRUE, 0.05);
SetStyle(rangeBC->GetYaxis(), "efficiency", 0.07, 0.8, kTRUE, 0.05);
rangeBC->Draw();
TLegend* legBC=new TLegend(0.8, 0.7, 0.95, 0.89);
legBC->SetBorderSize(0);
legBC->SetMargin(0.15);
legBC->SetFillColor(0);
if(hTRDEffBC) {
hTRDEffBC->SetStats(kFALSE);
SetStyle(hTRDEffBC, 1, kRed, 2, 24, kRed, 1); legBC->AddEntry(hTRDEffBC, "TPC-TRD", "p");
SetStyle(hTOFEffBC, 1, kBlue, 2, 24, kBlue, 1); legBC->AddEntry(hTOFEffBC, "TRD-TOF", "p");
hTRDEffBC->Draw("same");
hTOFEffBC->Draw("same");
legBC->Draw();
lat->DrawLatex(200., 1.44, "Matching efficiency at 1<p_{T}<3 GeV/c");
}
delete funcConst;
}
//_________________________________________________________________
void AliTRDcheckESD::PlotPidSummaryFromCF(Double_t* trendValues, const Char_t* /*triggerName*/, Bool_t /*useIsolatedBC*/, Bool_t /*cutTOFbc*/) {
//
// PID summary
//
// trendValues will be filled with trending variables
// trendValues[12] : PH plateau height from slices times 0.002
// trendValues[13] : statistical error of trendValues[12]
// trendValues[14] : PH slope from slices times 0.002
// trendValues[15] : statistical error of trendValues[14]
// trendValues[16] : Landau MPV of tracklet Qtot distribution at p=1GeV/c times 0.002
// trendValues[17] : Landau width of tracklet Qtot distribution at p=1GeV/c times 0.002
// trendValues[18] : PH plateau height from slices
// trendValues[19] : statistical error of trendValues[19]
// trendValues[20] : PH slope from slices
// trendValues[21] : statistical error of trendValues[20]
// trendValues[22] : Landau MPV of tracklet Qtot distribution at p=1GeV/c
// trendValues[23] : Landau width of tracklet Qtot distribution at p=1GeV/c
//
if(!fHistos) return;
AliCFContainer* qtotCF = (AliCFContainer*)fHistos->FindObject("QtotCF");
if(!qtotCF) return;
AliCFContainer* phCF = (AliCFContainer*)fHistos->FindObject("PulseHeightCF");
if(!phCF) return;
AliCFContainer* centCF = (AliCFContainer*)fHistos->FindObject("CentralityCF");
if(!centCF) return;
TLatex *lat=new TLatex();
lat->SetTextSize(0.07);
lat->SetTextColor(2);
lat->SetTextFont(42);
gPad->SetTopMargin(0.05); gPad->SetBottomMargin(0.001);
gPad->SetLeftMargin(0.001); gPad->SetRightMargin(0.001);
gPad->Divide(3,3,0.,0.);
TList* l=gPad->GetListOfPrimitives();
if(gROOT->FindObject("rangeEtaPhi2")) delete gROOT->FindObject("rangeEtaPhi2");
TH2F* rangeEtaPhi = new TH2F("rangeEtaPhi2", "", 10, -0.99, +0.99, 10, -3.15, 3.15);
SetStyle(rangeEtaPhi->GetXaxis(), "#eta", 0.07, 0.8, kTRUE, 0.05);
SetStyle(rangeEtaPhi->GetYaxis(), "detector #varphi", 0.07, 0.8, kTRUE, 0.05);
rangeEtaPhi->SetStats(kFALSE);
// eta-phi distr. for <Qtot> in layer 0
TVirtualPad* pad;
TProfile2D* hProf2D;
TH1D* hqtot = (TH1D*)qtotCF->Project(0, qtotCF->GetVar(fgkVarNames[kTrackletQtot]));
for(Int_t iLayer=0; iLayer<6; ++iLayer) {
pad = ((TVirtualPad*)l->At((iLayer<3 ? iLayer*3 : (iLayer-3)*3+1))); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
rangeEtaPhi->Draw();
qtotCF->SetRangeUser(qtotCF->GetVar(fgkVarNames[kTrackletLayer]), Double_t(iLayer), Double_t(iLayer));
TH3D* hQtotEtaPhi = (TH3D*)qtotCF->Project(0, qtotCF->GetVar(fgkVarNames[kTrackPhiTRD]), qtotCF->GetVar(fgkVarNames[kTrackEtaTRD]), qtotCF->GetVar(fgkVarNames[kTrackletQtot]));
hProf2D = (hQtotEtaPhi ? hQtotEtaPhi->Project3DProfile() : 0x0);
if(hQtotEtaPhi) delete hQtotEtaPhi;
if(hProf2D) {
hProf2D->SetName(Form("Qtot_layer%d",iLayer));
hProf2D->SetStats(kFALSE);
hProf2D->SetMinimum(0.);
hProf2D->SetMaximum((hqtot->GetMean()<10 ? 4.0 : 2000.));
hProf2D->Draw("samecolz");
}
lat->DrawLatex(-0.9, 3.3, Form("TRD <Q_{tot}> Layer %d", iLayer));
DrawTRDGrid();
}
qtotCF->SetRangeUser(qtotCF->GetVar(fgkVarNames[kTrackletLayer]), 0.0, 5.0);
// PH versus slice number
pad = ((TVirtualPad*)l->At(2)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.03); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
if(gROOT->FindObject("rangePHslice")) delete gROOT->FindObject("rangePHslice");
TH2F* rangePHslice=new TH2F("rangePHslice", "", 8, -0.5, 7.5, 10, 0.0, (hqtot->GetMean()<10.0 ? 6.0 : 3000.));
rangePHslice->SetStats(kFALSE);
SetStyle(rangePHslice->GetXaxis(), "slice", 0.07, 0.8, kTRUE, 0.05);
SetStyle(rangePHslice->GetYaxis(), "PH", 0.07, 0.8, kTRUE, 0.05);
rangePHslice->Draw();
TF1* funcPol1 = new TF1("funcPol1", "[0]+[1]*x", 2.9, 6.4);
TH2D* hPH = (TH2D*)phCF->Project(0, phCF->GetVar(fgkVarNames[kTrackletSlice]), phCF->GetVar(fgkVarNames[kTrackletPHslice]));
TH1D* hSliceErr = new TH1D(Form("hSliceErr%f", gRandom->Rndm()), "", hPH->GetXaxis()->GetNbins(), hPH->GetXaxis()->GetXbins()->GetArray());
TH1D* hLandauFit = Proj2D(hPH, hSliceErr);
hPH->SetStats(kFALSE);
hPH->Draw("samecolz");
const Double_t kQx = 0.002;
if(trendValues) {
hSliceErr->Fit(funcPol1, "QME0", "goff", 2.9, 6.4);
trendValues[12] = kQx*funcPol1->GetParameter(0); // PH plateau
trendValues[13] = kQx*funcPol1->GetParError(0); // PH plateau
trendValues[14] = kQx*funcPol1->GetParameter(1); // PH slope
trendValues[15] = kQx*funcPol1->GetParError(1); // PH slope
trendValues[18] = funcPol1->GetParameter(0); // PH plateau
trendValues[19] = funcPol1->GetParError(0); // PH plateau
trendValues[20] = funcPol1->GetParameter(1); // PH slope
trendValues[21] = funcPol1->GetParError(1); // PH slope
}
hLandauFit->SetLineWidth(2);
hLandauFit->SetLineStyle(2);
hLandauFit->Draw("same");
delete funcPol1; delete hSliceErr;
// Qtot vs P
pad = ((TVirtualPad*)l->At(5)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.03); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
pad->SetLogz();
if(gROOT->FindObject("rangeQtotP")) delete gROOT->FindObject("rangeQtotP");
TH2F* rangeQtotP = new TH2F("rangeQtotP", "", 10, 0.0, 11.99, 10, 0.0, (hqtot->GetMean()<10.0 ? 11.99 : 5999.));
SetStyle(rangeQtotP->GetXaxis(), "P [GeV/c]", 0.07, 0.8, kTRUE, 0.05);
SetStyle(rangeQtotP->GetYaxis(), "Q_{tot}", 0.07, 0.8, kTRUE, 0.05);
rangeQtotP->SetStats(kFALSE);
rangeQtotP->Draw();
Int_t pVar = centCF->GetVar(fgkVarNames[kTrackP]);
if(pVar<0) pVar = centCF->GetVar(fgkVarNames[kTrackletP]);
TH2D* hQtotP = (TH2D*)centCF->Project(0, pVar, centCF->GetVar(fgkVarNames[kTrackletQtot]));
TH1D* mpvErr=new TH1D("mpvErr", "Landau MPV error vs. P", hQtotP->GetXaxis()->GetNbins(), hQtotP->GetXaxis()->GetXbins()->GetArray());
TH1D* widthErr=new TH1D("widthErr", "Landau width error vs. P", hQtotP->GetXaxis()->GetNbins(), hQtotP->GetXaxis()->GetXbins()->GetArray());
TH1D* landauChi2=new TH1D("landauChi2", "Landau fit #chi^{2} vs. P", hQtotP->GetXaxis()->GetNbins(), hQtotP->GetXaxis()->GetXbins()->GetArray());
if(hQtotP)
for(Int_t i=1; i<=hQtotP->GetXaxis()->GetNbins(); ++i)
hQtotP->SetBinContent(i, 1, 0.0);
TH1D* hQtotProj = (hQtotP ? Proj2D(hQtotP, mpvErr, widthErr, landauChi2) : 0x0);
//landauChi2->Scale(0.001);
if(hQtotProj) SetStyle(hQtotProj, 2, kBlue, 2, 1, kBlue, 1);
if(trendValues && hQtotProj && hQtotProj->GetEntries()>2) {
trendValues[16] = kQx*hQtotProj->GetBinContent(hQtotProj->FindBin(1.0)); // Landau MPV at 1GeV/c
trendValues[17] = kQx*hQtotProj->GetBinError(hQtotProj->FindBin(1.0)); // Landau width at 1 GeV/c
trendValues[22] = hQtotProj->GetBinContent(hQtotProj->FindBin(1.0)); // Landau MPV at 1GeV/c
trendValues[23] = hQtotProj->GetBinError(hQtotProj->FindBin(1.0)); // Landau width at 1 GeV/c
}
if(hQtotP) {
hQtotP->SetStats(kFALSE);
hQtotP->Draw("samecolz");
hQtotProj->Draw("same");
}
// Qtot vs P (fit results)
pad = ((TVirtualPad*)l->At(8)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.03); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
pad->SetLogz();
if(gROOT->FindObject("rangeQtotPfit")) delete gROOT->FindObject("rangeQtotPfit");
TH2F* rangeQtotPfit = new TH2F("rangeQtotPfit", "", 100, 0.0, 11.99, 100, 0.0, (hqtot->GetMean()<10.0 ? 6.0 : 3999.));
SetStyle(rangeQtotPfit->GetXaxis(), "P [GeV/c]", 0.07, 0.8, kTRUE, 0.05);
SetStyle(rangeQtotPfit->GetYaxis(), "Q_{tot}", 0.07, 0.8, kTRUE, 0.05);
rangeQtotPfit->SetStats(kFALSE);
rangeQtotPfit->Draw();
if(mpvErr) SetStyle(mpvErr, 1, kBlue, 2, 1, kBlue, 1);
if(widthErr) SetStyle(widthErr, 2, kRed, 2, 1, kRed, 1);
if(mpvErr) {
mpvErr->SetStats(kFALSE);
mpvErr->Draw("same");
}
if(widthErr) {
widthErr->SetStats(kFALSE);
widthErr->Draw("same");
}
TLegend* leg=new TLegend(0.2,0.6,0.5,0.9);
leg->SetFillColor(0);
leg->SetBorderSize(0);
leg->AddEntry("mpvErr","Landau MPV","l");
leg->AddEntry("widthErr","Landau width","l");
leg->Draw();
}
//__________________________________________________________________________________________________
void AliTRDcheckESD::PlotOtherSummaryFromCF(Double_t* /*trendValues*/) {
//
// Plot additional QA
//
if(!fHistos) return;
AliCFContainer* matchPhiEta = (AliCFContainer*)fHistos->FindObject("MatchingPhiEta");
AliCFContainer* trdChi2 = (AliCFContainer*)fHistos->FindObject("trdChi2");
AliCFContainer* trdBudget = (AliCFContainer*)fHistos->FindObject("trdBudget");
AliCFContainer* ploss = (AliCFContainer*)fHistos->FindObject("Ploss");
AliCFContainer* clusters = (AliCFContainer*)fHistos->FindObject("clustersPerTracklet");
AliCFContainer* clsRows = (AliCFContainer*)fHistos->FindObject("clustersVsRows");
TLatex *lat=new TLatex();
lat->SetTextSize(0.06);
lat->SetTextColor(2);
lat->SetNDC();
lat->SetTextFont(42);
TCanvas* c1 = new TCanvas("ESDsummary", "ESD summary 1", 1600, 1200);
gPad->SetTopMargin(0.05); gPad->SetBottomMargin(0.001);
gPad->SetLeftMargin(0.001); gPad->SetRightMargin(0.001);
gPad->Divide(3,3,0.,0.);
TList* l=gPad->GetListOfPrimitives();
TVirtualPad* pad=0x0;
// matching as a function of trigger class
if(matchPhiEta) {
matchPhiEta->SetRangeUser(matchPhiEta->GetVar(fgkVarNames[kTrackCharge]), -1.0, -1.0);
TH1F* hTRDEffTriggerNeg = EfficiencyFromPhiPt(matchPhiEta, -1, -1, 1, 0, kEventTrigger);
matchPhiEta->SetRangeUser(matchPhiEta->GetVar(fgkVarNames[kTrackCharge]), +1.0, +1.0);
TH1F* hTRDEffTriggerPos = EfficiencyFromPhiPt(matchPhiEta, -1, -1, 1, 0, kEventTrigger);
pad = ((TVirtualPad*)l->At(0)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.01);
pad->SetTopMargin(0.06); pad->SetBottomMargin(0.15);
hTRDEffTriggerNeg->SetStats(kFALSE);
SetStyle(hTRDEffTriggerNeg->GetYaxis(), "efficiency", 0.06, 1.0, kTRUE, 0.06);
hTRDEffTriggerNeg->GetXaxis()->SetRange(1,fNAssignedTriggers);
hTRDEffTriggerPos->GetXaxis()->SetRange(1,fNAssignedTriggers);
SetStyle(hTRDEffTriggerNeg, 1, 2, 2, 20, 2, 1);
SetStyle(hTRDEffTriggerPos, 1, 4, 2, 20, 4, 1);
hTRDEffTriggerNeg->Draw();
hTRDEffTriggerPos->Draw("same");
TLegend* legEff=new TLegend(0.5,0.5,0.7,0.7);
legEff->SetFillColor(0);
legEff->SetBorderSize(0);
legEff->AddEntry(hTRDEffTriggerNeg, "negatives", "l");
legEff->AddEntry(hTRDEffTriggerPos, "positives", "l");
legEff->Draw();
lat->DrawLatex(0.2, 0.95, "TPC-TRD matching efficiency");
}
if(trdChi2) {
// Track TRD chi2 vs (eta,phi)
TH3D* trdChi23D = (TH3D*)trdChi2->Project(0, trdChi2->GetVar(fgkVarNames[kTrackEtaTRD]),
trdChi2->GetVar(fgkVarNames[kTrackPhiTRD]),
trdChi2->GetVar(fgkVarNames[kTrackTrdChi2]));
trdChi23D->SetName("trdChi23D");
TProfile2D* prof2DChi2 = trdChi23D->Project3DProfile("yx");
prof2DChi2->SetName("prof2DChi2");
pad = ((TVirtualPad*)l->At(3)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.06); pad->SetBottomMargin(0.15);
prof2DChi2->SetStats(kFALSE);
prof2DChi2->SetTitle("");
SetStyle(prof2DChi2->GetXaxis(), "#eta", 0.06, 1.0, kTRUE, 0.06);
SetStyle(prof2DChi2->GetYaxis(), "#varphi (rad.)", 0.06, 1.0, kTRUE, 0.06);
prof2DChi2->SetMaximum(2.9);
prof2DChi2->Draw("colz");
lat->DrawLatex(0.2, 0.95, "TRD #chi^{2}");
DrawTRDGrid();
// Track TRD chi2 vs pt and charge
trdChi2->SetRangeUser(trdChi2->GetVar(fgkVarNames[kTrackCharge]), -1.0, -1.0);
TH2D* trdChi2VsPtNeg = (TH2D*)trdChi2->Project(0, trdChi2->GetVar(fgkVarNames[kTrackPt]),
trdChi2->GetVar(fgkVarNames[kTrackTrdChi2]));
trdChi2VsPtNeg->SetName("trdChi2VsPtNeg");
TProfile* trdChi2VsPtNegProf = trdChi2VsPtNeg->ProfileX();
trdChi2VsPtNegProf->SetName("trdChi2VsPtNegProf");
trdChi2->SetRangeUser(trdChi2->GetVar(fgkVarNames[kTrackCharge]), 1.0, 1.0);
TH2D* trdChi2VsPtPos = (TH2D*)trdChi2->Project(0, trdChi2->GetVar(fgkVarNames[kTrackPt]),
trdChi2->GetVar(fgkVarNames[kTrackTrdChi2]));
trdChi2VsPtPos->SetName("trdChi2VsPtPos");
TProfile* trdChi2VsPtPosProf = trdChi2VsPtPos->ProfileX();
trdChi2VsPtPosProf->SetName("trdChi2VsPtPosProf");
pad = ((TVirtualPad*)l->At(6)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.01);
pad->SetTopMargin(0.06); pad->SetBottomMargin(0.15);
trdChi2VsPtNegProf->SetStats(kFALSE);
trdChi2VsPtNegProf->SetTitle("");
SetStyle(trdChi2VsPtNegProf->GetXaxis(), "p_{T} (GeV/c)", 0.06, 1.0, kTRUE, 0.06);
SetStyle(trdChi2VsPtNegProf->GetYaxis(), "<TRD #chi^{2}>", 0.06, 1.0, kTRUE, 0.06);
SetStyle(trdChi2VsPtNegProf, 1, 2, 2, 20, 2, 1);
SetStyle(trdChi2VsPtPosProf, 1, 4, 2, 20, 4, 1);
trdChi2VsPtNegProf->Draw();
trdChi2VsPtPosProf->Draw("same");
lat->DrawLatex(0.2, 0.95, "TRD #chi^{2}");
}
if(trdBudget) {
// Track TRD budget vs (eta,phi)
TH3D* trdBudget3D = (TH3D*)trdBudget->Project(0, trdBudget->GetVar(fgkVarNames[kTrackEtaTRD]),
trdBudget->GetVar(fgkVarNames[kTrackPhiTRD]),
trdBudget->GetVar(fgkVarNames[kTrackTRDBudget]));
trdBudget3D->SetName("trdBudget3D");
TProfile2D* prof2DBudget = trdBudget3D->Project3DProfile("yx");
prof2DBudget->SetName("prof2DBudget");
pad = ((TVirtualPad*)l->At(1)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.06); pad->SetBottomMargin(0.15);
prof2DBudget->SetStats(kFALSE);
prof2DBudget->SetTitle("");
SetStyle(prof2DBudget->GetXaxis(), "#eta", 0.06, 1.0, kTRUE, 0.06);
SetStyle(prof2DBudget->GetYaxis(), "#varphi (rad.)", 0.06, 1.0, kTRUE, 0.06);
prof2DBudget->Draw("colz");
lat->DrawLatex(0.2, 0.95, "TRD budget");
DrawTRDGrid();
}
if(ploss) {
// momentum loss
ploss->SetRangeUser(ploss->GetVar(fgkVarNames[kTrackCharge]), -1.0, -1.0);
TH2D* plossLayerNeg = (TH2D*)ploss->Project(0, ploss->GetVar(fgkVarNames[kTrackletLayer]),
ploss->GetVar(fgkVarNames[kTrackPlossTRDlayer]));
plossLayerNeg->SetName("plossLayerNeg");
TProfile* plossLayerNegProf = plossLayerNeg->ProfileX();
plossLayerNegProf->SetName("plossLayerNegProf");
ploss->SetRangeUser(ploss->GetVar(fgkVarNames[kTrackCharge]), +1.0, +1.0);
TH2D* plossLayerPos = (TH2D*)ploss->Project(0, ploss->GetVar(fgkVarNames[kTrackletLayer]),
ploss->GetVar(fgkVarNames[kTrackPlossTRDlayer]));
plossLayerPos->SetName("plossLayerPos");
TProfile* plossLayerPosProf = plossLayerPos->ProfileX();
plossLayerPosProf->SetName("plossLayerPosProf");
ploss->SetRangeUser(ploss->GetVar(fgkVarNames[kTrackCharge]), -1.5, +1.5);
ploss->SetRangeUser(ploss->GetVar(fgkVarNames[kTrackletLayer]), 0.0, 0.0);
TH3D* ploss3Dl0 = (TH3D*)ploss->Project(0, ploss->GetVar(fgkVarNames[kTrackEtaTRD]),
ploss->GetVar(fgkVarNames[kTrackPhiTRD]),
ploss->GetVar(fgkVarNames[kTrackPlossTRDlayer]));
ploss3Dl0->SetName("ploss3Dl0");
TProfile2D* plossEtaPhiL0Prof = ploss3Dl0->Project3DProfile("yx");
plossEtaPhiL0Prof->SetName("plossEtaPhiL0Prof");
ploss->SetRangeUser(ploss->GetVar(fgkVarNames[kTrackletLayer]), 5.0, 5.0);
TH3D* ploss3Dl5 = (TH3D*)ploss->Project(0, ploss->GetVar(fgkVarNames[kTrackEtaTRD]),
ploss->GetVar(fgkVarNames[kTrackPhiTRD]),
ploss->GetVar(fgkVarNames[kTrackPlossTRDlayer]));
ploss3Dl5->SetName("ploss3Dl5");
TProfile2D* plossEtaPhiL5Prof = ploss3Dl5->Project3DProfile("yx");
plossEtaPhiL5Prof->SetName("plossEtaPhiL5Prof");
pad = ((TVirtualPad*)l->At(4)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.06); pad->SetBottomMargin(0.15);
plossEtaPhiL0Prof->SetStats(kFALSE);
plossEtaPhiL0Prof->SetTitle("");
SetStyle(plossEtaPhiL0Prof->GetXaxis(), "#eta", 0.06, 1.0, kTRUE, 0.06);
SetStyle(plossEtaPhiL0Prof->GetYaxis(), "#varphi (rad.)", 0.06, 1.0, kTRUE, 0.06);
plossEtaPhiL0Prof->SetMaximum(80.0);
plossEtaPhiL0Prof->SetMinimum(-20.0);
plossEtaPhiL0Prof->Draw("colz");
lat->DrawLatex(0.2, 0.95, "P_{loss} at layer 0");
DrawTRDGrid();
pad = ((TVirtualPad*)l->At(7)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.06); pad->SetBottomMargin(0.15);
plossEtaPhiL5Prof->SetStats(kFALSE);
plossEtaPhiL5Prof->SetTitle("");
SetStyle(plossEtaPhiL5Prof->GetXaxis(), "#eta", 0.06, 1.0, kTRUE, 0.06);
SetStyle(plossEtaPhiL5Prof->GetYaxis(), "#varphi (rad.)", 0.06, 1.0, kTRUE, 0.06);
plossEtaPhiL5Prof->SetMaximum(80.0);
plossEtaPhiL5Prof->SetMinimum(-20.0);
plossEtaPhiL5Prof->Draw("colz");
lat->DrawLatex(0.2, 0.95, "P_{loss} at layer 5");
DrawTRDGrid();
pad = ((TVirtualPad*)l->At(2)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.01);
pad->SetTopMargin(0.06); pad->SetBottomMargin(0.15);
plossLayerNegProf->SetStats(kFALSE);
plossLayerNegProf->SetTitle("");
SetStyle(plossLayerNegProf->GetYaxis(), "#Delta P (MeV/c)", 0.06, 1.0, kTRUE, 0.06);
SetStyle(plossLayerNegProf->GetXaxis(), "TRD layer", 0.06, 1.0, kTRUE, 0.06);
SetStyle(plossLayerNegProf, 1, 2, 2, 20, 2, 1);
SetStyle(plossLayerPosProf, 1, 4, 2, 20, 4, 1);
plossLayerNegProf->GetYaxis()->SetRangeUser(TMath::Min(plossLayerNegProf->GetMinimum(),plossLayerPosProf->GetMinimum()-5.0),
TMath::Max(plossLayerNegProf->GetMaximum(),plossLayerPosProf->GetMaximum())+5.0);
plossLayerNegProf->Draw();
plossLayerPosProf->Draw("same");
lat->DrawLatex(0.2, 0.95, "P_{loss} vs layer");
}
// clusters/tracklet and clusters/crossed rows
TH3D* clustersEtaPhi[6]={0x0};
TH3D* clsRowsEtaPhi[6]={0x0};
for(Int_t il=0;il<6;++il) {
if(clusters) {
clusters->SetRangeUser(clusters->GetVar(fgkVarNames[kTrackletLayer]), Double_t(il), Double_t(il));
clustersEtaPhi[il]=(TH3D*)clusters->Project(0, clusters->GetVar(fgkVarNames[kTrackEtaTRD]),
clusters->GetVar(fgkVarNames[kTrackPhiTRD]),
clusters->GetVar(fgkVarNames[kTrackletClusters]));
clustersEtaPhi[il]->SetName(Form("clustersEtaPhi%d",il));
}
if(clsRows) {
clsRows->SetRangeUser(clsRows->GetVar(fgkVarNames[kTrackletLayer]), Double_t(il), Double_t(il));
clsRowsEtaPhi[il]=(TH3D*)clsRows->Project(0, clsRows->GetVar(fgkVarNames[kTrackEtaTRD]),
clsRows->GetVar(fgkVarNames[kTrackPhiTRD]),
clsRows->GetVar(fgkVarNames[kTrackletClustersVsRows]));
clsRowsEtaPhi[il]->SetName(Form("clsRowsEtaPhi%d",il));
}
}
lat->SetTextSize(0.05);
Int_t layerPads[6] = {0, 2, 4, 1, 3, 5};
TCanvas* c2=0x0;
if(clusters) {
c2 = new TCanvas("ESDsummary2", "ESD summary 2", 1600, 1200);
gPad->SetTopMargin(0.05); gPad->SetBottomMargin(0.001);
gPad->SetLeftMargin(0.001); gPad->SetRightMargin(0.001);
gPad->Divide(3,2,0.,0.);
l=gPad->GetListOfPrimitives();
for(Int_t il=0;il<6;++il) {
TProfile2D* clustersEtaPhiProf = clustersEtaPhi[il]->Project3DProfile("yx");
pad = ((TVirtualPad*)l->At(layerPads[il])); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.06); pad->SetBottomMargin(0.15);
clustersEtaPhiProf->SetStats(kFALSE);
clustersEtaPhiProf->SetTitle("");
SetStyle(clustersEtaPhiProf->GetXaxis(), "#eta", 0.06, 1.0, kTRUE, 0.06);
SetStyle(clustersEtaPhiProf->GetYaxis(), "#varphi (rad.)", 0.06, 1.0, kTRUE, 0.06);
clustersEtaPhiProf->SetMaximum(30.);
clustersEtaPhiProf->Draw("colz");
lat->DrawLatex(0.2, 0.95, Form("Clusters / tracklet, layer %d", il));
DrawTRDGrid();
}
}
TCanvas* c3=0x0;
if(clsRows) {
c3 = new TCanvas("ESDsummary3", "ESD summary 3", 1600, 1200);
gPad->SetTopMargin(0.05); gPad->SetBottomMargin(0.001);
gPad->SetLeftMargin(0.001); gPad->SetRightMargin(0.001);
gPad->Divide(3,2,0.,0.);
l=gPad->GetListOfPrimitives();
for(Int_t il=0;il<6;++il) {
TProfile2D* clsRowsEtaPhiProf = clsRowsEtaPhi[il]->Project3DProfile("yx");
pad = ((TVirtualPad*)l->At(layerPads[il])); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.13);
pad->SetTopMargin(0.06); pad->SetBottomMargin(0.15);
clsRowsEtaPhiProf->SetStats(kFALSE);
clsRowsEtaPhiProf->SetTitle("");
SetStyle(clsRowsEtaPhiProf->GetXaxis(), "#eta", 0.06, 1.0, kTRUE, 0.06);
SetStyle(clsRowsEtaPhiProf->GetYaxis(), "#varphi (rad.)", 0.06, 1.0, kTRUE, 0.06);
clsRowsEtaPhiProf->Draw("colz");
lat->DrawLatex(0.2, 0.95, Form("Clusters / crossed rows, layer %d", il));
DrawTRDGrid();
}
}
if(matchPhiEta || trdChi2 || trdBudget || ploss) c1->SaveAs("esdSummary1.gif");
if(clusters) c2->SaveAs("esdSummary2.gif");
if(clsRows) c3->SaveAs("esdSummary3.gif");
}
//__________________________________________________________________________________________________
void AliTRDcheckESD::DrawTRDGrid() {
//
// Draw a grid of lines showing the TRD supermodule and stack structure in (eta,phi) coordinates.
// The canvas on which to draw must already exist.
//
TLine line;
line.SetLineColor(2);
line.SetLineWidth(1);
line.SetLineStyle(2);
for(Int_t i=-9; i<=9; ++i) {
line.DrawLine(-0.92, 2.0*TMath::Pi()/18.0*i, +0.92, 2.0*TMath::Pi()/18.0*i);
}
line.DrawLine(-0.85, -3.15, -0.85, 3.15);
line.DrawLine(-0.54, -3.15, -0.54, 3.15);
line.DrawLine(-0.16, -3.15, -0.16, 3.15);
line.DrawLine(+0.16, -3.15, +0.16, 3.15);
line.DrawLine(+0.54, -3.15, +0.54, 3.15);
line.DrawLine(+0.85, -3.15, +0.85, 3.15);
}
//_________________________________________________________________
void AliTRDcheckESD::SetStyle(TH1* hist,
Int_t lineStyle, Int_t lineColor, Int_t lineWidth,
Int_t markerStyle, Int_t markerColor, Int_t markerSize) {
//
// Set style settings for histograms
//
if(!hist) return;
hist->SetLineStyle(lineStyle);
hist->SetLineColor(lineColor);
hist->SetLineWidth(lineWidth);
hist->SetMarkerStyle(markerStyle);
hist->SetMarkerColor(markerColor);
hist->SetMarkerSize(markerSize);
}
//____________________________________________________________________
void AliTRDcheckESD::SetStyle(TAxis* axis, const Char_t* title, Float_t titleSize, Float_t titleOffset, Bool_t centerTitle,
Float_t labelSize) {
//
// Set style settings for axes
//
if(!axis) return;
axis->SetTitle(title);
axis->SetTitleSize(titleSize);
axis->SetTitleOffset(titleOffset);
axis->CenterTitle(centerTitle);
axis->SetLabelSize(labelSize);
axis->SetTitleFont(42);
axis->SetLabelFont(42);
axis->SetNdivisions(507);
}
//____________________________________________________________________
void AliTRDcheckESD::FindIsolatedBCs(TH1D* bcHist, Bool_t isIsolated[3500]) {
//
// Find the isolated bunch crossings
//
Int_t isolationSize = 5; // number of free bunches in both directions
for(Int_t bcBin=1; bcBin<=bcHist->GetXaxis()->GetNbins(); ++bcBin) {
Int_t bc = TMath::Nint(bcHist->GetBinCenter(bcBin));
if(bc<-0.001 || bc>3499.01) {
isIsolated[bc] = kFALSE;
continue;
}
Double_t entries = bcHist->GetBinContent(bcBin);
if(entries<0.001) {
isIsolated[bc] = kFALSE;
continue; // no entries
}
// check isolation
isIsolated[bc] = kTRUE;
for(Int_t ibc = TMath::Max(1,bcBin-isolationSize); ibc<=TMath::Min(3499, bcBin+isolationSize); ++ibc) {
if(ibc==bcBin) continue;
if(bcHist->GetBinContent(ibc)>0.01) {
isIsolated[bc] = kFALSE;
break;
}
}
} // end loop over BC bins
cout << "Isolated bunches: " << endl;
for(Int_t ibc=0; ibc<3500; ++ibc)
if(isIsolated[ibc]) cout << "BC #" << ibc << endl;
}
//__________________________________________________________________________________________________
Int_t AliTRDcheckESD::GetTriggerIndex(const Char_t* name, Bool_t createNew/*=kTRUE*/) {
//
// Return the index of trigger "name" in the trigger histogram.
// If the index for this trigger does not exist yet, then assign one if createNew is set to TRUE
//
//cout << "GetTriggerIndex for " << name << endl;
TH1F* triggerHist = (TH1F*)fHistos->FindObject("hTriggerDefs");
TString nameStr=name;
for(Int_t i=1; i<=triggerHist->GetXaxis()->GetNbins(); ++i) {
if(!nameStr.CompareTo(triggerHist->GetXaxis()->GetBinLabel(i))) {
//cout << " index found: " << i << endl;
return i;
}
}
if(createNew) {
triggerHist->GetXaxis()->SetBinLabel(fNAssignedTriggers+1, name);
for(Int_t i=1;i<fHistos->GetEntries();++i) {
TString objType = fHistos->At(i)->IsA()->GetName();
if(!objType.Contains("AliCFContainer")) continue;
AliCFContainer* cf=(AliCFContainer*)fHistos->At(i);
Int_t trigVar = cf->GetVar(fgkVarNames[kEventTrigger]);
if(trigVar>=0)
for(Int_t istep=0;istep<cf->GetNStep();++istep)
cf->GetAxis(trigVar, istep)->SetBinLabel(fNAssignedTriggers+1, name);
} // end loop over histograms and CFs
++fNAssignedTriggers;
return fNAssignedTriggers+1;
}
else {
return -1;
}
}
//__________________________________________________________________________________________________
void AliTRDcheckESD::PrintTriggers() const {
//
// Print the available triggers for this run
//
if(!fHistos) {
cout << "Warning in AliTRDcheckESD::PrintTriggers(): No file loaded!" << endl;
return;
}
TH1F* hTriggers = (TH1F*)fHistos->FindObject("hTriggerDefs");
cout << "Triggers found in this run" << endl;
cout << "==========================" << endl;
cout << "Name Index Entries " << endl;
for(Int_t it=1; it<hTriggers->GetXaxis()->GetNbins(); ++it) {
if(hTriggers->GetXaxis()->GetBinLabel(it)[0]!='\0') {
cout << hTriggers->GetXaxis()->GetBinLabel(it) << " " << hTriggers->GetXaxis()->GetBinCenter(it) << " " << hTriggers->GetBinContent(it) << endl;
}
}
}
//__________________________________________________________________________________________________
Int_t AliTRDcheckESD::GetTriggerCounter(const Char_t* triggerName) const {
//
// Get the number of events for a given trigger name
//
if(!fHistos) {
cout << "Warning in AliTRDcheckESD::PrintTriggers(): No file loaded!" << endl;
return -1;
}
TH1F* hTriggers = (TH1F*)fHistos->FindObject("hTriggerDefs");
Int_t counter = -1;
for(Int_t it=1; it<hTriggers->GetXaxis()->GetNbins(); ++it) {
TString trgString = hTriggers->GetXaxis()->GetBinLabel(it);
if(!trgString.CompareTo(triggerName))
counter = (Int_t)hTriggers->GetBinContent(it);
}
if(counter<0) {cout << "AliTRDcheckESD::GetTriggerCounter() Trigger not found !!";}
return counter;
}
//__________________________________________________________________________________________________________
Int_t AliTRDcheckESD::GetNAssignedTriggers() {
//
// Return the number of assigned triggers
//
return fNAssignedTriggers;
}
Update for the pid summary drawing (Ionut)
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* 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. *
**************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// Check basic detector results at ESD level //
// - Geometrical efficiency //
// - Tracking efficiency //
// - PID efficiency //
// - Refit efficiency //
// //
// Author //
// Alex Bercuci <A.Bercuci@gsi.de> //
// Ionut Arsene <i.c.arsene@gsi.de> //
// //
// The analysis task fills AliCFContainer objects defined in the //
// configuration macro using the AddCFContainer() method. //
// The CF containers can be filled with any of the variables defined //
// in ETrdCfVariables and at any of the steps defined in ETrdCfSteps. //
// To define a new variable one needs to: //
// 1. Add an entry in the ETrdCfVariables enumeration //
// 2. Add the corresponding variable name (and in the correct order) //
// in fgkVarNames //
// 3. Define how the variable is filled in one of the Fill functions: //
// FillEventInfo(), FillTrackInfo(), FillTrackletInfo(), //
// FillTrackletSliceInfo(). //
// To define a new step one needs to: //
// 1. Add an entry in the ETrdCfSteps //
// 2. Add the corresponding name in fgkStepNames //
// 3. Define the track level cuts for this step in IsTrackSelected() //
// //
//////////////////////////////////////////////////////////////////////////
#include <TClonesArray.h>
#include <TCanvas.h>
#include <TObjArray.h>
#include <TPad.h>
#include <TLegend.h>
#include <TLatex.h>
#include <TLine.h>
#include <TF1.h>
#include <TH1D.h>
#include <TH2D.h>
#include <TH3D.h>
#include <TH2I.h>
#include <TH2F.h>
#include <TH3S.h>
#include <TH3F.h>
#include <TProfile2D.h>
#include <TProfile.h>
#include <TGraphErrors.h>
#include <TGraphAsymmErrors.h>
#include <TFile.h>
#include <TTree.h>
#include <TROOT.h>
#include <TChain.h>
#include <TParticle.h>
#include <TTimeStamp.h>
#include <TRandom.h>
#include <TString.h>
#include "AliLog.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisCuts.h"
#include "AliPhysicsSelection.h"
#include "AliESDEvent.h"
#include "AliESDkink.h"
#include "AliMCEvent.h"
#include "AliESDInputHandler.h"
#include "AliMCEventHandler.h"
#include "AliESDpid.h"
#include "AliExternalTrackParam.h"
#include "AliESDtrack.h"
#include "AliMCParticle.h"
#include "AliPID.h"
#include "AliStack.h"
#include "AliTrackReference.h"
#include "AliMultiplicity.h"
#include "AliCFContainer.h"
#include "AliTRDcheckESD.h"
#include <iostream>
using std::cout;
using std::endl;
ClassImp(AliTRDcheckESD)
const Float_t AliTRDcheckESD::fgkxTPC = 290.;
const Float_t AliTRDcheckESD::fgkxTOF = 365.;
const Char_t* AliTRDcheckESD::fgkVarNames[AliTRDcheckESD::kNTrdCfVariables] = {
"vtxZ", "multiplicity", "trigger", "BC", "TOFBC", "DCAxy", "DCAz", "charge", "OuterParam rad.", "phiVtx", "phi",
"etaVtx", "eta", "pt", "ptTRD", "P", "PTRD", "TRDchi2", "tracklets", "clusters", "TrdQuality",
"TrdBudget", "TOFchi2", "Qtot0", "ClustersPerRows", "Clusters/tracklet", "TrdP", "TrdPloss", "layer", "slice", "PH0"
};
const Char_t* AliTRDcheckESD::fgkStepNames[AliTRDcheckESD::kNSteps] = {"TPC", "TRD", "TOF", "TOFin", "TOFout"};
FILE* AliTRDcheckESD::fgFile = NULL;
//____________________________________________________________________
AliTRDcheckESD::AliTRDcheckESD():
AliAnalysisTaskSE()
,fStatus(0)
,fNRefFigures(0)
,fESD(NULL)
,fMC(NULL)
,fESDpid(new AliESDpid)
,fHistos(NULL)
,fReferenceTrackFilter(NULL)
,fPhysSelTriggersEnabled(kFALSE)
,fUserEnabledTriggers("")
,fNAssignedTriggers(0)
{
//
// Default constructor
//
SetNameTitle("TRDcheckESD", "Check TRD @ ESD level");
SetMC(kTRUE);
}
//____________________________________________________________________
AliTRDcheckESD::AliTRDcheckESD(char* name):
AliAnalysisTaskSE(name)
,fStatus(0)
,fNRefFigures(0)
,fESD(NULL)
,fMC(NULL)
,fESDpid(new AliESDpid)
,fHistos(NULL)
,fReferenceTrackFilter(NULL)
,fPhysSelTriggersEnabled(kFALSE)
,fUserEnabledTriggers("")
,fNAssignedTriggers(0)
{
//
// Default constructor
//
SetMC(kTRUE);
SetTitle("Check TRD @ ESD level");
DefineOutput(1, TObjArray::Class());
}
//____________________________________________________________________
AliTRDcheckESD::~AliTRDcheckESD()
{
// Destructor
if(fHistos && !(AliAnalysisManager::GetAnalysisManager() && AliAnalysisManager::GetAnalysisManager()->IsProofMode())){
if(fHistos->IsOwner()) fHistos->Delete();
delete fHistos;
fHistos = NULL;
}
}
//____________________________________________________________________
void AliTRDcheckESD::FillEventInfo(Double_t* values) {
//
// Fill event information
//
values[kEventVtxZ] = fESD->GetPrimaryVertex()->GetZ();
values[kEventBC] = fESD->GetBunchCrossNumber();
const AliMultiplicity* mult=fESD->GetMultiplicity();
Double_t itsNTracklets = mult->GetNumberOfTracklets();
values[kEventMult] = itsNTracklets;
}
//____________________________________________________________________
void AliTRDcheckESD::FillTrackInfo(Double_t* values, AliESDtrack* esdTrack) {
//
// Fill track information
//
Float_t dcaxy,dcaz;
esdTrack->GetImpactParameters(dcaxy,dcaz);
values[kTrackDCAxy] = dcaxy;
values[kTrackDCAz] = dcaz;
values[kTrackCharge] = esdTrack->Charge();
values[kTrackPt] = esdTrack->Pt();
values[kTrackPhi] = esdTrack->Phi();
values[kTrackEta] = esdTrack->Eta();
values[kTrackP] = esdTrack->P();
values[kTrackTrdTracklets] = esdTrack->GetTRDntracklets();
values[kTrackTrdClusters] = esdTrack->GetTRDncls();
values[kTrackTrdChi2] = esdTrack->GetTRDchi2()/(esdTrack->GetTRDntracklets()>0 ? esdTrack->GetTRDntracklets() : 1.0);
values[kTrackTrdQuality] = esdTrack->GetTRDQuality();
values[kTrackTRDBudget] = -1.0*esdTrack->GetTRDBudget();
values[kTrackTOFBC] = esdTrack->GetTOFBunchCrossing(fESD->GetMagneticField());
values[kTrackTOFchi2] = esdTrack->GetTOFchi2();
const AliExternalTrackParam *out=esdTrack->GetOuterParam();
Double_t p[3];
if(out->GetXYZ(p))
values[kTrackOuterParamRadius] = TMath::Sqrt(p[0]*p[0]+p[1]*p[1]);
else
values[kTrackOuterParamRadius] = 0.0;
}
//____________________________________________________________________
void AliTRDcheckESD::FillTrackletInfo(Double_t* values, AliESDtrack* esdTrack, Int_t iPlane,
Double_t* localSagitaPhi, Double_t localMom[][3], Bool_t* localMomGood) {
//
// Fill TRD tracklet info
//
values[kTrackletClustersVsRows] = esdTrack->GetTRDtrkltClCross(iPlane);
values[kTrackletClusters] = esdTrack->GetTRDtrkltOccupancy(iPlane);
values[kTrackletQtot] = esdTrack->GetTRDslice(iPlane, 0);
values[kTrackletP] = esdTrack->GetTRDmomentum(iPlane);
values[kTrackPlossTRDlayer] = 1000.0*(esdTrack->P() - values[kTrackletP]); // p loss in MeV
values[kTrackletLayer] = iPlane;
values[kTrackPhiTRD] = localSagitaPhi[iPlane];
values[kTrackPtTRD] = (localMomGood[iPlane] ? TMath::Sqrt(localMom[iPlane][0]*localMom[iPlane][0]+
localMom[iPlane][1]*localMom[iPlane][1]) : values[kTrackPt]);
values[kTrackPTRD] = (localMomGood[iPlane] ? TMath::Sqrt(values[kTrackPtTRD]*values[kTrackPtTRD]+
localMom[iPlane][2]*localMom[iPlane][2]) : values[kTrackP]);
values[kTrackEtaTRD] = values[kTrackPTRD]-(localMomGood[iPlane] ? localMom[iPlane][2] : esdTrack->Pz());
values[kTrackEtaTRD] = (TMath::Abs(values[kTrackPTRD])>1.0e-8 ? (values[kTrackPTRD]+(localMomGood[iPlane] ? localMom[iPlane][2] : esdTrack->Pz()))/values[kTrackEtaTRD] : 0.0);
values[kTrackEtaTRD] = (values[kTrackEtaTRD]>1.0e-8 ? 0.5*TMath::Log(values[kTrackEtaTRD]) : -999.);
}
//____________________________________________________________________
void AliTRDcheckESD::FillTrackletSliceInfo(Double_t* values, AliESDtrack* esdTrack, Int_t iSlice) {
//
// Fill TRD tracklet info
//
values[kTrackletPHslice] = esdTrack->GetTRDslice(Int_t(values[kTrackletLayer]), iSlice);
values[kTrackletSlice] = iSlice;
}
//____________________________________________________________________
Bool_t AliTRDcheckESD::IsTrackSelected(AliESDtrack* track, Double_t* /*values*/, Int_t step) {
//
// Select tracks at each step
//
Bool_t referenceFilter = fReferenceTrackFilter->IsSelected(track);
if(step==kTPCreference) { // reference track filter
return referenceFilter;
}
if(step==kTRD) { // TRD reference track filter
return (referenceFilter && Int_t(track->GetTRDntracklets()>0));
}
if(step==kTOF) { // TRD+(TOFout || TOFpid) request
return (referenceFilter && Int_t(track->GetTRDntracklets())>0 &&
((track->GetStatus() & AliESDtrack::kTOFout) || (track->GetStatus() & AliESDtrack::kTOFpid)));
}
if(step==kTOFin) { // TOFin request
return (referenceFilter && (track->GetStatus() & AliESDtrack::kTOFin));
}
if(step==kTOFout) { // TOFout request
return (referenceFilter && (track->GetStatus() & AliESDtrack::kTOFout));
}
return kFALSE;
}
//____________________________________________________________________
void AliTRDcheckESD::UserCreateOutputObjects()
{
//
// Create Output Containers (TObjectArray containing 1D histograms)
//
Histos();
PostData(1, fHistos);
}
//____________________________________________________________________
void AliTRDcheckESD::MakeSummaryFromCF(Double_t* trendValues, const Char_t* /*triggerName*/, Bool_t /*useIsolatedBC*/, Bool_t /*cutTOFbc*/){
//
// Draw summary plots for the ESDcheck task using the CF container
//
cout << "Make summary from CF" << endl;
TCanvas *cOut=0x0;
if(gROOT->FindObject("trackingSummary")) delete gROOT->FindObject("trackingSummary");
cOut = new TCanvas("trackingSummary", "Tracking summary for the ESD task", 1600, 1200);
cOut->cd();
//PlotTrackingSummaryFromCF(trendValues, triggerName, useIsolatedBC, cutTOFbc);
PlotTrackingSummaryFromCF(trendValues);
cOut->SaveAs("trackingSummary.gif");
if(gROOT->FindObject("pidSummary")) delete gROOT->FindObject("pidSummary");
cOut = new TCanvas("pidSummary", "PID summary for the ESD task", 1600, 1200);
cOut->cd();
//PlotPidSummaryFromCF(trendValues, triggerName, useIsolatedBC, cutTOFbc);
PlotPidSummaryFromCF(trendValues);
cOut->SaveAs("pidSummary.gif");
if(gROOT->FindObject("centSummary")) delete gROOT->FindObject("centSummary");
cOut = new TCanvas("centSummary", "Centrality summary for the ESD task", 1600, 1200);
cOut->cd();
//PlotCentSummaryFromCF(trendValues, triggerName, useIsolatedBC, cutTOFbc);
PlotCentSummaryFromCF(trendValues);
cOut->SaveAs("centSummary.gif");
PlotOtherSummaryFromCF(trendValues);
if(trendValues)
for(Int_t i=0;i<50;++i) cout << "trend #" << i << " :: " << trendValues[i] << endl;
}
//____________________________________________________________________
void AliTRDcheckESD::UserExec(Option_t *){
//
// Run the Analysis
//
fESD = dynamic_cast<AliESDEvent*>(InputEvent());
fMC = MCEvent();
if(!fESD){
AliError("ESD event missing.");
return;
}
AliAnalysisManager *man=AliAnalysisManager::GetAnalysisManager();
AliInputEventHandler* inputHandler = (AliInputEventHandler*) (man->GetInputEventHandler());
if(!inputHandler) return;
if(!fPhysSelTriggersEnabled) {
InitializeCFContainers();
fPhysSelTriggersEnabled = kTRUE;
}
UInt_t isSelected = AliVEvent::kAny;
if(inputHandler){
if(inputHandler->GetEventSelection()) {
isSelected = inputHandler->IsEventSelected();
}
}
if(!isSelected) return;
TString triggerClasses = fESD->GetFiredTriggerClasses();
//cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++triggers fired: " << triggerClasses.Data() << endl;
TObjArray* triggers = triggerClasses.Tokenize(" ");
TObjArray* userTriggers = fUserEnabledTriggers.Tokenize(";");
if(triggers->GetEntries()<1) {delete triggers; delete userTriggers; return;}
Bool_t hasGoodTriggers = kFALSE;
Int_t triggerIndices[kNMaxAssignedTriggers] = {0};
Int_t nTrigFired=0;
Bool_t trigAlreadyChecked = kFALSE;
Bool_t trigSelected = kFALSE;
Int_t trigIdx = 0;
for(Int_t i=0; i<triggers->GetEntries(); ++i) {
TString trigStr=triggers->At(i)->GetName();
if(!trigStr.Contains("NOTRD") && !trigStr.Contains("MUON")) hasGoodTriggers = kTRUE; // check wheter TRD was read out in this event
if(trigStr.Contains("NOTRD")) continue;
if(trigStr.Contains("MUON")) continue;
if(i>=kNMaxAssignedTriggers) continue;
hasGoodTriggers = kTRUE;
// enable the "All triggers" bit
trigIdx = 1;
trigAlreadyChecked = kFALSE;
for(Int_t k=0;k<nTrigFired;++k)
if(triggerIndices[k]==trigIdx) {
trigAlreadyChecked = kTRUE;
break;
}
if(!trigAlreadyChecked) triggerIndices[nTrigFired++] = trigIdx;
trigSelected = kFALSE;
// check whether this trigger matches any of the user defined trigger families
for(Int_t j=0;j<userTriggers->GetEntries();++j) {
TString userTrigStr=userTriggers->At(j)->GetName();
if(trigStr.Contains(userTrigStr.Data())) {
trigSelected = kTRUE;
trigIdx = GetTriggerIndex(userTrigStr.Data(), kFALSE);
trigAlreadyChecked = kFALSE;
for(Int_t k=0;k<nTrigFired;++k)
if(triggerIndices[k]==trigIdx) {
trigAlreadyChecked = kTRUE;
break;
}
if(!trigAlreadyChecked) { // add trigger to the list of enabled triggers only if it was not added already
triggerIndices[nTrigFired++] = trigIdx;
}
}
}
trigIdx = GetTriggerIndex(trigStr.Data(), kFALSE);
if(trigIdx>0) trigSelected = kTRUE;
if(trigIdx==-1) trigIdx=1;
trigAlreadyChecked = kFALSE;
for(Int_t k=0;k<nTrigFired;++k)
if(triggerIndices[k]==trigIdx) {
trigAlreadyChecked = kTRUE;
break;
}
if(!trigAlreadyChecked) {
triggerIndices[nTrigFired++]=1; // 0-assigned to all other triggers
}
} // end loop over triggers
if(!trigSelected && hasGoodTriggers) {
triggerIndices[nTrigFired++]=2;
}
TH1F* hTrig = (TH1F*)fHistos->FindObject("hTriggerDefs");
for(Int_t i=0; i<nTrigFired; ++i)
hTrig->Fill(triggerIndices[i]);
if(!hasGoodTriggers) {
PostData(1, fHistos);
delete triggers;
delete userTriggers;
return;
}
Int_t* trigFiredIdx=new Int_t[nTrigFired];
for(Int_t i=0;i<nTrigFired;++i) trigFiredIdx[i] = triggerIndices[i];
// Get MC information if available
//AliStack * fStack = NULL;
if(HasMC()){
if(!fMC){
AliWarning("MC event missing");
SetMC(kFALSE);
} else {
if(!fMC->Stack()){
AliWarning("MC stack missing");
SetMC(kFALSE);
}
}
}
Double_t values[kNTrdCfVariables]; // array where the CF container variables are stored
for(Int_t i=0;i<kNTrdCfVariables; ++i) values[i] = -999.;
FillEventInfo(values);
Int_t multLimits[6] = {0, 700, 1400, 2100, 2800, 3500};
Int_t centralityClass = 0;
for(Int_t iCent=0; iCent<5; ++iCent) {
if(values[kEventMult]>=multLimits[iCent] && values[kEventMult]<multLimits[iCent+1])
centralityClass=iCent+1;
}
if(centralityClass == 0) return;
// radius of TRD entrance plane in each layer
Double_t rTRD[6] = {298.0, 311.0, 324.0, 337.0, 350.0, 363.0};
AliESDtrack *esdTrack(NULL);
for(Int_t itrk = 0; itrk < fESD->GetNumberOfTracks(); itrk++){
esdTrack = fESD->GetTrack(itrk);
Bool_t stepSelections[kNSteps];
for(Int_t is=0;is<kNSteps;++is) {
stepSelections[is] = IsTrackSelected(esdTrack, values, is);
}
if(!stepSelections[0]) continue;
FillTrackInfo(values, esdTrack);
// find position and momentum of the track at entrance in TRD
const AliExternalTrackParam *outerParam = esdTrack->GetOuterParam();
Double_t localCoord[6][3] = {{0.0}};
Bool_t localCoordGood[6];
for(Int_t il=0;il<6;++il)
localCoordGood[il] = (outerParam ? outerParam : esdTrack)->GetXYZAt(rTRD[il], fESD->GetMagneticField(), localCoord[il]);
Double_t localMom[6][3] = {{0.0}};
Bool_t localMomGood[6];
for(Int_t il=0; il<6; ++il)
localMomGood[il] = (outerParam ? outerParam : esdTrack)->GetPxPyPzAt(rTRD[il], fESD->GetMagneticField(), localMom[il]);
Double_t localSagitaPhi[6] = {-999.};
for(Int_t il=0; il<6; ++il)
localSagitaPhi[il] = (localCoordGood[il] ? TMath::ATan2(localCoord[il][1], localCoord[il][0]) : -999.);
if(!localMomGood[0]) continue;
// fill tracklet values such that the TRD local coordinates are filled
FillTrackletInfo(values, esdTrack, 0, localSagitaPhi, localMom, localMomGood);
for(Int_t itrig=0; itrig<nTrigFired; ++itrig) {
values[kEventTrigger] = Double_t(trigFiredIdx[itrig]);
// check if cf needs tracklet or slice info
FillGlobalTrackContainers(values, stepSelections, itrig);
for(Int_t iPlane=0; iPlane<6; iPlane++) {
FillTrackletInfo(values, esdTrack, iPlane, localSagitaPhi, localMom, localMomGood);
if(values[kTrackletQtot]>20.0) FillTrdTrackletContainers(values, stepSelections, itrig);
for(Int_t iSlice=0; iSlice<8; iSlice++) {
FillTrackletSliceInfo(values, esdTrack, iSlice);
if(values[kTrackletPHslice]>20.0) FillTrdSliceContainers(values, stepSelections, itrig);
} // end loop over slices
} // end loop over TRD layers
} // end loop over triggers
} // end loop over tracks
delete triggers;
delete userTriggers;
delete [] trigFiredIdx;
PostData(1, fHistos);
}
//____________________________________________________________________
TObjArray* AliTRDcheckESD::Histos()
{
// Retrieve histograms array if already build or build it
if(!fHistos) {
fHistos = new TObjArray();
fHistos->SetOwner(kTRUE);
}
TH1* h = 0x0;
// Trigger definitions
if(!(h=(TH1F*)gROOT->FindObject("hTriggerDefs"))) {
h = new TH1F("hTriggerDefs", "Trigger definitions", kNMaxAssignedTriggers, 0.5, 0.5+Float_t(kNMaxAssignedTriggers));
}
else h->Reset();
fHistos->Add(h);
return fHistos;
}
//__________________________________________________________________________________________________________
void AliTRDcheckESD::InitializeCFContainers() {
//
// Initialize the CF container
//
AliAnalysisManager* man=AliAnalysisManager::GetAnalysisManager();
AliInputEventHandler* inputHandler = (AliInputEventHandler*) (man->GetInputEventHandler());
if(!inputHandler) return;
GetTriggerIndex("All triggers", kTRUE);
GetTriggerIndex("Not specified triggers", kTRUE);
AliPhysicsSelection* physSel = (AliPhysicsSelection*)inputHandler->GetEventSelection();
const TList* trigList = (physSel ? physSel->GetCollisionTriggerClasses() : 0x0);
const TList* bgTrigList = (physSel ? physSel->GetBGTriggerClasses() : 0x0);
// Add collision triggers from PhysicsSelection
if(trigList) {
for(Int_t it=0; it<trigList->GetEntries(); ++it) {
TString trigName = trigList->At(it)->GetName();
TObjArray* arr = trigName.Tokenize(" ");
trigName = arr->At(0)->GetName();
trigName.Remove(0,1);
TObjArray* arr2 = trigName.Tokenize(",");
for(Int_t jt=0; jt<arr2->GetEntries(); ++jt) {
// Assign an index into the trigger histogram and the CF container for this trigger
GetTriggerIndex(arr2->At(jt)->GetName(), kTRUE);
}
delete arr;
}
}
// Add background triggers from PhysicsSelection
if(bgTrigList) {
for(Int_t it=0; it<bgTrigList->GetEntries(); ++it) {
TString trigName = bgTrigList->At(it)->GetName();
TObjArray* arr = trigName.Tokenize(" ");
trigName = arr->At(0)->GetName();
trigName.Remove(0,1);
TObjArray* arr2 = trigName.Tokenize(",");
for(Int_t jt=0; jt<arr2->GetEntries(); ++jt) {
// Assign an index into the trigger histogram and the CF container for this trigger
GetTriggerIndex(arr2->At(jt)->GetName(), kTRUE);
}
delete arr;
}
}
// Add user enabled triggers
TObjArray* arr = fUserEnabledTriggers.Tokenize(";");
for(Int_t it=0; it<arr->GetEntries(); ++it) {
GetTriggerIndex(arr->At(it)->GetName(), kTRUE);
}
delete arr;
}
//__________________________________________________________________________________________________________
void AliTRDcheckESD::AddCFContainer(const Char_t* name, const Char_t* title,
Int_t nSteps, Int_t* steps,
Int_t nVars, UInt_t* vars, TArrayD* binLimits) {
//
// Add a CF container
//
if(!fHistos) {
fHistos = new TObjArray();
fHistos->SetOwner(kTRUE);
}
// get number of bins for each variable
Int_t* nBins = new Int_t[nVars];
for(Int_t iv=0;iv<nVars;++iv)
nBins[iv] = binLimits[iv].GetSize()-1;
// create the CF container
AliCFContainer* cf = new AliCFContainer(name, title, nSteps, nVars, nBins);
// set CF container variable binning and name
for(Int_t iv=0;iv<nVars;++iv) {
cf->SetBinLimits(iv, binLimits[iv].GetArray());
cf->SetVarTitle(iv, fgkVarNames[vars[iv]]);
}
// set the step names
for(Int_t is=0; is<nSteps; ++is) {
cf->SetStepTitle(is, fgkStepNames[steps[is]]);
for(Int_t iv=0;iv<nVars;++iv) cf->GetAxis(iv, is)->SetUniqueID(vars[iv]);
}
fHistos->Add(cf);
}
//__________________________________________________________________________________________________
void AliTRDcheckESD::FillTrdSliceContainers(Double_t* values, Bool_t* stepSelections, Int_t itrig) {
//
// fill TRD slice info
//
if(!fHistos) return;
for(Int_t i=0;i<fHistos->GetEntries();++i) {
TString objType = fHistos->At(i)->IsA()->GetName();
if(!objType.Contains("AliCFContainer")) continue;
AliCFContainer* cf = (AliCFContainer*)fHistos->At(i);
TString varNames="";
for(Int_t ivar=0;ivar<cf->GetNVar();++ivar) {
varNames += cf->GetVarTitle(ivar); varNames += ";";
}
//if(cf->GetVar(fgkVarNames[kTrackletSlice])<0 && cf->GetVar(fgkVarNames[kTrackletPHslice])<0) continue;
if(!varNames.Contains(fgkVarNames[kTrackletSlice]) && !varNames.Contains(fgkVarNames[kTrackletPHslice])) continue;
//if((cf->GetVar(fgkVarNames[kEventTrigger])<0 && itrig==0) || (cf->GetVar(fgkVarNames[kEventTrigger])>=0))
if((!varNames.Contains(fgkVarNames[kEventTrigger]) && itrig==0) || varNames.Contains(fgkVarNames[kEventTrigger]))
FillCFContainer(cf, values, stepSelections);
}
}
//__________________________________________________________________________________________________
void AliTRDcheckESD::FillTrdTrackletContainers(Double_t* values, Bool_t* stepSelections, Int_t itrig) {
//
// fill global track info
//
if(!fHistos) return;
for(Int_t i=0;i<fHistos->GetEntries();++i) {
TString objType = fHistos->At(i)->IsA()->GetName();
if(!objType.Contains("AliCFContainer")) continue;
AliCFContainer* cf = (AliCFContainer*)fHistos->At(i);
TString varNames="";
for(Int_t ivar=0;ivar<cf->GetNVar();++ivar) {
varNames += cf->GetVarTitle(ivar); varNames += ";";
}
//if(cf->GetVar(fgkVarNames[kTrackletSlice])>=0 || cf->GetVar(fgkVarNames[kTrackletPHslice])>=0) continue;
if(varNames.Contains(fgkVarNames[kTrackletSlice]) || varNames.Contains(fgkVarNames[kTrackletPHslice])) continue;
//if(cf->GetVar(fgkVarNames[kTrackletLayer])<0 && cf->GetVar(fgkVarNames[kTrackletQtot])<0) continue;
if(!varNames.Contains(fgkVarNames[kTrackletLayer]) && !varNames.Contains(fgkVarNames[kTrackletQtot])) continue;
//if((cf->GetVar(fgkVarNames[kEventTrigger])<0 && itrig==0) || (cf->GetVar(fgkVarNames[kEventTrigger])>=0))
if((!varNames.Contains(fgkVarNames[kEventTrigger]) && itrig==0) || varNames.Contains(fgkVarNames[kEventTrigger]))
FillCFContainer(cf, values, stepSelections);
}
}
//__________________________________________________________________________________________________
void AliTRDcheckESD::FillGlobalTrackContainers(Double_t* values, Bool_t* stepSelections, Int_t itrig) {
//
// fill global track info
//
if(!fHistos) return;
for(Int_t i=0;i<fHistos->GetEntries();++i) {
TString objType = fHistos->At(i)->IsA()->GetName();
if(!objType.Contains("AliCFContainer")) continue;
AliCFContainer* cf = (AliCFContainer*)fHistos->At(i);
TString varNames="";
for(Int_t ivar=0;ivar<cf->GetNVar();++ivar) {
varNames += cf->GetVarTitle(ivar); varNames += ";";
}
/*if(cf->GetVar(fgkVarNames[kTrackletLayer])>=0 ||
cf->GetVar(fgkVarNames[kTrackletSlice])>=0 ||
cf->GetVar(fgkVarNames[kTrackletQtot])>=0 ||
cf->GetVar(fgkVarNames[kTrackletPHslice])>=0) continue;*/
if(varNames.Contains(fgkVarNames[kTrackletLayer]) ||
varNames.Contains(fgkVarNames[kTrackletSlice]) ||
varNames.Contains(fgkVarNames[kTrackletQtot]) ||
varNames.Contains(fgkVarNames[kTrackletPHslice])) continue;
/*if((cf->GetVar(fgkVarNames[kEventTrigger])<0 && itrig==0) ||
(cf->GetVar(fgkVarNames[kEventTrigger])>=0))*/
if((!varNames.Contains(fgkVarNames[kEventTrigger]) && itrig==0) ||
varNames.Contains(fgkVarNames[kEventTrigger]))
FillCFContainer(cf, values, stepSelections);
}
}
//__________________________________________________________________________________________________
void AliTRDcheckESD::FillCFContainer(AliCFContainer* cf, Double_t* values, Bool_t* stepSelections) {
//
// Fill CF container
//
Double_t* cfValues=new Double_t[cf->GetNVar()];
for(Int_t iv=0;iv<cf->GetNVar();++iv)
cfValues[iv] = values[cf->GetAxis(iv,0)->GetUniqueID()];
for(Int_t istep=0; istep<cf->GetNStep(); ++istep) {
TString stepTitle = cf->GetStepTitle(istep);
Int_t stepNo = -1;
for(Int_t is=0;is<kNSteps;++is)
if(!stepTitle.CompareTo(fgkStepNames[is])) {
stepNo = is;
break;
}
if(stepSelections[stepNo]) cf->Fill(cfValues, istep);
} // end loop over steps
delete [] cfValues;
}
//____________________________________________________________________
Bool_t AliTRDcheckESD::Load(const Char_t *file, const Char_t *dir, const Char_t *name)
{
//
// Load data from performance file
//
if(!TFile::Open(file)){
AliWarning(Form("Couldn't open file %s.", file));
return kFALSE;
}
if(dir){
if(!gFile->cd(dir)){
AliWarning(Form("Couldn't cd to %s in %s.", dir, file));
return kFALSE;
}
}
TObjArray *o(NULL);
const Char_t *tn=(name ? name : GetName());
if(!(o = (TObjArray*)gDirectory->Get(tn))){
AliWarning(Form("Missing histogram container %s.", tn));
return kFALSE;
}
fHistos = (TObjArray*)o->Clone(GetName());
TH1F* trigHist = (TH1F*)fHistos->FindObject("hTriggerDefs");
for(Int_t i=1;i<=trigHist->GetXaxis()->GetNbins();++i) {
if(trigHist->GetXaxis()->GetBinLabel(i)[0]!='\0') ++fNAssignedTriggers;
}
gFile->Close();
return kTRUE;
}
//_______________________________________________________
Bool_t AliTRDcheckESD::PutTrendValue(const Char_t *name, Double_t val)
{
// Dump trending value to default file
if(!fgFile){
fgFile = fopen("TRD.Performance.txt", "at");
}
fprintf(fgFile, "%s_%s %f\n", GetName(), name, val);
return kTRUE;
}
//____________________________________________________________________
void AliTRDcheckESD::Terminate(Option_t *)
{
// Steer post-processing
if(!fHistos){
fHistos = dynamic_cast<TObjArray *>(GetOutputData(1));
if(!fHistos){
AliError("Histogram container not found in output");
return;
}
}
}
//____________________________________________________________________
Int_t AliTRDcheckESD::Pdg2Idx(Int_t pdg) const
{
//
// Helper function converting PDG code into AliPID index
//
switch(pdg){
case kElectron:
case kPositron: return AliPID::kElectron;
case kMuonPlus:
case kMuonMinus: return AliPID::kMuon;
case kPiPlus:
case kPiMinus: return AliPID::kPion;
case kKPlus:
case kKMinus: return AliPID::kKaon;
case kProton:
case kProtonBar: return AliPID::kProton;
}
return -1;
}
//________________________________________________________
void AliTRDcheckESD::Process2D(TH2 * const h2, TGraphErrors **g)
{
//
// Do the processing
//
Int_t n = 0;
if((n=g[0]->GetN())) for(;n--;) g[0]->RemovePoint(n);
if((n=g[1]->GetN())) for(;n--;) g[1]->RemovePoint(n);
TF1 f("fg", "gaus", -3.,3.);
for(Int_t ibin = 1; ibin <= h2->GetNbinsX(); ibin++){
Double_t x = h2->GetXaxis()->GetBinCenter(ibin);
TH1D *h = h2->ProjectionY("py", ibin, ibin);
if(h->GetEntries()<100) continue;
//AdjustF1(h, f);
h->Fit(&f, "QN");
Int_t ip = g[0]->GetN();
g[0]->SetPoint(ip, x, f.GetParameter(1));
g[0]->SetPointError(ip, 0., f.GetParError(1));
g[1]->SetPoint(ip, x, f.GetParameter(2));
g[1]->SetPointError(ip, 0., f.GetParError(2));
}
return;
}
//____________________________________________________________________
void AliTRDcheckESD::PrintStatus(ULong_t status)
{
// Dump track status to stdout
printf("ITS[i(%d) o(%d) r(%d)] TPC[i(%d) o(%d) r(%d) p(%d)] TRD[i(%d) o(%d) r(%d) p(%d) s(%d)] HMPID[o(%d) p(%d)]\n"
,Bool_t(status & AliESDtrack::kITSin)
,Bool_t(status & AliESDtrack::kITSout)
,Bool_t(status & AliESDtrack::kITSrefit)
,Bool_t(status & AliESDtrack::kTPCin)
,Bool_t(status & AliESDtrack::kTPCout)
,Bool_t(status & AliESDtrack::kTPCrefit)
,Bool_t(status & AliESDtrack::kTPCpid)
,Bool_t(status & AliESDtrack::kTRDin)
,Bool_t(status & AliESDtrack::kTRDout)
,Bool_t(status & AliESDtrack::kTRDrefit)
,Bool_t(status & AliESDtrack::kTRDpid)
,Bool_t(status & AliESDtrack::kTRDStop)
,Bool_t(status & AliESDtrack::kHMPIDout)
,Bool_t(status & AliESDtrack::kHMPIDpid)
);
}
//____________________________________________________________________
TH1D* AliTRDcheckESD::Proj2D(TH2* hist, TH1* mpvErr, TH1* widthErr, TH1* chi2) {
//
// project the PH vs Slice 2D-histo into a 1D histo with Landau MPV and widths
//
TH1D* hProjection = (TH1D*)hist->ProjectionX(Form("hProjection_%f", gRandom->Rndm()));
hProjection->Reset();
TF1* fitLandau = new TF1("landauFunc","landau",20.,3000.);
TH1D *hD;
for(Int_t iBin=1;iBin<=hist->GetXaxis()->GetNbins();iBin++) {
if(gROOT->FindObject("projection"))
delete gROOT->FindObject("projection");
hD = (TH1D*)hist->ProjectionY("projection",iBin,iBin);
//hD->Rebin(4);
if(hD->Integral()>10) {
fitLandau->SetParameter(1, hD->GetBinCenter(hD->GetMaximumBin()));
fitLandau->SetParLimits(1, 0.2*hD->GetBinCenter(hD->GetMaximumBin()), 3.0*hD->GetBinCenter(hD->GetMaximumBin()));
fitLandau->SetParameter(0, 1000.);
fitLandau->SetParLimits(0, 1., 10000000.);
fitLandau->SetParameter(2, 0.5*hD->GetBinCenter(hD->GetMaximumBin()));
fitLandau->SetParLimits(2, 0.01*hD->GetBinCenter(hD->GetMaximumBin()), 1.0*hD->GetRMS());
hD->Fit(fitLandau, "Q0", "", hD->GetXaxis()->GetXmin(), hD->GetXaxis()->GetXmax());
hD->Fit(fitLandau, "Q0", "", hD->GetXaxis()->GetXmin(), hD->GetXaxis()->GetXmax());
hProjection->SetBinContent(iBin, fitLandau->GetParameter(1));
hProjection->SetBinError(iBin, fitLandau->GetParameter(2));
if(mpvErr) {
mpvErr->SetBinContent(iBin, fitLandau->GetParameter(1));
mpvErr->SetBinError(iBin, fitLandau->GetParError(1));
}
if(widthErr) {
widthErr->SetBinContent(iBin, fitLandau->GetParameter(2));
widthErr->SetBinError(iBin, fitLandau->GetParError(2));
}
if(chi2) {
chi2->SetBinContent(iBin, (fitLandau->GetNDF()>0 ? fitLandau->GetChisquare()/Double_t(fitLandau->GetNDF()) : 0.0));
}
}
else{
hProjection->SetBinContent(iBin, 0);
hProjection->SetBinError(iBin, 0);
}
}
return hProjection;
}
//____________________________________________________________________
TH2F* AliTRDcheckESD::Proj3D(TH3* hist, TH2* accMap, Int_t zbinLow, Int_t zbinHigh, Float_t &entries) {
//
// Project a 3D histogram to a 2D histogram in the Z axis interval [zbinLow,zbinHigh]
// Return the 2D histogram and also the number of entries into this projection (entries)
Int_t nBinsX = hist->GetXaxis()->GetNbins(); // X and Y axis bins are assumed to be all equal
Float_t minX = hist->GetXaxis()->GetXmin();
Float_t maxX = hist->GetXaxis()->GetXmax();
Int_t nBinsY = hist->GetYaxis()->GetNbins();
Float_t minY = hist->GetYaxis()->GetXmin();
Float_t maxY = hist->GetYaxis()->GetXmax();
Int_t nBinsZ = hist->GetZaxis()->GetNbins(); // Z axis bins (pt) might have different widths
TH2F* projHisto = (TH2F*)gROOT->FindObject("projHisto");
if(projHisto)
projHisto->Reset();
else
projHisto = new TH2F("projHisto", "projection", nBinsX, minX, maxX, nBinsY, minY, maxY);
for(Int_t iZ=1; iZ<=nBinsZ; iZ++) {
if(iZ<zbinLow) continue;
if(iZ>zbinHigh) continue;
for(Int_t iX=1; iX<=nBinsX; iX++) {
for(Int_t iY=1; iY<=nBinsY; iY++) {
if(accMap) {
if(accMap->GetBinContent(iX,iY)>0.1)
projHisto->SetBinContent(iX, iY, projHisto->GetBinContent(iX, iY)+hist->GetBinContent(iX,iY,iZ));
}
else // no acc. cut
projHisto->SetBinContent(iX, iY, projHisto->GetBinContent(iX, iY)+hist->GetBinContent(iX,iY,iZ));
// count only the entries which are inside the acceptance map
if(accMap) {
if(accMap->GetBinContent(iX,iY)>0.1)
entries+=hist->GetBinContent(iX,iY,iZ);
}
else // no acc. cut
entries+=hist->GetBinContent(iX,iY,iZ);
}
}
}
return projHisto;
}
//____________________________________________________________________
void AliTRDcheckESD::CheckActiveSM(TH1D* phiProj, Bool_t activeSM[18]) {
//
// Check the active super-modules
//
Double_t entries[18] = {0.0};
Double_t smPhiLimits[19];
for(Int_t ism=0; ism<=18; ++ism) smPhiLimits[ism] = -TMath::Pi() + (2.0*TMath::Pi()/18.0)*ism;
for(Int_t phiBin=1; phiBin<=phiProj->GetXaxis()->GetNbins(); ++phiBin) {
Double_t phi = phiProj->GetBinCenter(phiBin);
Int_t sm = -1;
for(Int_t ism=0; ism<18; ++ism)
if(phi>=smPhiLimits[ism] && phi<smPhiLimits[ism+1]) sm = ism;
if(sm==-1) continue;
entries[sm] += phiProj->GetBinContent(phiBin);
}
Double_t avEntries = Double_t(phiProj->Integral())/18.0;
for(Int_t ism=0; ism<18; ++ism)
if(entries[ism]>0.5*avEntries) activeSM[ism] = kTRUE;
}
//__________________________________________________________________________________________________
TH1F* AliTRDcheckESD::EfficiencyFromPhiPt(AliCFContainer* cf, Int_t minNtrkl, Int_t maxNtrkl,
Int_t stepNom, Int_t stepDenom, Int_t var) {
//
// Use the CF container to extract the efficiency vs pt (other variables beside pt also posible)
//
Int_t varTrackPhi = cf->GetVar(fgkVarNames[kTrackPhiTRD]);
Int_t otherVar = cf->GetVar(fgkVarNames[var]);
Int_t trdStepNumber = cf->GetStep(fgkStepNames[kTRD]);
Int_t tpcStepNumber = cf->GetStep(fgkStepNames[kTPCreference]);
TH1D* phiProj = (TH1D*)cf->Project(trdStepNumber, varTrackPhi);
Bool_t activeSM[18] = {kFALSE};
CheckActiveSM(phiProj, activeSM); delete phiProj;
Double_t smPhiLimits[19];
for(Int_t ism=0; ism<=18; ++ism) smPhiLimits[ism] = -TMath::Pi() + (2.0*TMath::Pi()/18.0)*ism;
TH2D* hNomPhiVar=0x0;
TH2D* hDenomPhiVar=0x0;
if((stepNom!=tpcStepNumber) &&
(minNtrkl>-1 && minNtrkl<7 && maxNtrkl>-1 && maxNtrkl<7)) {
cf->SetRangeUser(cf->GetVar(fgkVarNames[kTrackTrdTracklets]), Double_t(minNtrkl), Double_t(maxNtrkl));
hNomPhiVar = (TH2D*)cf->Project(stepNom, otherVar, varTrackPhi);
cf->SetRangeUser(cf->GetVar(fgkVarNames[kTrackTrdTracklets]), 0.0,6.0);
}
else
hNomPhiVar = (TH2D*)cf->Project(stepNom, otherVar, varTrackPhi);
if((stepDenom!=tpcStepNumber) &&
(minNtrkl>-1 && minNtrkl<7 && maxNtrkl>-1 && maxNtrkl<7)) {
cf->SetRangeUser(cf->GetVar(fgkVarNames[kTrackTrdTracklets]), Double_t(minNtrkl), Double_t(maxNtrkl));
hDenomPhiVar = (TH2D*)cf->Project(stepDenom, otherVar, varTrackPhi);
cf->SetRangeUser(cf->GetVar(fgkVarNames[kTrackTrdTracklets]), 0.0,6.0);
}
else
hDenomPhiVar = (TH2D*)cf->Project(stepDenom, otherVar, varTrackPhi);
TH1F* hEff = new TH1F(Form("hEff%s_%d_%d_%f", fgkVarNames[var], stepNom, stepDenom, gRandom->Rndm()), "",
hNomPhiVar->GetXaxis()->GetNbins(), hNomPhiVar->GetXaxis()->GetXbins()->GetArray());
for(Int_t ib=1;ib<=hNomPhiVar->GetXaxis()->GetNbins();++ib)
hEff->GetXaxis()->SetBinLabel(ib, hNomPhiVar->GetXaxis()->GetBinLabel(ib));
for(Int_t ivar=1; ivar<=hEff->GetXaxis()->GetNbins(); ++ivar) {
Double_t nom = 0.0; Double_t denom = 0.0;
Double_t eff = 0.0; Double_t err = 0.0;
for(Int_t iphi=1; iphi<=hNomPhiVar->GetYaxis()->GetNbins(); ++iphi) {
Double_t phi = hNomPhiVar->GetYaxis()->GetBinCenter(iphi);
Bool_t isActive = kFALSE;
for(Int_t ism=0; ism<18; ++ism)
if(phi>=smPhiLimits[ism] && phi<smPhiLimits[ism+1] && activeSM[ism])
isActive = kTRUE;
if(!isActive) continue;
nom += hNomPhiVar->GetBinContent(ivar, iphi);
denom += hDenomPhiVar->GetBinContent(ivar, iphi);
}
eff = (denom>0.001 ? nom/denom : 0.0);
err = (denom>0.001 && (denom-nom)>0.001 && nom>0.001 ? (TMath::Sqrt(nom*(denom-nom)/denom/denom/denom)) : 0.0);
hEff->SetBinContent(ivar, eff);
hEff->SetBinError(ivar, err);
} // end loop over pt bins
delete hNomPhiVar; delete hDenomPhiVar;
return hEff;
}
//____________________________________________________________________
TH1F* AliTRDcheckESD::EfficiencyTRD(TH3* tpc3D, TH3* trd3D, Bool_t useAcceptance) {
//
// Calculate the TRD-TPC matching efficiency as function of pt
//
if(!tpc3D || !trd3D) return NULL;
Int_t nBinsZ = trd3D->GetZaxis()->GetNbins();
// project everything on the eta-phi map to obtain an acceptance map
Float_t nada = 0.;
TH2F *trdAcc = (useAcceptance ? (TH2F*)Proj3D(trd3D, 0x0, 1, nBinsZ, nada)->Clone(Form("trdAcc%f", gRandom->Rndm())) : 0x0);
TH1D *phiProj = (trdAcc ? trdAcc->ProjectionY(Form("phiProj%f", gRandom->Rndm())) : 0x0);
// prepare the acceptance map
Bool_t activeSM[18] = {kFALSE};
Double_t smPhiLimits[19];
for(Int_t ism=0; ism<=18; ++ism) smPhiLimits[ism] = -TMath::Pi() + (2.0*TMath::Pi()/18.0)*ism;
if(phiProj) {
CheckActiveSM(phiProj, activeSM); // get the active SMs
trdAcc->Reset();
// Put 1 entry in every bin which belongs to an active SM
for(Int_t iY=1; iY<=trdAcc->GetYaxis()->GetNbins(); ++iY) {
Double_t phi = trdAcc->GetYaxis()->GetBinCenter(iY);
Bool_t isActive = kFALSE;
for(Int_t ism=0; ism<18; ++ism) {
if(phi>=smPhiLimits[ism] && phi<smPhiLimits[ism+1] && activeSM[ism]) {
isActive = kTRUE;
}
}
if(!isActive) continue;
for(Int_t iX=1; iX<=trdAcc->GetXaxis()->GetNbins(); ++iX)
if(trdAcc->GetXaxis()->GetBinCenter(iX)>=-0.85 && trdAcc->GetXaxis()->GetBinCenter(iX)<=0.85) trdAcc->SetBinContent(iX, iY, 1.0);
} // end for over Y(phi) bins
} // end if phiProj
// get the bin limits from the Z axis of 3D histos
Float_t *ptBinLimits = new Float_t[nBinsZ+1];
for(Int_t i=1; i<=nBinsZ; i++) {
ptBinLimits[i-1] = trd3D->GetZaxis()->GetBinLowEdge(i);
}
ptBinLimits[nBinsZ] = trd3D->GetZaxis()->GetBinUpEdge(nBinsZ);
TH1F *efficiency = new TH1F(Form("eff%d", Int_t(1000000.0*gRandom->Rndm())), "TRD-TPC matching efficiency", nBinsZ, ptBinLimits);
// loop over Z bins
Bool_t effGood = kFALSE;
for(Int_t i=1; i<=nBinsZ; i++) {
Float_t tpcEntries = 0.0; Float_t trdEntries = 0.0;
Proj3D(tpc3D, trdAcc, i, i, tpcEntries);
Proj3D(trd3D, trdAcc, i, i, trdEntries);
Float_t ratio = 0;
if(tpcEntries>0) ratio = trdEntries/tpcEntries;
Float_t error = 0;
if(tpcEntries>0 && trdEntries>0 && (tpcEntries-trdEntries)>=0.0)
error = TMath::Sqrt(trdEntries*(tpcEntries-trdEntries)/tpcEntries/tpcEntries/tpcEntries);
if(ratio>0.001) {
efficiency->SetBinContent(i,ratio);
efficiency->SetBinError(i,error);
effGood = kTRUE;
}
} // end loop over Z bins
if(!effGood) return 0x0;
return efficiency;
}
//__________________________________________________________________________________________________
void AliTRDcheckESD::PlotCentSummaryFromCF(Double_t* /*trendValues*/, const Char_t* /*triggerName*/, Bool_t /*useIsolatedBC*/, Bool_t /*cutTOFbc*/) {
//
// Make the centrality summary figure from the CF container
//
if(!fHistos) return;
AliCFContainer* matchPt=(AliCFContainer*)fHistos->FindObject("MatchingPt");
if(!matchPt) return;
AliCFContainer* centCF=(AliCFContainer*)fHistos->FindObject("CentralityCF");
if(!centCF) return;
AliCFContainer* clustersCF=(AliCFContainer*)fHistos->FindObject("ClustersCF");
if(!clustersCF) return;
TLatex* lat=new TLatex();
lat->SetTextSize(0.06);
lat->SetTextColor(2);
gPad->SetTopMargin(0.05); gPad->SetBottomMargin(0.001); gPad->SetLeftMargin(0.001); gPad->SetRightMargin(0.001);
gPad->Divide(3,3,0.,0.);
TList* l=gPad->GetListOfPrimitives();
TVirtualPad* pad=0x0;
if(gROOT->FindObject("rangeEffPt")) delete gROOT->FindObject("rangeEffPt");
TH2F* rangeEffPt=new TH2F("rangeEffPt", "",10,0.,10.,10,0.,1.3);
rangeEffPt->SetStats(kFALSE);
SetStyle(rangeEffPt->GetXaxis(), "p_{T} [GeV/c]", 0.07, 0.8, kTRUE, 0.05);
SetStyle(rangeEffPt->GetYaxis(), "efficiency", 0.07, 0.8, kTRUE, 0.05);
Int_t padsForEffs[5] = {0,3,6,1,4};
for(Int_t iCent=1; iCent<6; ++iCent) {
pad = ((TVirtualPad*)l->At(padsForEffs[iCent-1])); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.02); pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
rangeEffPt->Draw();
TLine line;
line.SetLineStyle(2);
line.SetLineWidth(2);
line.DrawLine(rangeEffPt->GetXaxis()->GetXmin(), 0.7, rangeEffPt->GetXaxis()->GetXmax(), 0.7);
line.DrawLine(rangeEffPt->GetXaxis()->GetXmin(), 0.9, rangeEffPt->GetXaxis()->GetXmax(), 0.9);
matchPt->SetRangeUser(matchPt->GetVar(fgkVarNames[kEventMult]), Double_t(iCent), Double_t(iCent), kTRUE);
matchPt->SetRangeUser(matchPt->GetVar(fgkVarNames[kTrackCharge]), +1.0, +1.0);
TH1F* hEffPosAll = EfficiencyFromPhiPt(matchPt, 0, 6, 1, 0);
TH1F* hEffPosTrk4 = EfficiencyFromPhiPt(matchPt, 4, 4, 1, 0);
TH1F* hEffPosTrk5 = EfficiencyFromPhiPt(matchPt, 5, 5, 1, 0);
TH1F* hEffPosTrk6 = EfficiencyFromPhiPt(matchPt, 6, 6, 1, 0);
matchPt->SetRangeUser(matchPt->GetVar(fgkVarNames[kTrackCharge]), -1.0, -1.0);
TH1F* hEffNegAll = EfficiencyFromPhiPt(matchPt, 0, 6, 1, 0);
TH1F* hEffNegTrk4 = EfficiencyFromPhiPt(matchPt, 4, 4, 1, 0);
TH1F* hEffNegTrk5 = EfficiencyFromPhiPt(matchPt, 5, 5, 1, 0);
TH1F* hEffNegTrk6 = EfficiencyFromPhiPt(matchPt, 6, 6, 1, 0);
matchPt->SetRangeUser(matchPt->GetVar(fgkVarNames[kTrackTrdTracklets]), 0.0, 6.0);
matchPt->SetRangeUser(matchPt->GetVar(fgkVarNames[kTrackCharge]), -1.0, +1.0);
SetStyle(hEffPosAll, 1, kRed, 1, 24, kRed, 1);
SetStyle(hEffPosTrk4, 1, kRed, 1, 25, kRed, 1);
SetStyle(hEffPosTrk5, 1, kRed, 1, 26, kRed, 1);
SetStyle(hEffPosTrk6, 1, kRed, 1, 27, kRed, 1);
SetStyle(hEffNegAll, 1, kBlue, 1, 24, kBlue, 1);
SetStyle(hEffNegTrk4, 1, kBlue, 1, 25, kBlue, 1);
SetStyle(hEffNegTrk5, 1, kBlue, 1, 26, kBlue, 1);
SetStyle(hEffNegTrk6, 1, kBlue, 1, 27, kBlue, 1);
hEffPosAll->Draw("same");
hEffNegAll->Draw("same");
hEffPosTrk4->Draw("same");
hEffNegTrk4->Draw("same");
hEffPosTrk5->Draw("same");
hEffNegTrk5->Draw("same");
hEffPosTrk6->Draw("same");
hEffNegTrk6->Draw("same");
TLegend* leg=new TLegend(0.18, 0.7, 0.77, 0.89);
if(iCent==1) {
leg->SetFillColor(0);
leg->SetNColumns(2);
leg->SetMargin(0.1);
leg->SetBorderSize(0);
leg->AddEntry(hEffPosAll, "pos. (#geq 1 tracklet)", "p");
leg->AddEntry(hEffNegAll, "neg. (#geq 1 tracklet)", "p");
leg->AddEntry(hEffPosTrk4, "pos. (4 tracklets)", "p");
leg->AddEntry(hEffNegTrk4, "neg. (4 tracklets)", "p");
leg->AddEntry(hEffPosTrk5, "pos. (5 tracklets)", "p");
leg->AddEntry(hEffNegTrk5, "neg. (5 tracklets)", "p");
leg->AddEntry(hEffPosTrk6, "pos. (6 tracklets)", "p");
leg->AddEntry(hEffNegTrk6, "neg. (6 tracklets)", "p");
leg->Draw();
}
lat->DrawLatex(0.2, 1.32, Form("%.0f < SPD tracklets < %.0f", matchPt->GetAxis(matchPt->GetVar(fgkVarNames[kEventMult]),0)->GetBinLowEdge(iCent), matchPt->GetAxis(matchPt->GetVar(fgkVarNames[kEventMult]),0)->GetBinUpEdge(iCent)));
} // end for loop over multiplicity classes
// Reset the modified user ranges of the CF container
matchPt->SetRangeUser(matchPt->GetVar(fgkVarNames[kEventMult]), 0., 3500.);
// Cluster distributions in all multiplicity classes
pad = ((TVirtualPad*)l->At(2)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.02);
pad->SetTopMargin(0.02); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
if(gROOT->FindObject("rangeNcls")) delete gROOT->FindObject("rangeNcls");
TH2F* rangeNcls = new TH2F("rangeNcls", "", 10, 0.0, 199.9, 10, 0.0, 1.199);
SetStyle(rangeNcls->GetXaxis(), "# TRD clusters", 0.07, 0.8, kTRUE, 0.05);
SetStyle(rangeNcls->GetYaxis(), "entries (a.u.)", 0.07, 0.8, kTRUE, 0.05);
rangeNcls->SetStats(kFALSE);
rangeNcls->Draw();
TH1D* hNcls[6]={0x0};
TLegend* legCls=new TLegend(0.7, 0.75, 0.97, 0.97);
legCls->SetBorderSize(0);
legCls->SetFillColor(0);
legCls->SetMargin(0.15);
for(Int_t iCent=0; iCent<6; ++iCent) {
if(iCent>0)
clustersCF->SetRangeUser(clustersCF->GetVar(fgkVarNames[kEventMult]), Double_t(iCent), Double_t(iCent), kTRUE);
hNcls[iCent] = (TH1D*)clustersCF->Project(0, clustersCF->GetVar(fgkVarNames[kTrackTrdClusters]));
if(!hNcls[iCent]) continue;
hNcls[iCent]->SetLineColor(iCent<4 ? iCent+1 : iCent+2);
Double_t maximum = hNcls[iCent]->GetMaximum();
if(maximum>1.0)
hNcls[iCent]->Scale(1.0/maximum);
hNcls[iCent]->SetStats(kFALSE);
hNcls[iCent]->SetTitle("");
hNcls[iCent]->SetLineWidth(2);
if(hNcls[iCent]->Integral()>0.01) {
hNcls[iCent]->Draw("same");
legCls->AddEntry(hNcls[iCent], (iCent==0 ? "all centralities" : Form("%.0f < SPD tracklets < %.0f", clustersCF->GetAxis(clustersCF->GetVar(fgkVarNames[kEventMult]),0)->GetBinLowEdge(iCent),
clustersCF->GetAxis(clustersCF->GetVar(fgkVarNames[kEventMult]),0)->GetBinUpEdge(iCent))), "l");
}
}
legCls->Draw();
clustersCF->SetRangeUser(clustersCF->GetVar(fgkVarNames[kEventMult]), 0.0, 6.0, kTRUE);
// Qtot distributions
pad = ((TVirtualPad*)l->At(5)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.02);
pad->SetTopMargin(0.02); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
if(gROOT->FindObject("rangeQtot")) delete gROOT->FindObject("rangeQtot");
TH2F* rangeQtot = new TH2F("rangeQtot", "", 10, 0.0, 9.999, 10, 0.0, 1.199);
SetStyle(rangeQtot->GetXaxis(), "Q_{tot} (a.u.)", 0.07, 0.8, kTRUE, 0.05);
SetStyle(rangeQtot->GetYaxis(), "entries (a.u.)", 0.07, 0.8, kTRUE, 0.05);
rangeQtot->SetStats(kFALSE);
rangeQtot->Draw();
TH1D* hQtot[6+1]={0x0};
TLegend* leg2=new TLegend(0.6, 0.7, 0.9, 0.97);
leg2->SetFillColor(0);
leg2->SetBorderSize(0);
for(Int_t iCent=0; iCent<6; ++iCent) {
if(iCent>0)
centCF->SetRangeUser(centCF->GetVar(fgkVarNames[kEventMult]), Double_t(iCent), Double_t(iCent), kTRUE);
hQtot[iCent] = (TH1D*)centCF->Project(0, centCF->GetVar(fgkVarNames[kTrackletQtot]));
if(!hQtot[iCent]) continue;
hQtot[iCent]->SetBinContent(1, 0);
Double_t maximum = hQtot[iCent]->GetMaximum();
if(maximum>1.0)
hQtot[iCent]->Scale(1.0/maximum);
hQtot[iCent]->SetLineColor(iCent<4 ? iCent+1 : iCent+2);
hQtot[iCent]->SetStats(kFALSE);
hQtot[iCent]->SetTitle("");
hQtot[iCent]->SetLineWidth(2);
if(hQtot[iCent]->Integral()>0.01) {
hQtot[iCent]->Draw(iCent==0 ? "" : "same");
leg2->AddEntry(hQtot[iCent], (iCent==0 ? "all centralities" : Form("%.0f < SPD tracklets < %.0f", centCF->GetAxis(centCF->GetVar(fgkVarNames[kEventMult]),0)->GetBinLowEdge(iCent),
centCF->GetAxis(centCF->GetVar(fgkVarNames[kEventMult]),0)->GetBinUpEdge(iCent))), "l");
}
}
leg2->Draw();
centCF->SetRangeUser(centCF->GetVar(fgkVarNames[kEventMult]), 0.0, 5.0, kTRUE);
}
//_________________________________________________________________
void AliTRDcheckESD::PlotTrackingSummaryFromCF(Double_t* trendValues, const Char_t* /*triggerName*/, Bool_t /*useIsolatedBC*/, Bool_t /*cutTOFbc*/) {
//
// Plot tracking summary
//
// trendValues will be filled with trending variables
// trendValues[0] : TPC-TRD matching efficiency for positive tracks in the range 1.0<pt<3.0 GeV/c
// trendValues[1] : statistical error of trendValues[0]
// trendValues[2] : TPC-TRD matching efficiency for negative tracks in the range 1.0<pt<3.0 GeV/c
// trendValues[3] : statistical error of trendValues[2]
// trendValues[4] : TRD-TOF matching efficiency for positive tracks in the range 1.0<pt<3.0 GeV/c
// trendValues[5] : statistical error of trendValues[4]
// trendValues[6] : TRD-TOF matching efficiency for negative tracks in the range 1.0<pt<3.0 GeV/c
// trendValues[7] : statistical error of trendValues[6]
// trendValues[8] : Average number of TRD tracklets per track in the range 1.0<pt<3.0 GeV/c
// trendValues[9] : statistical error of trendValues[8]
// trendValues[10]: Average number of TRD clusters per track in the range 1.0<p<3.0 GeV/c
// trendValues[11]: statistical error of trendValues[10]
//
if(!fHistos) return;
AliCFContainer* matchPhiEta=(AliCFContainer*)fHistos->FindObject("MatchingPhiEta");
if(!matchPhiEta) return;
AliCFContainer* matchPt=(AliCFContainer*)fHistos->FindObject("MatchingPt");
if(!matchPt) return;
AliCFContainer* clustersCF=(AliCFContainer*)fHistos->FindObject("ClustersCF");
if(!clustersCF) return;
AliCFContainer* bcCF=(AliCFContainer*)fHistos->FindObject("BunchCrossingsCF");
if(!bcCF) return;
TLatex *lat=new TLatex();
lat->SetTextSize(0.06);
lat->SetTextColor(2);
lat->SetTextFont(42);
gPad->SetTopMargin(0.05); gPad->SetBottomMargin(0.001);
gPad->SetLeftMargin(0.001); gPad->SetRightMargin(0.001);
gPad->Divide(3,3,0.,0.);
TList* l=gPad->GetListOfPrimitives();
// eta-phi distr. for positive TPC tracks
TVirtualPad* pad = ((TVirtualPad*)l->At(0)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
TH2D* hTPCrefPos = 0x0; TH2D* hTRDrefPos = 0x0; TH2D* hTOFrefPos = 0x0;
TH2D* hTPCrefNeg = 0x0; TH2D* hTRDrefNeg = 0x0; TH2D* hTOFrefNeg = 0x0;
matchPhiEta->SetRangeUser(matchPhiEta->GetVar(fgkVarNames[kTrackTrdTracklets]), 0.0, 6.0);
matchPhiEta->SetRangeUser(matchPhiEta->GetVar(fgkVarNames[kTrackCharge]), +1.0, +1.0); // positive charges
hTPCrefPos = (TH2D*)matchPhiEta->Project(0, matchPhiEta->GetVar(fgkVarNames[kTrackEtaTRD]), matchPhiEta->GetVar(fgkVarNames[kTrackPhiTRD]));
hTRDrefPos = (TH2D*)matchPhiEta->Project(1, matchPhiEta->GetVar(fgkVarNames[kTrackEtaTRD]), matchPhiEta->GetVar(fgkVarNames[kTrackPhiTRD]));
hTOFrefPos = (TH2D*)matchPhiEta->Project(2, matchPhiEta->GetVar(fgkVarNames[kTrackEtaTRD]), matchPhiEta->GetVar(fgkVarNames[kTrackPhiTRD]));
matchPhiEta->SetRangeUser(matchPhiEta->GetVar(fgkVarNames[kTrackCharge]), -1.0, -1.0); // negative charges
hTPCrefNeg = (TH2D*)matchPhiEta->Project(0, matchPhiEta->GetVar(fgkVarNames[kTrackEtaTRD]), matchPhiEta->GetVar(fgkVarNames[kTrackPhiTRD]));
hTRDrefNeg = (TH2D*)matchPhiEta->Project(1, matchPhiEta->GetVar(fgkVarNames[kTrackEtaTRD]), matchPhiEta->GetVar(fgkVarNames[kTrackPhiTRD]));
hTOFrefNeg = (TH2D*)matchPhiEta->Project(2, matchPhiEta->GetVar(fgkVarNames[kTrackEtaTRD]), matchPhiEta->GetVar(fgkVarNames[kTrackPhiTRD]));
matchPhiEta->SetRangeUser(matchPhiEta->GetVar(fgkVarNames[kTrackCharge]), -1.0, +1.0); // reset charge cut
if(gROOT->FindObject("rangeEtaPhi")) delete gROOT->FindObject("rangeEtaPhi");
TH2F* rangeEtaPhi = new TH2F("rangeEtaPhi", "", 10, -0.99, +0.99, 10, -3.15, 3.15);
SetStyle(rangeEtaPhi->GetXaxis(), "#eta", 0.07, 0.8, kTRUE, 0.05);
SetStyle(rangeEtaPhi->GetYaxis(), "detector #varphi", 0.07, 0.8, kTRUE, 0.05);
rangeEtaPhi->SetStats(kFALSE);
//----------------------------------------------
// eta-phi efficiency for positive TRD tracks
pad = ((TVirtualPad*)l->At(0)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
rangeEtaPhi->Draw();
TH2D* hTRDeffPos = (hTRDrefPos ? (TH2D*)hTRDrefPos->Clone("hTRDeffPos") : 0x0);
if(hTRDeffPos) {
hTRDeffPos->Reset();
hTRDeffPos->SetStats(kFALSE);
hTRDeffPos->Divide(hTRDrefPos, hTPCrefPos);
hTRDeffPos->SetMaximum(1.0);
hTRDeffPos->Draw("samecolz");
lat->DrawLatex(-0.9, 3.3, "TPC-TRD matching for positive tracks");
DrawTRDGrid();
}
//----------------------------------------------
// eta-phi efficiency for negative TRD tracks
pad = ((TVirtualPad*)l->At(3)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
rangeEtaPhi->Draw();
TH2D* hTRDeffNeg = (hTRDrefNeg ? (TH2D*)hTRDrefNeg->Clone("hTRDeffNeg") : 0x0);
if(hTRDeffNeg) {
hTRDeffNeg->Reset();
hTRDeffNeg->SetStats(kFALSE);
hTRDeffNeg->Divide(hTRDrefNeg, hTPCrefNeg);
hTRDeffNeg->SetMaximum(1.0);
hTRDeffNeg->Draw("samecolz");
lat->DrawLatex(-0.9, 3.3, "TPC-TRD matching for negative tracks");
DrawTRDGrid();
}
//----------------------------------------------
// eta-phi TRD-TOF matching efficiency for positive tracks
pad = ((TVirtualPad*)l->At(1)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
rangeEtaPhi->Draw();
TH2D* hTOFeffPos = (hTOFrefPos ? (TH2D*)hTOFrefPos->Clone("hTOFeffPos") : 0x0);
if(hTOFeffPos) {
hTOFeffPos->Reset();
hTOFeffPos->SetStats(kFALSE);
hTOFeffPos->Divide(hTOFrefPos, hTRDrefPos);
hTOFeffPos->SetMaximum(1.0);
hTOFeffPos->Draw("samecolz");
lat->DrawLatex(-0.9, 3.3, "TRD-TOF matching for positive tracks");
DrawTRDGrid();
}
//----------------------------------------------
// eta-phi TRD-TOF matching efficiency for negative tracks
pad = ((TVirtualPad*)l->At(4)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
rangeEtaPhi->Draw();
TH2D* hTOFeffNeg = (hTOFrefNeg ? (TH2D*)hTOFrefNeg->Clone("hTOFeffNeg") : 0x0);
if(hTOFeffNeg) {
hTOFeffNeg->Reset();
hTOFeffNeg->SetStats(kFALSE);
hTOFeffNeg->Divide(hTOFrefNeg, hTRDrefNeg);
hTOFeffNeg->SetMaximum(1.0);
hTOFeffNeg->Draw("samecolz");
lat->DrawLatex(-0.9, 3.3, "TRD-TOF matching for negative tracks");
DrawTRDGrid();
}
if(hTRDrefPos) delete hTRDrefPos; if(hTPCrefPos) delete hTPCrefPos; if(hTOFrefPos) delete hTOFrefPos;
if(hTRDrefNeg) delete hTRDrefNeg; if(hTPCrefNeg) delete hTPCrefNeg; if(hTOFrefNeg) delete hTOFrefNeg;
// switch to the Pt cf container
matchPt->SetRangeUser(matchPt->GetVar(fgkVarNames[kTrackCharge]), +1.0, +1.0);
TH1F* hTRDEffPtPosAll = EfficiencyFromPhiPt(matchPt, 0, 6, 1, 0);
TH1F* hTOFEffPtPosAll = EfficiencyFromPhiPt(matchPt, 0, 6, 2, 1);
TH1F* hTRDEffPtPosTrk4 = EfficiencyFromPhiPt(matchPt, 4, 4, 1, 0);
TH1F* hTOFEffPtPosTrk4 = EfficiencyFromPhiPt(matchPt, 4, 4, 2, 1);
TH1F* hTRDEffPtPosTrk5 = EfficiencyFromPhiPt(matchPt, 5, 5, 1, 0);
TH1F* hTOFEffPtPosTrk5 = EfficiencyFromPhiPt(matchPt, 5, 5, 2, 1);
TH1F* hTRDEffPtPosTrk6 = EfficiencyFromPhiPt(matchPt, 6, 6, 1, 0);
TH1F* hTOFEffPtPosTrk6 = EfficiencyFromPhiPt(matchPt, 6, 6, 2, 1);
matchPt->SetRangeUser(matchPt->GetVar(fgkVarNames[kTrackCharge]), -1.0, -1.0);
TH1F* hTRDEffPtNegAll = EfficiencyFromPhiPt(matchPt, 0, 6, 1, 0);
TH1F* hTOFEffPtNegAll = EfficiencyFromPhiPt(matchPt, 0, 6, 2, 1);
TH1F* hTRDEffPtNegTrk4 = EfficiencyFromPhiPt(matchPt, 4, 4, 1, 0);
TH1F* hTOFEffPtNegTrk4 = EfficiencyFromPhiPt(matchPt, 4, 4, 2, 1);
TH1F* hTRDEffPtNegTrk5 = EfficiencyFromPhiPt(matchPt, 5, 5, 1, 0);
TH1F* hTOFEffPtNegTrk5 = EfficiencyFromPhiPt(matchPt, 5, 5, 2, 1);
TH1F* hTRDEffPtNegTrk6 = EfficiencyFromPhiPt(matchPt, 6, 6, 1, 0);
TH1F* hTOFEffPtNegTrk6 = EfficiencyFromPhiPt(matchPt, 6, 6, 2, 1);
matchPt->SetRangeUser(matchPt->GetVar(fgkVarNames[kTrackCharge]), -1.0, +1.0);
TF1* funcConst = new TF1("constFunc", "[0]", 1.0, 3.0);
if(trendValues) {
if(hTRDEffPtPosAll && hTRDEffPtPosAll->Integral()>0.1) {
hTRDEffPtPosAll->Fit(funcConst, "Q0ME", "goff", 1.0, 3.0);
trendValues[0] = funcConst->GetParameter(0);
trendValues[1] = funcConst->GetParError(0);
}
}
if(trendValues) {
if(hTRDEffPtNegAll && hTRDEffPtNegAll->Integral()>0.1) {
hTRDEffPtNegAll->Fit(funcConst, "Q0ME", "goff", 1.0, 3.0);
trendValues[2] = funcConst->GetParameter(0);
trendValues[3] = funcConst->GetParError(0);
}
}
if(trendValues) {
if(hTOFEffPtPosAll && hTOFEffPtPosAll->Integral()>0.1) {
hTOFEffPtPosAll->Fit(funcConst, "Q0ME", "goff", 1.0, 3.0);
trendValues[4] = funcConst->GetParameter(0);
trendValues[5] = funcConst->GetParError(0);
}
}
if(trendValues) {
if(hTOFEffPtNegAll && hTOFEffPtNegAll->Integral()>0.1) {
hTOFEffPtNegAll->Fit(funcConst, "Q0ME", "goff", 1.0, 3.0);
trendValues[6] = funcConst->GetParameter(0);
trendValues[7] = funcConst->GetParError(0);
}
}
//---------------------------------------------------------
// TPC-TRD matching efficiency vs pt
pad = ((TVirtualPad*)l->At(6)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.02);
pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
if(gROOT->FindObject("rangeEffPt2")) delete gROOT->FindObject("rangeEffPt2");
TH2F* rangeEffPt=new TH2F("rangeEffPt2", "",10,0.,10.,10,0.,1.4);
rangeEffPt->SetStats(kFALSE);
SetStyle(rangeEffPt->GetXaxis(), "p_{T} [GeV/c]", 0.07, 0.8, kTRUE, 0.05);
SetStyle(rangeEffPt->GetYaxis(), "efficiency", 0.07, 0.8, kTRUE, 0.05);
rangeEffPt->Draw();
lat->DrawLatex(0.2, 1.44, "TPC-TRD matching efficiency");
//++++++++++++++++++
TLine line;
line.SetLineStyle(2);
line.SetLineWidth(2);
line.DrawLine(rangeEffPt->GetXaxis()->GetXmin(), 0.7, rangeEffPt->GetXaxis()->GetXmax(), 0.7);
line.DrawLine(rangeEffPt->GetXaxis()->GetXmin(), 0.9, rangeEffPt->GetXaxis()->GetXmax(), 0.9);
TLegend* leg=new TLegend(0.2, 0.7, 0.7, 0.89);
leg->SetNColumns(2);
leg->SetMargin(0.15);
leg->SetBorderSize(0);
leg->SetFillColor(0);
SetStyle(hTRDEffPtPosAll, 1, kRed, 1, 24, kRed, 1);
SetStyle(hTRDEffPtNegAll, 1, kBlue, 1, 24, kBlue, 1);
SetStyle(hTRDEffPtPosTrk4, 1, kRed, 1, 25, kRed, 1);
SetStyle(hTRDEffPtNegTrk4, 1, kBlue, 1, 25, kBlue, 1);
SetStyle(hTRDEffPtPosTrk5, 1, kRed, 1, 26, kRed, 1);
SetStyle(hTRDEffPtNegTrk5, 1, kBlue, 1, 26, kBlue, 1);
SetStyle(hTRDEffPtPosTrk6, 1, kRed, 1, 27, kRed, 1);
SetStyle(hTRDEffPtNegTrk6, 1, kBlue, 1, 27, kBlue, 1);
if(hTRDEffPtPosAll) {hTRDEffPtPosAll->Draw("same"); leg->AddEntry(hTRDEffPtPosAll, "pos. (#geq 1 tracklet)", "p");}
if(hTRDEffPtNegAll) {hTRDEffPtNegAll->Draw("same"); leg->AddEntry(hTRDEffPtNegAll, "neg. (#geq 1 tracklet)", "p");}
hTRDEffPtPosTrk4->Draw("same"); leg->AddEntry(hTRDEffPtPosTrk4, "pos. (4 tracklets)", "p");
hTRDEffPtNegTrk4->Draw("same"); leg->AddEntry(hTRDEffPtNegTrk4, "neg. (4 tracklets)", "p");
hTRDEffPtPosTrk5->Draw("same"); leg->AddEntry(hTRDEffPtPosTrk5, "pos. (5 tracklets)", "p");
hTRDEffPtNegTrk5->Draw("same"); leg->AddEntry(hTRDEffPtNegTrk5, "neg. (5 tracklets)", "p");
hTRDEffPtPosTrk6->Draw("same"); leg->AddEntry(hTRDEffPtPosTrk6, "pos. (6 tracklets)", "p");
hTRDEffPtNegTrk6->Draw("same"); leg->AddEntry(hTRDEffPtNegTrk6, "neg. (6 tracklets)", "p");
leg->Draw();
//---------------------------------------------------------
// TRD-TOF matching efficiency vs pt
pad = ((TVirtualPad*)l->At(7)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.02);
pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
rangeEffPt->Draw();
lat->DrawLatex(0.2, 1.44, "TRD-TOF matching efficiency");
SetStyle(hTOFEffPtPosAll, 1, kRed, 1, 24, kRed, 1);
SetStyle(hTOFEffPtPosTrk4, 1, kRed, 1, 25, kRed, 1);
SetStyle(hTOFEffPtPosTrk5, 1, kRed, 1, 26, kRed, 1);
SetStyle(hTOFEffPtPosTrk6, 1, kRed, 1, 27, kRed, 1);
SetStyle(hTOFEffPtNegAll, 1, kBlue, 1, 24, kBlue, 1);
SetStyle(hTOFEffPtNegTrk4, 1, kBlue, 1, 25, kBlue, 1);
SetStyle(hTOFEffPtNegTrk5, 1, kBlue, 1, 26, kBlue, 1);
SetStyle(hTOFEffPtNegTrk6, 1, kBlue, 1, 27, kBlue, 1);
if(hTOFEffPtPosAll) hTOFEffPtPosAll->Draw("same");
hTOFEffPtPosTrk4->Draw("same");
hTOFEffPtPosTrk5->Draw("same");
hTOFEffPtPosTrk6->Draw("same");
if(hTOFEffPtNegAll) hTOFEffPtNegAll->Draw("same");
hTOFEffPtNegTrk4->Draw("same");
hTOFEffPtNegTrk5->Draw("same");
hTOFEffPtNegTrk6->Draw("same");
//-----------------------------------------------------
// <ntracklets> vs (phi,eta)
pad = ((TVirtualPad*)l->At(2)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
rangeEtaPhi->Draw();
lat->DrawLatex(-0.9, 3.3, "TRD <N_{tracklets}>");
TH3D* hNtracklets = (TH3D*)matchPhiEta->Project(kTRD, matchPhiEta->GetVar(fgkVarNames[kTrackPhiTRD]), matchPhiEta->GetVar(fgkVarNames[kTrackEtaTRD]), matchPhiEta->GetVar(fgkVarNames[kTrackTrdTracklets]));
TProfile2D* hNtrackletsProf = hNtracklets->Project3DProfile();
delete hNtracklets;
if(hNtrackletsProf) {
hNtrackletsProf->SetStats(kFALSE);
hNtrackletsProf->SetMinimum(0.);
hNtrackletsProf->SetMaximum(6.);
hNtrackletsProf->Draw("samecolz");
DrawTRDGrid();
}
// calculate the trend value for tracklets/track
TH2D* hNtrackletsVsP = (TH2D*)matchPt->Project(kTRD, matchPt->GetVar(fgkVarNames[kTrackPt]), matchPt->GetVar(fgkVarNames[kTrackTrdTracklets]));
if(trendValues && hNtrackletsVsP && hNtrackletsVsP->GetEntries()>0.1) {
TProfile* hNtrackletsVsPprof = hNtrackletsVsP->ProfileX("hNtrackletsVsPprof");
hNtrackletsVsPprof->Fit(funcConst, "QME0", "goff", 1.0, 3.0);
trendValues[8] = funcConst->GetParameter(0);
trendValues[9] = funcConst->GetParError(0);
delete hNtrackletsVsP;
}
//--------------------------------------------------------------
// Nclusters per TRD track vs momentum
pad = ((TVirtualPad*)l->At(5)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.12);
pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
pad->SetLogz();
if(gROOT->FindObject("rangeNclsP")) delete gROOT->FindObject("rangeNclsP");
TH2F* rangeNclsP = new TH2F("rangeNclsP", "", 10, 0.0, 11.99, 10, 0.0, 199.0);
SetStyle(rangeNclsP->GetXaxis(), "p [GeV/c]", 0.07, 0.8, kTRUE, 0.05);
SetStyle(rangeNclsP->GetYaxis(), "#clusters", 0.07, 0.8, kTRUE, 0.05);
rangeNclsP->SetStats(kFALSE);
rangeNclsP->Draw();
lat->DrawLatex(1.0, 205., "TRD Clusters / track");
TH2D* hNclsVsP = (TH2D*)clustersCF->Project(0, clustersCF->GetVar(fgkVarNames[kTrackP]), clustersCF->GetVar(fgkVarNames[kTrackTrdClusters]));
if(hNclsVsP) {
hNclsVsP->SetStats(kFALSE);
hNclsVsP->Draw("samecolz");
}
if(trendValues && hNclsVsP && hNclsVsP->GetEntries()>10) {
TProfile* hNclsVsPprof = hNclsVsP->ProfileX("hNclsVsPprof");
hNclsVsPprof->Fit(funcConst, "QME0", "goff", 1.0, 3.0);
trendValues[10] = funcConst->GetParameter(0);
trendValues[11] = funcConst->GetParError(0);
}
//--------------------------------------------------------------
// TRD-TPC and TOF-TRD matching efficiency vs bunch crossing
pad = ((TVirtualPad*)l->At(8)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.02);
pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
TH1F* hTRDEffBC = EfficiencyFromPhiPt(bcCF, -1, -1, 1, 0, kEventBC);
TH1F* hTOFEffBC = EfficiencyFromPhiPt(bcCF, -1, -1, 2, 1, kEventBC);
if(gROOT->FindObject("rangeBC")) delete gROOT->FindObject("rangeBC");
TH2F* rangeBC = new TH2F("rangeBC", "", 10, -0.5, 3499.5, 10, 0.0, 1.4);
rangeBC->SetStats(kFALSE);
SetStyle(rangeBC->GetXaxis(), "Bunch crossing", 0.07, 0.8, kTRUE, 0.05);
SetStyle(rangeBC->GetYaxis(), "efficiency", 0.07, 0.8, kTRUE, 0.05);
rangeBC->Draw();
TLegend* legBC=new TLegend(0.8, 0.7, 0.95, 0.89);
legBC->SetBorderSize(0);
legBC->SetMargin(0.15);
legBC->SetFillColor(0);
if(hTRDEffBC) {
hTRDEffBC->SetStats(kFALSE);
SetStyle(hTRDEffBC, 1, kRed, 2, 24, kRed, 1); legBC->AddEntry(hTRDEffBC, "TPC-TRD", "p");
SetStyle(hTOFEffBC, 1, kBlue, 2, 24, kBlue, 1); legBC->AddEntry(hTOFEffBC, "TRD-TOF", "p");
hTRDEffBC->Draw("same");
hTOFEffBC->Draw("same");
legBC->Draw();
lat->DrawLatex(200., 1.44, "Matching efficiency at 1<p_{T}<3 GeV/c");
}
delete funcConst;
}
//_________________________________________________________________
void AliTRDcheckESD::PlotPidSummaryFromCF(Double_t* trendValues, const Char_t* /*triggerName*/, Bool_t /*useIsolatedBC*/, Bool_t /*cutTOFbc*/) {
//
// PID summary
//
// trendValues will be filled with trending variables
// trendValues[12] : PH plateau height from slices times 0.002
// trendValues[13] : statistical error of trendValues[12]
// trendValues[14] : PH slope from slices times 0.002
// trendValues[15] : statistical error of trendValues[14]
// trendValues[16] : Landau MPV of tracklet Qtot distribution at p=1GeV/c times 0.002
// trendValues[17] : Landau width of tracklet Qtot distribution at p=1GeV/c times 0.002
// trendValues[18] : PH plateau height from slices
// trendValues[19] : statistical error of trendValues[19]
// trendValues[20] : PH slope from slices
// trendValues[21] : statistical error of trendValues[20]
// trendValues[22] : Landau MPV of tracklet Qtot distribution at p=1GeV/c
// trendValues[23] : Landau width of tracklet Qtot distribution at p=1GeV/c
//
if(!fHistos) return;
AliCFContainer* qtotCF = (AliCFContainer*)fHistos->FindObject("QtotCF");
if(!qtotCF) return;
AliCFContainer* phCF = (AliCFContainer*)fHistos->FindObject("PulseHeightCF");
if(!phCF) return;
AliCFContainer* centCF = (AliCFContainer*)fHistos->FindObject("CentralityCF");
if(!centCF) return;
TLatex *lat=new TLatex();
lat->SetTextSize(0.07);
lat->SetTextColor(2);
lat->SetTextFont(42);
gPad->SetTopMargin(0.05); gPad->SetBottomMargin(0.001);
gPad->SetLeftMargin(0.001); gPad->SetRightMargin(0.001);
gPad->Divide(3,3,0.,0.);
TList* l=gPad->GetListOfPrimitives();
if(gROOT->FindObject("rangeEtaPhi2")) delete gROOT->FindObject("rangeEtaPhi2");
TH2F* rangeEtaPhi = new TH2F("rangeEtaPhi2", "", 10, -0.99, +0.99, 10, -3.15, 3.15);
SetStyle(rangeEtaPhi->GetXaxis(), "#eta", 0.07, 0.8, kTRUE, 0.05);
SetStyle(rangeEtaPhi->GetYaxis(), "detector #varphi", 0.07, 0.8, kTRUE, 0.05);
rangeEtaPhi->SetStats(kFALSE);
// eta-phi distr. for <Qtot> in layer 0
TVirtualPad* pad;
TProfile2D* hProf2D;
TH2D* hQtotMPV;
TH1D* tempProj1D;
TH1D* hqtot = (TH1D*)qtotCF->Project(0, qtotCF->GetVar(fgkVarNames[kTrackletQtot]));
qtotCF->SetRangeUser(qtotCF->GetVar(fgkVarNames[kTrackletQtot]), 0.0, 3000.);
for(Int_t iLayer=0; iLayer<6; ++iLayer) {
pad = ((TVirtualPad*)l->At((iLayer<3 ? iLayer*3 : (iLayer-3)*3+1))); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.1); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
rangeEtaPhi->Draw();
qtotCF->SetRangeUser(qtotCF->GetVar(fgkVarNames[kTrackletLayer]), Double_t(iLayer), Double_t(iLayer));
TH3D* hQtotEtaPhi = (TH3D*)qtotCF->Project(0, qtotCF->GetVar(fgkVarNames[kTrackPhiTRD]), qtotCF->GetVar(fgkVarNames[kTrackEtaTRD]), qtotCF->GetVar(fgkVarNames[kTrackletQtot]));
hQtotEtaPhi->Rebin3D(2,2,1);
//hProf2D = (hQtotEtaPhi ? hQtotEtaPhi->Project3DProfile() : 0x0);
hQtotMPV = new TH2D(Form("QtotMPV_layer%d",iLayer),"",hQtotEtaPhi->GetYaxis()->GetNbins(),
hQtotEtaPhi->GetYaxis()->GetXmin(), hQtotEtaPhi->GetYaxis()->GetXmax(),
hQtotEtaPhi->GetXaxis()->GetNbins(), hQtotEtaPhi->GetXaxis()->GetXmin(), hQtotEtaPhi->GetXaxis()->GetXmax());
for(Int_t iphi=1; iphi<hQtotEtaPhi->GetYaxis()->GetNbins(); ++iphi) {
for(Int_t ieta=1; ieta<hQtotEtaPhi->GetXaxis()->GetNbins(); ++ieta) {
tempProj1D = hQtotEtaPhi->ProjectionZ("tempProj",ieta,ieta,iphi,iphi);
Int_t maxBin = tempProj1D->GetMaximumBin();
if(maxBin<3) continue;
if(maxBin>tempProj1D->GetXaxis()->GetNbins()-3) continue;
Double_t mpv = tempProj1D->GetBinContent(maxBin)*tempProj1D->GetBinCenter(maxBin)+
tempProj1D->GetBinContent(maxBin-1)*tempProj1D->GetBinCenter(maxBin-1)+
tempProj1D->GetBinContent(maxBin+1)*tempProj1D->GetBinCenter(maxBin+1)+
tempProj1D->GetBinContent(maxBin-2)*tempProj1D->GetBinCenter(maxBin-2)+
tempProj1D->GetBinContent(maxBin+2)*tempProj1D->GetBinCenter(maxBin+2);
Double_t norm = tempProj1D->GetBinContent(maxBin-2)+tempProj1D->GetBinContent(maxBin-1)+tempProj1D->GetBinContent(maxBin)+tempProj1D->GetBinContent(maxBin+1)+tempProj1D->GetBinContent(maxBin+2);
if(norm>0.5) mpv = mpv / (norm);
delete tempProj1D;
hQtotMPV->SetBinContent(iphi,ieta,mpv);
}
}
if(hQtotMPV) {
hQtotMPV->SetStats(kFALSE);
hQtotMPV->SetMinimum(500.);
hQtotMPV->SetMaximum((hqtot->GetMean()<10 ? 4.0 : 1500.));
hQtotMPV->Draw("samecolz");
}
if(hQtotEtaPhi) delete hQtotEtaPhi;
if(hProf2D) {
hProf2D->SetName(Form("Qtot_layer%d",iLayer));
hProf2D->SetStats(kFALSE);
hProf2D->SetMinimum(500.);
hProf2D->SetMaximum((hqtot->GetMean()<10 ? 4.0 : 1500.));
hProf2D->Draw("samecolz");
}
lat->DrawLatex(-0.9, 3.3, Form("TRD Q_{tot} MPV Layer %d", iLayer));
DrawTRDGrid();
}
qtotCF->SetRangeUser(qtotCF->GetVar(fgkVarNames[kTrackletLayer]), 0.0, 5.0);
qtotCF->SetRangeUser(qtotCF->GetVar(fgkVarNames[kTrackletQtot]), 0.0, 10000.);
// PH versus slice number
pad = ((TVirtualPad*)l->At(2)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.03); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
if(gROOT->FindObject("rangePHslice")) delete gROOT->FindObject("rangePHslice");
TH2F* rangePHslice=new TH2F("rangePHslice", "", 8, -0.5, 7.5, 10, 0.0, (hqtot->GetMean()<10.0 ? 6.0 : 3000.));
rangePHslice->SetStats(kFALSE);
SetStyle(rangePHslice->GetXaxis(), "slice", 0.07, 0.8, kTRUE, 0.05);
SetStyle(rangePHslice->GetYaxis(), "PH", 0.07, 0.8, kTRUE, 0.05);
rangePHslice->Draw();
TF1* funcPol1 = new TF1("funcPol1", "[0]+[1]*x", 2.9, 6.4);
TH2D* hPH = (TH2D*)phCF->Project(0, phCF->GetVar(fgkVarNames[kTrackletSlice]), phCF->GetVar(fgkVarNames[kTrackletPHslice]));
TH1D* hSliceErr = new TH1D(Form("hSliceErr%f", gRandom->Rndm()), "", hPH->GetXaxis()->GetNbins(), hPH->GetXaxis()->GetXbins()->GetArray());
TH1D* hLandauFit = Proj2D(hPH, hSliceErr);
hPH->SetStats(kFALSE);
hPH->Draw("samecolz");
const Double_t kQx = 0.002;
if(trendValues) {
hSliceErr->Fit(funcPol1, "QME0", "goff", 2.9, 6.4);
trendValues[12] = kQx*funcPol1->GetParameter(0); // PH plateau
trendValues[13] = kQx*funcPol1->GetParError(0); // PH plateau
trendValues[14] = kQx*funcPol1->GetParameter(1); // PH slope
trendValues[15] = kQx*funcPol1->GetParError(1); // PH slope
trendValues[18] = funcPol1->GetParameter(0); // PH plateau
trendValues[19] = funcPol1->GetParError(0); // PH plateau
trendValues[20] = funcPol1->GetParameter(1); // PH slope
trendValues[21] = funcPol1->GetParError(1); // PH slope
}
hLandauFit->SetLineWidth(2);
hLandauFit->SetLineStyle(2);
hLandauFit->Draw("same");
delete funcPol1; delete hSliceErr;
// Qtot vs P
pad = ((TVirtualPad*)l->At(5)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.03); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
pad->SetLogz();
if(gROOT->FindObject("rangeQtotP")) delete gROOT->FindObject("rangeQtotP");
TH2F* rangeQtotP = new TH2F("rangeQtotP", "", 10, 0.0, 11.99, 10, 0.0, (hqtot->GetMean()<10.0 ? 11.99 : 5999.));
SetStyle(rangeQtotP->GetXaxis(), "P [GeV/c]", 0.07, 0.8, kTRUE, 0.05);
SetStyle(rangeQtotP->GetYaxis(), "Q_{tot}", 0.07, 0.8, kTRUE, 0.05);
rangeQtotP->SetStats(kFALSE);
rangeQtotP->Draw();
Int_t pVar = centCF->GetVar(fgkVarNames[kTrackP]);
if(pVar<0) pVar = centCF->GetVar(fgkVarNames[kTrackletP]);
TH2D* hQtotP = (TH2D*)centCF->Project(0, pVar, centCF->GetVar(fgkVarNames[kTrackletQtot]));
TH1D* mpvErr=new TH1D("mpvErr", "Landau MPV error vs. P", hQtotP->GetXaxis()->GetNbins(), hQtotP->GetXaxis()->GetXbins()->GetArray());
TH1D* widthErr=new TH1D("widthErr", "Landau width error vs. P", hQtotP->GetXaxis()->GetNbins(), hQtotP->GetXaxis()->GetXbins()->GetArray());
TH1D* landauChi2=new TH1D("landauChi2", "Landau fit #chi^{2} vs. P", hQtotP->GetXaxis()->GetNbins(), hQtotP->GetXaxis()->GetXbins()->GetArray());
if(hQtotP)
for(Int_t i=1; i<=hQtotP->GetXaxis()->GetNbins(); ++i)
hQtotP->SetBinContent(i, 1, 0.0);
TH1D* hQtotProj = (hQtotP ? Proj2D(hQtotP, mpvErr, widthErr, landauChi2) : 0x0);
//landauChi2->Scale(0.001);
if(hQtotProj) SetStyle(hQtotProj, 2, kBlue, 2, 1, kBlue, 1);
if(trendValues && hQtotProj && hQtotProj->GetEntries()>2) {
trendValues[16] = kQx*hQtotProj->GetBinContent(hQtotProj->FindBin(1.0)); // Landau MPV at 1GeV/c
trendValues[17] = kQx*hQtotProj->GetBinError(hQtotProj->FindBin(1.0)); // Landau width at 1 GeV/c
trendValues[22] = hQtotProj->GetBinContent(hQtotProj->FindBin(1.0)); // Landau MPV at 1GeV/c
trendValues[23] = hQtotProj->GetBinError(hQtotProj->FindBin(1.0)); // Landau width at 1 GeV/c
}
if(hQtotP) {
hQtotP->SetStats(kFALSE);
hQtotP->Draw("samecolz");
hQtotProj->Draw("same");
}
// Qtot vs P (fit results)
pad = ((TVirtualPad*)l->At(8)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.03); pad->SetBottomMargin(0.15);
pad->SetGridx(kFALSE); pad->SetGridy(kFALSE);
pad->SetLogz();
if(gROOT->FindObject("rangeQtotPfit")) delete gROOT->FindObject("rangeQtotPfit");
TH2F* rangeQtotPfit = new TH2F("rangeQtotPfit", "", 100, 0.0, 11.99, 100, 0.0, (hqtot->GetMean()<10.0 ? 6.0 : 3999.));
SetStyle(rangeQtotPfit->GetXaxis(), "P [GeV/c]", 0.07, 0.8, kTRUE, 0.05);
SetStyle(rangeQtotPfit->GetYaxis(), "Q_{tot}", 0.07, 0.8, kTRUE, 0.05);
rangeQtotPfit->SetStats(kFALSE);
rangeQtotPfit->Draw();
if(mpvErr) SetStyle(mpvErr, 1, kBlue, 2, 1, kBlue, 1);
if(widthErr) SetStyle(widthErr, 2, kRed, 2, 1, kRed, 1);
if(mpvErr) {
mpvErr->SetStats(kFALSE);
mpvErr->Draw("same");
}
if(widthErr) {
widthErr->SetStats(kFALSE);
widthErr->Draw("same");
}
TLegend* leg=new TLegend(0.2,0.6,0.5,0.9);
leg->SetFillColor(0);
leg->SetBorderSize(0);
leg->AddEntry("mpvErr","Landau MPV","l");
leg->AddEntry("widthErr","Landau width","l");
leg->Draw();
}
//__________________________________________________________________________________________________
void AliTRDcheckESD::PlotOtherSummaryFromCF(Double_t* /*trendValues*/) {
//
// Plot additional QA
//
if(!fHistos) return;
AliCFContainer* matchPhiEta = (AliCFContainer*)fHistos->FindObject("MatchingPhiEta");
AliCFContainer* trdChi2 = (AliCFContainer*)fHistos->FindObject("trdChi2");
AliCFContainer* trdBudget = (AliCFContainer*)fHistos->FindObject("trdBudget");
AliCFContainer* ploss = (AliCFContainer*)fHistos->FindObject("Ploss");
AliCFContainer* clusters = (AliCFContainer*)fHistos->FindObject("clustersPerTracklet");
AliCFContainer* clsRows = (AliCFContainer*)fHistos->FindObject("clustersVsRows");
TLatex *lat=new TLatex();
lat->SetTextSize(0.06);
lat->SetTextColor(2);
lat->SetNDC();
lat->SetTextFont(42);
TCanvas* c1 = new TCanvas("ESDsummary", "ESD summary 1", 1600, 1200);
gPad->SetTopMargin(0.05); gPad->SetBottomMargin(0.001);
gPad->SetLeftMargin(0.001); gPad->SetRightMargin(0.001);
gPad->Divide(3,3,0.,0.);
TList* l=gPad->GetListOfPrimitives();
TVirtualPad* pad=0x0;
// matching as a function of trigger class
if(matchPhiEta) {
matchPhiEta->SetRangeUser(matchPhiEta->GetVar(fgkVarNames[kTrackCharge]), -1.0, -1.0);
TH1F* hTRDEffTriggerNeg = EfficiencyFromPhiPt(matchPhiEta, -1, -1, 1, 0, kEventTrigger);
matchPhiEta->SetRangeUser(matchPhiEta->GetVar(fgkVarNames[kTrackCharge]), +1.0, +1.0);
TH1F* hTRDEffTriggerPos = EfficiencyFromPhiPt(matchPhiEta, -1, -1, 1, 0, kEventTrigger);
pad = ((TVirtualPad*)l->At(0)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.01);
pad->SetTopMargin(0.06); pad->SetBottomMargin(0.15);
hTRDEffTriggerNeg->SetStats(kFALSE);
SetStyle(hTRDEffTriggerNeg->GetYaxis(), "efficiency", 0.06, 1.0, kTRUE, 0.06);
hTRDEffTriggerNeg->GetXaxis()->SetRange(1,fNAssignedTriggers);
hTRDEffTriggerPos->GetXaxis()->SetRange(1,fNAssignedTriggers);
SetStyle(hTRDEffTriggerNeg, 1, 2, 2, 20, 2, 1);
SetStyle(hTRDEffTriggerPos, 1, 4, 2, 20, 4, 1);
hTRDEffTriggerNeg->Draw();
hTRDEffTriggerPos->Draw("same");
TLegend* legEff=new TLegend(0.5,0.5,0.7,0.7);
legEff->SetFillColor(0);
legEff->SetBorderSize(0);
legEff->AddEntry(hTRDEffTriggerNeg, "negatives", "l");
legEff->AddEntry(hTRDEffTriggerPos, "positives", "l");
legEff->Draw();
lat->DrawLatex(0.2, 0.95, "TPC-TRD matching efficiency");
}
if(trdChi2) {
// Track TRD chi2 vs (eta,phi)
TH3D* trdChi23D = (TH3D*)trdChi2->Project(0, trdChi2->GetVar(fgkVarNames[kTrackEtaTRD]),
trdChi2->GetVar(fgkVarNames[kTrackPhiTRD]),
trdChi2->GetVar(fgkVarNames[kTrackTrdChi2]));
trdChi23D->SetName("trdChi23D");
TProfile2D* prof2DChi2 = trdChi23D->Project3DProfile("yx");
prof2DChi2->SetName("prof2DChi2");
pad = ((TVirtualPad*)l->At(3)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.06); pad->SetBottomMargin(0.15);
prof2DChi2->SetStats(kFALSE);
prof2DChi2->SetTitle("");
SetStyle(prof2DChi2->GetXaxis(), "#eta", 0.06, 1.0, kTRUE, 0.06);
SetStyle(prof2DChi2->GetYaxis(), "#varphi (rad.)", 0.06, 1.0, kTRUE, 0.06);
prof2DChi2->SetMaximum(2.9);
prof2DChi2->Draw("colz");
lat->DrawLatex(0.2, 0.95, "TRD #chi^{2}");
DrawTRDGrid();
// Track TRD chi2 vs pt and charge
trdChi2->SetRangeUser(trdChi2->GetVar(fgkVarNames[kTrackCharge]), -1.0, -1.0);
TH2D* trdChi2VsPtNeg = (TH2D*)trdChi2->Project(0, trdChi2->GetVar(fgkVarNames[kTrackPt]),
trdChi2->GetVar(fgkVarNames[kTrackTrdChi2]));
trdChi2VsPtNeg->SetName("trdChi2VsPtNeg");
TProfile* trdChi2VsPtNegProf = trdChi2VsPtNeg->ProfileX();
trdChi2VsPtNegProf->SetName("trdChi2VsPtNegProf");
trdChi2->SetRangeUser(trdChi2->GetVar(fgkVarNames[kTrackCharge]), 1.0, 1.0);
TH2D* trdChi2VsPtPos = (TH2D*)trdChi2->Project(0, trdChi2->GetVar(fgkVarNames[kTrackPt]),
trdChi2->GetVar(fgkVarNames[kTrackTrdChi2]));
trdChi2VsPtPos->SetName("trdChi2VsPtPos");
TProfile* trdChi2VsPtPosProf = trdChi2VsPtPos->ProfileX();
trdChi2VsPtPosProf->SetName("trdChi2VsPtPosProf");
pad = ((TVirtualPad*)l->At(6)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.01);
pad->SetTopMargin(0.06); pad->SetBottomMargin(0.15);
trdChi2VsPtNegProf->SetStats(kFALSE);
trdChi2VsPtNegProf->SetTitle("");
SetStyle(trdChi2VsPtNegProf->GetXaxis(), "p_{T} (GeV/c)", 0.06, 1.0, kTRUE, 0.06);
SetStyle(trdChi2VsPtNegProf->GetYaxis(), "<TRD #chi^{2}>", 0.06, 1.0, kTRUE, 0.06);
SetStyle(trdChi2VsPtNegProf, 1, 2, 2, 20, 2, 1);
SetStyle(trdChi2VsPtPosProf, 1, 4, 2, 20, 4, 1);
trdChi2VsPtNegProf->Draw();
trdChi2VsPtPosProf->Draw("same");
lat->DrawLatex(0.2, 0.95, "TRD #chi^{2}");
}
if(trdBudget) {
// Track TRD budget vs (eta,phi)
TH3D* trdBudget3D = (TH3D*)trdBudget->Project(0, trdBudget->GetVar(fgkVarNames[kTrackEtaTRD]),
trdBudget->GetVar(fgkVarNames[kTrackPhiTRD]),
trdBudget->GetVar(fgkVarNames[kTrackTRDBudget]));
trdBudget3D->SetName("trdBudget3D");
TProfile2D* prof2DBudget = trdBudget3D->Project3DProfile("yx");
prof2DBudget->SetName("prof2DBudget");
pad = ((TVirtualPad*)l->At(1)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.06); pad->SetBottomMargin(0.15);
prof2DBudget->SetStats(kFALSE);
prof2DBudget->SetTitle("");
SetStyle(prof2DBudget->GetXaxis(), "#eta", 0.06, 1.0, kTRUE, 0.06);
SetStyle(prof2DBudget->GetYaxis(), "#varphi (rad.)", 0.06, 1.0, kTRUE, 0.06);
prof2DBudget->Draw("colz");
lat->DrawLatex(0.2, 0.95, "TRD budget");
DrawTRDGrid();
}
if(ploss) {
// momentum loss
ploss->SetRangeUser(ploss->GetVar(fgkVarNames[kTrackCharge]), -1.0, -1.0);
TH2D* plossLayerNeg = (TH2D*)ploss->Project(0, ploss->GetVar(fgkVarNames[kTrackletLayer]),
ploss->GetVar(fgkVarNames[kTrackPlossTRDlayer]));
plossLayerNeg->SetName("plossLayerNeg");
TProfile* plossLayerNegProf = plossLayerNeg->ProfileX();
plossLayerNegProf->SetName("plossLayerNegProf");
ploss->SetRangeUser(ploss->GetVar(fgkVarNames[kTrackCharge]), +1.0, +1.0);
TH2D* plossLayerPos = (TH2D*)ploss->Project(0, ploss->GetVar(fgkVarNames[kTrackletLayer]),
ploss->GetVar(fgkVarNames[kTrackPlossTRDlayer]));
plossLayerPos->SetName("plossLayerPos");
TProfile* plossLayerPosProf = plossLayerPos->ProfileX();
plossLayerPosProf->SetName("plossLayerPosProf");
ploss->SetRangeUser(ploss->GetVar(fgkVarNames[kTrackCharge]), -1.5, +1.5);
ploss->SetRangeUser(ploss->GetVar(fgkVarNames[kTrackletLayer]), 0.0, 0.0);
TH3D* ploss3Dl0 = (TH3D*)ploss->Project(0, ploss->GetVar(fgkVarNames[kTrackEtaTRD]),
ploss->GetVar(fgkVarNames[kTrackPhiTRD]),
ploss->GetVar(fgkVarNames[kTrackPlossTRDlayer]));
ploss3Dl0->SetName("ploss3Dl0");
TProfile2D* plossEtaPhiL0Prof = ploss3Dl0->Project3DProfile("yx");
plossEtaPhiL0Prof->SetName("plossEtaPhiL0Prof");
ploss->SetRangeUser(ploss->GetVar(fgkVarNames[kTrackletLayer]), 5.0, 5.0);
TH3D* ploss3Dl5 = (TH3D*)ploss->Project(0, ploss->GetVar(fgkVarNames[kTrackEtaTRD]),
ploss->GetVar(fgkVarNames[kTrackPhiTRD]),
ploss->GetVar(fgkVarNames[kTrackPlossTRDlayer]));
ploss3Dl5->SetName("ploss3Dl5");
TProfile2D* plossEtaPhiL5Prof = ploss3Dl5->Project3DProfile("yx");
plossEtaPhiL5Prof->SetName("plossEtaPhiL5Prof");
pad = ((TVirtualPad*)l->At(4)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.06); pad->SetBottomMargin(0.15);
plossEtaPhiL0Prof->SetStats(kFALSE);
plossEtaPhiL0Prof->SetTitle("");
SetStyle(plossEtaPhiL0Prof->GetXaxis(), "#eta", 0.06, 1.0, kTRUE, 0.06);
SetStyle(plossEtaPhiL0Prof->GetYaxis(), "#varphi (rad.)", 0.06, 1.0, kTRUE, 0.06);
plossEtaPhiL0Prof->SetMaximum(80.0);
plossEtaPhiL0Prof->SetMinimum(-20.0);
plossEtaPhiL0Prof->Draw("colz");
lat->DrawLatex(0.2, 0.95, "P_{loss} at layer 0");
DrawTRDGrid();
pad = ((TVirtualPad*)l->At(7)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.06); pad->SetBottomMargin(0.15);
plossEtaPhiL5Prof->SetStats(kFALSE);
plossEtaPhiL5Prof->SetTitle("");
SetStyle(plossEtaPhiL5Prof->GetXaxis(), "#eta", 0.06, 1.0, kTRUE, 0.06);
SetStyle(plossEtaPhiL5Prof->GetYaxis(), "#varphi (rad.)", 0.06, 1.0, kTRUE, 0.06);
plossEtaPhiL5Prof->SetMaximum(80.0);
plossEtaPhiL5Prof->SetMinimum(-20.0);
plossEtaPhiL5Prof->Draw("colz");
lat->DrawLatex(0.2, 0.95, "P_{loss} at layer 5");
DrawTRDGrid();
pad = ((TVirtualPad*)l->At(2)); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.01);
pad->SetTopMargin(0.06); pad->SetBottomMargin(0.15);
plossLayerNegProf->SetStats(kFALSE);
plossLayerNegProf->SetTitle("");
SetStyle(plossLayerNegProf->GetYaxis(), "#Delta P (MeV/c)", 0.06, 1.0, kTRUE, 0.06);
SetStyle(plossLayerNegProf->GetXaxis(), "TRD layer", 0.06, 1.0, kTRUE, 0.06);
SetStyle(plossLayerNegProf, 1, 2, 2, 20, 2, 1);
SetStyle(plossLayerPosProf, 1, 4, 2, 20, 4, 1);
plossLayerNegProf->GetYaxis()->SetRangeUser(TMath::Min(plossLayerNegProf->GetMinimum(),plossLayerPosProf->GetMinimum()-5.0),
TMath::Max(plossLayerNegProf->GetMaximum(),plossLayerPosProf->GetMaximum())+5.0);
plossLayerNegProf->Draw();
plossLayerPosProf->Draw("same");
lat->DrawLatex(0.2, 0.95, "P_{loss} vs layer");
}
// clusters/tracklet and clusters/crossed rows
TH3D* clustersEtaPhi[6]={0x0};
TH3D* clsRowsEtaPhi[6]={0x0};
for(Int_t il=0;il<6;++il) {
if(clusters) {
clusters->SetRangeUser(clusters->GetVar(fgkVarNames[kTrackletLayer]), Double_t(il), Double_t(il));
clustersEtaPhi[il]=(TH3D*)clusters->Project(0, clusters->GetVar(fgkVarNames[kTrackEtaTRD]),
clusters->GetVar(fgkVarNames[kTrackPhiTRD]),
clusters->GetVar(fgkVarNames[kTrackletClusters]));
clustersEtaPhi[il]->SetName(Form("clustersEtaPhi%d",il));
}
if(clsRows) {
clsRows->SetRangeUser(clsRows->GetVar(fgkVarNames[kTrackletLayer]), Double_t(il), Double_t(il));
clsRowsEtaPhi[il]=(TH3D*)clsRows->Project(0, clsRows->GetVar(fgkVarNames[kTrackEtaTRD]),
clsRows->GetVar(fgkVarNames[kTrackPhiTRD]),
clsRows->GetVar(fgkVarNames[kTrackletClustersVsRows]));
clsRowsEtaPhi[il]->SetName(Form("clsRowsEtaPhi%d",il));
}
}
lat->SetTextSize(0.05);
Int_t layerPads[6] = {0, 2, 4, 1, 3, 5};
TCanvas* c2=0x0;
if(clusters) {
c2 = new TCanvas("ESDsummary2", "ESD summary 2", 1600, 1200);
gPad->SetTopMargin(0.05); gPad->SetBottomMargin(0.001);
gPad->SetLeftMargin(0.001); gPad->SetRightMargin(0.001);
gPad->Divide(3,2,0.,0.);
l=gPad->GetListOfPrimitives();
for(Int_t il=0;il<6;++il) {
TProfile2D* clustersEtaPhiProf = clustersEtaPhi[il]->Project3DProfile("yx");
pad = ((TVirtualPad*)l->At(layerPads[il])); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.1);
pad->SetTopMargin(0.06); pad->SetBottomMargin(0.15);
clustersEtaPhiProf->SetStats(kFALSE);
clustersEtaPhiProf->SetTitle("");
SetStyle(clustersEtaPhiProf->GetXaxis(), "#eta", 0.06, 1.0, kTRUE, 0.06);
SetStyle(clustersEtaPhiProf->GetYaxis(), "#varphi (rad.)", 0.06, 1.0, kTRUE, 0.06);
clustersEtaPhiProf->SetMaximum(30.);
clustersEtaPhiProf->Draw("colz");
lat->DrawLatex(0.2, 0.95, Form("Clusters / tracklet, layer %d", il));
DrawTRDGrid();
}
}
TCanvas* c3=0x0;
if(clsRows) {
c3 = new TCanvas("ESDsummary3", "ESD summary 3", 1600, 1200);
gPad->SetTopMargin(0.05); gPad->SetBottomMargin(0.001);
gPad->SetLeftMargin(0.001); gPad->SetRightMargin(0.001);
gPad->Divide(3,2,0.,0.);
l=gPad->GetListOfPrimitives();
for(Int_t il=0;il<6;++il) {
TProfile2D* clsRowsEtaPhiProf = clsRowsEtaPhi[il]->Project3DProfile("yx");
pad = ((TVirtualPad*)l->At(layerPads[il])); pad->cd();
pad->SetLeftMargin(0.15); pad->SetRightMargin(0.13);
pad->SetTopMargin(0.06); pad->SetBottomMargin(0.15);
clsRowsEtaPhiProf->SetStats(kFALSE);
clsRowsEtaPhiProf->SetTitle("");
SetStyle(clsRowsEtaPhiProf->GetXaxis(), "#eta", 0.06, 1.0, kTRUE, 0.06);
SetStyle(clsRowsEtaPhiProf->GetYaxis(), "#varphi (rad.)", 0.06, 1.0, kTRUE, 0.06);
clsRowsEtaPhiProf->Draw("colz");
lat->DrawLatex(0.2, 0.95, Form("Clusters / crossed rows, layer %d", il));
DrawTRDGrid();
}
}
if(matchPhiEta || trdChi2 || trdBudget || ploss) c1->SaveAs("esdSummary1.gif");
if(clusters) c2->SaveAs("esdSummary2.gif");
if(clsRows) c3->SaveAs("esdSummary3.gif");
}
//__________________________________________________________________________________________________
void AliTRDcheckESD::DrawTRDGrid() {
//
// Draw a grid of lines showing the TRD supermodule and stack structure in (eta,phi) coordinates.
// The canvas on which to draw must already exist.
//
TLine line;
line.SetLineColor(2);
line.SetLineWidth(1);
line.SetLineStyle(2);
for(Int_t i=-9; i<=9; ++i) {
line.DrawLine(-0.92, 2.0*TMath::Pi()/18.0*i, +0.92, 2.0*TMath::Pi()/18.0*i);
}
line.DrawLine(-0.85, -3.15, -0.85, 3.15);
line.DrawLine(-0.54, -3.15, -0.54, 3.15);
line.DrawLine(-0.16, -3.15, -0.16, 3.15);
line.DrawLine(+0.16, -3.15, +0.16, 3.15);
line.DrawLine(+0.54, -3.15, +0.54, 3.15);
line.DrawLine(+0.85, -3.15, +0.85, 3.15);
}
//_________________________________________________________________
void AliTRDcheckESD::SetStyle(TH1* hist,
Int_t lineStyle, Int_t lineColor, Int_t lineWidth,
Int_t markerStyle, Int_t markerColor, Int_t markerSize) {
//
// Set style settings for histograms
//
if(!hist) return;
hist->SetLineStyle(lineStyle);
hist->SetLineColor(lineColor);
hist->SetLineWidth(lineWidth);
hist->SetMarkerStyle(markerStyle);
hist->SetMarkerColor(markerColor);
hist->SetMarkerSize(markerSize);
}
//____________________________________________________________________
void AliTRDcheckESD::SetStyle(TAxis* axis, const Char_t* title, Float_t titleSize, Float_t titleOffset, Bool_t centerTitle,
Float_t labelSize) {
//
// Set style settings for axes
//
if(!axis) return;
axis->SetTitle(title);
axis->SetTitleSize(titleSize);
axis->SetTitleOffset(titleOffset);
axis->CenterTitle(centerTitle);
axis->SetLabelSize(labelSize);
axis->SetTitleFont(42);
axis->SetLabelFont(42);
axis->SetNdivisions(507);
}
//____________________________________________________________________
void AliTRDcheckESD::FindIsolatedBCs(TH1D* bcHist, Bool_t isIsolated[3500]) {
//
// Find the isolated bunch crossings
//
Int_t isolationSize = 5; // number of free bunches in both directions
for(Int_t bcBin=1; bcBin<=bcHist->GetXaxis()->GetNbins(); ++bcBin) {
Int_t bc = TMath::Nint(bcHist->GetBinCenter(bcBin));
if(bc<-0.001 || bc>3499.01) {
isIsolated[bc] = kFALSE;
continue;
}
Double_t entries = bcHist->GetBinContent(bcBin);
if(entries<0.001) {
isIsolated[bc] = kFALSE;
continue; // no entries
}
// check isolation
isIsolated[bc] = kTRUE;
for(Int_t ibc = TMath::Max(1,bcBin-isolationSize); ibc<=TMath::Min(3499, bcBin+isolationSize); ++ibc) {
if(ibc==bcBin) continue;
if(bcHist->GetBinContent(ibc)>0.01) {
isIsolated[bc] = kFALSE;
break;
}
}
} // end loop over BC bins
cout << "Isolated bunches: " << endl;
for(Int_t ibc=0; ibc<3500; ++ibc)
if(isIsolated[ibc]) cout << "BC #" << ibc << endl;
}
//__________________________________________________________________________________________________
Int_t AliTRDcheckESD::GetTriggerIndex(const Char_t* name, Bool_t createNew/*=kTRUE*/) {
//
// Return the index of trigger "name" in the trigger histogram.
// If the index for this trigger does not exist yet, then assign one if createNew is set to TRUE
//
//cout << "GetTriggerIndex for " << name << endl;
TH1F* triggerHist = (TH1F*)fHistos->FindObject("hTriggerDefs");
TString nameStr=name;
for(Int_t i=1; i<=triggerHist->GetXaxis()->GetNbins(); ++i) {
if(!nameStr.CompareTo(triggerHist->GetXaxis()->GetBinLabel(i))) {
//cout << " index found: " << i << endl;
return i;
}
}
if(createNew) {
triggerHist->GetXaxis()->SetBinLabel(fNAssignedTriggers+1, name);
for(Int_t i=1;i<fHistos->GetEntries();++i) {
TString objType = fHistos->At(i)->IsA()->GetName();
if(!objType.Contains("AliCFContainer")) continue;
AliCFContainer* cf=(AliCFContainer*)fHistos->At(i);
Int_t trigVar = cf->GetVar(fgkVarNames[kEventTrigger]);
if(trigVar>=0)
for(Int_t istep=0;istep<cf->GetNStep();++istep)
cf->GetAxis(trigVar, istep)->SetBinLabel(fNAssignedTriggers+1, name);
} // end loop over histograms and CFs
++fNAssignedTriggers;
return fNAssignedTriggers+1;
}
else {
return -1;
}
}
//__________________________________________________________________________________________________
void AliTRDcheckESD::PrintTriggers() const {
//
// Print the available triggers for this run
//
if(!fHistos) {
cout << "Warning in AliTRDcheckESD::PrintTriggers(): No file loaded!" << endl;
return;
}
TH1F* hTriggers = (TH1F*)fHistos->FindObject("hTriggerDefs");
cout << "Triggers found in this run" << endl;
cout << "==========================" << endl;
cout << "Name Index Entries " << endl;
for(Int_t it=1; it<hTriggers->GetXaxis()->GetNbins(); ++it) {
if(hTriggers->GetXaxis()->GetBinLabel(it)[0]!='\0') {
cout << hTriggers->GetXaxis()->GetBinLabel(it) << " " << hTriggers->GetXaxis()->GetBinCenter(it) << " " << hTriggers->GetBinContent(it) << endl;
}
}
}
//__________________________________________________________________________________________________
Int_t AliTRDcheckESD::GetTriggerCounter(const Char_t* triggerName) const {
//
// Get the number of events for a given trigger name
//
if(!fHistos) {
cout << "Warning in AliTRDcheckESD::PrintTriggers(): No file loaded!" << endl;
return -1;
}
TH1F* hTriggers = (TH1F*)fHistos->FindObject("hTriggerDefs");
Int_t counter = -1;
for(Int_t it=1; it<hTriggers->GetXaxis()->GetNbins(); ++it) {
TString trgString = hTriggers->GetXaxis()->GetBinLabel(it);
if(!trgString.CompareTo(triggerName))
counter = (Int_t)hTriggers->GetBinContent(it);
}
if(counter<0) {cout << "AliTRDcheckESD::GetTriggerCounter() Trigger not found !!";}
return counter;
}
//__________________________________________________________________________________________________________
Int_t AliTRDcheckESD::GetNAssignedTriggers() {
//
// Return the number of assigned triggers
//
return fNAssignedTriggers;
}
|
/*
* Copyright (c) 2015-2019 Dubalu LLC
*
* 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 "index_resolver_lru.h"
#include "database/flags.h" // for DB_*
#include "database/handler.h" // for DatabaseHandler
#include "database/utils.h" // for UNKNOWN_REVISION
#include "manager.h" // XapiandManager::dispatch_command, XapiandManager::resolve_index_endpoints
#include "opts.h" // for opts::*
#include "reserved/schema.h" // RESERVED_*
#include "reserved/fields.h" // ID_FIELD_NAME, ...
#include "server/discovery.h" // for primary_updater
#include "serialise.h" // for KEYWORD_STR
#define L_SHARDS L_NOTHING
// #undef L_CALL
// #define L_CALL L_STACKED_DIM_GREY
// #undef L_SHARDS
// #define L_SHARDS L_DARK_SLATE_BLUE
IndexSettingsShard::IndexSettingsShard() :
version(UNKNOWN_REVISION),
modified(false)
{
}
IndexSettings::IndexSettings() :
version(UNKNOWN_REVISION),
loaded(false),
saved(false),
modified(false),
stalled(std::chrono::steady_clock::time_point::min()),
num_shards(0),
num_replicas_plus_master(0)
{
}
IndexSettings::IndexSettings(Xapian::rev version, bool loaded, bool saved, bool modified, std::chrono::steady_clock::time_point stalled, size_t num_shards, size_t num_replicas_plus_master, const std::vector<IndexSettingsShard>& shards) :
version(version),
loaded(loaded),
saved(saved),
modified(modified),
stalled(stalled),
num_shards(num_shards),
num_replicas_plus_master(num_replicas_plus_master),
shards(shards)
{
#ifndef NDEBUG
size_t replicas_size = 0;
for (auto& shard : shards) {
auto replicas_size_ = shard.nodes.size();
assert(replicas_size_ != 0 && (!replicas_size || replicas_size == replicas_size_));
replicas_size = replicas_size_;
}
#endif
}
std::string
IndexSettings::__repr__() const {
std::vector<std::string> qq;
for (auto& ss : shards) {
std::vector<std::string> q;
for (auto& s : ss.nodes) {
q.push_back(repr(s));
}
qq.push_back(strings::format("[{}]", strings::join(q, ", ")));
}
return strings::format("[{}]", strings::join(qq, ", "));
}
std::mutex IndexResolverLRU::resolve_index_lru_mtx;
lru::lru<std::string, IndexSettings> IndexResolverLRU::resolve_index_lru(opts.resolver_cache_size);
constexpr int CONFLICT_RETRIES = 10; // Number of tries for resolving version conflicts
void
settle_replicas(IndexSettings& index_settings, std::vector<std::shared_ptr<const Node>>& nodes, size_t num_replicas_plus_master)
{
L_CALL("settle_replicas(<index_settings>, {})", num_replicas_plus_master);
size_t total_nodes = Node::total_nodes();
if (num_replicas_plus_master > total_nodes) {
num_replicas_plus_master = total_nodes;
}
for (auto& shard : index_settings.shards) {
auto shard_nodes_size = shard.nodes.size();
assert(shard_nodes_size);
if (shard_nodes_size < num_replicas_plus_master) {
std::unordered_set<std::string> used;
for (size_t i = 0; i < shard_nodes_size; ++i) {
used.insert(strings::lower(shard.nodes[i]));
}
if (nodes.empty()) {
nodes = Node::nodes();
}
auto primary = strings::lower(shard.nodes[0]);
size_t idx = 0;
for (const auto& node : nodes) {
if (node->lower_name() == primary) {
break;
}
++idx;
}
auto nodes_size = nodes.size();
for (auto n = shard_nodes_size; n < num_replicas_plus_master; ++n) {
std::shared_ptr<const Node> node;
do {
node = nodes[++idx % nodes_size];
assert(idx < nodes_size * 2);
} while (used.count(node->lower_name()));
shard.nodes.push_back(node->name());
used.insert(node->lower_name());
}
shard.modified = true;
index_settings.saved = false;
} else if (shard_nodes_size > num_replicas_plus_master) {
assert(num_replicas_plus_master);
shard.nodes.resize(num_replicas_plus_master);
shard.modified = true;
index_settings.saved = false;
}
}
}
std::vector<IndexSettingsShard>
calculate_shards(size_t routing_key, std::vector<std::shared_ptr<const Node>>& nodes, size_t num_shards)
{
L_CALL("calculate_shards({}, {})", routing_key, num_shards);
std::vector<IndexSettingsShard> shards;
if (Node::total_nodes()) {
if (routing_key < num_shards) {
routing_key += num_shards;
}
for (size_t s = 0; s < num_shards; ++s) {
IndexSettingsShard shard;
if (nodes.empty()) {
nodes = Node::nodes();
}
size_t idx = (routing_key - s) % nodes.size();
auto node = nodes[idx];
shard.nodes.push_back(node->name());
shard.modified = true;
shards.push_back(std::move(shard));
}
}
return shards;
}
void
update_primary(const std::string& unsharded_normalized_path, IndexSettings& index_settings, std::shared_ptr<const Node> primary_node)
{
L_CALL("update_primary({}, <index_settings>)", repr(unsharded_normalized_path));
auto now = std::chrono::steady_clock::now();
if (index_settings.stalled > now) {
return;
}
bool updated = false;
size_t shard_num = 0;
for (auto& shard : index_settings.shards) {
++shard_num;
auto it_b = shard.nodes.begin();
auto it_e = shard.nodes.end();
auto it = it_b;
for (; it != it_e; ++it) {
auto node = Node::get_node(*it);
if (node && !node->empty()) {
if (node->is_active() || (primary_node && *node == *primary_node)) {
break;
}
}
}
if (it != it_b && it != it_e) {
if (primary_node) {
auto normalized_path = index_settings.shards.size() > 1 ? strings::format("{}/.__{}", unsharded_normalized_path, shard_num) : unsharded_normalized_path;
auto from_node = Node::get_node(*it_b);
auto to_node = Node::get_node(*it);
L_INFO("Primary shard {} moved from node {}{}" + INFO_COL + " to {}{}",
repr(normalized_path),
from_node->col().ansi(), from_node->name(),
to_node->col().ansi(), to_node->name());
std::swap(*it, *it_b);
updated = true;
shard.modified = true;
index_settings.saved = false;
} else if (index_settings.stalled == std::chrono::steady_clock::time_point::min()) {
index_settings.stalled = now + std::chrono::milliseconds(opts.database_stall_time);
break;
} else if (index_settings.stalled <= now) {
auto node = Node::get_node(*it_b);
if (node->last_seen() <= index_settings.stalled) {
auto normalized_path = index_settings.shards.size() > 1 ? strings::format("{}/.__{}", unsharded_normalized_path, shard_num) : unsharded_normalized_path;
XapiandManager::dispatch_command(XapiandManager::Command::ELECT_PRIMARY, normalized_path);
}
index_settings.stalled = now + std::chrono::milliseconds(opts.database_stall_time);
}
}
}
#ifdef XAPIAND_CLUSTERING
if (!opts.solo) {
if (updated) {
index_settings.stalled = std::chrono::steady_clock::time_point::min();
primary_updater()->debounce(unsharded_normalized_path, index_settings.shards.size(), unsharded_normalized_path);
}
}
#endif
}
void
save_shards(const std::string& unsharded_normalized_path, size_t num_replicas_plus_master, IndexSettingsShard& shard)
{
L_CALL("save_shards(<shard>)");
if (shard.modified) {
Endpoint endpoint(".xapiand/indices");
auto endpoints = XapiandManager::resolve_index_endpoints(endpoint, true);
assert(!endpoints.empty());
DatabaseHandler db_handler(endpoints, DB_CREATE_OR_OPEN | DB_WRITABLE);
MsgPack obj({
{ RESERVED_IGNORE, SCHEMA_FIELD_NAME },
{ ID_FIELD_NAME, {
{ RESERVED_TYPE, KEYWORD_STR },
} },
{ "number_of_shards", {
{ RESERVED_INDEX, "none" },
{ RESERVED_TYPE, "positive" },
} },
{ "number_of_replicas", {
{ RESERVED_INDEX, "none" },
{ RESERVED_TYPE, "positive" },
{ RESERVED_VALUE, num_replicas_plus_master - 1 },
} },
{ "shards", {
{ RESERVED_INDEX, "field_terms" },
{ RESERVED_TYPE, "array/keyword" },
{ RESERVED_VALUE, shard.nodes },
} },
});
auto info = db_handler.update(unsharded_normalized_path, shard.version, false, true, obj, false, msgpack_type).first;
shard.version = info.version;
shard.modified = false;
}
}
void
save_settings(const std::string& unsharded_normalized_path, IndexSettings& index_settings)
{
L_CALL("save_settings(<index_settings>)");
assert(index_settings.shards.size() == index_settings.num_shards);
if (index_settings.num_shards == 1) {
save_shards(unsharded_normalized_path, index_settings.num_replicas_plus_master, index_settings.shards[0]);
index_settings.saved = true;
index_settings.loaded = true;
} else if (index_settings.num_shards != 0) {
if (!index_settings.shards[0].nodes.empty()) {
if (index_settings.modified) {
Endpoint endpoint(".xapiand/indices");
auto endpoints = XapiandManager::resolve_index_endpoints(endpoint, true);
assert(!endpoints.empty());
DatabaseHandler db_handler(endpoints, DB_CREATE_OR_OPEN | DB_WRITABLE);
MsgPack obj({
{ RESERVED_IGNORE, SCHEMA_FIELD_NAME },
{ ID_FIELD_NAME, {
{ RESERVED_TYPE, KEYWORD_STR },
} },
{ "number_of_shards", {
{ RESERVED_INDEX, "none" },
{ RESERVED_TYPE, "positive" },
{ RESERVED_VALUE, index_settings.num_shards },
} },
{ "number_of_replicas", {
{ RESERVED_INDEX, "none" },
{ RESERVED_TYPE, "positive" },
{ RESERVED_VALUE, index_settings.num_replicas_plus_master - 1 },
} },
{ "shards", {
{ RESERVED_INDEX, "field_terms" },
{ RESERVED_TYPE, "array/keyword" },
} },
});
auto info = db_handler.update(unsharded_normalized_path, index_settings.version, false, true, obj, false, msgpack_type).first;
index_settings.version = info.version;
index_settings.modified = false;
}
}
size_t shard_num = 0;
for (auto& shard : index_settings.shards) {
if (!shard.nodes.empty()) {
auto shard_normalized_path = strings::format("{}/.__{}", unsharded_normalized_path, ++shard_num);
save_shards(shard_normalized_path, index_settings.num_replicas_plus_master, shard);
}
}
index_settings.saved = true;
index_settings.loaded = true;
}
}
IndexSettingsShard
load_replicas(const Endpoint& endpoint, const MsgPack& obj)
{
L_CALL("load_replicas(<obj>)");
IndexSettingsShard shard;
auto it = obj.find(VERSION_FIELD_NAME);
if (it != obj.end()) {
auto& version_val = it.value();
if (!version_val.is_number()) {
THROW(Error, "Inconsistency in '{}' configured for {}: Invalid version number", VERSION_FIELD_NAME, repr(endpoint.to_string()));
}
shard.version = version_val.u64();
}
it = obj.find("shards");
if (it != obj.end()) {
auto& replicas_val = it.value();
if (!replicas_val.is_array()) {
THROW(Error, "Inconsistency in 'shards' configured for {}: Invalid array", repr(endpoint.to_string()));
}
for (auto& node_name_val : replicas_val) {
if (!node_name_val.is_string()) {
THROW(Error, "Inconsistency in 'shards' configured for {}: Invalid node name", repr(endpoint.to_string()));
}
shard.nodes.push_back(node_name_val.str());
}
}
return shard;
}
IndexSettings
load_settings(const std::string& unsharded_normalized_path)
{
L_CALL("load_settings(<index_endpoints>, {})", repr(unsharded_normalized_path));
auto nodes = Node::nodes();
assert(!nodes.empty());
Endpoint endpoint(".xapiand/indices");
for (int t = DB_RETRIES; t >= 0; --t) {
try {
IndexSettings index_settings;
auto endpoints = XapiandManager::resolve_index_endpoints(endpoint, true);
if(endpoints.empty()) {
continue;
}
DatabaseHandler db_handler(endpoints, DB_CREATE_OR_OPEN | DB_WRITABLE);
auto document = db_handler.get_document(unsharded_normalized_path);
auto obj = document.get_obj();
auto it = obj.find(VERSION_FIELD_NAME);
if (it != obj.end()) {
auto& version_val = it.value();
if (!version_val.is_number()) {
THROW(Error, "Inconsistency in '{}' configured for {}: Invalid version number", VERSION_FIELD_NAME, repr(endpoint.to_string()));
}
index_settings.version = version_val.u64();
} else {
auto version_ser = document.get_value(DB_SLOT_VERSION);
if (version_ser.empty()) {
THROW(Error, "Inconsistency in '{}' configured for {}: No version number", VERSION_FIELD_NAME, repr(endpoint.to_string()));
}
index_settings.version = sortable_unserialise(version_ser);
}
it = obj.find("number_of_replicas");
if (it != obj.end()) {
auto& n_replicas_val = it.value();
if (!n_replicas_val.is_number()) {
THROW(Error, "Inconsistency in 'number_of_replicas' configured for {}: Invalid number", repr(endpoint.to_string()));
}
index_settings.num_replicas_plus_master = n_replicas_val.u64() + 1;
}
it = obj.find("number_of_shards");
if (it != obj.end()) {
auto& n_shards_val = it.value();
if (!n_shards_val.is_number()) {
THROW(Error, "Inconsistency in 'number_of_shards' configured for {}: Invalid number", repr(endpoint.to_string()));
}
index_settings.num_shards = n_shards_val.u64();
size_t replicas_size = 0;
for (size_t shard_num = 1; shard_num <= index_settings.num_shards; ++shard_num) {
auto shard_normalized_path = strings::format("{}/.__{}", unsharded_normalized_path, shard_num);
auto replica_document = db_handler.get_document(shard_normalized_path);
auto shard = load_replicas(endpoint, replica_document.get_obj());
auto replicas_size_ = shard.nodes.size();
if (replicas_size_ == 0 || replicas_size_ > index_settings.num_replicas_plus_master || (replicas_size && replicas_size != replicas_size_)) {
THROW(Error, "Inconsistency in number of replicas configured for {}", repr(endpoint.to_string()));
}
replicas_size = replicas_size_;
index_settings.shards.push_back(std::move(shard));
}
}
if (!index_settings.num_shards) {
auto shard = load_replicas(endpoint, obj);
auto replicas_size_ = shard.nodes.size();
if (replicas_size_ == 0 || replicas_size_ > index_settings.num_replicas_plus_master) {
THROW(Error, "Inconsistency in number of replicas configured for {}", repr(endpoint.to_string()));
}
index_settings.shards.push_back(std::move(shard));
index_settings.num_shards = 1;
}
index_settings.loaded = true;
return index_settings;
} catch (const Xapian::DocNotFoundError&) {
break;
} catch (const Xapian::DatabaseNotFoundError&) {
break;
} catch (const Xapian::DatabaseNotAvailableError&) {
if (t == 0) { throw; }
}
}
return {};
}
MsgPack
shards_to_obj(const std::vector<IndexSettingsShard>& shards)
{
MsgPack nodes = MsgPack::ARRAY();
for (auto& shard : shards) {
MsgPack node_replicas = MsgPack::ARRAY();
for (auto name : shard.nodes) {
auto node = Node::get_node(name);
node_replicas.append(MsgPack({
{ "node", node ? MsgPack(node->name()) : MsgPack::NIL() },
}));
}
nodes.append(std::move(node_replicas));
}
return nodes;
}
std::vector<std::vector<std::shared_ptr<const Node>>>
IndexResolverLRU::resolve_nodes(const IndexSettings& index_settings)
{
L_CALL("IndexResolverLRU::resolve_nodes({})", shards_to_obj(index_settings.shards).to_string());
std::vector<std::vector<std::shared_ptr<const Node>>> nodes;
for (auto& shard : index_settings.shards) {
std::vector<std::shared_ptr<const Node>> node_replicas;
for (auto name : shard.nodes) {
auto node = Node::get_node(name);
node_replicas.push_back(std::move(node));
}
nodes.push_back(std::move(node_replicas));
}
return nodes;
}
IndexSettings
IndexResolverLRU::resolve_index_settings(std::string_view normalized_path, bool writable, [[maybe_unused]] bool primary, const MsgPack* settings, std::shared_ptr<const Node> primary_node, bool reload, bool rebuild, bool clear)
{
L_CALL("IndexResolverLRU::resolve_index_settings({}, {}, {}, {}, {}, {}, {}, {})", repr(normalized_path), writable, primary, settings ? settings->to_string() : "null", primary_node ? repr(primary_node->to_string()) : "null", reload, rebuild, clear);
auto strict = opts.strict;
if (settings) {
if (settings->is_map()) {
auto strict_it = settings->find(RESERVED_STRICT);
if (strict_it != settings->end()) {
auto& strict_val = strict_it.value();
if (strict_val.is_boolean()) {
strict = strict_val.as_boolean();
} else {
THROW(ClientError, "Data inconsistency, '{}' must be boolean", RESERVED_STRICT);
}
}
auto settings_it = settings->find(RESERVED_SETTINGS);
if (settings_it != settings->end()) {
settings = &settings_it.value();
} else {
settings = nullptr;
}
} else {
settings = nullptr;
}
}
IndexSettings index_settings;
if (strings::startswith(normalized_path, ".xapiand/")) {
// Everything inside .xapiand has the primary shard inside
// the current leader and replicas everywhere.
if (settings) {
THROW(ClientError, "Cannot modify settings of cluster indices.");
}
// Primary databases in .xapiand are always in the master (or local, if master is unavailable)
primary_node = Node::get_primary_node();
if (!primary_node->is_active()) {
L_WARNING("Primary node {}{}" + WARNING_COL + " is not active!", primary_node->col().ansi(), primary_node->to_string());
}
IndexSettingsShard shard;
shard.nodes.push_back(primary_node->name());
for (const auto& node : Node::nodes()) {
if (!Node::is_superset(node, primary_node)) {
shard.nodes.push_back(node->name());
}
}
if (normalized_path == ".xapiand/indices") {
// .xapiand/indices have the default number of shards
for (size_t i = 0; i < opts.num_shards; ++i) {
index_settings.shards.push_back(shard);
}
index_settings.num_shards = opts.num_shards;
} else {
// Everything else inside .xapiand has a single shard
// (.xapiand/nodes, .xapiand/indices/.__N, .xapiand/* etc.)
index_settings.shards.push_back(shard);
index_settings.num_shards = 1;
}
return index_settings;
}
std::unique_lock<std::mutex> lk(resolve_index_lru_mtx);
if (primary_node) {
reload = true;
rebuild = true;
}
auto it_e = resolve_index_lru.end();
auto it = it_e;
if (!settings && !reload && !rebuild && !clear) {
it = resolve_index_lru.find(std::string(normalized_path));
if (it != it_e) {
index_settings = it->second;
if (!writable || index_settings.saved) {
return index_settings;
}
}
}
bool store_lru = false;
auto unsharded = unsharded_path(normalized_path);
std::string unsharded_normalized_path = std::string(unsharded.first);
if (!reload) {
it = resolve_index_lru.find(unsharded_normalized_path);
}
if (it != it_e) {
if (clear) {
resolve_index_lru.erase(it);
return {};
}
index_settings = it->second;
lk.unlock();
L_SHARDS("Node settings for {} loaded from LRU", unsharded_normalized_path);
} else {
lk.unlock();
index_settings = load_settings(unsharded_normalized_path);
store_lru = true;
if (!index_settings.shards.empty()) {
for (auto& shard : index_settings.shards) {
if (shard.nodes.empty()) {
rebuild = true; // There were missing replicas, rebuild!
break;
}
}
L_SHARDS("Node settings for {} loaded", unsharded_normalized_path);
} else {
index_settings.num_shards = opts.num_shards;
index_settings.num_replicas_plus_master = opts.num_replicas + 1;
index_settings.modified = true;
index_settings.saved = false;
L_SHARDS("Node settings for {} initialized", unsharded_normalized_path);
}
}
assert(Node::total_nodes());
if (settings) {
auto num_shards = index_settings.num_shards;
auto num_replicas_plus_master = index_settings.num_replicas_plus_master;
auto num_shards_it = settings->find("number_of_shards");
if (num_shards_it != settings->end()) {
auto& num_shards_val = num_shards_it.value();
if (num_shards_val.is_number()) {
num_shards = num_shards_val.u64();
if (num_shards == 0 || num_shards > 9999UL) {
THROW(ClientError, "Invalid 'number_of_shards' setting");
}
} else {
THROW(ClientError, "Data inconsistency, 'number_of_shards' must be integer");
}
} else if (writable) {
if (strict && !index_settings.loaded) {
THROW(MissingTypeError, "Value of 'number_of_shards' is missing");
}
}
auto num_replicas_it = settings->find("number_of_replicas");
if (num_replicas_it != settings->end()) {
auto& num_replicas_val = num_replicas_it.value();
if (num_replicas_val.is_number()) {
num_replicas_plus_master = num_replicas_val.u64() + 1;
if (num_replicas_plus_master == 0 || num_replicas_plus_master > 9999UL) {
THROW(ClientError, "Invalid 'number_of_replicas' setting");
}
} else {
THROW(ClientError, "Data inconsistency, 'number_of_replicas' must be numeric");
}
} else if (writable) {
if (strict && !index_settings.loaded) {
THROW(MissingTypeError, "Value of 'number_of_replicas' is missing");
}
}
if (!index_settings.shards.empty()) {
if (num_shards != index_settings.num_shards) {
if (index_settings.loaded) {
THROW(ClientError, "It is not allowed to change 'number_of_shards' setting");
}
rebuild = true;
}
if (num_replicas_plus_master != index_settings.num_replicas_plus_master) {
rebuild = true;
}
}
if (index_settings.num_replicas_plus_master != num_replicas_plus_master) {
index_settings.num_replicas_plus_master = num_replicas_plus_master;
index_settings.modified = true;
index_settings.saved = false;
}
if (index_settings.num_shards != num_shards) {
index_settings.num_shards = num_shards;
index_settings.modified = true;
index_settings.saved = false;
index_settings.shards.clear();
}
} else if (writable) {
if (strict && !index_settings.loaded) {
THROW(MissingTypeError, "Index settings are missing");
}
}
if (rebuild || index_settings.shards.empty()) {
L_SHARDS(" Configuring {} replicas for {} shards", index_settings.num_replicas_plus_master - 1, index_settings.num_shards);
std::vector<std::shared_ptr<const Node>> node_nodes;
if (index_settings.shards.empty()) {
size_t routing_key = jump_consistent_hash(unsharded_normalized_path, Node::total_nodes());
index_settings.shards = calculate_shards(routing_key, node_nodes, index_settings.num_shards);
assert(!index_settings.shards.empty());
index_settings.modified = true;
index_settings.saved = false;
}
settle_replicas(index_settings, node_nodes, index_settings.num_replicas_plus_master);
if (writable) {
update_primary(unsharded_normalized_path, index_settings, primary_node);
}
store_lru = true;
}
if (!index_settings.shards.empty()) {
if (writable && !index_settings.saved) {
save_settings(unsharded_normalized_path, index_settings);
store_lru = true;
}
IndexSettings shard_settings;
if (store_lru) {
lk.lock();
resolve_index_lru[unsharded_normalized_path] = IndexSettings(
index_settings.version,
index_settings.loaded,
index_settings.saved,
index_settings.modified,
index_settings.stalled,
index_settings.num_shards,
index_settings.num_replicas_plus_master,
index_settings.shards);
size_t shard_num = 0;
for (auto& shard : index_settings.shards) {
assert(!shard.nodes.empty());
auto shard_normalized_path = strings::format("{}/.__{}", unsharded_normalized_path, ++shard_num);
std::vector<IndexSettingsShard> shard_shards;
shard_shards.push_back(shard);
resolve_index_lru[shard_normalized_path] = IndexSettings(
shard.version,
index_settings.loaded,
index_settings.saved,
shard.modified,
index_settings.stalled,
1,
index_settings.num_replicas_plus_master,
shard_shards);
if (shard_normalized_path == normalized_path) {
shard_settings = resolve_index_lru[shard_normalized_path];
}
}
lk.unlock();
} else {
size_t shard_num = 0;
for (auto& shard : index_settings.shards) {
assert(!shard.nodes.empty());
auto shard_normalized_path = strings::format("{}/.__{}", unsharded_normalized_path, ++shard_num);
if (shard_normalized_path == normalized_path) {
std::vector<IndexSettingsShard> shard_shards;
shard_shards.push_back(shard);
shard_settings = IndexSettings(
shard.version,
index_settings.loaded,
index_settings.saved,
shard.modified,
index_settings.stalled,
1,
index_settings.num_replicas_plus_master,
shard_shards);
break;
}
}
}
if (!shard_settings.shards.empty()) {
return shard_settings;
}
}
return index_settings;
}
Endpoints
IndexResolverLRU::resolve_index_endpoints(const Endpoint& endpoint, bool writable, bool primary, const MsgPack* settings)
{
L_CALL("IndexResolverLRU::resolve_index_endpoints({}, {}, {}, {})", repr(endpoint.to_string()), writable, primary, settings ? settings->to_string() : "null");
auto unsharded = unsharded_path(endpoint.path);
std::string unsharded_normalized_path_holder;
if (unsharded.second) {
unsharded_normalized_path_holder = std::string(unsharded.first);
}
auto& unsharded_normalized_path = unsharded.second ? unsharded_normalized_path_holder : endpoint.path;
bool rebuild = false;
int t = CONFLICT_RETRIES;
while (true) {
try {
Endpoints endpoints;
auto index_settings = resolve_index_settings(unsharded_normalized_path, writable, primary, settings, nullptr, t != CONFLICT_RETRIES, rebuild, false);
auto nodes = resolve_nodes(index_settings);
bool retry = !rebuild;
rebuild = false;
int n_shards = nodes.size();
size_t shard_num = 0;
for (const auto& shard_nodes : nodes) {
auto path = n_shards == 1 ? unsharded_normalized_path : strings::format("{}/.__{}", unsharded_normalized_path, ++shard_num);
if (!unsharded.second || path == endpoint.path) {
Endpoint node_endpoint;
for (const auto& node : shard_nodes) {
node_endpoint = Endpoint(path, node);
if (writable) {
if (Node::is_active(node)) {
L_SHARDS("Active writable node used (of {} nodes) {}", Node::total_nodes(), node ? node->__repr__() : "null");
break;
}
rebuild = retry;
break;
} else {
if (Node::is_active(node)) {
L_SHARDS("Active node used (of {} nodes) {}", Node::total_nodes(), node ? node->__repr__() : "null");
break;
}
if (primary) {
L_SHARDS("Inactive primary node used (of {} nodes) {}", Node::total_nodes(), node ? node->__repr__() : "null");
break;
}
L_SHARDS("Inactive node ignored (of {} nodes) {}", Node::total_nodes(), node ? node->__repr__() : "null");
}
}
endpoints.add(node_endpoint);
if (rebuild || unsharded.second) {
break;
}
}
}
if (!rebuild) {
return endpoints;
}
} catch (const Xapian::DocVersionConflictError&) {
if (--t == 0) { throw; }
}
}
}
Code format
/*
* Copyright (c) 2015-2019 Dubalu LLC
*
* 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 "index_resolver_lru.h"
#include "database/flags.h" // for DB_*
#include "database/handler.h" // for DatabaseHandler
#include "database/utils.h" // for UNKNOWN_REVISION
#include "manager.h" // XapiandManager::dispatch_command, XapiandManager::resolve_index_endpoints
#include "opts.h" // for opts::*
#include "reserved/schema.h" // RESERVED_*
#include "reserved/fields.h" // ID_FIELD_NAME, ...
#include "server/discovery.h" // for primary_updater
#include "serialise.h" // for KEYWORD_STR
#define L_SHARDS L_NOTHING
// #undef L_CALL
// #define L_CALL L_STACKED_DIM_GREY
// #undef L_SHARDS
// #define L_SHARDS L_DARK_SLATE_BLUE
IndexSettingsShard::IndexSettingsShard() :
version(UNKNOWN_REVISION),
modified(false)
{
}
IndexSettings::IndexSettings() :
version(UNKNOWN_REVISION),
loaded(false),
saved(false),
modified(false),
stalled(std::chrono::steady_clock::time_point::min()),
num_shards(0),
num_replicas_plus_master(0)
{
}
IndexSettings::IndexSettings(Xapian::rev version, bool loaded, bool saved, bool modified, std::chrono::steady_clock::time_point stalled, size_t num_shards, size_t num_replicas_plus_master, const std::vector<IndexSettingsShard>& shards) :
version(version),
loaded(loaded),
saved(saved),
modified(modified),
stalled(stalled),
num_shards(num_shards),
num_replicas_plus_master(num_replicas_plus_master),
shards(shards)
{
#ifndef NDEBUG
size_t replicas_size = 0;
for (auto& shard : shards) {
auto replicas_size_ = shard.nodes.size();
assert(replicas_size_ != 0 && (!replicas_size || replicas_size == replicas_size_));
replicas_size = replicas_size_;
}
#endif
}
std::string
IndexSettings::__repr__() const {
std::vector<std::string> qq;
for (auto& ss : shards) {
std::vector<std::string> q;
for (auto& s : ss.nodes) {
q.push_back(repr(s));
}
qq.push_back(strings::format("[{}]", strings::join(q, ", ")));
}
return strings::format("[{}]", strings::join(qq, ", "));
}
std::mutex IndexResolverLRU::resolve_index_lru_mtx;
lru::lru<std::string, IndexSettings> IndexResolverLRU::resolve_index_lru(opts.resolver_cache_size);
constexpr int CONFLICT_RETRIES = 10; // Number of tries for resolving version conflicts
void
settle_replicas(IndexSettings& index_settings, std::vector<std::shared_ptr<const Node>>& nodes, size_t num_replicas_plus_master)
{
L_CALL("settle_replicas(<index_settings>, {})", num_replicas_plus_master);
size_t total_nodes = Node::total_nodes();
if (num_replicas_plus_master > total_nodes) {
num_replicas_plus_master = total_nodes;
}
for (auto& shard : index_settings.shards) {
auto shard_nodes_size = shard.nodes.size();
assert(shard_nodes_size);
if (shard_nodes_size < num_replicas_plus_master) {
std::unordered_set<std::string> used;
for (size_t i = 0; i < shard_nodes_size; ++i) {
used.insert(strings::lower(shard.nodes[i]));
}
if (nodes.empty()) {
nodes = Node::nodes();
}
auto primary = strings::lower(shard.nodes[0]);
size_t idx = 0;
for (const auto& node : nodes) {
if (node->lower_name() == primary) {
break;
}
++idx;
}
auto nodes_size = nodes.size();
for (auto n = shard_nodes_size; n < num_replicas_plus_master; ++n) {
std::shared_ptr<const Node> node;
do {
node = nodes[++idx % nodes_size];
assert(idx < nodes_size * 2);
} while (used.count(node->lower_name()));
shard.nodes.push_back(node->name());
used.insert(node->lower_name());
}
shard.modified = true;
index_settings.saved = false;
} else if (shard_nodes_size > num_replicas_plus_master) {
assert(num_replicas_plus_master);
shard.nodes.resize(num_replicas_plus_master);
shard.modified = true;
index_settings.saved = false;
}
}
}
std::vector<IndexSettingsShard>
calculate_shards(size_t routing_key, std::vector<std::shared_ptr<const Node>>& nodes, size_t num_shards)
{
L_CALL("calculate_shards({}, {})", routing_key, num_shards);
std::vector<IndexSettingsShard> shards;
if (Node::total_nodes()) {
if (routing_key < num_shards) {
routing_key += num_shards;
}
for (size_t s = 0; s < num_shards; ++s) {
IndexSettingsShard shard;
if (nodes.empty()) {
nodes = Node::nodes();
}
size_t idx = (routing_key - s) % nodes.size();
auto node = nodes[idx];
shard.nodes.push_back(node->name());
shard.modified = true;
shards.push_back(std::move(shard));
}
}
return shards;
}
void
update_primary(const std::string& unsharded_normalized_path, IndexSettings& index_settings, std::shared_ptr<const Node> primary_node)
{
L_CALL("update_primary({}, <index_settings>)", repr(unsharded_normalized_path));
auto now = std::chrono::steady_clock::now();
if (index_settings.stalled > now) {
return;
}
bool updated = false;
size_t shard_num = 0;
for (auto& shard : index_settings.shards) {
++shard_num;
auto it_b = shard.nodes.begin();
auto it_e = shard.nodes.end();
auto it = it_b;
for (; it != it_e; ++it) {
auto node = Node::get_node(*it);
if (node && !node->empty()) {
if (node->is_active() || (primary_node && *node == *primary_node)) {
break;
}
}
}
if (it != it_b && it != it_e) {
if (primary_node) {
auto normalized_path = index_settings.shards.size() > 1 ? strings::format("{}/.__{}", unsharded_normalized_path, shard_num) : unsharded_normalized_path;
auto from_node = Node::get_node(*it_b);
auto to_node = Node::get_node(*it);
L_INFO("Primary shard {} moved from node {}{}" + INFO_COL + " to {}{}",
repr(normalized_path),
from_node->col().ansi(), from_node->name(),
to_node->col().ansi(), to_node->name());
std::swap(*it, *it_b);
updated = true;
shard.modified = true;
index_settings.saved = false;
} else if (index_settings.stalled == std::chrono::steady_clock::time_point::min()) {
index_settings.stalled = now + std::chrono::milliseconds(opts.database_stall_time);
break;
} else if (index_settings.stalled <= now) {
auto node = Node::get_node(*it_b);
if (node->last_seen() <= index_settings.stalled) {
auto normalized_path = index_settings.shards.size() > 1 ? strings::format("{}/.__{}", unsharded_normalized_path, shard_num) : unsharded_normalized_path;
XapiandManager::dispatch_command(XapiandManager::Command::ELECT_PRIMARY, normalized_path);
}
index_settings.stalled = now + std::chrono::milliseconds(opts.database_stall_time);
}
}
}
#ifdef XAPIAND_CLUSTERING
if (!opts.solo) {
if (updated) {
index_settings.stalled = std::chrono::steady_clock::time_point::min();
primary_updater()->debounce(unsharded_normalized_path, index_settings.shards.size(), unsharded_normalized_path);
}
}
#endif
}
void
save_shards(const std::string& unsharded_normalized_path, size_t num_replicas_plus_master, IndexSettingsShard& shard)
{
L_CALL("save_shards(<shard>)");
if (shard.modified) {
Endpoint endpoint(".xapiand/indices");
auto endpoints = XapiandManager::resolve_index_endpoints(endpoint, true);
assert(!endpoints.empty());
DatabaseHandler db_handler(endpoints, DB_CREATE_OR_OPEN | DB_WRITABLE);
MsgPack obj({
{ RESERVED_IGNORE, SCHEMA_FIELD_NAME },
{ ID_FIELD_NAME, {
{ RESERVED_TYPE, KEYWORD_STR },
} },
{ "number_of_shards", {
{ RESERVED_INDEX, "none" },
{ RESERVED_TYPE, "positive" },
} },
{ "number_of_replicas", {
{ RESERVED_INDEX, "none" },
{ RESERVED_TYPE, "positive" },
{ RESERVED_VALUE, num_replicas_plus_master - 1 },
} },
{ "shards", {
{ RESERVED_INDEX, "field_terms" },
{ RESERVED_TYPE, "array/keyword" },
{ RESERVED_VALUE, shard.nodes },
} },
});
auto info = db_handler.update(unsharded_normalized_path, shard.version, false, true, obj, false, msgpack_type).first;
shard.version = info.version;
shard.modified = false;
}
}
void
save_settings(const std::string& unsharded_normalized_path, IndexSettings& index_settings)
{
L_CALL("save_settings(<index_settings>)");
assert(index_settings.shards.size() == index_settings.num_shards);
if (index_settings.num_shards == 1) {
save_shards(unsharded_normalized_path, index_settings.num_replicas_plus_master, index_settings.shards[0]);
index_settings.saved = true;
index_settings.loaded = true;
} else if (index_settings.num_shards != 0) {
if (!index_settings.shards[0].nodes.empty()) {
if (index_settings.modified) {
Endpoint endpoint(".xapiand/indices");
auto endpoints = XapiandManager::resolve_index_endpoints(endpoint, true);
assert(!endpoints.empty());
DatabaseHandler db_handler(endpoints, DB_CREATE_OR_OPEN | DB_WRITABLE);
MsgPack obj({
{ RESERVED_IGNORE, SCHEMA_FIELD_NAME },
{ ID_FIELD_NAME, {
{ RESERVED_TYPE, KEYWORD_STR },
} },
{ "number_of_shards", {
{ RESERVED_INDEX, "none" },
{ RESERVED_TYPE, "positive" },
{ RESERVED_VALUE, index_settings.num_shards },
} },
{ "number_of_replicas", {
{ RESERVED_INDEX, "none" },
{ RESERVED_TYPE, "positive" },
{ RESERVED_VALUE, index_settings.num_replicas_plus_master - 1 },
} },
{ "shards", {
{ RESERVED_INDEX, "field_terms" },
{ RESERVED_TYPE, "array/keyword" },
} },
});
auto info = db_handler.update(unsharded_normalized_path, index_settings.version, false, true, obj, false, msgpack_type).first;
index_settings.version = info.version;
index_settings.modified = false;
}
}
size_t shard_num = 0;
for (auto& shard : index_settings.shards) {
if (!shard.nodes.empty()) {
auto shard_normalized_path = strings::format("{}/.__{}", unsharded_normalized_path, ++shard_num);
save_shards(shard_normalized_path, index_settings.num_replicas_plus_master, shard);
}
}
index_settings.saved = true;
index_settings.loaded = true;
}
}
IndexSettingsShard
load_replicas(const Endpoint& endpoint, const MsgPack& obj)
{
L_CALL("load_replicas(<obj>)");
IndexSettingsShard shard;
auto it = obj.find(VERSION_FIELD_NAME);
if (it != obj.end()) {
auto& version_val = it.value();
if (!version_val.is_number()) {
THROW(Error, "Inconsistency in '{}' configured for {}: Invalid version number", VERSION_FIELD_NAME, repr(endpoint.to_string()));
}
shard.version = version_val.u64();
}
it = obj.find("shards");
if (it != obj.end()) {
auto& replicas_val = it.value();
if (!replicas_val.is_array()) {
THROW(Error, "Inconsistency in 'shards' configured for {}: Invalid array", repr(endpoint.to_string()));
}
for (auto& node_name_val : replicas_val) {
if (!node_name_val.is_string()) {
THROW(Error, "Inconsistency in 'shards' configured for {}: Invalid node name", repr(endpoint.to_string()));
}
shard.nodes.push_back(node_name_val.str());
}
}
return shard;
}
IndexSettings
load_settings(const std::string& unsharded_normalized_path)
{
L_CALL("load_settings(<index_endpoints>, {})", repr(unsharded_normalized_path));
auto nodes = Node::nodes();
assert(!nodes.empty());
Endpoint endpoint(".xapiand/indices");
for (int t = DB_RETRIES; t >= 0; --t) {
try {
IndexSettings index_settings;
auto endpoints = XapiandManager::resolve_index_endpoints(endpoint, true);
if(endpoints.empty()) {
continue;
}
DatabaseHandler db_handler(endpoints, DB_CREATE_OR_OPEN | DB_WRITABLE);
auto document = db_handler.get_document(unsharded_normalized_path);
auto obj = document.get_obj();
auto it = obj.find(VERSION_FIELD_NAME);
if (it != obj.end()) {
auto& version_val = it.value();
if (!version_val.is_number()) {
THROW(Error, "Inconsistency in '{}' configured for {}: Invalid version number", VERSION_FIELD_NAME, repr(endpoint.to_string()));
}
index_settings.version = version_val.u64();
} else {
auto version_ser = document.get_value(DB_SLOT_VERSION);
if (version_ser.empty()) {
THROW(Error, "Inconsistency in '{}' configured for {}: No version number", VERSION_FIELD_NAME, repr(endpoint.to_string()));
}
index_settings.version = sortable_unserialise(version_ser);
}
it = obj.find("number_of_replicas");
if (it != obj.end()) {
auto& n_replicas_val = it.value();
if (!n_replicas_val.is_number()) {
THROW(Error, "Inconsistency in 'number_of_replicas' configured for {}: Invalid number", repr(endpoint.to_string()));
}
index_settings.num_replicas_plus_master = n_replicas_val.u64() + 1;
}
it = obj.find("number_of_shards");
if (it != obj.end()) {
auto& n_shards_val = it.value();
if (!n_shards_val.is_number()) {
THROW(Error, "Inconsistency in 'number_of_shards' configured for {}: Invalid number", repr(endpoint.to_string()));
}
index_settings.num_shards = n_shards_val.u64();
size_t replicas_size = 0;
for (size_t shard_num = 1; shard_num <= index_settings.num_shards; ++shard_num) {
auto shard_normalized_path = strings::format("{}/.__{}", unsharded_normalized_path, shard_num);
auto replica_document = db_handler.get_document(shard_normalized_path);
auto shard = load_replicas(endpoint, replica_document.get_obj());
auto replicas_size_ = shard.nodes.size();
if (replicas_size_ == 0 || replicas_size_ > index_settings.num_replicas_plus_master || (replicas_size && replicas_size != replicas_size_)) {
THROW(Error, "Inconsistency in number of replicas configured for {}", repr(endpoint.to_string()));
}
replicas_size = replicas_size_;
index_settings.shards.push_back(std::move(shard));
}
}
if (!index_settings.num_shards) {
auto shard = load_replicas(endpoint, obj);
auto replicas_size_ = shard.nodes.size();
if (replicas_size_ == 0 || replicas_size_ > index_settings.num_replicas_plus_master) {
THROW(Error, "Inconsistency in number of replicas configured for {}", repr(endpoint.to_string()));
}
index_settings.shards.push_back(std::move(shard));
index_settings.num_shards = 1;
}
index_settings.loaded = true;
return index_settings;
} catch (const Xapian::DocNotFoundError&) {
break;
} catch (const Xapian::DatabaseNotFoundError&) {
break;
} catch (const Xapian::DatabaseNotAvailableError&) {
if (t == 0) { throw; }
}
}
return {};
}
MsgPack
shards_to_obj(const std::vector<IndexSettingsShard>& shards)
{
MsgPack nodes = MsgPack::ARRAY();
for (auto& shard : shards) {
MsgPack node_replicas = MsgPack::ARRAY();
for (auto name : shard.nodes) {
auto node = Node::get_node(name);
node_replicas.append(MsgPack({
{ "node", node ? MsgPack(node->name()) : MsgPack::NIL() },
}));
}
nodes.append(std::move(node_replicas));
}
return nodes;
}
std::vector<std::vector<std::shared_ptr<const Node>>>
IndexResolverLRU::resolve_nodes(const IndexSettings& index_settings)
{
L_CALL("IndexResolverLRU::resolve_nodes({})", shards_to_obj(index_settings.shards).to_string());
std::vector<std::vector<std::shared_ptr<const Node>>> nodes;
for (auto& shard : index_settings.shards) {
std::vector<std::shared_ptr<const Node>> node_replicas;
for (auto name : shard.nodes) {
auto node = Node::get_node(name);
node_replicas.push_back(std::move(node));
}
nodes.push_back(std::move(node_replicas));
}
return nodes;
}
IndexSettings
IndexResolverLRU::resolve_index_settings(std::string_view normalized_path, bool writable, [[maybe_unused]] bool primary, const MsgPack* settings, std::shared_ptr<const Node> primary_node, bool reload, bool rebuild, bool clear)
{
L_CALL("IndexResolverLRU::resolve_index_settings({}, {}, {}, {}, {}, {}, {}, {})", repr(normalized_path), writable, primary, settings ? settings->to_string() : "null", primary_node ? repr(primary_node->to_string()) : "null", reload, rebuild, clear);
auto strict = opts.strict;
if (settings) {
if (settings->is_map()) {
auto strict_it = settings->find(RESERVED_STRICT);
if (strict_it != settings->end()) {
auto& strict_val = strict_it.value();
if (strict_val.is_boolean()) {
strict = strict_val.as_boolean();
} else {
THROW(ClientError, "Data inconsistency, '{}' must be boolean", RESERVED_STRICT);
}
}
auto settings_it = settings->find(RESERVED_SETTINGS);
if (settings_it != settings->end()) {
settings = &settings_it.value();
} else {
settings = nullptr;
}
} else {
settings = nullptr;
}
}
IndexSettings index_settings;
if (strings::startswith(normalized_path, ".xapiand/")) {
// Everything inside .xapiand has the primary shard inside
// the current leader and replicas everywhere.
if (settings) {
THROW(ClientError, "Cannot modify settings of cluster indices.");
}
// Primary databases in .xapiand are always in the master (or local, if master is unavailable)
primary_node = Node::get_primary_node();
if (!primary_node->is_active()) {
L_WARNING("Primary node {}{}" + WARNING_COL + " is not active!", primary_node->col().ansi(), primary_node->to_string());
}
IndexSettingsShard shard;
shard.nodes.push_back(primary_node->name());
for (const auto& node : Node::nodes()) {
if (!Node::is_superset(node, primary_node)) {
shard.nodes.push_back(node->name());
}
}
if (normalized_path == ".xapiand/indices") {
// .xapiand/indices have the default number of shards
for (size_t i = 0; i < opts.num_shards; ++i) {
index_settings.shards.push_back(shard);
}
index_settings.num_shards = opts.num_shards;
} else {
// Everything else inside .xapiand has a single shard
// (.xapiand/nodes, .xapiand/indices/.__N, .xapiand/* etc.)
index_settings.shards.push_back(shard);
index_settings.num_shards = 1;
}
return index_settings;
}
std::unique_lock<std::mutex> lk(resolve_index_lru_mtx);
if (primary_node) {
reload = true;
rebuild = true;
}
auto it_e = resolve_index_lru.end();
auto it = it_e;
if (!settings && !reload && !rebuild && !clear) {
it = resolve_index_lru.find(std::string(normalized_path));
if (it != it_e) {
index_settings = it->second;
if (!writable || index_settings.saved) {
return index_settings;
}
}
}
bool store_lru = false;
auto unsharded = unsharded_path(normalized_path);
std::string unsharded_normalized_path = std::string(unsharded.first);
if (!reload) {
it = resolve_index_lru.find(unsharded_normalized_path);
}
if (it != it_e) {
if (clear) {
resolve_index_lru.erase(it);
return {};
}
index_settings = it->second;
lk.unlock();
L_SHARDS("Node settings for {} loaded from LRU", unsharded_normalized_path);
} else {
lk.unlock();
index_settings = load_settings(unsharded_normalized_path);
store_lru = true;
if (!index_settings.shards.empty()) {
for (auto& shard : index_settings.shards) {
if (shard.nodes.empty()) {
rebuild = true; // There were missing replicas, rebuild!
break;
}
}
L_SHARDS("Node settings for {} loaded", unsharded_normalized_path);
} else {
index_settings.num_shards = opts.num_shards;
index_settings.num_replicas_plus_master = opts.num_replicas + 1;
index_settings.modified = true;
index_settings.saved = false;
L_SHARDS("Node settings for {} initialized", unsharded_normalized_path);
}
}
assert(Node::total_nodes());
if (settings) {
auto num_shards = index_settings.num_shards;
auto num_replicas_plus_master = index_settings.num_replicas_plus_master;
auto num_shards_it = settings->find("number_of_shards");
if (num_shards_it != settings->end()) {
auto& num_shards_val = num_shards_it.value();
if (num_shards_val.is_number()) {
num_shards = num_shards_val.u64();
if (num_shards == 0 || num_shards > 9999UL) {
THROW(ClientError, "Invalid 'number_of_shards' setting");
}
} else {
THROW(ClientError, "Data inconsistency, 'number_of_shards' must be integer");
}
} else if (writable) {
if (strict && !index_settings.loaded) {
THROW(MissingTypeError, "Value of 'number_of_shards' is missing");
}
}
auto num_replicas_it = settings->find("number_of_replicas");
if (num_replicas_it != settings->end()) {
auto& num_replicas_val = num_replicas_it.value();
if (num_replicas_val.is_number()) {
num_replicas_plus_master = num_replicas_val.u64() + 1;
if (num_replicas_plus_master == 0 || num_replicas_plus_master > 9999UL) {
THROW(ClientError, "Invalid 'number_of_replicas' setting");
}
} else {
THROW(ClientError, "Data inconsistency, 'number_of_replicas' must be numeric");
}
} else if (writable) {
if (strict && !index_settings.loaded) {
THROW(MissingTypeError, "Value of 'number_of_replicas' is missing");
}
}
if (!index_settings.shards.empty()) {
if (num_shards != index_settings.num_shards) {
if (index_settings.loaded) {
THROW(ClientError, "It is not allowed to change 'number_of_shards' setting");
}
rebuild = true;
}
if (num_replicas_plus_master != index_settings.num_replicas_plus_master) {
rebuild = true;
}
}
if (index_settings.num_replicas_plus_master != num_replicas_plus_master) {
index_settings.num_replicas_plus_master = num_replicas_plus_master;
index_settings.modified = true;
index_settings.saved = false;
}
if (index_settings.num_shards != num_shards) {
index_settings.num_shards = num_shards;
index_settings.modified = true;
index_settings.saved = false;
index_settings.shards.clear();
}
} else if (writable) {
if (strict && !index_settings.loaded) {
THROW(MissingTypeError, "Index settings are missing");
}
}
if (rebuild || index_settings.shards.empty()) {
L_SHARDS(" Configuring {} replicas for {} shards", index_settings.num_replicas_plus_master - 1, index_settings.num_shards);
std::vector<std::shared_ptr<const Node>> node_nodes;
if (index_settings.shards.empty()) {
size_t routing_key = jump_consistent_hash(unsharded_normalized_path, Node::total_nodes());
index_settings.shards = calculate_shards(routing_key, node_nodes, index_settings.num_shards);
assert(!index_settings.shards.empty());
index_settings.modified = true;
index_settings.saved = false;
}
settle_replicas(index_settings, node_nodes, index_settings.num_replicas_plus_master);
if (writable) {
update_primary(unsharded_normalized_path, index_settings, primary_node);
}
store_lru = true;
}
if (!index_settings.shards.empty()) {
if (writable && !index_settings.saved) {
save_settings(unsharded_normalized_path, index_settings);
store_lru = true;
}
IndexSettings shard_settings;
if (store_lru) {
lk.lock();
resolve_index_lru[unsharded_normalized_path] = IndexSettings(
index_settings.version,
index_settings.loaded,
index_settings.saved,
index_settings.modified,
index_settings.stalled,
index_settings.num_shards,
index_settings.num_replicas_plus_master,
index_settings.shards);
size_t shard_num = 0;
for (auto& shard : index_settings.shards) {
assert(!shard.nodes.empty());
auto shard_normalized_path = strings::format("{}/.__{}", unsharded_normalized_path, ++shard_num);
std::vector<IndexSettingsShard> shard_shards;
shard_shards.push_back(shard);
resolve_index_lru[shard_normalized_path] = IndexSettings(
shard.version,
index_settings.loaded,
index_settings.saved,
shard.modified,
index_settings.stalled,
1,
index_settings.num_replicas_plus_master,
shard_shards);
if (shard_normalized_path == normalized_path) {
shard_settings = resolve_index_lru[shard_normalized_path];
}
}
lk.unlock();
} else {
size_t shard_num = 0;
for (auto& shard : index_settings.shards) {
assert(!shard.nodes.empty());
auto shard_normalized_path = strings::format("{}/.__{}", unsharded_normalized_path, ++shard_num);
if (shard_normalized_path == normalized_path) {
std::vector<IndexSettingsShard> shard_shards;
shard_shards.push_back(shard);
shard_settings = IndexSettings(
shard.version,
index_settings.loaded,
index_settings.saved,
shard.modified,
index_settings.stalled,
1,
index_settings.num_replicas_plus_master,
shard_shards);
break;
}
}
}
if (!shard_settings.shards.empty()) {
return shard_settings;
}
}
return index_settings;
}
Endpoints
IndexResolverLRU::resolve_index_endpoints(const Endpoint& endpoint, bool writable, bool primary, const MsgPack* settings)
{
L_CALL("IndexResolverLRU::resolve_index_endpoints({}, {}, {}, {})", repr(endpoint.to_string()), writable, primary, settings ? settings->to_string() : "null");
auto unsharded = unsharded_path(endpoint.path);
std::string unsharded_normalized_path_holder;
if (unsharded.second) {
unsharded_normalized_path_holder = std::string(unsharded.first);
}
auto& unsharded_normalized_path = unsharded.second ? unsharded_normalized_path_holder : endpoint.path;
bool rebuild = false;
int t = CONFLICT_RETRIES;
while (true) {
try {
Endpoints endpoints;
auto index_settings = resolve_index_settings(unsharded_normalized_path, writable, primary, settings, nullptr, t != CONFLICT_RETRIES, rebuild, false);
auto nodes = resolve_nodes(index_settings);
bool retry = !rebuild;
rebuild = false;
int n_shards = nodes.size();
size_t shard_num = 0;
for (const auto& shard_nodes : nodes) {
auto path = n_shards == 1 ? unsharded_normalized_path : strings::format("{}/.__{}", unsharded_normalized_path, ++shard_num);
if (!unsharded.second || path == endpoint.path) {
Endpoint node_endpoint;
for (const auto& node : shard_nodes) {
node_endpoint = Endpoint(path, node);
if (writable) {
if (Node::is_active(node)) {
L_SHARDS("Active writable node used (of {} nodes) {}", Node::total_nodes(), node ? node->__repr__() : "null");
break;
}
rebuild = retry;
break;
} else {
if (Node::is_active(node)) {
L_SHARDS("Active node used (of {} nodes) {}", Node::total_nodes(), node ? node->__repr__() : "null");
break;
}
if (primary) {
L_SHARDS("Inactive primary node used (of {} nodes) {}", Node::total_nodes(), node ? node->__repr__() : "null");
break;
}
L_SHARDS("Inactive node ignored (of {} nodes) {}", Node::total_nodes(), node ? node->__repr__() : "null");
}
}
endpoints.add(node_endpoint);
if (rebuild || unsharded.second) {
break;
}
}
}
if (!rebuild) {
return endpoints;
}
} catch (const Xapian::DocVersionConflictError&) {
if (--t == 0) { throw; }
}
}
}
|
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
/*!
\class QGraphicsScene
\brief The QGraphicsScene class provides a surface for managing a large
number of 2D graphical items.
\since 4.2
\ingroup multimedia
\ingroup graphicsview-api
\mainclass
The class serves as a container for QGraphicsItems. It is used together
with QGraphicsView for visualizing graphical items, such as lines,
rectangles, text, or even custom items, on a 2D surface. QGraphicsScene is
part of \l{The Graphics View Framework}.
QGraphicsScene also provides functionality that lets you efficiently
determine both the location of items, and for determining what items are
visible within an arbitrary area on the scene. With the QGraphicsView
widget, you can either visualize the whole scene, or zoom in and view only
parts of the scene.
Example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 0
Note that QGraphicsScene has no visual appearance of its own; it only
manages the items. You need to create a QGraphicsView widget to visualize
the scene.
To add items to a scene, you start off by constructing a QGraphicsScene
object. Then, you have two options: either add your existing QGraphicsItem
objects by calling addItem(), or you can call one of the convenience
functions addEllipse(), addLine(), addPath(), addPixmap(), addPolygon(),
addRect(), or addText(), which all return a pointer to the newly added item.
The dimensions of the items added with these functions are relative to the
item's coordinate system, and the items position is initialized to (0,
0) in the scene.
You can then visualize the scene using QGraphicsView. When the scene
changes, (e.g., when an item moves or is transformed) QGraphicsScene
emits the changed() signal. To remove an item, call removeItem().
QGraphicsScene uses an indexing algorithm to manage the location of items
efficiently. By default, a BSP (Binary Space Partitioning) tree is used; an
algorithm suitable for large scenes where most items remain static (i.e.,
do not move around). You can choose to disable this index by calling
setItemIndexMethod(). For more information about the available indexing
algorithms, see the itemIndexMethod property.
The scene's bounding rect is set by calling setSceneRect(). Items can be
placed at any position on the scene, and the size of the scene is by
default unlimited. The scene rect is used only for internal bookkeeping,
maintaining the scene's item index. If the scene rect is unset,
QGraphicsScene will use the bounding area of all items, as returned by
itemsBoundingRect(), as the scene rect. However, itemsBoundingRect() is a
relatively time consuming function, as it operates by collecting
positional information for every item on the scene. Because of this, you
should always set the scene rect when operating on large scenes.
One of QGraphicsScene's greatest strengths is its ability to efficiently
determine the location of items. Even with millions of items on the scene,
the items() functions can determine the location of an item within few
milliseconds. There are several overloads to items(): one that finds items
at a certain position, one that finds items inside or intersecting with a
polygon or a rectangle, and more. The list of returned items is sorted by
stacking order, with the topmost item being the first item in the list.
For convenience, there is also an itemAt() function that returns the
topmost item at a given position.
QGraphicsScene maintains selection information for the scene. To select
items, call setSelectionArea(), and to clear the current selection, call
clearSelection(). Call selectedItems() to get the list of all selected
items.
\section1 Event Handling and Propagation
Another responsibility that QGraphicsScene has, is to propagate events
from QGraphicsView. To send an event to a scene, you construct an event
that inherits QEvent, and then send it using, for example,
QApplication::sendEvent(). event() is responsible for dispatching
the event to the individual items. Some common events are handled by
convenience event handlers. For example, key press events are handled by
keyPressEvent(), and mouse press events are handled by mousePressEvent().
Key events are delivered to the \e {focus item}. To set the focus item,
you can either call setFocusItem(), passing an item that accepts focus, or
the item itself can call QGraphicsItem::setFocus(). Call focusItem() to
get the current focus item. For compatibility with widgets, the scene also
maintains its own focus information. By default, the scene does not have
focus, and all key events are discarded. If setFocus() is called, or if an
item on the scene gains focus, the scene automatically gains focus. If the
scene has focus, hasFocus() will return true, and key events will be
forwarded to the focus item, if any. If the scene loses focus, (i.e.,
someone calls clearFocus(),) while an item has focus, the scene will
maintain its item focus information, and once the scene regains focus, it
will make sure the last focus item regains focus.
For mouse-over effects, QGraphicsScene dispatches \e {hover
events}. If an item accepts hover events (see
QGraphicsItem::acceptHoverEvents()), it will receive a \l
{QEvent::}{GraphicsSceneHoverEnter} event when the mouse enters
its area. As the mouse continues moving inside the item's area,
QGraphicsScene will send it \l {QEvent::}{GraphicsSceneHoverMove}
events. When the mouse leaves the item's area, the item will
receive a \l {QEvent::}{GraphicsSceneHoverLeave} event.
All mouse events are delivered to the current \e {mouse grabber}
item. An item becomes the scene's mouse grabber if it accepts
mouse events (see QGraphicsItem::acceptedMouseButtons()) and it
receives a mouse press. It stays the mouse grabber until it
receives a mouse release when no other mouse buttons are
pressed. You can call mouseGrabberItem() to determine what item is
currently grabbing the mouse.
\sa QGraphicsItem, QGraphicsView
*/
/*!
\enum QGraphicsScene::SceneLayer
\since 4.3
This enum describes the rendering layers in a QGraphicsScene. When
QGraphicsScene draws the scene contents, it renders each of these layers
separately, in order.
Each layer represents a flag that can be OR'ed together when calling
functions such as invalidate() or QGraphicsView::invalidateScene().
\value ItemLayer The item layer. QGraphicsScene renders all items are in
this layer by calling the virtual function drawItems(). The item layer is
drawn after the background layer, but before the foreground layer.
\value BackgroundLayer The background layer. QGraphicsScene renders the
scene's background in this layer by calling the virtual function
drawBackground(). The background layer is drawn first of all layers.
\value ForegroundLayer The foreground layer. QGraphicsScene renders the
scene's foreground in this layer by calling the virtual function
drawForeground(). The foreground layer is drawn last of all layers.
\value AllLayers All layers; this value represents a combination of all
three layers.
\sa invalidate(), QGraphicsView::invalidateScene()
*/
/*!
\enum QGraphicsScene::ItemIndexMethod
This enum describes the indexing algorithms QGraphicsScene provides for
managing positional information about items on the scene.
\value BspTreeIndex A Binary Space Partitioning tree is applied. All
QGraphicsScene's item location algorithms are of an order close to
logarithmic complexity, by making use of binary search. Adding, moving and
removing items is logarithmic. This approach is best for static scenes
(i.e., scenes where most items do not move).
\value NoIndex No index is applied. Item location is of linear complexity,
as all items on the scene are searched. Adding, moving and removing items,
however, is done in constant time. This approach is ideal for dynamic
scenes, where many items are added, moved or removed continuously.
\sa setItemIndexMethod(), bspTreeDepth
*/
#include "qgraphicsscene.h"
#ifndef QT_NO_GRAPHICSVIEW
#include "qgraphicsitem.h"
#include "qgraphicsitem_p.h"
#include "qgraphicslayout.h"
#include "qgraphicsscene_p.h"
#include "qgraphicssceneevent.h"
#include "qgraphicsview.h"
#include "qgraphicsview_p.h"
#include "qgraphicswidget.h"
#include "qgraphicswidget_p.h"
#include <QtCore/qdebug.h>
#include <QtCore/qlist.h>
#include <QtCore/qmath.h>
#include <QtCore/qrect.h>
#include <QtCore/qset.h>
#include <QtCore/qstack.h>
#include <QtCore/qtimer.h>
#include <QtCore/qvarlengtharray.h>
#include <QtGui/qapplication.h>
#include <QtGui/qdesktopwidget.h>
#include <QtGui/qevent.h>
#include <QtGui/qgraphicslayout.h>
#include <QtGui/qgraphicsproxywidget.h>
#include <QtGui/qgraphicswidget.h>
#include <QtGui/qmatrix.h>
#include <QtGui/qpaintengine.h>
#include <QtGui/qpainter.h>
#include <QtGui/qpixmapcache.h>
#include <QtGui/qpolygon.h>
#include <QtGui/qstyleoption.h>
#include <QtGui/qtooltip.h>
#include <QtGui/qtransform.h>
#include <private/qapplication_p.h>
#include <private/qobject_p.h>
#ifdef Q_WS_X11
#include <private/qt_x11_p.h>
#endif
QT_BEGIN_NAMESPACE
static inline bool qt_notclosestLeaf(const QGraphicsItem *item1, const QGraphicsItem *item2);
static inline bool QRectF_intersects(const QRectF &s, const QRectF &r)
{
qreal xp = s.left();
qreal yp = s.top();
qreal w = s.width();
qreal h = s.height();
qreal l1 = xp;
qreal r1 = xp;
if (w < 0)
l1 += w;
else
r1 += w;
qreal l2 = r.left();
qreal r2 = r.left();
if (w < 0)
l2 += r.width();
else
r2 += r.width();
if (l1 >= r2 || l2 >= r1)
return false;
qreal t1 = yp;
qreal b1 = yp;
if (h < 0)
t1 += h;
else
b1 += h;
qreal t2 = r.top();
qreal b2 = r.top();
if (r.height() < 0)
t2 += r.height();
else
b2 += r.height();
return !(t1 >= b2 || t2 >= b1);
}
// QRectF::intersects() returns false always if either the source or target
// rectangle's width or height are 0. This works around that problem.
static inline void _q_adjustRect(QRectF *rect)
{
Q_ASSERT(rect);
if (!rect->width())
rect->adjust(-0.00001, 0, 0.00001, 0);
if (!rect->height())
rect->adjust(0, -0.00001, 0, 0.00001);
}
static inline QRectF adjustedItemBoundingRect(const QGraphicsItem *item)
{
Q_ASSERT(item);
QRectF boundingRect(item->boundingRect());
_q_adjustRect(&boundingRect);
return boundingRect;
}
static void _q_hoverFromMouseEvent(QGraphicsSceneHoverEvent *hover, const QGraphicsSceneMouseEvent *mouseEvent)
{
hover->setWidget(mouseEvent->widget());
hover->setPos(mouseEvent->pos());
hover->setScenePos(mouseEvent->scenePos());
hover->setScreenPos(mouseEvent->screenPos());
hover->setLastPos(mouseEvent->lastPos());
hover->setLastScenePos(mouseEvent->lastScenePos());
hover->setLastScreenPos(mouseEvent->lastScreenPos());
hover->setModifiers(mouseEvent->modifiers());
hover->setAccepted(mouseEvent->isAccepted());
}
/*!
\internal
*/
QGraphicsScenePrivate::QGraphicsScenePrivate()
: changedSignalMask(0),
indexMethod(QGraphicsScene::BspTreeIndex),
bspTreeDepth(0),
lastItemCount(0),
hasSceneRect(false),
updateAll(false),
calledEmitUpdated(false),
processDirtyItemsEmitted(false),
selectionChanging(0),
needSortTopLevelItems(true),
regenerateIndex(true),
purgePending(false),
indexTimerId(0),
restartIndexTimer(false),
stickyFocus(false),
hasFocus(false),
focusItem(0),
lastFocusItem(0),
tabFocusFirst(0),
activeWindow(0),
activationRefCount(0),
lastMouseGrabberItem(0),
lastMouseGrabberItemHasImplicitMouseGrab(false),
dragDropItem(0),
enterWidget(0),
lastDropAction(Qt::IgnoreAction),
allItemsIgnoreHoverEvents(true),
allItemsUseDefaultCursor(true),
painterStateProtection(true),
sortCacheEnabled(false),
updatingSortCache(false),
style(0)
{
}
/*!
\internal
*/
void QGraphicsScenePrivate::init()
{
Q_Q(QGraphicsScene);
// Keep this index so we can check for connected slots later on.
changedSignalMask = (1 << q->metaObject()->indexOfSignal("changed(QList<QRectF>)"));
qApp->d_func()->scene_list.append(q);
q->update();
}
/*!
\internal
*/
QList<QGraphicsItem *> QGraphicsScenePrivate::estimateItemsInRect(const QRectF &rect) const
{
const_cast<QGraphicsScenePrivate *>(this)->purgeRemovedItems();
const_cast<QGraphicsScenePrivate *>(this)->_q_updateSortCache();
if (indexMethod == QGraphicsScene::BspTreeIndex) {
// ### Only do this once in a while.
QGraphicsScenePrivate *that = const_cast<QGraphicsScenePrivate *>(this);
// Get items from BSP tree
QList<QGraphicsItem *> items = that->bspTree.items(rect);
// Fill in with any unindexed items
for (int i = 0; i < unindexedItems.size(); ++i) {
if (QGraphicsItem *item = unindexedItems.at(i)) {
if (!item->d_ptr->itemDiscovered && item->d_ptr->visible && !(item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)) {
QRectF boundingRect = item->sceneBoundingRect();
if (QRectF_intersects(boundingRect, rect)) {
item->d_ptr->itemDiscovered = 1;
items << item;
}
}
}
}
// Reset the discovered state of all discovered items
for (int i = 0; i < items.size(); ++i)
items.at(i)->d_func()->itemDiscovered = 0;
return items;
}
QList<QGraphicsItem *> itemsInRect;
for (int i = 0; i < unindexedItems.size(); ++i) {
if (QGraphicsItem *item = unindexedItems.at(i)) {
if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)
continue;
if (item->d_ptr->visible && !item->d_ptr->isFullyTransparent())
itemsInRect << item;
}
}
for (int i = 0; i < indexedItems.size(); ++i) {
if (QGraphicsItem *item = indexedItems.at(i)) {
if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)
continue;
if (item->d_ptr->visible && !item->d_ptr->isFullyTransparent())
itemsInRect << item;
}
}
return itemsInRect;
}
/*!
\internal
*/
void QGraphicsScenePrivate::addToIndex(QGraphicsItem *item)
{
if (indexMethod == QGraphicsScene::BspTreeIndex) {
if (item->d_func()->index != -1) {
bspTree.insertItem(item, item->sceneBoundingRect());
foreach (QGraphicsItem *child, item->children())
child->addToIndex();
} else {
// The BSP tree is regenerated if the number of items grows to a
// certain threshold, or if the bounding rect of the graph doubles in
// size.
startIndexTimer();
}
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::removeFromIndex(QGraphicsItem *item)
{
if (indexMethod == QGraphicsScene::BspTreeIndex) {
int index = item->d_func()->index;
if (index != -1) {
bspTree.removeItem(item, item->sceneBoundingRect());
freeItemIndexes << index;
indexedItems[index] = 0;
item->d_func()->index = -1;
unindexedItems << item;
foreach (QGraphicsItem *child, item->children())
child->removeFromIndex();
}
startIndexTimer();
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::resetIndex()
{
purgeRemovedItems();
if (indexMethod == QGraphicsScene::BspTreeIndex) {
for (int i = 0; i < indexedItems.size(); ++i) {
if (QGraphicsItem *item = indexedItems.at(i)) {
item->d_ptr->index = -1;
unindexedItems << item;
}
}
indexedItems.clear();
freeItemIndexes.clear();
regenerateIndex = true;
startIndexTimer();
}
}
static inline int intmaxlog(int n)
{
return (n > 0 ? qMax(qCeil(qLn(qreal(n)) / qLn(qreal(2))), 5) : 0);
}
/*!
\internal
*/
void QGraphicsScenePrivate::_q_updateIndex()
{
if (!indexTimerId)
return;
Q_Q(QGraphicsScene);
q->killTimer(indexTimerId);
indexTimerId = 0;
purgeRemovedItems();
// Add unindexedItems to indexedItems
QRectF unindexedItemsBoundingRect;
for (int i = 0; i < unindexedItems.size(); ++i) {
if (QGraphicsItem *item = unindexedItems.at(i)) {
unindexedItemsBoundingRect |= item->sceneBoundingRect();
if (!freeItemIndexes.isEmpty()) {
int freeIndex = freeItemIndexes.takeFirst();
item->d_func()->index = freeIndex;
indexedItems[freeIndex] = item;
} else {
item->d_func()->index = indexedItems.size();
indexedItems << item;
}
}
}
// Update growing scene rect.
QRectF oldGrowingItemsBoundingRect = growingItemsBoundingRect;
growingItemsBoundingRect |= unindexedItemsBoundingRect;
// Determine whether we should regenerate the BSP tree.
if (indexMethod == QGraphicsScene::BspTreeIndex) {
int depth = bspTreeDepth;
if (depth == 0) {
int oldDepth = intmaxlog(lastItemCount);
depth = intmaxlog(indexedItems.size());
static const int slack = 100;
if (bspTree.leafCount() == 0 || (oldDepth != depth && qAbs(lastItemCount - indexedItems.size()) > slack)) {
// ### Crude algorithm.
regenerateIndex = true;
}
}
// Regenerate the tree.
if (regenerateIndex) {
regenerateIndex = false;
bspTree.initialize(q->sceneRect(), depth);
unindexedItems = indexedItems;
lastItemCount = indexedItems.size();
q->update();
// Take this opportunity to reset our largest-item counter for
// untransformable items. When the items are inserted into the BSP
// tree, we'll get an accurate calculation.
largestUntransformableItem = QRectF();
}
}
// Insert all unindexed items into the tree.
for (int i = 0; i < unindexedItems.size(); ++i) {
if (QGraphicsItem *item = unindexedItems.at(i)) {
QRectF rect = item->sceneBoundingRect();
if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)
continue;
if (indexMethod == QGraphicsScene::BspTreeIndex)
bspTree.insertItem(item, rect);
// If the item ignores view transformations, update our
// largest-item-counter to ensure that the view can accurately
// discover untransformable items when drawing.
if (item->d_ptr->itemIsUntransformable()) {
QGraphicsItem *topmostUntransformable = item;
while (topmostUntransformable && (topmostUntransformable->d_ptr->ancestorFlags
& QGraphicsItemPrivate::AncestorIgnoresTransformations)) {
topmostUntransformable = topmostUntransformable->parentItem();
}
// ### Verify that this is the correct largest untransformable rectangle.
largestUntransformableItem |= item->mapToItem(topmostUntransformable, item->boundingRect()).boundingRect();
}
}
}
unindexedItems.clear();
// Notify scene rect changes.
if (!hasSceneRect && growingItemsBoundingRect != oldGrowingItemsBoundingRect)
emit q->sceneRectChanged(growingItemsBoundingRect);
}
/*!
\internal
*/
void QGraphicsScenePrivate::_q_emitUpdated()
{
Q_Q(QGraphicsScene);
calledEmitUpdated = false;
// Ensure all views are connected if anything is connected. This disables
// the optimization that items send updates directly to the views, but it
// needs to happen in order to keep compatibility with the behavior from
// Qt 4.4 and backward.
if (connectedSignals & changedSignalMask) {
for (int i = 0; i < views.size(); ++i) {
QGraphicsView *view = views.at(i);
if (!view->d_func()->connectedToScene) {
view->d_func()->connectedToScene = true;
q->connect(q, SIGNAL(changed(QList<QRectF>)),
views.at(i), SLOT(updateScene(QList<QRectF>)));
}
}
} else {
updateAll = false;
for (int i = 0; i < views.size(); ++i)
views.at(i)->d_func()->processPendingUpdates();
return;
}
// Notify the changes to anybody interested.
QList<QRectF> oldUpdatedRects;
oldUpdatedRects = updateAll ? (QList<QRectF>() << q->sceneRect()) : updatedRects;
updateAll = false;
updatedRects.clear();
emit q->changed(oldUpdatedRects);
}
/*!
\internal
*/
void QGraphicsScenePrivate::registerTopLevelItem(QGraphicsItem *item)
{
needSortTopLevelItems = true;
topLevelItems.append(item);
}
/*!
\internal
*/
void QGraphicsScenePrivate::unregisterTopLevelItem(QGraphicsItem *item)
{
topLevelItems.removeOne(item);
}
/*!
\internal
Updates all items in the pending update list. At this point, the list is
unlikely to contain partially constructed items.
*/
void QGraphicsScenePrivate::_q_updateLater()
{
foreach (QGraphicsItem *item, pendingUpdateItems)
item->update();
pendingUpdateItems.clear();
}
/*!
\internal
*/
void QGraphicsScenePrivate::_q_polishItems()
{
const QVariant booleanTrueVariant(true);
foreach (QGraphicsItem *item, unpolishedItems) {
if (!item->d_ptr->explicitlyHidden) {
item->itemChange(QGraphicsItem::ItemVisibleChange, booleanTrueVariant);
item->itemChange(QGraphicsItem::ItemVisibleHasChanged, booleanTrueVariant);
}
if (item->isWidget()) {
QEvent event(QEvent::Polish);
QApplication::sendEvent((QGraphicsWidget *)item, &event);
}
}
unpolishedItems.clear();
}
void QGraphicsScenePrivate::_q_processDirtyItems()
{
processDirtyItemsEmitted = false;
const bool wasPendingSceneUpdate = calledEmitUpdated;
const QRectF oldGrowingItemsBoundingRect = growingItemsBoundingRect;
processDirtyItemsRecursive(0);
if (!hasSceneRect && oldGrowingItemsBoundingRect != growingItemsBoundingRect)
emit q_func()->sceneRectChanged(growingItemsBoundingRect);
if (wasPendingSceneUpdate)
return;
for (int i = 0; i < views.size(); ++i)
views.at(i)->d_func()->processPendingUpdates();
if (calledEmitUpdated) {
// We did a compatibility QGraphicsScene::update in processDirtyItemsRecursive
// and we cannot wait for the control to reach the eventloop before the
// changed signal is emitted, so we emit it now.
_q_emitUpdated();
}
// Immediately dispatch all pending update requests on the views.
for (int i = 0; i < views.size(); ++i) {
QWidget *viewport = views.at(i)->d_func()->viewport;
if (qt_widget_private(viewport)->paintOnScreen())
QCoreApplication::sendPostedEvents(viewport, QEvent::UpdateRequest);
else
QCoreApplication::sendPostedEvents(viewport->window(), QEvent::UpdateRequest);
}
}
/*!
\internal
Schedules an item for removal. This function leaves some stale indexes
around in the BSP tree if called from the item's destructor; these will
be cleaned up the next time someone triggers purgeRemovedItems().
Note: This function might get called from QGraphicsItem's destructor. \a item is
being destroyed, so we cannot call any pure virtual functions on it (such
as boundingRect()). Also, it is unnecessary to update the item's own state
in any way.
*/
void QGraphicsScenePrivate::removeItemHelper(QGraphicsItem *item)
{
Q_Q(QGraphicsScene);
// Clear focus on the item to remove any reference in the focusWidget chain.
item->clearFocus();
markDirty(item, QRectF(), false, false, false, false, /*removingItemFromScene=*/true);
if (!item->d_ptr->inDestructor) {
// Can potentially call item->boundingRect() (virtual function), that's why
// we only can call this function if the item is not in its destructor.
removeFromIndex(item);
} else if (item->d_ptr->index != -1) {
// Important: The index is useless until purgeRemovedItems() is called.
indexedItems[item->d_ptr->index] = (QGraphicsItem *)0;
if (!purgePending)
purgePending = true;
removedItems << item;
} else {
// Recently added items are purged immediately. unindexedItems() never
// contains stale items.
unindexedItems.removeAll(item);
}
if (!item->d_ptr->inDestructor && item == tabFocusFirst) {
QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
widget->d_func()->fixFocusChainBeforeReparenting(0, 0);
}
item->d_func()->scene = 0;
// Remove from parent, or unregister from toplevels.
if (QGraphicsItem *parentItem = item->parentItem()) {
if (parentItem->scene()) {
Q_ASSERT_X(parentItem->scene() == q, "QGraphicsScene::removeItem",
"Parent item's scene is different from this item's scene");
item->d_ptr->setParentItemHelper(0);
}
} else {
unregisterTopLevelItem(item);
}
if (!item->d_ptr->inDestructor) {
// Remove from our item lists.
int index = item->d_func()->index;
if (index != -1) {
freeItemIndexes << index;
indexedItems[index] = 0;
} else {
unindexedItems.removeAll(item);
}
}
// Reset the mouse grabber and focus item data.
if (item == focusItem)
focusItem = 0;
if (item == lastFocusItem)
lastFocusItem = 0;
if (item == activeWindow) {
// ### deactivate...
activeWindow = 0;
}
// Disable selectionChanged() for individual items
++selectionChanging;
int oldSelectedItemsSize = selectedItems.size();
// Update selected & hovered item bookkeeping
selectedItems.remove(item);
hoverItems.removeAll(item);
cachedItemsUnderMouse.removeAll(item);
unpolishedItems.removeAll(item);
pendingUpdateItems.removeAll(item);
resetDirtyItem(item);
//We remove all references of item from the sceneEventFilter arrays
QMultiMap<QGraphicsItem*, QGraphicsItem*>::iterator iterator = sceneEventFilters.begin();
while (iterator != sceneEventFilters.end()) {
if (iterator.value() == item || iterator.key() == item)
iterator = sceneEventFilters.erase(iterator);
else
++iterator;
}
if (!item->d_ptr->inDestructor) {
// Remove all children recursively
for (int i = 0; i < item->d_ptr->children.size(); ++i)
q->removeItem(item->d_ptr->children.at(i));
}
// Reset the mouse grabber and focus item data.
if (mouseGrabberItems.contains(item))
ungrabMouse(item, /* item is dying */ item->d_ptr->inDestructor);
// Reset the keyboard grabber
if (keyboardGrabberItems.contains(item))
ungrabKeyboard(item, /* item is dying */ item->d_ptr->inDestructor);
// Reset the last mouse grabber item
if (item == lastMouseGrabberItem)
lastMouseGrabberItem = 0;
// Reenable selectionChanged() for individual items
--selectionChanging;
if (!selectionChanging && selectedItems.size() != oldSelectedItemsSize)
emit q->selectionChanged();
}
/*!
\internal
Removes stale pointers from all data structures.
*/
void QGraphicsScenePrivate::purgeRemovedItems()
{
if (!purgePending && removedItems.isEmpty())
return;
// Remove stale items from the BSP tree.
if (indexMethod != QGraphicsScene::NoIndex)
bspTree.removeItems(removedItems);
// Purge this list.
removedItems.clear();
freeItemIndexes.clear();
for (int i = 0; i < indexedItems.size(); ++i) {
if (!indexedItems.at(i))
freeItemIndexes << i;
}
purgePending = false;
}
/*!
\internal
Starts or restarts the timer used for reindexing unindexed items.
*/
void QGraphicsScenePrivate::startIndexTimer(int interval)
{
Q_Q(QGraphicsScene);
if (indexTimerId) {
restartIndexTimer = true;
} else {
indexTimerId = q->startTimer(interval);
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::addPopup(QGraphicsWidget *widget)
{
Q_ASSERT(widget);
Q_ASSERT(!popupWidgets.contains(widget));
popupWidgets << widget;
if (QGraphicsWidget *focusWidget = widget->focusWidget()) {
focusWidget->setFocus(Qt::PopupFocusReason);
} else {
grabKeyboard((QGraphicsItem *)widget);
if (focusItem && popupWidgets.size() == 1) {
QFocusEvent event(QEvent::FocusOut, Qt::PopupFocusReason);
sendEvent(focusItem, &event);
}
}
grabMouse((QGraphicsItem *)widget);
}
/*!
\internal
Remove \a widget from the popup list. Important notes:
\a widget is guaranteed to be in the list of popups, but it might not be
the last entry; you can hide any item in the pop list before the others,
and this must cause all later mouse grabbers to lose the grab.
*/
void QGraphicsScenePrivate::removePopup(QGraphicsWidget *widget, bool itemIsDying)
{
Q_ASSERT(widget);
int index = popupWidgets.indexOf(widget);
Q_ASSERT(index != -1);
for (int i = popupWidgets.size() - 1; i >= index; --i) {
QGraphicsWidget *widget = popupWidgets.takeLast();
ungrabMouse(widget, itemIsDying);
if (focusItem && popupWidgets.isEmpty()) {
QFocusEvent event(QEvent::FocusIn, Qt::PopupFocusReason);
sendEvent(focusItem, &event);
} else {
ungrabKeyboard((QGraphicsItem *)widget, itemIsDying);
}
if (!itemIsDying && widget->isVisible()) {
widget->hide();
widget->QGraphicsItem::d_ptr->explicitlyHidden = 0;
}
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::grabMouse(QGraphicsItem *item, bool implicit)
{
// Append to list of mouse grabber items, and send a mouse grab event.
if (mouseGrabberItems.contains(item)) {
if (mouseGrabberItems.last() == item) {
Q_ASSERT(!implicit);
if (!lastMouseGrabberItemHasImplicitMouseGrab) {
qWarning("QGraphicsItem::grabMouse: already a mouse grabber");
} else {
// Upgrade to an explicit mouse grab
lastMouseGrabberItemHasImplicitMouseGrab = false;
}
} else {
qWarning("QGraphicsItem::grabMouse: already blocked by mouse grabber: %p",
mouseGrabberItems.last());
}
return;
}
// Send ungrab event to the last grabber.
if (!mouseGrabberItems.isEmpty()) {
QGraphicsItem *last = mouseGrabberItems.last();
if (lastMouseGrabberItemHasImplicitMouseGrab) {
// Implicit mouse grab is immediately lost.
last->ungrabMouse();
} else {
// Just send ungrab event to current grabber.
QEvent ungrabEvent(QEvent::UngrabMouse);
sendEvent(last, &ungrabEvent);
}
}
mouseGrabberItems << item;
lastMouseGrabberItemHasImplicitMouseGrab = implicit;
// Send grab event to current grabber.
QEvent grabEvent(QEvent::GrabMouse);
sendEvent(item, &grabEvent);
}
/*!
\internal
*/
void QGraphicsScenePrivate::ungrabMouse(QGraphicsItem *item, bool itemIsDying)
{
int index = mouseGrabberItems.indexOf(item);
if (index == -1) {
qWarning("QGraphicsItem::ungrabMouse: not a mouse grabber");
return;
}
if (item != mouseGrabberItems.last()) {
// Recursively ungrab the next mouse grabber until we reach this item
// to ensure state consistency.
ungrabMouse(mouseGrabberItems.at(index + 1), itemIsDying);
}
if (!popupWidgets.isEmpty() && item == popupWidgets.last()) {
// If the item is a popup, go via removePopup to ensure state
// consistency and that it gets hidden correctly - beware that
// removePopup() reenters this function to continue removing the grab.
removePopup((QGraphicsWidget *)item, itemIsDying);
return;
}
// Send notification about mouse ungrab.
if (!itemIsDying) {
QEvent event(QEvent::UngrabMouse);
sendEvent(item, &event);
}
// Remove the item from the list of grabbers. Whenever this happens, we
// reset the implicitGrab (there can be only ever be one implicit grabber
// in a scene, and it is always the latest grabber; if the implicit grab
// is lost, it is not automatically regained.
mouseGrabberItems.takeLast();
lastMouseGrabberItemHasImplicitMouseGrab = false;
// Send notification about mouse regrab. ### It's unfortunate that all the
// items get a GrabMouse event, but this is a rare case with a simple
// implementation and it does ensure a consistent state.
if (!itemIsDying && !mouseGrabberItems.isEmpty()) {
QGraphicsItem *last = mouseGrabberItems.last();
QEvent event(QEvent::GrabMouse);
sendEvent(last, &event);
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::clearMouseGrabber()
{
if (!mouseGrabberItems.isEmpty())
mouseGrabberItems.first()->ungrabMouse();
lastMouseGrabberItem = 0;
}
/*!
\internal
*/
void QGraphicsScenePrivate::grabKeyboard(QGraphicsItem *item)
{
if (keyboardGrabberItems.contains(item)) {
if (keyboardGrabberItems.last() == item)
qWarning("QGraphicsItem::grabKeyboard: already a keyboard grabber");
else
qWarning("QGraphicsItem::grabKeyboard: already blocked by keyboard grabber: %p",
keyboardGrabberItems.last());
return;
}
// Send ungrab event to the last grabber.
if (!keyboardGrabberItems.isEmpty()) {
// Just send ungrab event to current grabber.
QEvent ungrabEvent(QEvent::UngrabKeyboard);
sendEvent(keyboardGrabberItems.last(), &ungrabEvent);
}
keyboardGrabberItems << item;
// Send grab event to current grabber.
QEvent grabEvent(QEvent::GrabKeyboard);
sendEvent(item, &grabEvent);
}
/*!
\internal
*/
void QGraphicsScenePrivate::ungrabKeyboard(QGraphicsItem *item, bool itemIsDying)
{
int index = keyboardGrabberItems.lastIndexOf(item);
if (index == -1) {
qWarning("QGraphicsItem::ungrabKeyboard: not a keyboard grabber");
return;
}
if (item != keyboardGrabberItems.last()) {
// Recursively ungrab the topmost keyboard grabber until we reach this
// item to ensure state consistency.
ungrabKeyboard(keyboardGrabberItems.at(index + 1), itemIsDying);
}
// Send notification about keyboard ungrab.
if (!itemIsDying) {
QEvent event(QEvent::UngrabKeyboard);
sendEvent(item, &event);
}
// Remove the item from the list of grabbers.
keyboardGrabberItems.takeLast();
// Send notification about mouse regrab.
if (!itemIsDying && !keyboardGrabberItems.isEmpty()) {
QGraphicsItem *last = keyboardGrabberItems.last();
QEvent event(QEvent::GrabKeyboard);
sendEvent(last, &event);
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::clearKeyboardGrabber()
{
if (!keyboardGrabberItems.isEmpty())
ungrabKeyboard(keyboardGrabberItems.first());
}
void QGraphicsScenePrivate::enableMouseTrackingOnViews()
{
foreach (QGraphicsView *view, views)
view->viewport()->setMouseTracking(true);
}
/*!
Returns all items for the screen position in \a event.
*/
QList<QGraphicsItem *> QGraphicsScenePrivate::itemsAtPosition(const QPoint &screenPos,
const QPointF &scenePos,
QWidget *widget) const
{
Q_Q(const QGraphicsScene);
QGraphicsView *view = widget ? qobject_cast<QGraphicsView *>(widget->parentWidget()) : 0;
QList<QGraphicsItem *> items;
if (view)
items = view->items(view->viewport()->mapFromGlobal(screenPos));
else
items = q->items(scenePos);
return items;
}
/*!
\internal
Checks if item collides with the path and mode, but also checks that if it
doesn't collide, maybe its frame rect will.
*/
bool QGraphicsScenePrivate::itemCollidesWithPath(QGraphicsItem *item,
const QPainterPath &path,
Qt::ItemSelectionMode mode)
{
if (item->collidesWithPath(path, mode))
return true;
if (item->isWidget()) {
// Check if this is a window, and if its frame rect collides.
QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
if (widget->isWindow()) {
QRectF frameRect = widget->windowFrameRect();
QPainterPath framePath;
framePath.addRect(frameRect);
bool intersects = path.intersects(frameRect);
if (mode == Qt::IntersectsItemShape || mode == Qt::IntersectsItemBoundingRect)
return intersects || path.contains(frameRect.topLeft())
|| framePath.contains(path.elementAt(0));
return !intersects && path.contains(frameRect.topLeft());
}
}
return false;
}
/*!
\internal
*/
void QGraphicsScenePrivate::storeMouseButtonsForMouseGrabber(QGraphicsSceneMouseEvent *event)
{
for (int i = 0x1; i <= 0x10; i <<= 1) {
if (event->buttons() & i) {
mouseGrabberButtonDownPos.insert(Qt::MouseButton(i),
mouseGrabberItems.last()->d_ptr->genericMapFromScene(event->scenePos(),
event->widget()));
mouseGrabberButtonDownScenePos.insert(Qt::MouseButton(i), event->scenePos());
mouseGrabberButtonDownScreenPos.insert(Qt::MouseButton(i), event->screenPos());
}
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::installSceneEventFilter(QGraphicsItem *watched, QGraphicsItem *filter)
{
sceneEventFilters.insert(watched, filter);
}
/*!
\internal
*/
void QGraphicsScenePrivate::removeSceneEventFilter(QGraphicsItem *watched, QGraphicsItem *filter)
{
if (!sceneEventFilters.contains(watched))
return;
QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator it = sceneEventFilters.lowerBound(watched);
QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator end = sceneEventFilters.upperBound(watched);
do {
if (it.value() == filter)
it = sceneEventFilters.erase(it);
else
++it;
} while (it != end);
}
/*!
\internal
*/
bool QGraphicsScenePrivate::filterEvent(QGraphicsItem *item, QEvent *event)
{
if (item && !sceneEventFilters.contains(item))
return false;
QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator it = sceneEventFilters.lowerBound(item);
QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator end = sceneEventFilters.upperBound(item);
while (it != end) {
// ### The filterer and filteree might both be deleted.
if (it.value()->sceneEventFilter(it.key(), event))
return true;
++it;
}
return false;
}
/*!
\internal
This is the final dispatch point for any events from the scene to the
item. It filters the event first - if the filter returns true, the event
is considered to have been eaten by the filter, and is therefore stopped
(the default filter returns false). Then/otherwise, if the item is
enabled, the event is sent; otherwise it is stopped.
*/
bool QGraphicsScenePrivate::sendEvent(QGraphicsItem *item, QEvent *event)
{
if (filterEvent(item, event))
return false;
return (item && item->isEnabled()) ? item->sceneEvent(event) : false;
}
/*!
\internal
*/
void QGraphicsScenePrivate::cloneDragDropEvent(QGraphicsSceneDragDropEvent *dest,
QGraphicsSceneDragDropEvent *source)
{
dest->setWidget(source->widget());
dest->setPos(source->pos());
dest->setScenePos(source->scenePos());
dest->setScreenPos(source->screenPos());
dest->setButtons(source->buttons());
dest->setModifiers(source->modifiers());
dest->setPossibleActions(source->possibleActions());
dest->setProposedAction(source->proposedAction());
dest->setDropAction(source->dropAction());
dest->setSource(source->source());
dest->setMimeData(source->mimeData());
}
/*!
\internal
*/
void QGraphicsScenePrivate::sendDragDropEvent(QGraphicsItem *item,
QGraphicsSceneDragDropEvent *dragDropEvent)
{
dragDropEvent->setPos(item->d_ptr->genericMapFromScene(dragDropEvent->scenePos(), dragDropEvent->widget()));
sendEvent(item, dragDropEvent);
}
/*!
\internal
*/
void QGraphicsScenePrivate::sendHoverEvent(QEvent::Type type, QGraphicsItem *item,
QGraphicsSceneHoverEvent *hoverEvent)
{
QGraphicsSceneHoverEvent event(type);
event.setWidget(hoverEvent->widget());
event.setPos(item->d_ptr->genericMapFromScene(hoverEvent->scenePos(), hoverEvent->widget()));
event.setScenePos(hoverEvent->scenePos());
event.setScreenPos(hoverEvent->screenPos());
event.setLastPos(item->d_ptr->genericMapFromScene(hoverEvent->lastScenePos(), hoverEvent->widget()));
event.setLastScenePos(hoverEvent->lastScenePos());
event.setLastScreenPos(hoverEvent->lastScreenPos());
event.setModifiers(hoverEvent->modifiers());
sendEvent(item, &event);
}
/*!
\internal
*/
void QGraphicsScenePrivate::sendMouseEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
if (mouseEvent->button() == 0 && mouseEvent->buttons() == 0 && lastMouseGrabberItemHasImplicitMouseGrab) {
// ### This is a temporary fix for until we get proper mouse
// grab events.
clearMouseGrabber();
return;
}
QGraphicsItem *item = mouseGrabberItems.last();
for (int i = 0x1; i <= 0x10; i <<= 1) {
Qt::MouseButton button = Qt::MouseButton(i);
mouseEvent->setButtonDownPos(button, mouseGrabberButtonDownPos.value(button, item->d_ptr->genericMapFromScene(mouseEvent->scenePos(), mouseEvent->widget())));
mouseEvent->setButtonDownScenePos(button, mouseGrabberButtonDownScenePos.value(button, mouseEvent->scenePos()));
mouseEvent->setButtonDownScreenPos(button, mouseGrabberButtonDownScreenPos.value(button, mouseEvent->screenPos()));
}
mouseEvent->setPos(item->d_ptr->genericMapFromScene(mouseEvent->scenePos(), mouseEvent->widget()));
mouseEvent->setLastPos(item->d_ptr->genericMapFromScene(mouseEvent->lastScenePos(), mouseEvent->widget()));
sendEvent(item, mouseEvent);
}
/*!
\internal
*/
void QGraphicsScenePrivate::mousePressEventHandler(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_Q(QGraphicsScene);
// Ignore by default, unless we find a mouse grabber that accepts it.
mouseEvent->ignore();
// Deliver to any existing mouse grabber.
if (!mouseGrabberItems.isEmpty()) {
// The event is ignored by default, but we disregard the event's
// accepted state after delivery; the mouse is grabbed, after all.
sendMouseEvent(mouseEvent);
return;
}
// Start by determining the number of items at the current position.
// Reuse value from earlier calculations if possible.
if (cachedItemsUnderMouse.isEmpty()) {
cachedItemsUnderMouse = itemsAtPosition(mouseEvent->screenPos(),
mouseEvent->scenePos(),
mouseEvent->widget());
}
// Update window activation.
QGraphicsWidget *newActiveWindow = windowForItem(cachedItemsUnderMouse.value(0));
if (newActiveWindow != activeWindow)
q->setActiveWindow(newActiveWindow);
// Set focus on the topmost enabled item that can take focus.
bool setFocus = false;
foreach (QGraphicsItem *item, cachedItemsUnderMouse) {
if (item->isEnabled() && (item->flags() & QGraphicsItem::ItemIsFocusable)) {
if (!item->isWidget() || ((QGraphicsWidget *)item)->focusPolicy() & Qt::ClickFocus) {
setFocus = true;
if (item != q->focusItem())
q->setFocusItem(item, Qt::MouseFocusReason);
break;
}
}
}
// If nobody could take focus, clear it.
if (!stickyFocus && !setFocus)
q->setFocusItem(0, Qt::MouseFocusReason);
// Find a mouse grabber by sending mouse press events to all mouse grabber
// candidates one at a time, until the event is accepted. It's accepted by
// default, so the receiver has to explicitly ignore it for it to pass
// through.
foreach (QGraphicsItem *item, cachedItemsUnderMouse) {
if (!(item->acceptedMouseButtons() & mouseEvent->button())) {
// Skip items that don't accept the event's mouse button.
continue;
}
grabMouse(item, /* implicit = */ true);
mouseEvent->accept();
// check if the item we are sending to are disabled (before we send the event)
bool disabled = !item->isEnabled();
bool isWindow = item->isWindow();
if (mouseEvent->type() == QEvent::GraphicsSceneMouseDoubleClick
&& item != lastMouseGrabberItem && lastMouseGrabberItem) {
// If this item is different from the item that received the last
// mouse event, and mouseEvent is a doubleclick event, then the
// event is converted to a press. Known limitation:
// Triple-clicking will not generate a doubleclick, though.
QGraphicsSceneMouseEvent mousePress(QEvent::GraphicsSceneMousePress);
mousePress.accept();
mousePress.setButton(mouseEvent->button());
mousePress.setButtons(mouseEvent->buttons());
mousePress.setScreenPos(mouseEvent->screenPos());
mousePress.setScenePos(mouseEvent->scenePos());
mousePress.setModifiers(mouseEvent->modifiers());
mousePress.setWidget(mouseEvent->widget());
mousePress.setButtonDownPos(mouseEvent->button(),
mouseEvent->buttonDownPos(mouseEvent->button()));
mousePress.setButtonDownScenePos(mouseEvent->button(),
mouseEvent->buttonDownScenePos(mouseEvent->button()));
mousePress.setButtonDownScreenPos(mouseEvent->button(),
mouseEvent->buttonDownScreenPos(mouseEvent->button()));
sendMouseEvent(&mousePress);
mouseEvent->setAccepted(mousePress.isAccepted());
} else {
sendMouseEvent(mouseEvent);
}
bool dontSendUngrabEvents = mouseGrabberItems.isEmpty() || mouseGrabberItems.last() != item;
if (disabled) {
ungrabMouse(item, /* itemIsDying = */ dontSendUngrabEvents);
break;
}
if (mouseEvent->isAccepted()) {
if (!mouseGrabberItems.isEmpty())
storeMouseButtonsForMouseGrabber(mouseEvent);
lastMouseGrabberItem = item;
return;
}
ungrabMouse(item, /* itemIsDying = */ dontSendUngrabEvents);
// Don't propagate through windows.
if (isWindow)
break;
}
// Is the event still ignored? Then the mouse press goes to the scene.
// Reset the mouse grabber, clear the selection, clear focus, and leave
// the event ignored so that it can propagate through the originating
// view.
if (!mouseEvent->isAccepted()) {
clearMouseGrabber();
QGraphicsView *view = mouseEvent->widget() ? qobject_cast<QGraphicsView *>(mouseEvent->widget()->parentWidget()) : 0;
bool dontClearSelection = view && view->dragMode() == QGraphicsView::ScrollHandDrag;
if (!dontClearSelection) {
// Clear the selection if the originating view isn't in scroll
// hand drag mode. The view will clear the selection if no drag
// happened.
q->clearSelection();
}
}
}
QGraphicsWidget *QGraphicsScenePrivate::windowForItem(const QGraphicsItem *item) const
{
if (!item)
return 0;
do {
if (item->isWidget())
return static_cast<const QGraphicsWidget *>(item)->window();
item = item->parentItem();
} while (item);
return 0;
}
void QGraphicsScenePrivate::recursive_items_helper(QGraphicsItem *item, QRectF rect,
QList<QGraphicsItem *> *items,
const QTransform &parentTransform,
const QTransform &viewTransform,
Qt::ItemSelectionMode mode, Qt::SortOrder order,
qreal parentOpacity) const
{
// Calculate opacity.
qreal opacity;
if (item) {
if (!item->d_ptr->visible)
return;
QGraphicsItem *p = item->d_ptr->parent;
bool itemIgnoresParentOpacity = item->d_ptr->flags & QGraphicsItem::ItemIgnoresParentOpacity;
bool parentDoesntPropagateOpacity = (p && (p->d_ptr->flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren));
if (!itemIgnoresParentOpacity && !parentDoesntPropagateOpacity) {
opacity = parentOpacity * item->opacity();
} else {
opacity = item->d_ptr->opacity;
}
if (opacity == 0.0 && !(item->d_ptr->flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren))
return;
} else {
opacity = parentOpacity;
}
// Calculate the full transform for this item.
QTransform transform = parentTransform;
bool keep = false;
if (item) {
item->d_ptr->combineTransformFromParent(&transform, &viewTransform);
// ### This does not take the clip into account.
QRectF brect = item->boundingRect();
_q_adjustRect(&brect);
keep = true;
if (mode == Qt::ContainsItemShape || mode == Qt::ContainsItemBoundingRect)
keep = rect.contains(transform.mapRect(brect)) && rect != brect;
else
keep = rect.intersects(transform.mapRect(brect));
if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) {
QPainterPath rectPath;
rectPath.addRect(rect);
keep = itemCollidesWithPath(item, transform.inverted().map(rectPath), mode);
}
}
bool childClip = (item && (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape));
bool dontProcessItem = !item || !keep;
bool dontProcessChildren = item && dontProcessItem && childClip;
// Find and sort children.
QList<QGraphicsItem *> &children = item ? item->d_ptr->children : const_cast<QGraphicsScenePrivate *>(this)->topLevelItems;
if (!dontProcessChildren) {
if (item && item->d_ptr->needSortChildren) {
item->d_ptr->needSortChildren = 0;
qStableSort(children.begin(), children.end(), qt_notclosestLeaf);
} else if (!item && needSortTopLevelItems) {
const_cast<QGraphicsScenePrivate *>(this)->needSortTopLevelItems = false;
qStableSort(children.begin(), children.end(), qt_notclosestLeaf);
}
}
childClip &= !dontProcessChildren & !children.isEmpty();
// Clip.
if (childClip)
rect &= transform.map(item->shape()).controlPointRect();
// Process children behind
int i = 0;
if (!dontProcessChildren) {
for (i = 0; i < children.size(); ++i) {
QGraphicsItem *child = children.at(i);
if (!(child->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent))
break;
recursive_items_helper(child, rect, items, transform, viewTransform,
mode, order, opacity);
}
}
// Process item
if (!dontProcessItem)
items->append(item);
// Process children in front
if (!dontProcessChildren) {
for (; i < children.size(); ++i)
recursive_items_helper(children.at(i), rect, items, transform, viewTransform,
mode, order, opacity);
}
if (!item && order == Qt::AscendingOrder) {
int n = items->size();
for (int i = 0; i < n / 2; ++i) {
QGraphicsItem *tmp = (*items)[n - i - 1];
(*items)[n - i - 1] = (*items)[i];
(*items)[i] = tmp;
}
}
}
QList<QGraphicsItem *> QGraphicsScenePrivate::items_helper(const QPointF &pos) const
{
QList<QGraphicsItem *> items;
// The index returns a rough estimate of what items are inside the rect.
// Refine it by iterating through all returned items.
QRectF adjustedRect = QRectF(pos, QSize(1,1));
foreach (QGraphicsItem *item, estimateItemsInRect(adjustedRect)) {
// Find the item's scene transform in a clever way.
QTransform x = item->sceneTransform();
bool keep = false;
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
const QRectF br(adjustedItemBoundingRect(item));
// Rect intersects/contains item's shape
if (QRectF_intersects(adjustedRect, x.mapRect(br))) {
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
if (item->contains(xinv.map(pos))) {
items << item;
keep = true;
}
}
}
if (keep && (item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) {
// Recurse into children that clip children.
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok)
childItems_helper(&items, item, xinv.map(pos));
}
}
sortItems(&items, Qt::AscendingOrder, sortCacheEnabled);
return items;
}
QList<QGraphicsItem *> QGraphicsScenePrivate::items_helper(const QRectF &rect,
Qt::ItemSelectionMode mode,
Qt::SortOrder order) const
{
QList<QGraphicsItem *> items;
QPainterPath path;
// The index returns a rough estimate of what items are inside the rect.
// Refine it by iterating through all returned items.
QRectF adjustedRect(rect);
_q_adjustRect(&adjustedRect);
foreach (QGraphicsItem *item, estimateItemsInRect(adjustedRect)) {
// Find the item's scene transform in a clever way.
QTransform x = item->sceneTransform();
bool keep = false;
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
const QRectF br(adjustedItemBoundingRect(item));
if (mode >= Qt::ContainsItemBoundingRect) {
// Rect intersects/contains item's bounding rect
QRectF mbr = x.mapRect(br);
if ((mode == Qt::IntersectsItemBoundingRect && QRectF_intersects(rect, mbr))
|| (mode == Qt::ContainsItemBoundingRect && rect != mbr && rect.contains(mbr))) {
items << item;
keep = true;
}
} else {
// Rect intersects/contains item's shape
if (QRectF_intersects(adjustedRect, x.mapRect(br))) {
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
if (path.isEmpty())
path.addRect(rect);
if (itemCollidesWithPath(item, xinv.map(path), mode)) {
items << item;
keep = true;
}
}
}
}
if (keep && (item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) {
// Recurse into children that clip children.
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
if (x.type() <= QTransform::TxScale) {
// Rect
childItems_helper(&items, item, xinv.mapRect(rect), mode);
} else {
// Polygon
childItems_helper(&items, item, xinv.map(rect), mode);
}
}
}
}
if (order != Qt::SortOrder(-1))
sortItems(&items, order, sortCacheEnabled);
return items;
}
QList<QGraphicsItem *> QGraphicsScenePrivate::items_helper(const QPolygonF &polygon,
Qt::ItemSelectionMode mode,
Qt::SortOrder order) const
{
QList<QGraphicsItem *> items;
QRectF polyRect(polygon.boundingRect());
_q_adjustRect(&polyRect);
QPainterPath path;
// The index returns a rough estimate of what items are inside the rect.
// Refine it by iterating through all returned items.
foreach (QGraphicsItem *item, estimateItemsInRect(polyRect)) {
// Find the item's scene transform in a clever way.
QTransform x = item->sceneTransform();
bool keep = false;
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
const QRectF br(adjustedItemBoundingRect(item));
if (mode >= Qt::ContainsItemBoundingRect) {
// Polygon contains/intersects item's bounding rect
if (path == QPainterPath())
path.addPolygon(polygon);
if ((mode == Qt::IntersectsItemBoundingRect && path.intersects(x.mapRect(br)))
|| (mode == Qt::ContainsItemBoundingRect && path.contains(x.mapRect(br)))) {
items << item;
keep = true;
}
} else {
// Polygon contains/intersects item's shape
if (QRectF_intersects(polyRect, x.mapRect(br))) {
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
if (path == QPainterPath())
path.addPolygon(polygon);
if (itemCollidesWithPath(item, xinv.map(path), mode)) {
items << item;
keep = true;
}
}
}
}
if (keep && (item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) {
// Recurse into children that clip children.
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok)
childItems_helper(&items, item, xinv.map(polygon), mode);
}
}
if (order != Qt::SortOrder(-1))
sortItems(&items, order, sortCacheEnabled);
return items;
}
QList<QGraphicsItem *> QGraphicsScenePrivate::items_helper(const QPainterPath &path,
Qt::ItemSelectionMode mode,
Qt::SortOrder order) const
{
QList<QGraphicsItem *> items;
QRectF pathRect(path.controlPointRect());
_q_adjustRect(&pathRect);
// The index returns a rough estimate of what items are inside the rect.
// Refine it by iterating through all returned items.
foreach (QGraphicsItem *item, estimateItemsInRect(pathRect)) {
// Find the item's scene transform in a clever way.
QTransform x = item->sceneTransform();
bool keep = false;
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
const QRectF br(adjustedItemBoundingRect(item));
if (mode >= Qt::ContainsItemBoundingRect) {
// Path contains/intersects item's bounding rect
if ((mode == Qt::IntersectsItemBoundingRect && path.intersects(x.mapRect(br)))
|| (mode == Qt::ContainsItemBoundingRect && path.contains(x.mapRect(br)))) {
items << item;
keep = true;
}
} else {
// Path contains/intersects item's shape
if (QRectF_intersects(pathRect, x.mapRect(br))) {
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
if (itemCollidesWithPath(item, xinv.map(path), mode)) {
items << item;
keep = true;
}
}
}
}
if (keep && (item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) {
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok)
childItems_helper(&items, item, xinv.map(path), mode);
}
}
if (order != Qt::SortOrder(-1))
sortItems(&items, order, sortCacheEnabled);
return items;
}
void QGraphicsScenePrivate::childItems_helper(QList<QGraphicsItem *> *items,
const QGraphicsItem *parent,
const QPointF &pos) const
{
bool parentClip = (parent->flags() & QGraphicsItem::ItemClipsChildrenToShape);
if (parentClip && parent->d_ptr->isClippedAway())
return;
// ### is this needed?
if (parentClip && !parent->boundingRect().contains(pos))
return;
QList<QGraphicsItem *> &children = parent->d_ptr->children;
for (int i = 0; i < children.size(); ++i) {
QGraphicsItem *item = children.at(i);
if (item->d_ptr->transformData && !item->d_ptr->transformData->computedFullTransform().isInvertible())
continue;
// Skip invisible items and all their children.
if (item->d_ptr->isInvisible())
continue;
bool keep = false;
if (!item->d_ptr->isClippedAway()) {
if (item->contains(item->mapFromParent(pos))) {
items->append(item);
keep = true;
}
}
if ((keep || !(item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) && !item->d_ptr->children.isEmpty())
// Recurse into children.
childItems_helper(items, item, item->mapFromParent(pos));
}
}
void QGraphicsScenePrivate::childItems_helper(QList<QGraphicsItem *> *items,
const QGraphicsItem *parent,
const QRectF &rect,
Qt::ItemSelectionMode mode) const
{
bool parentClip = (parent->flags() & QGraphicsItem::ItemClipsChildrenToShape);
if (parentClip && parent->d_ptr->isClippedAway())
return;
QRectF adjustedRect(rect);
_q_adjustRect(&adjustedRect);
QRectF r = !parentClip ? adjustedRect : adjustedRect.intersected(adjustedItemBoundingRect(parent));
if (r.isEmpty())
return;
QPainterPath path;
QList<QGraphicsItem *> &children = parent->d_ptr->children;
for (int i = 0; i < children.size(); ++i) {
QGraphicsItem *item = children.at(i);
if (item->d_ptr->transformData && !item->d_ptr->transformData->computedFullTransform().isInvertible())
continue;
// Skip invisible items and all their children.
if (item->d_ptr->isInvisible())
continue;
bool keep = false;
if (!item->d_ptr->isClippedAway()) {
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
const QRectF br(adjustedItemBoundingRect(item));
QRectF mbr = item->mapRectToParent(br);
if (mode >= Qt::ContainsItemBoundingRect) {
// Rect intersects/contains item's bounding rect
if ((mode == Qt::IntersectsItemBoundingRect && QRectF_intersects(rect, mbr))
|| (mode == Qt::ContainsItemBoundingRect && rect != mbr && rect.contains(br))) {
items->append(item);
keep = true;
}
} else {
// Rect intersects/contains item's shape
if (QRectF_intersects(rect, mbr)) {
if (path == QPainterPath())
path.addRect(rect);
if (itemCollidesWithPath(item, item->mapFromParent(path), mode)) {
items->append(item);
keep = true;
}
}
}
}
if ((keep || !(item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) && !item->d_ptr->children.isEmpty()) {
// Recurse into children.
if (!item->d_ptr->transformData || item->d_ptr->transformData->computedFullTransform().type() <= QTransform::TxScale) {
// Rect
childItems_helper(items, item, item->mapRectFromParent(rect), mode);
} else {
// Polygon
childItems_helper(items, item, item->mapFromParent(rect), mode);
}
}
}
}
void QGraphicsScenePrivate::childItems_helper(QList<QGraphicsItem *> *items,
const QGraphicsItem *parent,
const QPolygonF &polygon,
Qt::ItemSelectionMode mode) const
{
bool parentClip = (parent->flags() & QGraphicsItem::ItemClipsChildrenToShape);
if (parentClip && parent->d_ptr->isClippedAway())
return;
QRectF polyRect(polygon.boundingRect());
_q_adjustRect(&polyRect);
QRectF r = !parentClip ? polyRect : polyRect.intersected(adjustedItemBoundingRect(parent));
if (r.isEmpty())
return;
QPainterPath path;
QList<QGraphicsItem *> &children = parent->d_ptr->children;
for (int i = 0; i < children.size(); ++i) {
QGraphicsItem *item = children.at(i);
if (item->d_ptr->transformData && !item->d_ptr->transformData->computedFullTransform().isInvertible())
continue;
// Skip invisible items.
if (item->d_ptr->isInvisible())
continue;
bool keep = false;
if (!item->d_ptr->isClippedAway()) {
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
const QRectF br(adjustedItemBoundingRect(item));
if (mode >= Qt::ContainsItemBoundingRect) {
// Polygon contains/intersects item's bounding rect
if (path == QPainterPath())
path.addPolygon(polygon);
if ((mode == Qt::IntersectsItemBoundingRect && path.intersects(item->mapRectToParent(br)))
|| (mode == Qt::ContainsItemBoundingRect && path.contains(item->mapRectToParent(br)))) {
items->append(item);
keep = true;
}
} else {
// Polygon contains/intersects item's shape
if (QRectF_intersects(polyRect, item->mapRectToParent(br))) {
if (path == QPainterPath())
path.addPolygon(polygon);
if (itemCollidesWithPath(item, item->mapFromParent(path), mode)) {
items->append(item);
keep = true;
}
}
}
}
if ((keep || !(item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) && !item->d_ptr->children.isEmpty()) {
// Recurse into children that clip children.
childItems_helper(items, item, item->mapFromParent(polygon), mode);
}
}
}
void QGraphicsScenePrivate::childItems_helper(QList<QGraphicsItem *> *items,
const QGraphicsItem *parent,
const QPainterPath &path,
Qt::ItemSelectionMode mode) const
{
bool parentClip = (parent->flags() & QGraphicsItem::ItemClipsChildrenToShape);
if (parentClip && parent->d_ptr->isClippedAway())
return;
QRectF pathRect(path.boundingRect());
_q_adjustRect(&pathRect);
QRectF r = !parentClip ? pathRect : pathRect.intersected(adjustedItemBoundingRect(parent));
if (r.isEmpty())
return;
QList<QGraphicsItem *> &children = parent->d_ptr->children;
for (int i = 0; i < children.size(); ++i) {
QGraphicsItem *item = children.at(i);
if (item->d_ptr->transformData && !item->d_ptr->transformData->computedFullTransform().isInvertible())
continue;
// Skip invisible items.
if (item->d_ptr->isInvisible())
continue;
bool keep = false;
if (!item->d_ptr->isClippedAway()) {
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
const QRectF br(adjustedItemBoundingRect(item));
if (mode >= Qt::ContainsItemBoundingRect) {
// Polygon contains/intersects item's bounding rect
if ((mode == Qt::IntersectsItemBoundingRect && path.intersects(item->mapRectToParent(br)))
|| (mode == Qt::ContainsItemBoundingRect && path.contains(item->mapRectToParent(br)))) {
items->append(item);
keep = true;
}
} else {
// Path contains/intersects item's shape
if (QRectF_intersects(pathRect, item->mapRectToParent(br))) {
if (itemCollidesWithPath(item, item->mapFromParent(path), mode)) {
items->append(item);
keep = true;
}
}
}
}
if ((keep || !(item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) && !item->d_ptr->children.isEmpty()) {
// Recurse into children that clip children.
childItems_helper(items, item, item->mapFromParent(path), mode);
}
}
}
void QGraphicsScenePrivate::invalidateSortCache()
{
Q_Q(QGraphicsScene);
if (!sortCacheEnabled || updatingSortCache)
return;
updatingSortCache = true;
QMetaObject::invokeMethod(q, "_q_updateSortCache", Qt::QueuedConnection);
}
/*!
\internal
Should not be exported, but we can't change that now.
### Qt 5: Remove symbol / make static
*/
inline bool qt_closestLeaf(const QGraphicsItem *item1, const QGraphicsItem *item2)
{
// Return true if sibling item1 is on top of item2.
const QGraphicsItemPrivate *d1 = item1->d_ptr;
const QGraphicsItemPrivate *d2 = item2->d_ptr;
bool f1 = d1->flags & QGraphicsItem::ItemStacksBehindParent;
bool f2 = d2->flags & QGraphicsItem::ItemStacksBehindParent;
if (f1 != f2) return f2;
qreal z1 = d1->z;
qreal z2 = d2->z;
return z1 > z2;
}
static inline bool qt_notclosestLeaf(const QGraphicsItem *item1, const QGraphicsItem *item2)
{
return qt_closestLeaf(item2, item1);
}
/*!
\internal
Should not be exported, but we can't change that now.
*/
inline bool qt_closestItemFirst(const QGraphicsItem *item1, const QGraphicsItem *item2)
{
return QGraphicsScenePrivate::closestItemFirst_withoutCache(item1, item2);
}
/*!
Returns true if \a item1 is on top of \a item2.
\internal
*/
bool QGraphicsScenePrivate::closestItemFirst_withoutCache(const QGraphicsItem *item1, const QGraphicsItem *item2)
{
// Siblings? Just check their z-values.
const QGraphicsItemPrivate *d1 = item1->d_ptr;
const QGraphicsItemPrivate *d2 = item2->d_ptr;
if (d1->parent == d2->parent)
return qt_closestLeaf(item1, item2);
// Find common ancestor, and each item's ancestor closest to the common
// ancestor.
int item1Depth = d1->depth;
int item2Depth = d2->depth;
const QGraphicsItem *p = item1;
const QGraphicsItem *t1 = item1;
while (item1Depth > item2Depth && (p = p->d_ptr->parent)) {
if (p == item2) {
// item2 is one of item1's ancestors; item1 is on top
return !(t1->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent);
}
t1 = p;
--item1Depth;
}
p = item2;
const QGraphicsItem *t2 = item2;
while (item2Depth > item1Depth && (p = p->d_ptr->parent)) {
if (p == item1) {
// item1 is one of item2's ancestors; item1 is not on top
return (t2->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent);
}
t2 = p;
--item2Depth;
}
// item1Ancestor is now at the same level as item2Ancestor, but not the same.
const QGraphicsItem *a1 = t1;
const QGraphicsItem *a2 = t2;
while (a1) {
const QGraphicsItem *p1 = a1;
const QGraphicsItem *p2 = a2;
a1 = a1->parentItem();
a2 = a2->parentItem();
if (a1 && a1 == a2)
return qt_closestLeaf(p1, p2);
}
// No common ancestor? Then just compare the items' toplevels directly.
return qt_closestLeaf(t1->topLevelItem(), t2->topLevelItem());
}
/*!
Returns true if \a item2 is on top of \a item1.
\internal
*/
bool QGraphicsScenePrivate::closestItemLast_withoutCache(const QGraphicsItem *item1, const QGraphicsItem *item2)
{
return closestItemFirst_withoutCache(item2, item1);
}
void QGraphicsScenePrivate::climbTree(QGraphicsItem *item, int *stackingOrder)
{
if (!item->d_ptr->children.isEmpty()) {
QList<QGraphicsItem *> childList = item->d_ptr->children;
qSort(childList.begin(), childList.end(), qt_closestLeaf);
for (int i = 0; i < childList.size(); ++i) {
QGraphicsItem *item = childList.at(i);
if (!(item->flags() & QGraphicsItem::ItemStacksBehindParent))
climbTree(childList.at(i), stackingOrder);
}
item->d_ptr->globalStackingOrder = (*stackingOrder)++;
for (int i = 0; i < childList.size(); ++i) {
QGraphicsItem *item = childList.at(i);
if (item->flags() & QGraphicsItem::ItemStacksBehindParent)
climbTree(childList.at(i), stackingOrder);
}
} else {
item->d_ptr->globalStackingOrder = (*stackingOrder)++;
}
}
void QGraphicsScenePrivate::_q_updateSortCache()
{
_q_updateIndex();
if (!sortCacheEnabled || !updatingSortCache)
return;
updatingSortCache = false;
int stackingOrder = 0;
QList<QGraphicsItem *> topLevels;
for (int i = 0; i < indexedItems.size(); ++i) {
QGraphicsItem *item = indexedItems.at(i);
if (item && item->parentItem() == 0)
topLevels << item;
}
for (int i = 0; i < unindexedItems.size(); ++i) {
QGraphicsItem *item = unindexedItems.at(i);
if (item->parentItem() == 0)
topLevels << item;
}
qSort(topLevels.begin(), topLevels.end(), qt_closestLeaf);
for (int i = 0; i < topLevels.size(); ++i)
climbTree(topLevels.at(i), &stackingOrder);
}
void QGraphicsScenePrivate::sortItems(QList<QGraphicsItem *> *itemList, Qt::SortOrder order,
bool sortCacheEnabled)
{
if (sortCacheEnabled) {
if (order == Qt::AscendingOrder) {
qSort(itemList->begin(), itemList->end(), closestItemFirst_withCache);
} else if (order == Qt::DescendingOrder) {
qSort(itemList->begin(), itemList->end(), closestItemLast_withCache);
}
} else {
if (order == Qt::AscendingOrder) {
qSort(itemList->begin(), itemList->end(), closestItemFirst_withoutCache);
} else if (order == Qt::DescendingOrder) {
qSort(itemList->begin(), itemList->end(), closestItemLast_withoutCache);
}
}
}
/*!
\internal
Set the font and propagate the changes if the font is different from the
current font.
*/
void QGraphicsScenePrivate::setFont_helper(const QFont &font)
{
if (this->font == font && this->font.resolve() == font.resolve())
return;
updateFont(font);
}
/*!
\internal
Resolve the scene's font against the application font, and propagate the
changes too all items in the scene.
*/
void QGraphicsScenePrivate::resolveFont()
{
QFont naturalFont = QApplication::font();
naturalFont.resolve(0);
QFont resolvedFont = font.resolve(naturalFont);
updateFont(resolvedFont);
}
/*!
\internal
Update the font, and whether or not it has changed, reresolve all fonts in
the scene.
*/
void QGraphicsScenePrivate::updateFont(const QFont &font)
{
Q_Q(QGraphicsScene);
// Update local font setting.
this->font = font;
// Resolve the fonts of all top-level widget items, or widget items
// whose parent is not a widget.
foreach (QGraphicsItem *item, q->items()) {
if (!item->parentItem()) {
// Resolvefont for an item is a noop operation, but
// every item can be a widget, or can have a widget
// childre.
item->d_ptr->resolveFont(font.resolve());
}
}
// Send the scene a FontChange event.
QEvent event(QEvent::FontChange);
QApplication::sendEvent(q, &event);
}
/*!
\internal
Set the palette and propagate the changes if the palette is different from
the current palette.
*/
void QGraphicsScenePrivate::setPalette_helper(const QPalette &palette)
{
if (this->palette == palette && this->palette.resolve() == palette.resolve())
return;
updatePalette(palette);
}
/*!
\internal
Resolve the scene's palette against the application palette, and propagate
the changes too all items in the scene.
*/
void QGraphicsScenePrivate::resolvePalette()
{
QPalette naturalPalette = QApplication::palette();
naturalPalette.resolve(0);
QPalette resolvedPalette = palette.resolve(naturalPalette);
updatePalette(resolvedPalette);
}
/*!
\internal
Update the palette, and whether or not it has changed, reresolve all
palettes in the scene.
*/
void QGraphicsScenePrivate::updatePalette(const QPalette &palette)
{
Q_Q(QGraphicsScene);
// Update local palette setting.
this->palette = palette;
// Resolve the palettes of all top-level widget items, or widget items
// whose parent is not a widget.
foreach (QGraphicsItem *item, q->items()) {
if (!item->parentItem()) {
// Resolvefont for an item is a noop operation, but
// every item can be a widget, or can have a widget
// childre.
item->d_ptr->resolvePalette(palette.resolve());
}
}
// Send the scene a PaletteChange event.
QEvent event(QEvent::PaletteChange);
QApplication::sendEvent(q, &event);
}
/*!
Constructs a QGraphicsScene object. The \a parent parameter is
passed to QObject's constructor.
*/
QGraphicsScene::QGraphicsScene(QObject *parent)
: QObject(*new QGraphicsScenePrivate, parent)
{
d_func()->init();
}
/*!
Constructs a QGraphicsScene object, using \a sceneRect for its
scene rectangle. The \a parent parameter is passed to QObject's
constructor.
\sa sceneRect
*/
QGraphicsScene::QGraphicsScene(const QRectF &sceneRect, QObject *parent)
: QObject(*new QGraphicsScenePrivate, parent)
{
setSceneRect(sceneRect);
d_func()->init();
}
/*!
Constructs a QGraphicsScene object, using the rectangle specified
by (\a x, \a y), and the given \a width and \a height for its
scene rectangle. The \a parent parameter is passed to QObject's
constructor.
\sa sceneRect
*/
QGraphicsScene::QGraphicsScene(qreal x, qreal y, qreal width, qreal height, QObject *parent)
: QObject(*new QGraphicsScenePrivate, parent)
{
setSceneRect(x, y, width, height);
d_func()->init();
}
/*!
Destroys the QGraphicsScene object.
*/
QGraphicsScene::~QGraphicsScene()
{
Q_D(QGraphicsScene);
// Remove this scene from qApp's global scene list.
qApp->d_func()->scene_list.removeAll(this);
clear();
// Remove this scene from all associated views.
for (int j = 0; j < d->views.size(); ++j)
d->views.at(j)->setScene(0);
}
/*!
\property QGraphicsScene::sceneRect
\brief the scene rectangle; the bounding rectangle of the scene
The scene rectangle defines the extent of the scene. It is
primarily used by QGraphicsView to determine the view's default
scrollable area, and by QGraphicsScene to manage item indexing.
If unset, or if set to a null QRectF, sceneRect() will return the largest
bounding rect of all items on the scene since the scene was created (i.e.,
a rectangle that grows when items are added to or moved in the scene, but
never shrinks).
\sa width(), height(), QGraphicsView::sceneRect
*/
QRectF QGraphicsScene::sceneRect() const
{
Q_D(const QGraphicsScene);
const_cast<QGraphicsScenePrivate *>(d)->_q_updateIndex();
return d->hasSceneRect ? d->sceneRect : d->growingItemsBoundingRect;
}
void QGraphicsScene::setSceneRect(const QRectF &rect)
{
Q_D(QGraphicsScene);
if (rect != d->sceneRect) {
d->hasSceneRect = !rect.isNull();
d->sceneRect = rect;
d->resetIndex();
emit sceneRectChanged(rect);
}
}
/*!
\fn qreal QGraphicsScene::width() const
This convenience function is equivalent to calling sceneRect().width().
\sa height()
*/
/*!
\fn qreal QGraphicsScene::height() const
This convenience function is equivalent to calling \c sceneRect().height().
\sa width()
*/
/*!
Renders the \a source rect from scene into \a target, using \a painter. This
function is useful for capturing the contents of the scene onto a paint
device, such as a QImage (e.g., to take a screenshot), or for printing
with QPrinter. For example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 1
If \a source is a null rect, this function will use sceneRect() to
determine what to render. If \a target is a null rect, the dimensions of \a
painter's paint device will be used.
The source rect contents will be transformed according to \a
aspectRatioMode to fit into the target rect. By default, the aspect ratio
is kept, and \a source is scaled to fit in \a target.
\sa QGraphicsView::render()
*/
void QGraphicsScene::render(QPainter *painter, const QRectF &target, const QRectF &source,
Qt::AspectRatioMode aspectRatioMode)
{
// Default source rect = scene rect
QRectF sourceRect = source;
if (sourceRect.isNull())
sourceRect = sceneRect();
// Default target rect = device rect
QRectF targetRect = target;
if (targetRect.isNull()) {
if (painter->device()->devType() == QInternal::Picture)
targetRect = sourceRect;
else
targetRect.setRect(0, 0, painter->device()->width(), painter->device()->height());
}
// Find the ideal x / y scaling ratio to fit \a source into \a target.
qreal xratio = targetRect.width() / sourceRect.width();
qreal yratio = targetRect.height() / sourceRect.height();
// Scale according to the aspect ratio mode.
switch (aspectRatioMode) {
case Qt::KeepAspectRatio:
xratio = yratio = qMin(xratio, yratio);
break;
case Qt::KeepAspectRatioByExpanding:
xratio = yratio = qMax(xratio, yratio);
break;
case Qt::IgnoreAspectRatio:
break;
}
// Find all items to draw, and reverse the list (we want to draw
// in reverse order).
QList<QGraphicsItem *> itemList = items(sourceRect, Qt::IntersectsItemBoundingRect);
QGraphicsItem **itemArray = new QGraphicsItem *[itemList.size()];
int numItems = itemList.size();
for (int i = 0; i < numItems; ++i)
itemArray[numItems - i - 1] = itemList.at(i);
itemList.clear();
painter->save();
// Transform the painter.
painter->setClipRect(targetRect);
QTransform painterTransform;
painterTransform *= QTransform()
.translate(targetRect.left(), targetRect.top())
.scale(xratio, yratio)
.translate(-sourceRect.left(), -sourceRect.top());
painter->setWorldTransform(painterTransform, true);
// Two unit vectors.
QLineF v1(0, 0, 1, 0);
QLineF v2(0, 0, 0, 1);
// Generate the style options
QStyleOptionGraphicsItem *styleOptionArray = new QStyleOptionGraphicsItem[numItems];
for (int i = 0; i < numItems; ++i)
itemArray[i]->d_ptr->initStyleOption(&styleOptionArray[i], painterTransform, targetRect.toRect());
// Render the scene.
drawBackground(painter, sourceRect);
drawItems(painter, numItems, itemArray, styleOptionArray);
drawForeground(painter, sourceRect);
delete [] itemArray;
delete [] styleOptionArray;
painter->restore();
}
/*!
\property QGraphicsScene::itemIndexMethod
\brief the item indexing method.
QGraphicsScene applies an indexing algorithm to the scene, to speed up
item discovery functions like items() and itemAt(). Indexing is most
efficient for static scenes (i.e., where items don't move around). For
dynamic scenes, or scenes with many animated items, the index bookkeeping
can outweight the fast lookup speeds.
For the common case, the default index method BspTreeIndex works fine. If
your scene uses many animations and you are experiencing slowness, you can
disable indexing by calling \c setItemIndexMethod(NoIndex).
\sa bspTreeDepth
*/
QGraphicsScene::ItemIndexMethod QGraphicsScene::itemIndexMethod() const
{
Q_D(const QGraphicsScene);
return d->indexMethod;
}
void QGraphicsScene::setItemIndexMethod(ItemIndexMethod method)
{
Q_D(QGraphicsScene);
d->resetIndex();
d->indexMethod = method;
}
/*!
\property QGraphicsScene::bspTreeDepth
\brief the depth of QGraphicsScene's BSP index tree
\since 4.3
This property has no effect when NoIndex is used.
This value determines the depth of QGraphicsScene's BSP tree. The depth
directly affects QGraphicsScene's performance and memory usage; the latter
growing exponentially with the depth of the tree. With an optimal tree
depth, QGraphicsScene can instantly determine the locality of items, even
for scenes with thousands or millions of items. This also greatly improves
rendering performance.
By default, the value is 0, in which case Qt will guess a reasonable
default depth based on the size, location and number of items in the
scene. If these parameters change frequently, however, you may experience
slowdowns as QGraphicsScene retunes the depth internally. You can avoid
potential slowdowns by fixating the tree depth through setting this
property.
The depth of the tree and the size of the scene rectangle decide the
granularity of the scene's partitioning. The size of each scene segment is
determined by the following algorithm:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 2
The BSP tree has an optimal size when each segment contains between 0 and
10 items.
\sa itemIndexMethod
*/
int QGraphicsScene::bspTreeDepth() const
{
Q_D(const QGraphicsScene);
return d->bspTreeDepth;
}
void QGraphicsScene::setBspTreeDepth(int depth)
{
Q_D(QGraphicsScene);
if (d->bspTreeDepth == depth)
return;
if (depth < 0) {
qWarning("QGraphicsScene::setBspTreeDepth: invalid depth %d ignored; must be >= 0", depth);
return;
}
d->bspTreeDepth = depth;
d->resetIndex();
}
/*!
\property QGraphicsScene::sortCacheEnabled
\brief whether sort caching is enabled
\since 4.5
When enabled, this property adds a cache that speeds up sorting and
transformations for scenes with deep hierarchies (i.e., items with many
levels of descendents), at the cost of using more memory (approx. 100 more
bytes of memory per item).
Items that are not part of a deep hierarchy suffer no penalty from this
cache.
*/
bool QGraphicsScene::isSortCacheEnabled() const
{
Q_D(const QGraphicsScene);
return d->sortCacheEnabled;
}
void QGraphicsScene::setSortCacheEnabled(bool enabled)
{
Q_D(QGraphicsScene);
if (enabled == d->sortCacheEnabled)
return;
if ((d->sortCacheEnabled = enabled))
d->invalidateSortCache();
}
/*!
Calculates and returns the bounding rect of all items on the scene. This
function works by iterating over all items, and because if this, it can
be slow for large scenes.
\sa sceneRect()
*/
QRectF QGraphicsScene::itemsBoundingRect() const
{
QRectF boundingRect;
foreach (QGraphicsItem *item, items())
boundingRect |= item->sceneBoundingRect();
return boundingRect;
}
/*!
Returns a list of all items on the scene, in no particular order.
\sa addItem(), removeItem()
*/
QList<QGraphicsItem *> QGraphicsScene::items() const
{
Q_D(const QGraphicsScene);
const_cast<QGraphicsScenePrivate *>(d)->purgeRemovedItems();
// If freeItemIndexes is empty, we know there are no holes in indexedItems and
// unindexedItems.
if (d->freeItemIndexes.isEmpty()) {
if (d->unindexedItems.isEmpty())
return d->indexedItems;
return d->indexedItems + d->unindexedItems;
}
// Rebuild the list of items to avoid holes. ### We could also just
// compress the item lists at this point.
QList<QGraphicsItem *> itemList;
foreach (QGraphicsItem *item, d->indexedItems + d->unindexedItems) {
if (item)
itemList << item;
}
return itemList;
}
/*!
Returns all visible items at position \a pos in the scene. The items are
listed in descending Z order (i.e., the first item in the list is the
top-most item, and the last item is the bottom-most item).
\sa itemAt()
*/
QList<QGraphicsItem *> QGraphicsScene::items(const QPointF &pos) const
{
Q_D(const QGraphicsScene);
return d->items_helper(pos);
}
/*!
\fn QList<QGraphicsItem *> QGraphicsScene::items(const QRectF &rectangle, Qt::ItemSelectionMode mode) const
\overload
Returns all visible items that, depending on \a mode, are either inside or
intersect with the specified \a rectangle.
The default value for \a mode is Qt::IntersectsItemShape; all items whose
exact shape intersects with or is contained by \a rectangle are returned.
\sa itemAt()
*/
QList<QGraphicsItem *> QGraphicsScene::items(const QRectF &rect, Qt::ItemSelectionMode mode) const
{
Q_D(const QGraphicsScene);
QList<QGraphicsItem *> itemList;
d->recursive_items_helper(0, rect, &itemList, QTransform(), QTransform(), mode, Qt::AscendingOrder);
return itemList;
}
/*!
\fn QList<QGraphicsItem *> QGraphicsScene::items(qreal x, qreal y, qreal w, qreal h, Qt::ItemSelectionMode mode) const
\since 4.3
This convenience function is equivalent to calling items(QRectF(\a x, \a y, \a w, \a h), \a mode).
*/
/*!
\overload
Returns all visible items that, depending on \a mode, are either inside or
intersect with the polygon \a polygon.
The default value for \a mode is Qt::IntersectsItemShape; all items whose
exact shape intersects with or is contained by \a polygon are returned.
\sa itemAt()
*/
QList<QGraphicsItem *> QGraphicsScene::items(const QPolygonF &polygon, Qt::ItemSelectionMode mode) const
{
Q_D(const QGraphicsScene);
return d->items_helper(polygon, mode, Qt::AscendingOrder);
}
/*!
\overload
Returns all visible items that, depending on \a path, are either inside or
intersect with the path \a path.
The default value for \a mode is Qt::IntersectsItemShape; all items whose
exact shape intersects with or is contained by \a path are returned.
\sa itemAt()
*/
QList<QGraphicsItem *> QGraphicsScene::items(const QPainterPath &path, Qt::ItemSelectionMode mode) const
{
Q_D(const QGraphicsScene);
return d->items_helper(path, mode, Qt::AscendingOrder);
}
/*!
Returns a list of all items that collide with \a item. Collisions are
determined by calling QGraphicsItem::collidesWithItem(); the collision
detection is determined by \a mode. By default, all items whose shape
intersects \a item or is contained inside \a item's shape are returned.
The items are returned in descending Z order (i.e., the first item in the
list is the top-most item, and the last item is the bottom-most item).
\sa items(), itemAt(), QGraphicsItem::collidesWithItem()
*/
QList<QGraphicsItem *> QGraphicsScene::collidingItems(const QGraphicsItem *item,
Qt::ItemSelectionMode mode) const
{
Q_D(const QGraphicsScene);
if (!item) {
qWarning("QGraphicsScene::collidingItems: cannot find collisions for null item");
return QList<QGraphicsItem *>();
}
QList<QGraphicsItem *> tmp;
foreach (QGraphicsItem *itemInVicinity, d->estimateItemsInRect(item->sceneBoundingRect())) {
if (item != itemInVicinity && item->collidesWithItem(itemInVicinity, mode))
tmp << itemInVicinity;
}
d->sortItems(&tmp, Qt::AscendingOrder, d->sortCacheEnabled);
return tmp;
}
/*!
\fn QGraphicsItem *QGraphicsScene::itemAt(const QPointF &position) const
Returns the topmost visible item at the specified \a position, or 0 if
there are no items at this position.
\note The topmost item is the one with the highest Z-value.
\sa items(), collidingItems(), QGraphicsItem::setZValue()
*/
QGraphicsItem *QGraphicsScene::itemAt(const QPointF &pos) const
{
QList<QGraphicsItem *> itemsAtPoint = items(pos);
return itemsAtPoint.isEmpty() ? 0 : itemsAtPoint.first();
}
/*!
\fn QGraphicsScene::itemAt(qreal x, qreal y) const
\overload
Returns the topmost item at the position specified by (\a x, \a
y), or 0 if there are no items at this position.
This convenience function is equivalent to calling \c
{itemAt(QPointF(x, y))}.
\note The topmost item is the one with the highest Z-value.
*/
/*!
Returns a list of all currently selected items. The items are
returned in no particular order.
\sa setSelectionArea()
*/
QList<QGraphicsItem *> QGraphicsScene::selectedItems() const
{
Q_D(const QGraphicsScene);
// Optimization: Lazily removes items that are not selected.
QGraphicsScene *that = const_cast<QGraphicsScene *>(this);
QSet<QGraphicsItem *> actuallySelectedSet;
foreach (QGraphicsItem *item, that->d_func()->selectedItems) {
if (item->isSelected())
actuallySelectedSet << item;
}
that->d_func()->selectedItems = actuallySelectedSet;
return d->selectedItems.values();
}
/*!
Returns the selection area that was previously set with
setSelectionArea(), or an empty QPainterPath if no selection area has been
set.
\sa setSelectionArea()
*/
QPainterPath QGraphicsScene::selectionArea() const
{
Q_D(const QGraphicsScene);
return d->selectionArea;
}
/*!
Sets the selection area to \a path. All items within this area are
immediately selected, and all items outside are unselected. You can get
the list of all selected items by calling selectedItems().
For an item to be selected, it must be marked as \e selectable
(QGraphicsItem::ItemIsSelectable).
\sa clearSelection(), selectionArea()
*/
void QGraphicsScene::setSelectionArea(const QPainterPath &path)
{
setSelectionArea(path, Qt::IntersectsItemShape);
}
/*!
\overload
\since 4.3
Sets the selection area to \a path using \a mode to determine if items are
included in the selection area.
\sa clearSelection(), selectionArea()
*/
void QGraphicsScene::setSelectionArea(const QPainterPath &path, Qt::ItemSelectionMode mode)
{
Q_D(QGraphicsScene);
// Note: with boolean path operations, we can improve performance here
// quite a lot by "growing" the old path instead of replacing it. That
// allows us to only check the intersect area for changes, instead of
// reevaluating the whole path over again.
d->selectionArea = path;
QSet<QGraphicsItem *> unselectItems = d->selectedItems;
// Disable emitting selectionChanged() for individual items.
++d->selectionChanging;
bool changed = false;
// Set all items in path to selected.
foreach (QGraphicsItem *item, items(path, mode)) {
if (item->flags() & QGraphicsItem::ItemIsSelectable) {
if (!item->isSelected())
changed = true;
unselectItems.remove(item);
item->setSelected(true);
}
}
// Unselect all items outside path.
foreach (QGraphicsItem *item, unselectItems) {
item->setSelected(false);
changed = true;
}
// Reenable emitting selectionChanged() for individual items.
--d->selectionChanging;
if (!d->selectionChanging && changed)
emit selectionChanged();
}
/*!
Clears the current selection.
\sa setSelectionArea(), selectedItems()
*/
void QGraphicsScene::clearSelection()
{
Q_D(QGraphicsScene);
// Disable emitting selectionChanged
++d->selectionChanging;
bool changed = !d->selectedItems.isEmpty();
foreach (QGraphicsItem *item, d->selectedItems)
item->setSelected(false);
d->selectedItems.clear();
// Reenable emitting selectionChanged() for individual items.
--d->selectionChanging;
if (!d->selectionChanging && changed)
emit selectionChanged();
}
/*!
\since 4.4
Removes and deletes all items from the scene, but otherwise leaves the
state of the scene unchanged.
\sa addItem()
*/
void QGraphicsScene::clear()
{
Q_D(QGraphicsScene);
// Recursive descent delete
for (int i = 0; i < d->indexedItems.size(); ++i) {
if (QGraphicsItem *item = d->indexedItems.at(i)) {
if (!item->parentItem())
delete item;
}
}
QList<QGraphicsItem *> unindexedParents;
for (int i = 0; i < d->unindexedItems.size(); ++i) {
QGraphicsItem *item = d->unindexedItems.at(i);
if (!item->parentItem())
unindexedParents << item;
}
d->unindexedItems.clear();
qDeleteAll(unindexedParents);
d->indexedItems.clear();
d->freeItemIndexes.clear();
d->lastItemCount = 0;
d->bspTree.clear();
d->largestUntransformableItem = QRectF();
d->allItemsIgnoreHoverEvents = true;
d->allItemsUseDefaultCursor = true;
}
/*!
Groups all items in \a items into a new QGraphicsItemGroup, and returns a
pointer to the group. The group is created with the common ancestor of \a
items as its parent, and with position (0, 0). The items are all
reparented to the group, and their positions and transformations are
mapped to the group. If \a items is empty, this function will return an
empty top-level QGraphicsItemGroup.
QGraphicsScene has ownership of the group item; you do not need to delete
it. To dismantle (ungroup) a group, call destroyItemGroup().
\sa destroyItemGroup(), QGraphicsItemGroup::addToGroup()
*/
QGraphicsItemGroup *QGraphicsScene::createItemGroup(const QList<QGraphicsItem *> &items)
{
// Build a list of the first item's ancestors
QList<QGraphicsItem *> ancestors;
int n = 0;
if (!items.isEmpty()) {
QGraphicsItem *parent = items.at(n++);
while ((parent = parent->parentItem()))
ancestors.append(parent);
}
// Find the common ancestor for all items
QGraphicsItem *commonAncestor = 0;
if (!ancestors.isEmpty()) {
while (n < items.size()) {
int commonIndex = -1;
QGraphicsItem *parent = items.at(n++);
do {
int index = ancestors.indexOf(parent, qMax(0, commonIndex));
if (index != -1) {
commonIndex = index;
break;
}
} while ((parent = parent->parentItem()));
if (commonIndex == -1) {
commonAncestor = 0;
break;
}
commonAncestor = ancestors.at(commonIndex);
}
}
// Create a new group at that level
QGraphicsItemGroup *group = new QGraphicsItemGroup(commonAncestor);
if (!commonAncestor)
addItem(group);
foreach (QGraphicsItem *item, items)
group->addToGroup(item);
return group;
}
/*!
Reparents all items in \a group to \a group's parent item, then removes \a
group from the scene, and finally deletes it. The items' positions and
transformations are mapped from the group to the group's parent.
\sa createItemGroup(), QGraphicsItemGroup::removeFromGroup()
*/
void QGraphicsScene::destroyItemGroup(QGraphicsItemGroup *group)
{
foreach (QGraphicsItem *item, group->children())
group->removeFromGroup(item);
removeItem(group);
delete group;
}
/*!
Adds or moves the item \a item and all its childen to the scene.
If the item is visible (i.e., QGraphicsItem::isVisible() returns
true), QGraphicsScene will emit changed() once control goes back
to the event loop.
If the item is already in a different scene, it will first be removed from
its old scene, and then added to this scene as a top-level.
QGraphicsScene will send ItemSceneChange notifications to \a item while
it is added to the scene. If item does not currently belong to a scene, only one
notification is sent. If it does belong to scene already (i.e., it is
moved to this scene), QGraphicsScene will send an addition notification as
the item is removed from its previous scene.
\sa removeItem(), addEllipse(), addLine(), addPath(), addPixmap(),
addRect(), addText(), addWidget()
*/
void QGraphicsScene::addItem(QGraphicsItem *item)
{
Q_D(QGraphicsScene);
if (!item) {
qWarning("QGraphicsScene::addItem: cannot add null item");
return;
}
if (item->scene() == this) {
qWarning("QGraphicsScene::addItem: item has already been added to this scene");
return;
}
// Remove this item from its existing scene
if (QGraphicsScene *oldScene = item->scene())
oldScene->removeItem(item);
// Notify the item that its scene is changing, and allow the item to
// react.
const QVariant newSceneVariant(item->itemChange(QGraphicsItem::ItemSceneChange,
qVariantFromValue<QGraphicsScene *>(this)));
QGraphicsScene *targetScene = qVariantValue<QGraphicsScene *>(newSceneVariant);
if (targetScene != this) {
if (targetScene && item->scene() != targetScene)
targetScene->addItem(item);
return;
}
// Prevent reusing a recently deleted pointer: purge all removed items
// from our lists.
d->purgeRemovedItems();
// Invalidate any sort caching; arrival of a new item means we need to
// resort.
d->invalidateSortCache();
// Detach this item from its parent if the parent's scene is different
// from this scene.
if (QGraphicsItem *itemParent = item->parentItem()) {
if (itemParent->scene() != this)
item->setParentItem(0);
}
// Add the item to this scene
item->d_func()->scene = targetScene;
// Indexing requires sceneBoundingRect(), but because \a item might
// not be completely constructed at this point, we need to store it in
// a temporary list and schedule an indexing for later.
d->unindexedItems << item;
item->d_func()->index = -1;
d->startIndexTimer(0);
// Add to list of toplevels if this item is a toplevel.
if (!item->d_ptr->parent)
d->registerTopLevelItem(item);
// Update the scene's sort cache settings.
item->d_ptr->globalStackingOrder = -1;
d->invalidateSortCache();
// Add to list of items that require an update. We cannot assume that the
// item is fully constructed, so calling item->update() can lead to a pure
// virtual function call to boundingRect().
if (!d->updateAll) {
if (d->pendingUpdateItems.isEmpty())
QMetaObject::invokeMethod(this, "_q_updateLater", Qt::QueuedConnection);
d->pendingUpdateItems << item;
}
// Disable selectionChanged() for individual items
++d->selectionChanging;
int oldSelectedItemSize = d->selectedItems.size();
// Enable mouse tracking if the item accepts hover events or has a cursor set.
if (d->allItemsIgnoreHoverEvents && d->itemAcceptsHoverEvents_helper(item)) {
d->allItemsIgnoreHoverEvents = false;
d->enableMouseTrackingOnViews();
}
#ifndef QT_NO_CURSOR
if (d->allItemsUseDefaultCursor && item->hasCursor()) {
d->allItemsUseDefaultCursor = false;
if (d->allItemsIgnoreHoverEvents) // already enabled otherwise
d->enableMouseTrackingOnViews();
}
#endif //QT_NO_CURSOR
// Update selection lists
if (item->isSelected())
d->selectedItems << item;
if (item->isWidget() && item->isVisible() && static_cast<QGraphicsWidget *>(item)->windowType() == Qt::Popup)
d->addPopup(static_cast<QGraphicsWidget *>(item));
// Update creation order focus chain. Make sure to leave the widget's
// internal tab order intact.
if (item->isWidget()) {
QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
if (!d->tabFocusFirst) {
// No first tab focus widget - make this the first tab focus
// widget.
d->tabFocusFirst = widget;
} else if (!widget->parentWidget()) {
// Adding a widget that is not part of a tab focus chain.
QGraphicsWidget *last = d->tabFocusFirst->d_func()->focusPrev;
QGraphicsWidget *lastNew = widget->d_func()->focusPrev;
last->d_func()->focusNext = widget;
widget->d_func()->focusPrev = last;
d->tabFocusFirst->d_func()->focusPrev = lastNew;
lastNew->d_func()->focusNext = d->tabFocusFirst;
}
}
// Add all children recursively
foreach (QGraphicsItem *child, item->children())
addItem(child);
// Resolve font and palette.
item->d_ptr->resolveFont(d->font.resolve());
item->d_ptr->resolvePalette(d->palette.resolve());
if (!item->d_ptr->explicitlyHidden) {
if (d->unpolishedItems.isEmpty())
QMetaObject::invokeMethod(this, "_q_polishItems", Qt::QueuedConnection);
d->unpolishedItems << item;
}
// Reenable selectionChanged() for individual items
--d->selectionChanging;
if (!d->selectionChanging && d->selectedItems.size() != oldSelectedItemSize)
emit selectionChanged();
// Deliver post-change notification
item->itemChange(QGraphicsItem::ItemSceneHasChanged, newSceneVariant);
}
/*!
Creates and adds an ellipse item to the scene, and returns the item
pointer. The geometry of the ellipse is defined by \a rect, and its pen
and brush are initialized to \a pen and \a brush.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addLine(), addPath(), addPixmap(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsEllipseItem *QGraphicsScene::addEllipse(const QRectF &rect, const QPen &pen, const QBrush &brush)
{
QGraphicsEllipseItem *item = new QGraphicsEllipseItem(rect);
item->setPen(pen);
item->setBrush(brush);
addItem(item);
return item;
}
/*!
\fn QGraphicsEllipseItem *QGraphicsScene::addEllipse(qreal x, qreal y, qreal w, qreal h, const QPen &pen, const QBrush &brush)
\since 4.3
This convenience function is equivalent to calling addEllipse(QRectF(\a x,
\a y, \a w, \a h), \a pen, \a brush).
*/
/*!
Creates and adds a line item to the scene, and returns the item
pointer. The geometry of the line is defined by \a line, and its pen
is initialized to \a pen.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addPath(), addPixmap(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsLineItem *QGraphicsScene::addLine(const QLineF &line, const QPen &pen)
{
QGraphicsLineItem *item = new QGraphicsLineItem(line);
item->setPen(pen);
addItem(item);
return item;
}
/*!
\fn QGraphicsLineItem *QGraphicsScene::addLine(qreal x1, qreal y1, qreal x2, qreal y2, const QPen &pen)
\since 4.3
This convenience function is equivalent to calling addLine(QLineF(\a x1,
\a y1, \a x2, \a y2), \a pen).
*/
/*!
Creates and adds a path item to the scene, and returns the item
pointer. The geometry of the path is defined by \a path, and its pen and
brush are initialized to \a pen and \a brush.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPixmap(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsPathItem *QGraphicsScene::addPath(const QPainterPath &path, const QPen &pen, const QBrush &brush)
{
QGraphicsPathItem *item = new QGraphicsPathItem(path);
item->setPen(pen);
item->setBrush(brush);
addItem(item);
return item;
}
/*!
Creates and adds a pixmap item to the scene, and returns the item
pointer. The pixmap is defined by \a pixmap.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPath(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsPixmapItem *QGraphicsScene::addPixmap(const QPixmap &pixmap)
{
QGraphicsPixmapItem *item = new QGraphicsPixmapItem(pixmap);
addItem(item);
return item;
}
/*!
Creates and adds a polygon item to the scene, and returns the item
pointer. The polygon is defined by \a polygon, and its pen and
brush are initialized to \a pen and \a brush.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPath(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsPolygonItem *QGraphicsScene::addPolygon(const QPolygonF &polygon,
const QPen &pen, const QBrush &brush)
{
QGraphicsPolygonItem *item = new QGraphicsPolygonItem(polygon);
item->setPen(pen);
item->setBrush(brush);
addItem(item);
return item;
}
/*!
Creates and adds a rectangle item to the scene, and returns the item
pointer. The geometry of the rectangle is defined by \a rect, and its pen
and brush are initialized to \a pen and \a brush.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0). For example, if a QRect(50, 50, 100,
100) is added, its top-left corner will be at (50, 50) relative to the
origin in the items coordinate system.
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPixmap(), addPixmap(), addText(),
addItem(), addWidget()
*/
QGraphicsRectItem *QGraphicsScene::addRect(const QRectF &rect, const QPen &pen, const QBrush &brush)
{
QGraphicsRectItem *item = new QGraphicsRectItem(rect);
item->setPen(pen);
item->setBrush(brush);
addItem(item);
return item;
}
/*!
\fn QGraphicsRectItem *QGraphicsScene::addRect(qreal x, qreal y, qreal w, qreal h, const QPen &pen, const QBrush &brush)
\since 4.3
This convenience function is equivalent to calling addRect(QRectF(\a x,
\a y, \a w, \a h), \a pen, \a brush).
*/
/*!
Creates and adds a text item to the scene, and returns the item
pointer. The text string is initialized to \a text, and its font
is initialized to \a font.
The item's position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPixmap(), addPixmap(), addRect(),
addItem(), addWidget()
*/
QGraphicsTextItem *QGraphicsScene::addText(const QString &text, const QFont &font)
{
QGraphicsTextItem *item = new QGraphicsTextItem(text);
item->setFont(font);
addItem(item);
return item;
}
/*!
Creates and adds a QGraphicsSimpleTextItem to the scene, and returns the
item pointer. The text string is initialized to \a text, and its font is
initialized to \a font.
The item's position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPixmap(), addPixmap(), addRect(),
addItem(), addWidget()
*/
QGraphicsSimpleTextItem *QGraphicsScene::addSimpleText(const QString &text, const QFont &font)
{
QGraphicsSimpleTextItem *item = new QGraphicsSimpleTextItem(text);
item->setFont(font);
addItem(item);
return item;
}
/*!
Creates a new QGraphicsProxyWidget for \a widget, adds it to the scene,
and returns a pointer to the proxy. \a wFlags set the default window flags
for the embedding proxy widget.
The item's position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
Note that widgets with the Qt::WA_PaintOnScreen widget attribute
set and widgets that wrap an external application or controller
are not supported. Examples are QGLWidget and QAxWidget.
\sa addEllipse(), addLine(), addPixmap(), addPixmap(), addRect(),
addText(), addSimpleText(), addItem()
*/
QGraphicsProxyWidget *QGraphicsScene::addWidget(QWidget *widget, Qt::WindowFlags wFlags)
{
QGraphicsProxyWidget *proxy = new QGraphicsProxyWidget(0, wFlags);
proxy->setWidget(widget);
addItem(proxy);
return proxy;
}
/*!
Removes the item \a item and all its children from the scene. The
ownership of \a item is passed on to the caller (i.e.,
QGraphicsScene will no longer delete \a item when destroyed).
\sa addItem()
*/
void QGraphicsScene::removeItem(QGraphicsItem *item)
{
// ### Refactoring: This function shares much functionality with _q_removeItemLater()
Q_D(QGraphicsScene);
if (!item) {
qWarning("QGraphicsScene::removeItem: cannot remove 0-item");
return;
}
if (item->scene() != this) {
qWarning("QGraphicsScene::removeItem: item %p's scene (%p)"
" is different from this scene (%p)",
item, item->scene(), this);
return;
}
// Notify the item that it's scene is changing to 0, allowing the item to
// react.
const QVariant newSceneVariant(item->itemChange(QGraphicsItem::ItemSceneChange,
qVariantFromValue<QGraphicsScene *>(0)));
QGraphicsScene *targetScene = qVariantValue<QGraphicsScene *>(newSceneVariant);
if (targetScene != 0 && targetScene != this) {
targetScene->addItem(item);
return;
}
d->removeItemHelper(item);
// Deliver post-change notification
item->itemChange(QGraphicsItem::ItemSceneHasChanged, newSceneVariant);
}
/*!
Returns the scene's current focus item, or 0 if no item currently has
focus.
The focus item receives keyboard input when the scene receives a
key event.
\sa setFocusItem(), QGraphicsItem::hasFocus()
*/
QGraphicsItem *QGraphicsScene::focusItem() const
{
Q_D(const QGraphicsScene);
return d->focusItem;
}
/*!
Sets the scene's focus item to \a item, with the focus reason \a
focusReason, after removing focus from any previous item that may have had
focus.
If \a item is 0, or if it either does not accept focus (i.e., it does not
have the QGraphicsItem::ItemIsFocusable flag enabled), or is not visible
or not enabled, this function only removes focus from any previous
focusitem.
If item is not 0, and the scene does not currently have focus (i.e.,
hasFocus() returns false), this function will call setFocus()
automatically.
\sa focusItem(), hasFocus(), setFocus()
*/
void QGraphicsScene::setFocusItem(QGraphicsItem *item, Qt::FocusReason focusReason)
{
Q_D(QGraphicsScene);
if (item == d->focusItem)
return;
if (item && (!(item->flags() & QGraphicsItem::ItemIsFocusable)
|| !item->isVisible() || !item->isEnabled())) {
item = 0;
}
if (item) {
setFocus(focusReason);
if (item == d->focusItem)
return;
}
if (d->focusItem) {
QFocusEvent event(QEvent::FocusOut, focusReason);
d->lastFocusItem = d->focusItem;
d->focusItem = 0;
d->sendEvent(d->lastFocusItem, &event);
}
if (item) {
if (item->isWidget()) {
// Update focus child chain.
static_cast<QGraphicsWidget *>(item)->d_func()->setFocusWidget();
}
d->focusItem = item;
QFocusEvent event(QEvent::FocusIn, focusReason);
d->sendEvent(item, &event);
}
}
/*!
Returns true if the scene has focus; otherwise returns false. If the scene
has focus, it will will forward key events from QKeyEvent to any item that
has focus.
\sa setFocus(), setFocusItem()
*/
bool QGraphicsScene::hasFocus() const
{
Q_D(const QGraphicsScene);
return d->hasFocus;
}
/*!
Sets focus on the scene by sending a QFocusEvent to the scene, passing \a
focusReason as the reason. If the scene regains focus after having
previously lost it while an item had focus, the last focus item will
receive focus with \a focusReason as the reason.
If the scene already has focus, this function does nothing.
\sa hasFocus(), clearFocus(), setFocusItem()
*/
void QGraphicsScene::setFocus(Qt::FocusReason focusReason)
{
Q_D(QGraphicsScene);
if (d->hasFocus)
return;
QFocusEvent event(QEvent::FocusIn, focusReason);
QCoreApplication::sendEvent(this, &event);
}
/*!
Clears focus from the scene. If any item has focus when this function is
called, it will lose focus, and regain focus again once the scene regains
focus.
A scene that does not have focus ignores key events.
\sa hasFocus(), setFocus(), setFocusItem()
*/
void QGraphicsScene::clearFocus()
{
Q_D(QGraphicsScene);
if (d->hasFocus) {
d->hasFocus = false;
setFocusItem(0, Qt::OtherFocusReason);
}
}
/*!
\property QGraphicsScene::stickyFocus
\brief whether or not clicking the scene will clear focus
If this property is false (the default), then clicking on the scene
background or on an item that does not accept focus, will clear
focus. Otherwise, focus will remain unchanged.
The focus change happens in response to a mouse press. You can reimplement
mousePressEvent() in a subclass of QGraphicsScene to toggle this property
based on where the user has clicked.
\sa clearFocus(), setFocusItem()
*/
void QGraphicsScene::setStickyFocus(bool enabled)
{
Q_D(QGraphicsScene);
d->stickyFocus = enabled;
}
bool QGraphicsScene::stickyFocus() const
{
Q_D(const QGraphicsScene);
return d->stickyFocus;
}
/*!
Returns the current mouse grabber item, or 0 if no item is currently
grabbing the mouse. The mouse grabber item is the item that receives all
mouse events sent to the scene.
An item becomes a mouse grabber when it receives and accepts a
mouse press event, and it stays the mouse grabber until either of
the following events occur:
\list
\o If the item receives a mouse release event when there are no other
buttons pressed, it loses the mouse grab.
\o If the item becomes invisible (i.e., someone calls \c {item->setVisible(false))},
or if it becomes disabled (i.e., someone calls \c {item->setEnabled(false))},
it loses the mouse grab.
\o If the item is removed from the scene, it loses the mouse grab.
\endlist
If the item loses its mouse grab, the scene will ignore all mouse events
until a new item grabs the mouse (i.e., until a new item receives a mouse
press event).
*/
QGraphicsItem *QGraphicsScene::mouseGrabberItem() const
{
Q_D(const QGraphicsScene);
return !d->mouseGrabberItems.isEmpty() ? d->mouseGrabberItems.last() : 0;
}
/*!
\property QGraphicsScene::backgroundBrush
\brief the background brush of the scene.
Set this property to changes the scene's background to a different color,
gradient or texture. The default background brush is Qt::NoBrush. The
background is drawn before (behind) the items.
Example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 3
QGraphicsScene::render() calls drawBackground() to draw the scene
background. For more detailed control over how the background is drawn,
you can reimplement drawBackground() in a subclass of QGraphicsScene.
*/
QBrush QGraphicsScene::backgroundBrush() const
{
Q_D(const QGraphicsScene);
return d->backgroundBrush;
}
void QGraphicsScene::setBackgroundBrush(const QBrush &brush)
{
Q_D(QGraphicsScene);
d->backgroundBrush = brush;
foreach (QGraphicsView *view, d->views) {
view->resetCachedContent();
view->viewport()->update();
}
update();
}
/*!
\property QGraphicsScene::foregroundBrush
\brief the foreground brush of the scene.
Change this property to set the scene's foreground to a different
color, gradient or texture.
The foreground is drawn after (on top of) the items. The default
foreground brush is Qt::NoBrush ( i.e. the foreground is not
drawn).
Example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 4
QGraphicsScene::render() calls drawForeground() to draw the scene
foreground. For more detailed control over how the foreground is
drawn, you can reimplement the drawForeground() function in a
QGraphicsScene subclass.
*/
QBrush QGraphicsScene::foregroundBrush() const
{
Q_D(const QGraphicsScene);
return d->foregroundBrush;
}
void QGraphicsScene::setForegroundBrush(const QBrush &brush)
{
Q_D(QGraphicsScene);
d->foregroundBrush = brush;
foreach (QGraphicsView *view, views())
view->viewport()->update();
update();
}
/*!
This method is used by input methods to query a set of properties of
the scene to be able to support complex input method operations as support
for surrounding text and reconversions.
The \a query parameter specifies which property is queried.
\sa QWidget::inputMethodQuery()
*/
QVariant QGraphicsScene::inputMethodQuery(Qt::InputMethodQuery query) const
{
Q_D(const QGraphicsScene);
if (!d->focusItem)
return QVariant();
const QTransform matrix = d->focusItem->sceneTransform();
QVariant value = d->focusItem->inputMethodQuery(query);
if (value.type() == QVariant::RectF)
value = matrix.mapRect(value.toRectF());
else if (value.type() == QVariant::PointF)
value = matrix.map(value.toPointF());
else if (value.type() == QVariant::Rect)
value = matrix.mapRect(value.toRect());
else if (value.type() == QVariant::Point)
value = matrix.map(value.toPoint());
return value;
}
/*!
\fn void QGraphicsScene::update(const QRectF &rect)
Schedules a redraw of the area \a rect on the scene.
\sa sceneRect(), changed()
*/
void QGraphicsScene::update(const QRectF &rect)
{
Q_D(QGraphicsScene);
if (d->updateAll || (rect.isEmpty() && !rect.isNull()))
return;
// Check if anyone's connected; if not, we can send updates directly to
// the views. Otherwise or if there are no views, use old behavior.
bool directUpdates = !(d->connectedSignals & d->changedSignalMask) && !d->views.isEmpty();
if (rect.isNull()) {
d->updateAll = true;
d->updatedRects.clear();
if (directUpdates) {
// Update all views.
for (int i = 0; i < d->views.size(); ++i)
d->views.at(i)->d_func()->updateAll();
}
} else {
if (directUpdates) {
// Update all views.
for (int i = 0; i < d->views.size(); ++i) {
QGraphicsView *view = d->views.at(i);
view->d_func()->updateRegion(QRegion(view->mapFromScene(rect).boundingRect()));
}
} else {
d->updatedRects << rect;
}
}
if (!d->calledEmitUpdated) {
d->calledEmitUpdated = true;
QMetaObject::invokeMethod(this, "_q_emitUpdated", Qt::QueuedConnection);
}
}
/*!
\fn void QGraphicsScene::update(qreal x, qreal y, qreal w, qreal h)
\overload
\since 4.3
This function is equivalent to calling update(QRectF(\a x, \a y, \a w,
\a h));
*/
/*!
Invalidates and schedules a redraw of the \a layers in \a rect on the
scene. Any cached content in \a layers is unconditionally invalidated and
redrawn.
You can use this function overload to notify QGraphicsScene of changes to
the background or the foreground of the scene. This function is commonly
used for scenes with tile-based backgrounds to notify changes when
QGraphicsView has enabled
\l{QGraphicsView::CacheBackground}{CacheBackground}.
Example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 5
Note that QGraphicsView currently supports background caching only (see
QGraphicsView::CacheBackground). This function is equivalent to calling
update() if any layer but BackgroundLayer is passed.
\sa QGraphicsView::resetCachedContent()
*/
void QGraphicsScene::invalidate(const QRectF &rect, SceneLayers layers)
{
foreach (QGraphicsView *view, views())
view->invalidateScene(rect, layers);
update(rect);
}
/*!
\fn void QGraphicsScene::invalidate(qreal x, qreal y, qreal w, qreal h, SceneLayers layers)
\overload
\since 4.3
This convenience function is equivalent to calling invalidate(QRectF(\a x, \a
y, \a w, \a h), \a layers);
*/
/*!
Returns a list of all the views that display this scene.
\sa QGraphicsView::scene()
*/
QList <QGraphicsView *> QGraphicsScene::views() const
{
Q_D(const QGraphicsScene);
return d->views;
}
/*!
This slot \e advances the scene by one step, by calling
QGraphicsItem::advance() for all items on the scene. This is done in two
phases: in the first phase, all items are notified that the scene is about
to change, and in the second phase all items are notified that they can
move. In the first phase, QGraphicsItem::advance() is called passing a
value of 0 as an argument, and 1 is passed in the second phase.
\sa QGraphicsItem::advance(), QGraphicsItemAnimation, QTimeLine
*/
void QGraphicsScene::advance()
{
for (int i = 0; i < 2; ++i) {
foreach (QGraphicsItem *item, items())
item->advance(i);
}
}
/*!
Processes the event \a event, and dispatches it to the respective
event handlers.
In addition to calling the convenience event handlers, this
function is responsible for converting mouse move events to hover
events for when there is no mouse grabber item. Hover events are
delivered directly to items; there is no convenience function for
them.
Unlike QWidget, QGraphicsScene does not have the convenience functions
\l{QWidget::}{enterEvent()} and \l{QWidget::}{leaveEvent()}. Use this
function to obtain those events instead.
\sa contextMenuEvent(), keyPressEvent(), keyReleaseEvent(),
mousePressEvent(), mouseMoveEvent(), mouseReleaseEvent(),
mouseDoubleClickEvent(), focusInEvent(), focusOutEvent()
*/
bool QGraphicsScene::event(QEvent *event)
{
Q_D(QGraphicsScene);
switch (event->type()) {
case QEvent::GraphicsSceneMousePress:
case QEvent::GraphicsSceneMouseMove:
case QEvent::GraphicsSceneMouseRelease:
case QEvent::GraphicsSceneMouseDoubleClick:
case QEvent::GraphicsSceneHoverEnter:
case QEvent::GraphicsSceneHoverLeave:
case QEvent::GraphicsSceneHoverMove:
// Reset the under-mouse list to ensure that this event gets fresh
// item-under-mouse data. Be careful about this list; if people delete
// items from inside event handlers, this list can quickly end up
// having stale pointers in it. We need to clear it before dispatching
// events that use it.
// ### this should only be cleared if we received a new mouse move event,
// which relies on us fixing the replay mechanism in QGraphicsView.
d->cachedItemsUnderMouse.clear();
default:
break;
}
switch (event->type()) {
case QEvent::GraphicsSceneDragEnter:
dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
break;
case QEvent::GraphicsSceneDragMove:
dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
break;
case QEvent::GraphicsSceneDragLeave:
dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
break;
case QEvent::GraphicsSceneDrop:
dropEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
break;
case QEvent::GraphicsSceneContextMenu:
contextMenuEvent(static_cast<QGraphicsSceneContextMenuEvent *>(event));
break;
case QEvent::KeyPress:
if (!d->focusItem) {
QKeyEvent *k = static_cast<QKeyEvent *>(event);
if (k->key() == Qt::Key_Tab || k->key() == Qt::Key_Backtab) {
if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier?
bool res = false;
if (k->key() == Qt::Key_Backtab
|| (k->key() == Qt::Key_Tab && (k->modifiers() & Qt::ShiftModifier))) {
res = focusNextPrevChild(false);
} else if (k->key() == Qt::Key_Tab) {
res = focusNextPrevChild(true);
}
if (!res)
event->ignore();
return true;
}
}
}
keyPressEvent(static_cast<QKeyEvent *>(event));
break;
case QEvent::KeyRelease:
keyReleaseEvent(static_cast<QKeyEvent *>(event));
break;
case QEvent::ShortcutOverride: {
QGraphicsItem *parent = focusItem();
while (parent) {
d->sendEvent(parent, event);
if (event->isAccepted())
return true;
parent = parent->parentItem();
}
}
return false;
case QEvent::GraphicsSceneMouseMove:
mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
break;
case QEvent::GraphicsSceneMousePress:
mousePressEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
break;
case QEvent::GraphicsSceneMouseRelease:
mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
break;
case QEvent::GraphicsSceneMouseDoubleClick:
mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
break;
case QEvent::GraphicsSceneWheel:
wheelEvent(static_cast<QGraphicsSceneWheelEvent *>(event));
break;
case QEvent::FocusIn:
focusInEvent(static_cast<QFocusEvent *>(event));
break;
case QEvent::FocusOut:
focusOutEvent(static_cast<QFocusEvent *>(event));
break;
case QEvent::GraphicsSceneHoverEnter:
case QEvent::GraphicsSceneHoverLeave:
case QEvent::GraphicsSceneHoverMove:
d->dispatchHoverEvent(static_cast<QGraphicsSceneHoverEvent *>(event));
break;
case QEvent::Leave:
d->leaveScene();
break;
case QEvent::GraphicsSceneHelp:
helpEvent(static_cast<QGraphicsSceneHelpEvent *>(event));
break;
case QEvent::InputMethod:
inputMethodEvent(static_cast<QInputMethodEvent *>(event));
break;
case QEvent::WindowActivate: {
if (!d->activationRefCount++) {
// Notify all non-window widgets.
foreach (QGraphicsItem *item, items()) {
if (item->isWidget() && item->isVisible() && !item->isWindow() && !item->parentWidget()) {
QEvent event(QEvent::WindowActivate);
QApplication::sendEvent(static_cast<QGraphicsWidget *>(item), &event);
}
}
// Restore window activation.
QGraphicsItem *nextFocusItem = d->focusItem ? d->focusItem : d->lastFocusItem;
if (nextFocusItem && nextFocusItem->window())
setActiveWindow(static_cast<QGraphicsWidget *>(nextFocusItem));
else if (d->tabFocusFirst && d->tabFocusFirst->isWindow())
setActiveWindow(d->tabFocusFirst);
}
break;
}
case QEvent::WindowDeactivate: {
if (!--d->activationRefCount) {
// Remove window activation.
setActiveWindow(0);
// Notify all non-window widgets.
foreach (QGraphicsItem *item, items()) {
if (item->isWidget() && item->isVisible() && !item->isWindow() && !item->parentWidget()) {
QEvent event(QEvent::WindowDeactivate);
QApplication::sendEvent(static_cast<QGraphicsWidget *>(item), &event);
}
}
}
break;
}
case QEvent::ApplicationFontChange: {
// Resolve the existing scene font.
d->resolveFont();
break;
}
case QEvent::FontChange:
// Update the entire scene when the font changes.
update();
break;
case QEvent::ApplicationPaletteChange: {
// Resolve the existing scene palette.
d->resolvePalette();
break;
}
case QEvent::PaletteChange:
// Update the entire scene when the palette changes.
update();
break;
case QEvent::StyleChange:
// Reresolve all widgets' styles. Update all top-level widgets'
// geometries that do not have an explicit style set.
update();
break;
case QEvent::Timer:
if (d->indexTimerId && static_cast<QTimerEvent *>(event)->timerId() == d->indexTimerId) {
if (d->restartIndexTimer) {
d->restartIndexTimer = false;
} else {
// this call will kill the timer
d->_q_updateIndex();
}
}
// Fallthrough intended - support timers in subclasses.
default:
return QObject::event(event);
}
return true;
}
/*!
\reimp
QGraphicsScene filters QApplication's events to detect palette and font
changes.
*/
bool QGraphicsScene::eventFilter(QObject *watched, QEvent *event)
{
if (watched != qApp)
return false;
switch (event->type()) {
case QEvent::ApplicationPaletteChange:
QApplication::postEvent(this, new QEvent(QEvent::ApplicationPaletteChange));
break;
case QEvent::ApplicationFontChange:
QApplication::postEvent(this, new QEvent(QEvent::ApplicationFontChange));
break;
default:
break;
}
return false;
}
/*!
This event handler, for event \a contextMenuEvent, can be reimplemented in
a subclass to receive context menu events. The default implementation
forwards the event to the topmost item that accepts context menu events at
the position of the event. If no items accept context menu events at this
position, the event is ignored.
\sa QGraphicsItem::contextMenuEvent()
*/
void QGraphicsScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *contextMenuEvent)
{
Q_D(QGraphicsScene);
// Ignore by default.
contextMenuEvent->ignore();
// Send the event to all items at this position until one item accepts the
// event.
foreach (QGraphicsItem *item, d->itemsAtPosition(contextMenuEvent->screenPos(),
contextMenuEvent->scenePos(),
contextMenuEvent->widget())) {
contextMenuEvent->setPos(item->d_ptr->genericMapFromScene(contextMenuEvent->scenePos(),
contextMenuEvent->widget()));
contextMenuEvent->accept();
if (!d->sendEvent(item, contextMenuEvent))
break;
if (contextMenuEvent->isAccepted())
break;
}
}
/*!
This event handler, for event \a event, can be reimplemented in a subclass
to receive drag enter events for the scene.
The default implementation accepts the event and prepares the scene to
accept drag move events.
\sa QGraphicsItem::dragEnterEvent(), dragMoveEvent(), dragLeaveEvent(),
dropEvent()
*/
void QGraphicsScene::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
{
Q_D(QGraphicsScene);
d->dragDropItem = 0;
d->lastDropAction = Qt::IgnoreAction;
event->accept();
}
/*!
This event handler, for event \a event, can be reimplemented in a subclass
to receive drag move events for the scene.
\sa QGraphicsItem::dragMoveEvent(), dragEnterEvent(), dragLeaveEvent(),
dropEvent()
*/
void QGraphicsScene::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
{
Q_D(QGraphicsScene);
event->ignore();
if (!d->mouseGrabberItems.isEmpty()) {
// Mouse grabbers that start drag events lose the mouse grab.
d->clearMouseGrabber();
d->mouseGrabberButtonDownPos.clear();
d->mouseGrabberButtonDownScenePos.clear();
d->mouseGrabberButtonDownScreenPos.clear();
}
bool eventDelivered = false;
// Find the topmost enabled items under the cursor. They are all
// candidates for accepting drag & drop events.
foreach (QGraphicsItem *item, d->itemsAtPosition(event->screenPos(),
event->scenePos(),
event->widget())) {
if (!item->isEnabled() || !item->acceptDrops())
continue;
if (item != d->dragDropItem) {
// Enter the new drag drop item. If it accepts the event, we send
// the leave to the parent item.
QGraphicsSceneDragDropEvent dragEnter(QEvent::GraphicsSceneDragEnter);
d->cloneDragDropEvent(&dragEnter, event);
dragEnter.setDropAction(event->proposedAction());
d->sendDragDropEvent(item, &dragEnter);
event->setAccepted(dragEnter.isAccepted());
event->setDropAction(dragEnter.dropAction());
if (!event->isAccepted()) {
// Propagate to the item under
continue;
}
d->lastDropAction = event->dropAction();
if (d->dragDropItem) {
// Leave the last drag drop item. A perfect implementation
// would set the position of this event to the point where
// this event and the last event intersect with the item's
// shape, but that's not easy to do. :-)
QGraphicsSceneDragDropEvent dragLeave(QEvent::GraphicsSceneDragLeave);
d->cloneDragDropEvent(&dragLeave, event);
d->sendDragDropEvent(d->dragDropItem, &dragLeave);
}
// We've got a new drag & drop item
d->dragDropItem = item;
}
// Send the move event.
event->setDropAction(d->lastDropAction);
event->accept();
d->sendDragDropEvent(item, event);
if (event->isAccepted())
d->lastDropAction = event->dropAction();
eventDelivered = true;
break;
}
if (!eventDelivered) {
if (d->dragDropItem) {
// Leave the last drag drop item
QGraphicsSceneDragDropEvent dragLeave(QEvent::GraphicsSceneDragLeave);
d->cloneDragDropEvent(&dragLeave, event);
d->sendDragDropEvent(d->dragDropItem, &dragLeave);
d->dragDropItem = 0;
}
// Propagate
event->setDropAction(Qt::IgnoreAction);
}
}
/*!
This event handler, for event \a event, can be reimplemented in a subclass
to receive drag leave events for the scene.
\sa QGraphicsItem::dragLeaveEvent(), dragEnterEvent(), dragMoveEvent(),
dropEvent()
*/
void QGraphicsScene::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
{
Q_D(QGraphicsScene);
if (d->dragDropItem) {
// Leave the last drag drop item
d->sendDragDropEvent(d->dragDropItem, event);
d->dragDropItem = 0;
}
}
/*!
This event handler, for event \a event, can be reimplemented in a subclass
to receive drop events for the scene.
\sa QGraphicsItem::dropEvent(), dragEnterEvent(), dragMoveEvent(),
dragLeaveEvent()
*/
void QGraphicsScene::dropEvent(QGraphicsSceneDragDropEvent *event)
{
Q_UNUSED(event);
Q_D(QGraphicsScene);
if (d->dragDropItem) {
// Drop on the last drag drop item
d->sendDragDropEvent(d->dragDropItem, event);
d->dragDropItem = 0;
}
}
/*!
This event handler, for event \a focusEvent, can be reimplemented in a
subclass to receive focus in events.
The default implementation sets focus on the scene, and then on the last
focus item.
\sa QGraphicsItem::focusOutEvent()
*/
void QGraphicsScene::focusInEvent(QFocusEvent *focusEvent)
{
Q_D(QGraphicsScene);
d->hasFocus = true;
switch (focusEvent->reason()) {
case Qt::TabFocusReason:
if (!focusNextPrevChild(true))
focusEvent->ignore();
break;
case Qt::BacktabFocusReason:
if (!focusNextPrevChild(false))
focusEvent->ignore();
break;
default:
if (d->lastFocusItem) {
// Set focus on the last focus item
setFocusItem(d->lastFocusItem, focusEvent->reason());
}
break;
}
}
/*!
This event handler, for event \a focusEvent, can be reimplemented in a
subclass to receive focus out events.
The default implementation removes focus from any focus item, then removes
focus from the scene.
\sa QGraphicsItem::focusInEvent()
*/
void QGraphicsScene::focusOutEvent(QFocusEvent *focusEvent)
{
Q_D(QGraphicsScene);
d->hasFocus = false;
setFocusItem(0, focusEvent->reason());
// Remove all popups when the scene loses focus.
if (!d->popupWidgets.isEmpty())
d->removePopup(d->popupWidgets.first());
}
/*!
This event handler, for event \a helpEvent, can be
reimplemented in a subclass to receive help events. The events
are of type QEvent::ToolTip, which are created when a tooltip is
requested.
The default implementation shows the tooltip of the topmost
item, i.e., the item with the highest z-value, at the mouse
cursor position. If no item has a tooltip set, this function
does nothing.
\sa QGraphicsItem::toolTip(), QGraphicsSceneHelpEvent
*/
void QGraphicsScene::helpEvent(QGraphicsSceneHelpEvent *helpEvent)
{
#ifdef QT_NO_TOOLTIP
Q_UNUSED(helpEvent);
#else
// Find the first item that does tooltips
Q_D(QGraphicsScene);
QList<QGraphicsItem *> itemsAtPos = d->itemsAtPosition(helpEvent->screenPos(),
helpEvent->scenePos(),
helpEvent->widget());
QGraphicsItem *toolTipItem = 0;
for (int i = 0; i < itemsAtPos.size(); ++i) {
QGraphicsItem *tmp = itemsAtPos.at(i);
if (!tmp->toolTip().isEmpty()) {
toolTipItem = tmp;
break;
}
}
// Show or hide the tooltip
QString text;
QPoint point;
if (toolTipItem && !toolTipItem->toolTip().isEmpty()) {
text = toolTipItem->toolTip();
point = helpEvent->screenPos();
}
QToolTip::showText(point, text);
helpEvent->setAccepted(!text.isEmpty());
#endif
}
bool QGraphicsScenePrivate::itemAcceptsHoverEvents_helper(const QGraphicsItem *item) const
{
return item->acceptHoverEvents()
|| (item->isWidget() && static_cast<const QGraphicsWidget *>(item)->d_func()->hasDecoration());
}
/*!
This event handler, for event \a hoverEvent, can be reimplemented in a
subclass to receive hover enter events. The default implementation
forwards the event to the topmost item that accepts hover events at the
scene position from the event.
\sa QGraphicsItem::hoverEvent(), QGraphicsItem::setAcceptHoverEvents()
*/
bool QGraphicsScenePrivate::dispatchHoverEvent(QGraphicsSceneHoverEvent *hoverEvent)
{
if (allItemsIgnoreHoverEvents)
return false;
// Find the first item that accepts hover events, reusing earlier
// calculated data is possible.
if (cachedItemsUnderMouse.isEmpty()) {
cachedItemsUnderMouse = itemsAtPosition(hoverEvent->screenPos(),
hoverEvent->scenePos(),
hoverEvent->widget());
}
QGraphicsItem *item = 0;
for (int i = 0; i < cachedItemsUnderMouse.size(); ++i) {
QGraphicsItem *tmp = cachedItemsUnderMouse.at(i);
if (itemAcceptsHoverEvents_helper(tmp)) {
item = tmp;
break;
}
}
// Find the common ancestor item for the new topmost hoverItem and the
// last item in the hoverItem list.
QGraphicsItem *commonAncestorItem = (item && !hoverItems.isEmpty()) ? item->commonAncestorItem(hoverItems.last()) : 0;
while (commonAncestorItem && !itemAcceptsHoverEvents_helper(commonAncestorItem))
commonAncestorItem = commonAncestorItem->parentItem();
if (commonAncestorItem && commonAncestorItem->window() != item->window()) {
// The common ancestor isn't in the same window as the two hovered
// items.
commonAncestorItem = 0;
}
// Check if the common ancestor item is known.
int index = commonAncestorItem ? hoverItems.indexOf(commonAncestorItem) : -1;
// Send hover leaves to any existing hovered children of the common
// ancestor item.
for (int i = hoverItems.size() - 1; i > index; --i) {
QGraphicsItem *lastItem = hoverItems.takeLast();
if (itemAcceptsHoverEvents_helper(lastItem))
sendHoverEvent(QEvent::GraphicsSceneHoverLeave, lastItem, hoverEvent);
}
// Item is a child of a known item. Generate enter events for the
// missing links.
QList<QGraphicsItem *> parents;
QGraphicsItem *parent = item;
while (parent && parent != commonAncestorItem) {
parents.prepend(parent);
if (parent->isWindow()) {
// Stop at the window - we don't deliver beyond this point.
break;
}
parent = parent->parentItem();
}
for (int i = 0; i < parents.size(); ++i) {
parent = parents.at(i);
hoverItems << parent;
if (itemAcceptsHoverEvents_helper(parent))
sendHoverEvent(QEvent::GraphicsSceneHoverEnter, parent, hoverEvent);
}
// Generate a move event for the item itself
if (item && !hoverItems.isEmpty() && item == hoverItems.last()) {
sendHoverEvent(QEvent::GraphicsSceneHoverMove, item, hoverEvent);
return true;
}
return false;
}
/*!
\internal
Handles all actions necessary to clean up the scene when the mouse leaves
the view.
*/
void QGraphicsScenePrivate::leaveScene()
{
Q_Q(QGraphicsScene);
#ifndef QT_NO_TOOLTIP
// Remove any tooltips
QToolTip::showText(QPoint(), QString());
#endif
// Send HoverLeave events to all existing hover items, topmost first.
QGraphicsView *senderWidget = qobject_cast<QGraphicsView *>(q->sender());
QGraphicsSceneHoverEvent hoverEvent;
hoverEvent.setWidget(senderWidget);
if (senderWidget) {
QPoint cursorPos = QCursor::pos();
hoverEvent.setScenePos(senderWidget->mapToScene(senderWidget->mapFromGlobal(cursorPos)));
hoverEvent.setLastScenePos(hoverEvent.scenePos());
hoverEvent.setScreenPos(cursorPos);
hoverEvent.setLastScreenPos(hoverEvent.screenPos());
}
while (!hoverItems.isEmpty()) {
QGraphicsItem *lastItem = hoverItems.takeLast();
if (lastItem->acceptHoverEvents()
|| (lastItem->isWidget() && static_cast<QGraphicsWidget*>(lastItem)->d_func()->hasDecoration()))
sendHoverEvent(QEvent::GraphicsSceneHoverLeave, lastItem, &hoverEvent);
}
}
/*!
This event handler, for event \a keyEvent, can be reimplemented in a
subclass to receive keypress events. The default implementation forwards
the event to current focus item.
\sa QGraphicsItem::keyPressEvent(), focusItem()
*/
void QGraphicsScene::keyPressEvent(QKeyEvent *keyEvent)
{
// ### Merge this function with keyReleaseEvent; they are identical
// ### (except this comment).
Q_D(QGraphicsScene);
QGraphicsItem *item = !d->keyboardGrabberItems.isEmpty() ? d->keyboardGrabberItems.last() : 0;
if (!item)
item = focusItem();
if (item) {
QGraphicsItem *p = item;
do {
// Accept the event by default
keyEvent->accept();
// Send it; QGraphicsItem::keyPressEvent ignores it. If the event
// is filtered out, stop propagating it.
if (!d->sendEvent(p, keyEvent))
break;
} while (!keyEvent->isAccepted() && !p->isWindow() && (p = p->parentItem()));
} else {
keyEvent->ignore();
}
}
/*!
This event handler, for event \a keyEvent, can be reimplemented in a
subclass to receive key release events. The default implementation
forwards the event to current focus item.
\sa QGraphicsItem::keyReleaseEvent(), focusItem()
*/
void QGraphicsScene::keyReleaseEvent(QKeyEvent *keyEvent)
{
// ### Merge this function with keyPressEvent; they are identical (except
// ### this comment).
Q_D(QGraphicsScene);
QGraphicsItem *item = !d->keyboardGrabberItems.isEmpty() ? d->keyboardGrabberItems.last() : 0;
if (!item)
item = focusItem();
if (item) {
QGraphicsItem *p = item;
do {
// Accept the event by default
keyEvent->accept();
// Send it; QGraphicsItem::keyPressEvent ignores it. If the event
// is filtered out, stop propagating it.
if (!d->sendEvent(p, keyEvent))
break;
} while (!keyEvent->isAccepted() && !p->isWindow() && (p = p->parentItem()));
} else {
keyEvent->ignore();
}
}
/*!
This event handler, for event \a mouseEvent, can be reimplemented
in a subclass to receive mouse press events for the scene.
The default implementation depends on the state of the scene. If
there is a mouse grabber item, then the event is sent to the mouse
grabber. Otherwise, it is forwarded to the topmost item that
accepts mouse events at the scene position from the event, and
that item promptly becomes the mouse grabber item.
If there is no item at the given position on the scene, the
selection area is reset, any focus item loses its input focus, and
the event is then ignored.
\sa QGraphicsItem::mousePressEvent(),
QGraphicsItem::setAcceptedMouseButtons()
*/
void QGraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_D(QGraphicsScene);
d->mousePressEventHandler(mouseEvent);
}
/*!
This event handler, for event \a mouseEvent, can be reimplemented
in a subclass to receive mouse move events for the scene.
The default implementation depends on the mouse grabber state. If there is
a mouse grabber item, the event is sent to the mouse grabber. If there
are any items that accept hover events at the current position, the event
is translated into a hover event and accepted; otherwise it's ignored.
\sa QGraphicsItem::mousePressEvent(), QGraphicsItem::mouseReleaseEvent(),
QGraphicsItem::mouseDoubleClickEvent(), QGraphicsItem::setAcceptedMouseButtons()
*/
void QGraphicsScene::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_D(QGraphicsScene);
if (d->mouseGrabberItems.isEmpty()) {
if (mouseEvent->buttons())
return;
QGraphicsSceneHoverEvent hover;
_q_hoverFromMouseEvent(&hover, mouseEvent);
mouseEvent->setAccepted(d->dispatchHoverEvent(&hover));
return;
}
// Forward the event to the mouse grabber
d->sendMouseEvent(mouseEvent);
mouseEvent->accept();
}
/*!
This event handler, for event \a mouseEvent, can be reimplemented
in a subclass to receive mouse release events for the scene.
The default implementation depends on the mouse grabber state. If
there is no mouse grabber, the event is ignored. Otherwise, if
there is a mouse grabber item, the event is sent to the mouse
grabber. If this mouse release represents the last pressed button
on the mouse, the mouse grabber item then loses the mouse grab.
\sa QGraphicsItem::mousePressEvent(), QGraphicsItem::mouseMoveEvent(),
QGraphicsItem::mouseDoubleClickEvent(), QGraphicsItem::setAcceptedMouseButtons()
*/
void QGraphicsScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_D(QGraphicsScene);
if (d->mouseGrabberItems.isEmpty()) {
mouseEvent->ignore();
return;
}
// Forward the event to the mouse grabber
d->sendMouseEvent(mouseEvent);
mouseEvent->accept();
// Reset the mouse grabber when the last mouse button has been released.
if (!mouseEvent->buttons()) {
if (!d->mouseGrabberItems.isEmpty()) {
d->lastMouseGrabberItem = d->mouseGrabberItems.last();
if (d->lastMouseGrabberItemHasImplicitMouseGrab)
d->mouseGrabberItems.last()->ungrabMouse();
} else {
d->lastMouseGrabberItem = 0;
}
// Generate a hoverevent
QGraphicsSceneHoverEvent hoverEvent;
_q_hoverFromMouseEvent(&hoverEvent, mouseEvent);
d->dispatchHoverEvent(&hoverEvent);
}
}
/*!
This event handler, for event \a mouseEvent, can be reimplemented
in a subclass to receive mouse doubleclick events for the scene.
If someone doubleclicks on the scene, the scene will first receive
a mouse press event, followed by a release event (i.e., a click),
then a doubleclick event, and finally a release event. If the
doubleclick event is delivered to a different item than the one
that received the first press and release, it will be delivered as
a press event. However, tripleclick events are not delivered as
doubleclick events in this case.
The default implementation is similar to mousePressEvent().
\sa QGraphicsItem::mousePressEvent(), QGraphicsItem::mouseMoveEvent(),
QGraphicsItem::mouseReleaseEvent(), QGraphicsItem::setAcceptedMouseButtons()
*/
void QGraphicsScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_D(QGraphicsScene);
d->mousePressEventHandler(mouseEvent);
}
/*!
This event handler, for event \a wheelEvent, can be reimplemented in a
subclass to receive mouse wheel events for the scene.
By default, the event is delivered to the topmost visible item under the
cursor. If ignored, the event propagates to the item beneath, and again
until the event is accepted, or it reaches the scene. If no items accept
the event, it is ignored.
\sa QGraphicsItem::wheelEvent()
*/
void QGraphicsScene::wheelEvent(QGraphicsSceneWheelEvent *wheelEvent)
{
Q_D(QGraphicsScene);
QList<QGraphicsItem *> wheelCandidates = d->itemsAtPosition(wheelEvent->screenPos(),
wheelEvent->scenePos(),
wheelEvent->widget());
bool hasSetFocus = false;
foreach (QGraphicsItem *item, wheelCandidates) {
if (!hasSetFocus && item->isEnabled() && (item->flags() & QGraphicsItem::ItemIsFocusable)) {
if (item->isWidget() && static_cast<QGraphicsWidget *>(item)->focusPolicy() == Qt::WheelFocus) {
hasSetFocus = true;
if (item != focusItem())
setFocusItem(item, Qt::MouseFocusReason);
}
}
wheelEvent->setPos(item->d_ptr->genericMapFromScene(wheelEvent->scenePos(),
wheelEvent->widget()));
wheelEvent->accept();
bool isWindow = item->isWindow();
d->sendEvent(item, wheelEvent);
if (isWindow || wheelEvent->isAccepted())
break;
}
}
/*!
This event handler, for event \a event, can be reimplemented in a
subclass to receive input method events for the scene.
The default implementation forwards the event to the focusItem().
If no item currently has focus, this function does nothing.
\sa QGraphicsItem::inputMethodEvent()
*/
void QGraphicsScene::inputMethodEvent(QInputMethodEvent *event)
{
Q_D(QGraphicsScene);
if (!d->focusItem)
return;
d->sendEvent(d->focusItem, event);
}
/*!
Draws the background of the scene using \a painter, before any items and
the foreground are drawn. Reimplement this function to provide a custom
background for the scene.
All painting is done in \e scene coordinates. The \a rect
parameter is the exposed rectangle.
If all you want is to define a color, texture, or gradient for the
background, you can call setBackgroundBrush() instead.
\sa drawForeground(), drawItems()
*/
void QGraphicsScene::drawBackground(QPainter *painter, const QRectF &rect)
{
Q_D(QGraphicsScene);
if (d->backgroundBrush.style() != Qt::NoBrush) {
if (d->painterStateProtection)
painter->save();
painter->setBrushOrigin(0, 0);
painter->fillRect(rect, backgroundBrush());
if (d->painterStateProtection)
painter->restore();
}
}
/*!
Draws the foreground of the scene using \a painter, after the background
and all items have been drawn. Reimplement this function to provide a
custom foreground for the scene.
All painting is done in \e scene coordinates. The \a rect
parameter is the exposed rectangle.
If all you want is to define a color, texture or gradient for the
foreground, you can call setForegroundBrush() instead.
\sa drawBackground(), drawItems()
*/
void QGraphicsScene::drawForeground(QPainter *painter, const QRectF &rect)
{
Q_D(QGraphicsScene);
if (d->foregroundBrush.style() != Qt::NoBrush) {
if (d->painterStateProtection)
painter->save();
painter->setBrushOrigin(0, 0);
painter->fillRect(rect, foregroundBrush());
if (d->painterStateProtection)
painter->restore();
}
}
static void _q_paintItem(QGraphicsItem *item, QPainter *painter,
const QStyleOptionGraphicsItem *option, QWidget *widget,
bool useWindowOpacity, bool painterStateProtection)
{
if (!item->isWidget()) {
item->paint(painter, option, widget);
return;
}
QGraphicsWidget *widgetItem = static_cast<QGraphicsWidget *>(item);
QGraphicsProxyWidget *proxy = qobject_cast<QGraphicsProxyWidget *>(widgetItem);
const qreal windowOpacity = (proxy && proxy->widget() && useWindowOpacity)
? proxy->widget()->windowOpacity() : 1.0;
const qreal oldPainterOpacity = painter->opacity();
if (qFuzzyIsNull(windowOpacity))
return;
// Set new painter opacity.
if (windowOpacity < 1.0)
painter->setOpacity(oldPainterOpacity * windowOpacity);
// set layoutdirection on the painter
Qt::LayoutDirection oldLayoutDirection = painter->layoutDirection();
painter->setLayoutDirection(widgetItem->layoutDirection());
if (widgetItem->isWindow() && widgetItem->windowType() != Qt::Popup && widgetItem->windowType() != Qt::ToolTip
&& !(widgetItem->windowFlags() & Qt::FramelessWindowHint)) {
if (painterStateProtection)
painter->save();
widgetItem->paintWindowFrame(painter, option, widget);
if (painterStateProtection)
painter->restore();
}
widgetItem->paint(painter, option, widget);
// Restore layoutdirection on the painter.
painter->setLayoutDirection(oldLayoutDirection);
// Restore painter opacity.
if (windowOpacity < 1.0)
painter->setOpacity(oldPainterOpacity);
}
static void _q_paintIntoCache(QPixmap *pix, QGraphicsItem *item, const QRegion &pixmapExposed,
const QTransform &itemToPixmap, QPainter::RenderHints renderHints,
const QStyleOptionGraphicsItem *option, bool painterStateProtection)
{
QPixmap subPix;
QPainter pixmapPainter;
QRect br = pixmapExposed.boundingRect();
// Don't use subpixmap if we get a full update.
if (pixmapExposed.isEmpty() || (pixmapExposed.numRects() == 1 && br.contains(pix->rect()))) {
pix->fill(Qt::transparent);
pixmapPainter.begin(pix);
} else {
subPix = QPixmap(br.size());
subPix.fill(Qt::transparent);
pixmapPainter.begin(&subPix);
pixmapPainter.translate(-br.topLeft());
if (!pixmapExposed.isEmpty()) {
// Applied to subPix; paint is adjusted to the coordinate space is
// correct.
pixmapPainter.setClipRegion(pixmapExposed);
}
}
pixmapPainter.setRenderHints(pixmapPainter.renderHints(), false);
pixmapPainter.setRenderHints(renderHints, true);
pixmapPainter.setWorldTransform(itemToPixmap, true);
// Render.
_q_paintItem(item, &pixmapPainter, option, 0, false, painterStateProtection);
pixmapPainter.end();
if (!subPix.isNull()) {
// Blit the subpixmap into the main pixmap.
pixmapPainter.begin(pix);
pixmapPainter.setCompositionMode(QPainter::CompositionMode_Source);
pixmapPainter.setClipRegion(pixmapExposed);
pixmapPainter.drawPixmap(br.topLeft(), subPix);
pixmapPainter.end();
}
}
/*!
\internal
Draws items directly, or using cache.
*/
void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painter,
const QStyleOptionGraphicsItem *option, QWidget *widget,
bool painterStateProtection)
{
QGraphicsItemPrivate *itemd = item->d_ptr;
QGraphicsItem::CacheMode cacheMode = QGraphicsItem::CacheMode(itemd->cacheMode);
// Render directly, using no cache.
if (cacheMode == QGraphicsItem::NoCache
#ifdef Q_WS_X11
|| !X11->use_xrender
#endif
) {
_q_paintItem(static_cast<QGraphicsWidget *>(item), painter, option, widget, true, painterStateProtection);
return;
}
const qreal oldPainterOpacity = painter->opacity();
qreal newPainterOpacity = oldPainterOpacity;
QGraphicsProxyWidget *proxy = item->isWidget() ? qobject_cast<QGraphicsProxyWidget *>(static_cast<QGraphicsWidget *>(item)) : 0;
if (proxy && proxy->widget()) {
const qreal windowOpacity = proxy->widget()->windowOpacity();
if (windowOpacity < 1.0)
newPainterOpacity *= windowOpacity;
}
// Item's (local) bounding rect
QRectF brect = item->boundingRect();
QRectF adjustedBrect(brect);
_q_adjustRect(&adjustedBrect);
if (adjustedBrect.isEmpty())
return;
// Fetch the off-screen transparent buffer and exposed area info.
QPixmapCache::Key pixmapKey;
QPixmap pix;
bool pixmapFound;
QGraphicsItemCache *itemCache = itemd->extraItemCache();
if (cacheMode == QGraphicsItem::ItemCoordinateCache) {
if (itemCache->boundingRect != brect.toRect()) {
itemCache->boundingRect = brect.toRect();
itemCache->allExposed = true;
itemCache->exposed.clear();
}
pixmapKey = itemCache->key;
} else {
pixmapKey = itemCache->deviceData.value(widget).key;
}
// Find pixmap in cache.
pixmapFound = QPixmapCache::find(pixmapKey, &pix);
// Render using item coordinate cache mode.
if (cacheMode == QGraphicsItem::ItemCoordinateCache) {
QSize pixmapSize;
bool fixedCacheSize = false;
QRectF brectAligned = brect.toAlignedRect();
if ((fixedCacheSize = itemCache->fixedSize.isValid())) {
pixmapSize = itemCache->fixedSize;
} else {
pixmapSize = brectAligned.size().toSize();
}
// Create or recreate the pixmap.
int adjust = itemCache->fixedSize.isValid() ? 0 : 2;
QSize adjustSize(adjust*2, adjust*2);
QRectF br = brectAligned.adjusted(-adjust, -adjust, adjust, adjust);
if (pix.isNull() || (!fixedCacheSize && (pixmapSize + adjustSize) != pix.size())) {
pix = QPixmap(pixmapSize + adjustSize);
itemCache->exposed.clear();
itemCache->allExposed = true;
}
// Redraw any newly exposed areas.
if (itemCache->allExposed || !itemCache->exposed.isEmpty()) {
//We know that we will modify the pixmap, removing it from the cache
//will detach the one we have and avoid a deep copy
if (pixmapFound)
QPixmapCache::remove(pixmapKey);
// Fit the item's bounding rect into the pixmap's coordinates.
QTransform itemToPixmap;
if (fixedCacheSize) {
const QPointF scale(pixmapSize.width() / brect.width(), pixmapSize.height() / brect.height());
itemToPixmap.scale(scale.x(), scale.y());
}
itemToPixmap.translate(-br.x(), -br.y());
// Generate the item's exposedRect and map its list of expose
// rects to device coordinates.
styleOptionTmp = *option;
QRegion pixmapExposed;
QRectF exposedRect;
if (!itemCache->allExposed) {
for (int i = 0; i < itemCache->exposed.size(); ++i) {
QRectF r = itemCache->exposed.at(i);
exposedRect |= r;
pixmapExposed += itemToPixmap.mapRect(r).toAlignedRect();
}
} else {
exposedRect = brect;
}
styleOptionTmp.exposedRect = exposedRect;
// Render.
_q_paintIntoCache(&pix, item, pixmapExposed, itemToPixmap, painter->renderHints(),
&styleOptionTmp, painterStateProtection);
// insert this pixmap into the cache.
itemCache->key = QPixmapCache::insert(pix);
// Reset expose data.
itemCache->allExposed = false;
itemCache->exposed.clear();
}
// Redraw the exposed area using the transformed painter. Depending on
// the hardware, this may be a server-side operation, or an expensive
// qpixmap-image-transform-pixmap roundtrip.
if (newPainterOpacity != oldPainterOpacity) {
painter->setOpacity(newPainterOpacity);
painter->drawPixmap(br, pix, QRectF(QPointF(), pix.size()));
painter->setOpacity(oldPainterOpacity);
} else {
painter->drawPixmap(br, pix, QRectF(QPointF(), pix.size()));
}
return;
}
// Render using device coordinate cache mode.
if (cacheMode == QGraphicsItem::DeviceCoordinateCache) {
// Find the item's bounds in device coordinates.
QRectF deviceBounds = painter->worldTransform().mapRect(brect);
QRect deviceRect = deviceBounds.toRect().adjusted(-1, -1, 1, 1);
if (deviceRect.isEmpty())
return;
QRect viewRect = widget ? widget->rect() : QRect();
if (widget && !viewRect.intersects(deviceRect))
return;
// Resort to direct rendering if the device rect exceeds the
// (optional) maximum bounds. (QGraphicsSvgItem uses this).
QSize maximumCacheSize =
itemd->extra(QGraphicsItemPrivate::ExtraMaxDeviceCoordCacheSize).toSize();
if (!maximumCacheSize.isEmpty()
&& (deviceRect.width() > maximumCacheSize.width()
|| deviceRect.height() > maximumCacheSize.height())) {
_q_paintItem(static_cast<QGraphicsWidget *>(item), painter, option, widget,
oldPainterOpacity != newPainterOpacity, painterStateProtection);
return;
}
// Create or reuse offscreen pixmap, possibly scroll/blit from the old one.
bool pixModified = false;
QGraphicsItemCache::DeviceData *deviceData = &itemCache->deviceData[widget];
bool invertable = true;
QTransform diff = deviceData->lastTransform.inverted(&invertable);
if (invertable)
diff *= painter->worldTransform();
deviceData->lastTransform = painter->worldTransform();
if (!invertable || diff.type() > QTransform::TxTranslate) {
pixModified = true;
itemCache->allExposed = true;
itemCache->exposed.clear();
pix = QPixmap();
}
// ### This is a pretty bad way to determine when to start partial
// exposure for DeviceCoordinateCache but it's the least intrusive
// approach for now.
#if 0
// Only if the device rect isn't fully contained.
bool allowPartialCacheExposure = !viewRect.contains(deviceRect);
#else
// Only if deviceRect is 20% taller or wider than the desktop.
QRect desktopRect = QApplication::desktop()->availableGeometry(widget);
bool allowPartialCacheExposure = (desktopRect.width() * 1.2 < deviceRect.width()
|| desktopRect.height() * 1.2 < deviceRect.height());
#endif
QRegion scrollExposure;
if (deviceData->cacheIndent != QPoint() || allowPartialCacheExposure) {
// Part of pixmap is drawn. Either device contains viewrect (big
// item covers whole screen) or parts of device are outside the
// viewport. In either case the device rect must be the intersect
// between the two.
int dx = deviceRect.left() < viewRect.left() ? viewRect.left() - deviceRect.left() : 0;
int dy = deviceRect.top() < viewRect.top() ? viewRect.top() - deviceRect.top() : 0;
QPoint newCacheIndent(dx, dy);
deviceRect &= viewRect;
if (pix.isNull()) {
deviceData->cacheIndent = QPoint();
itemCache->allExposed = true;
itemCache->exposed.clear();
pixModified = true;
}
// Copy / "scroll" the old pixmap onto the new ole and calculate
// scrolled exposure.
if (newCacheIndent != deviceData->cacheIndent || deviceRect.size() != pix.size()) {
QPoint diff = newCacheIndent - deviceData->cacheIndent;
QPixmap newPix(deviceRect.size());
// ### Investigate removing this fill (test with Plasma and
// graphicssystem raster).
newPix.fill(Qt::transparent);
if (!pix.isNull()) {
QPainter newPixPainter(&newPix);
newPixPainter.drawPixmap(-diff, pix);
newPixPainter.end();
}
QRegion exposed;
exposed += newPix.rect();
if (!pix.isNull())
exposed -= QRect(-diff, pix.size());
scrollExposure = exposed;
pix = newPix;
pixModified = true;
}
deviceData->cacheIndent = newCacheIndent;
} else {
// Full pixmap is drawn.
deviceData->cacheIndent = QPoint();
// Auto-adjust the pixmap size.
if (deviceRect.size() != pix.size()) {
// exposed needs to cover the whole pixmap
pix = QPixmap(deviceRect.size());
pixModified = true;
itemCache->allExposed = true;
itemCache->exposed.clear();
}
}
// Check for newly invalidated areas.
if (itemCache->allExposed || !itemCache->exposed.isEmpty() || !scrollExposure.isEmpty()) {
//We know that we will modify the pixmap, removing it from the cache
//will detach the one we have and avoid a deep copy
if (pixmapFound)
QPixmapCache::remove(pixmapKey);
// Construct an item-to-pixmap transform.
QPointF p = deviceRect.topLeft();
QTransform itemToPixmap = painter->worldTransform();
if (!p.isNull())
itemToPixmap *= QTransform::fromTranslate(-p.x(), -p.y());
// Map the item's logical expose to pixmap coordinates.
QRegion pixmapExposed = scrollExposure;
if (!itemCache->allExposed) {
const QVector<QRectF> &exposed = itemCache->exposed;
for (int i = 0; i < exposed.size(); ++i)
pixmapExposed += itemToPixmap.mapRect(exposed.at(i)).toRect().adjusted(-1, -1, 1, 1);
}
// Calculate the style option's exposedRect.
QRectF br;
if (itemCache->allExposed) {
br = item->boundingRect();
} else {
const QVector<QRectF> &exposed = itemCache->exposed;
for (int i = 0; i < exposed.size(); ++i)
br |= exposed.at(i);
QTransform pixmapToItem = itemToPixmap.inverted();
foreach (QRect r, scrollExposure.rects())
br |= pixmapToItem.mapRect(r);
}
styleOptionTmp = *option;
styleOptionTmp.exposedRect = br.adjusted(-1, -1, 1, 1);
// Render the exposed areas.
_q_paintIntoCache(&pix, item, pixmapExposed, itemToPixmap, painter->renderHints(),
&styleOptionTmp, painterStateProtection);
// Reset expose data.
pixModified = true;
itemCache->allExposed = false;
itemCache->exposed.clear();
}
if (pixModified) {
// Insert this pixmap into the cache.
deviceData->key = QPixmapCache::insert(pix);
}
// Redraw the exposed area using an untransformed painter. This
// effectively becomes a bitblit that does not transform the cache.
QTransform restoreTransform = painter->worldTransform();
painter->setWorldTransform(QTransform());
if (newPainterOpacity != oldPainterOpacity) {
painter->setOpacity(newPainterOpacity);
painter->drawPixmap(deviceRect.topLeft(), pix);
painter->setOpacity(oldPainterOpacity);
} else {
painter->drawPixmap(deviceRect.topLeft(), pix);
}
painter->setWorldTransform(restoreTransform);
return;
}
}
void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter,
const QTransform &viewTransform,
QRegion *exposedRegion, QWidget *widget,
QList<QGraphicsItem *> *topLevelItems,
qreal parentOpacity)
{
// Calculate opacity.
qreal opacity;
bool invisibleButChildIgnoresParentOpacity = false;
if (item) {
if (!item->d_ptr->visible)
return;
opacity = item->d_ptr->combineOpacityFromParent(parentOpacity);
if (opacity == 0.0 && !(item->d_ptr->flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)) {
invisibleButChildIgnoresParentOpacity = !item->d_ptr->childrenCombineOpacity();
if (!invisibleButChildIgnoresParentOpacity)
return;
}
} else {
opacity = parentOpacity;
}
// Item is invisible.
bool hasContents = item && !(item->d_ptr->flags & QGraphicsItem::ItemHasNoContents);
bool invisible = !hasContents || invisibleButChildIgnoresParentOpacity;
// Calculate the full transform for this item.
bool wasDirtyParentSceneTransform = false;
bool dontDrawItem = true;
QTransform transform;
if (item) {
if (item->d_ptr->itemIsUntransformable()) {
transform = item->deviceTransform(viewTransform);
} else {
if (item->d_ptr->dirtySceneTransform) {
item->d_ptr->sceneTransform = item->d_ptr->parent ? item->d_ptr->parent->d_ptr->sceneTransform
: QTransform();
item->d_ptr->combineTransformFromParent(&item->d_ptr->sceneTransform);
item->d_ptr->dirtySceneTransform = 0;
wasDirtyParentSceneTransform = true;
}
transform = item->d_ptr->sceneTransform;
transform *= viewTransform;
}
if (!invisible) {
QRectF brect = item->boundingRect();
// ### This does not take the clip into account.
_q_adjustRect(&brect);
QRect viewBoundingRect = transform.mapRect(brect).toRect();
item->d_ptr->paintedViewBoundingRects.insert(widget, viewBoundingRect);
viewBoundingRect.adjust(-1, -1, 1, 1);
if (exposedRegion)
dontDrawItem = !exposedRegion->intersects(viewBoundingRect);
else
dontDrawItem = viewBoundingRect.isEmpty();
}
}
// Find and sort children.
QList<QGraphicsItem *> tmp;
QList<QGraphicsItem *> *children = 0;
if (item) {
children = &item->d_ptr->children;
} else if (topLevelItems) {
children = topLevelItems;
} else if (indexMethod == QGraphicsScene::NoIndex || !exposedRegion) {
children = &this->topLevelItems;
} else {
QRectF sceneRect = viewTransform.inverted().mapRect(QRectF(exposedRegion->boundingRect().adjusted(-1, -1, 1, 1)));
if (!largestUntransformableItem.isEmpty()) {
// ### Nuke this when we move the indexing code into a separate
// class. All the largestUntransformableItem code should then go
// away, and the estimate function should return untransformable
// items as well.
QRectF untr = largestUntransformableItem;
QRectF ltri = viewTransform.inverted().mapRect(untr);
ltri.adjust(-untr.width(), -untr.height(), untr.width(), untr.height());
sceneRect.adjust(-ltri.width(), -ltri.height(), ltri.width(), ltri.height());
}
tmp = estimateItemsInRect(sceneRect);
QList<QGraphicsItem *> tli;
for (int i = 0; i < tmp.size(); ++i)
tmp.at(i)->topLevelItem()->d_ptr->itemDiscovered = 1;
// Sort if the toplevel list is unsorted.
if (needSortTopLevelItems) {
needSortTopLevelItems = false;
qStableSort(this->topLevelItems.begin(),
this->topLevelItems.end(), qt_notclosestLeaf);
}
for (int i = 0; i < this->topLevelItems.size(); ++i) {
// ### Investigate smarter ways. Looping through all top level
// items is not optimal. If the BSP tree is to have maximum
// effect, it should be possible to sort the subset of items
// quickly. We must use this approach for now, as it's the only
// current way to keep the stable sorting order (insertion order).
QGraphicsItem *item = this->topLevelItems.at(i);
if (item->d_ptr->itemDiscovered) {
item->d_ptr->itemDiscovered = 0;
tli << item;
}
}
tmp = tli;
children = &tmp;
}
bool childClip = (item && (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape));
bool dontDrawChildren = item && hasContents && dontDrawItem && childClip;
childClip &= !dontDrawChildren && !children->isEmpty();
if (item && invisible)
dontDrawItem = true;
// Clip children.
if (childClip) {
painter->save();
painter->setWorldTransform(transform);
painter->setClipPath(item->shape(), Qt::IntersectClip);
}
if (!dontDrawChildren) {
if (item && item->d_ptr->needSortChildren) {
item->d_ptr->needSortChildren = 0;
qStableSort(children->begin(), children->end(), qt_notclosestLeaf);
} else if (!item && needSortTopLevelItems && children != &tmp) {
needSortTopLevelItems = false;
qStableSort(children->begin(), children->end(), qt_notclosestLeaf);
}
}
// Draw children behind
int i = 0;
if (!dontDrawChildren) {
// ### Don't visit children that don't ignore parent opacity if this
// item is invisible.
for (i = 0; i < children->size(); ++i) {
QGraphicsItem *child = children->at(i);
if (wasDirtyParentSceneTransform)
child->d_ptr->dirtySceneTransform = 1;
if (!(child->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent))
break;
drawSubtreeRecursive(child, painter, viewTransform, exposedRegion, widget,
0, opacity);
}
}
// Draw item
if (!dontDrawItem) {
item->d_ptr->initStyleOption(&styleOptionTmp, transform, exposedRegion ? *exposedRegion : QRegion(), exposedRegion == 0);
bool clipsToShape = (item->d_ptr->flags & QGraphicsItem::ItemClipsToShape);
bool savePainter = clipsToShape || painterStateProtection;
if (savePainter)
painter->save();
if (!childClip)
painter->setWorldTransform(transform);
if (clipsToShape)
painter->setClipPath(item->shape(), Qt::IntersectClip);
painter->setOpacity(opacity);
drawItemHelper(item, painter, &styleOptionTmp, widget, painterStateProtection);
if (savePainter)
painter->restore();
}
// Draw children in front
if (!dontDrawChildren) {
// ### Don't visit children that don't ignore parent opacity if this
// item is invisible.
for (; i < children->size(); ++i) {
QGraphicsItem *child = children->at(i);
if (wasDirtyParentSceneTransform)
child->d_ptr->dirtySceneTransform = 1;
drawSubtreeRecursive(child, painter, viewTransform, exposedRegion,
widget, 0, opacity);
}
} else if (wasDirtyParentSceneTransform) {
item->d_ptr->invalidateChildrenSceneTransform();
}
// Restore child clip
if (childClip)
painter->restore();
}
void QGraphicsScenePrivate::markDirty(QGraphicsItem *item, const QRectF &rect, bool invalidateChildren,
bool maybeDirtyClipPath, bool force, bool ignoreOpacity,
bool removingItemFromScene)
{
Q_ASSERT(item);
if (updateAll)
return;
if (item->d_ptr->discardUpdateRequest(/*ignoreClipping=*/maybeDirtyClipPath,
/*ignoreVisibleBit=*/force,
/*ignoreDirtyBit=*/removingItemFromScene || invalidateChildren,
/*ignoreOpacity=*/ignoreOpacity)) {
return;
}
const bool fullItemUpdate = rect.isNull();
if (!fullItemUpdate && rect.isEmpty())
return;
if (!processDirtyItemsEmitted) {
QMetaObject::invokeMethod(q_ptr, "_q_processDirtyItems", Qt::QueuedConnection);
processDirtyItemsEmitted = true;
}
if (removingItemFromScene) {
// Note that this function can be called from the item's destructor, so
// do NOT call any virtual functions on it within this block.
if ((connectedSignals & changedSignalMask) || views.isEmpty()) {
// This block of code is kept for compatibility. Since 4.5, by default
// QGraphicsView does not connect the signal and we use the below
// method of delivering updates.
q_func()->update();
return;
}
for (int i = 0; i < views.size(); ++i) {
QGraphicsViewPrivate *viewPrivate = views.at(i)->d_func();
QRect rect = item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport);
rect.translate(viewPrivate->dirtyScrollOffset);
viewPrivate->updateRect(rect);
}
return;
}
bool hasNoContents = item->d_ptr->flags & QGraphicsItem::ItemHasNoContents;
if (!hasNoContents) {
item->d_ptr->dirty = 1;
if (fullItemUpdate)
item->d_ptr->fullUpdatePending = 1;
else if (!item->d_ptr->fullUpdatePending)
item->d_ptr->needsRepaint |= rect;
}
if (invalidateChildren) {
item->d_ptr->allChildrenDirty = 1;
item->d_ptr->dirtyChildren = 1;
}
if (force)
item->d_ptr->ignoreVisible = 1;
if (ignoreOpacity)
item->d_ptr->ignoreOpacity = 1;
QGraphicsItem *p = item->d_ptr->parent;
while (p && !p->d_ptr->dirtyChildren) {
p->d_ptr->dirtyChildren = 1;
p = p->d_ptr->parent;
}
}
void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool dirtyAncestorContainsChildren,
qreal parentOpacity)
{
Q_Q(QGraphicsScene);
bool wasDirtyParentViewBoundingRects = false;
bool wasDirtyParentSceneTransform = false;
qreal opacity = parentOpacity;
if (item) {
wasDirtyParentViewBoundingRects = item->d_ptr->paintedViewBoundingRectsNeedRepaint;
opacity = item->d_ptr->combineOpacityFromParent(parentOpacity);
const bool itemIsHidden = !item->d_ptr->ignoreVisible && !item->d_ptr->visible;
const bool itemIsFullyTransparent = !item->d_ptr->ignoreOpacity && opacity == 0.0;
if (item->d_ptr->dirtySceneTransform && !itemIsHidden && !item->d_ptr->itemIsUntransformable()
&& !(itemIsFullyTransparent && item->d_ptr->childrenCombineOpacity())) {
// Calculate the full scene transform for this item.
item->d_ptr->sceneTransform = item->d_ptr->parent ? item->d_ptr->parent->d_ptr->sceneTransform
: QTransform();
item->d_ptr->combineTransformFromParent(&item->d_ptr->sceneTransform);
item->d_ptr->dirtySceneTransform = 0;
wasDirtyParentSceneTransform = true;
}
if (itemIsHidden || itemIsFullyTransparent || (item->d_ptr->flags & QGraphicsItem::ItemHasNoContents)) {
// Make sure we don't process invisible items or items with no content.
item->d_ptr->dirty = 0;
item->d_ptr->paintedViewBoundingRectsNeedRepaint = 0;
}
}
// Process item.
if (item && (item->d_ptr->dirty || item->d_ptr->paintedViewBoundingRectsNeedRepaint)) {
const bool useCompatUpdate = views.isEmpty() || (connectedSignals & changedSignalMask);
const bool untransformableItem = item->d_ptr->itemIsUntransformable();
const QRectF itemBoundingRect = adjustedItemBoundingRect(item);
if (item->d_ptr->geometryChanged) {
// Update growingItemsBoundingRect.
if (!hasSceneRect)
growingItemsBoundingRect |= item->d_ptr->sceneTransform.mapRect(itemBoundingRect);
item->d_ptr->geometryChanged = 0;
}
if (useCompatUpdate && !untransformableItem && qFuzzyIsNull(item->boundingRegionGranularity())) {
// This block of code is kept for compatibility. Since 4.5, by default
// QGraphicsView does not connect the signal and we use the below
// method of delivering updates.
q->update(item->d_ptr->sceneTransform.mapRect(itemBoundingRect));
} else {
QRectF dirtyRect;
bool uninitializedDirtyRect = true;
for (int j = 0; j < views.size(); ++j) {
QGraphicsView *view = views.at(j);
QGraphicsViewPrivate *viewPrivate = view->d_func();
if (viewPrivate->fullUpdatePending)
continue;
switch (viewPrivate->viewportUpdateMode) {
case QGraphicsView::NoViewportUpdate:
continue;
case QGraphicsView::FullViewportUpdate:
view->viewport()->update();
viewPrivate->fullUpdatePending = 1;
continue;
default:
break;
}
QRect &paintedViewBoundingRect = item->d_ptr->paintedViewBoundingRects[viewPrivate->viewport];
if (item->d_ptr->paintedViewBoundingRectsNeedRepaint) {
wasDirtyParentViewBoundingRects = true;
paintedViewBoundingRect.translate(viewPrivate->dirtyScrollOffset);
if (!viewPrivate->updateRect(paintedViewBoundingRect))
paintedViewBoundingRect = QRect();
}
if (!item->d_ptr->dirty)
continue;
if (uninitializedDirtyRect) {
dirtyRect = itemBoundingRect;
if (!item->d_ptr->fullUpdatePending) {
_q_adjustRect(&item->d_ptr->needsRepaint);
dirtyRect &= item->d_ptr->needsRepaint;
}
uninitializedDirtyRect = false;
}
if (dirtyRect.isEmpty())
continue; // Discard updates outside the bounding rect.
bool valid = false;
if (untransformableItem) {
valid = item->d_ptr->updateHelper(viewPrivate, dirtyRect,
item->deviceTransform(view->viewportTransform()));
} else if (!view->isTransformed()) {
valid = item->d_ptr->updateHelper(viewPrivate, dirtyRect, item->d_ptr->sceneTransform);
} else {
QTransform deviceTransform = item->d_ptr->sceneTransform;
deviceTransform *= view->viewportTransform();
valid = !item->d_ptr->updateHelper(viewPrivate, dirtyRect, deviceTransform);
}
if (!valid)
paintedViewBoundingRect = QRect();
}
}
}
// Process root items / children.
if (!item || item->d_ptr->dirtyChildren) {
QList<QGraphicsItem *> *children = item ? &item->d_ptr->children : &topLevelItems;
const bool allChildrenDirty = item && item->d_ptr->allChildrenDirty;
if (!dirtyAncestorContainsChildren) {
dirtyAncestorContainsChildren = item && item->d_ptr->fullUpdatePending
&& (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape);
}
const bool parentIgnoresVisible = item && item->d_ptr->ignoreVisible;
const bool parentIgnoresOpacity = item && item->d_ptr->ignoreOpacity;
for (int i = 0; i < children->size(); ++i) {
QGraphicsItem *child = children->at(i);
if (wasDirtyParentSceneTransform)
child->d_ptr->dirtySceneTransform = 1;
if (wasDirtyParentViewBoundingRects)
child->d_ptr->paintedViewBoundingRectsNeedRepaint = 1;
if (parentIgnoresVisible)
child->d_ptr->ignoreVisible = 1;
if (parentIgnoresOpacity)
child->d_ptr->ignoreOpacity = 1;
if (allChildrenDirty) {
child->d_ptr->dirty = 1;
child->d_ptr->fullUpdatePending = 1;
child->d_ptr->dirtyChildren = 1;
child->d_ptr->allChildrenDirty = 1;
} else if (!child->d_ptr->dirty && !child->d_ptr->dirtyChildren) {
resetDirtyItem(child);
continue;
}
if (dirtyAncestorContainsChildren || updateAll) {
// No need to process this child's dirty rect, hence reset the dirty state.
// However, we have to continue the recursion because it might have a dirty
// view bounding rect that needs repaint. We also have to reset the dirty
// state of its descendants.
child->d_ptr->dirty = 0;
child->d_ptr->fullUpdatePending = 0;
if (updateAll)
child->d_ptr->paintedViewBoundingRectsNeedRepaint = 0;
}
processDirtyItemsRecursive(child, dirtyAncestorContainsChildren, opacity);
}
} else if (wasDirtyParentSceneTransform) {
item->d_ptr->invalidateChildrenSceneTransform();
}
if (item)
resetDirtyItem(item);
}
/*!
Paints the given \a items using the provided \a painter, after the
background has been drawn, and before the foreground has been
drawn. All painting is done in \e scene coordinates. Before
drawing each item, the painter must be transformed using
QGraphicsItem::sceneMatrix().
The \a options parameter is the list of style option objects for
each item in \a items. The \a numItems parameter is the number of
items in \a items and options in \a options. The \a widget
parameter is optional; if specified, it should point to the widget
that is being painted on.
The default implementation prepares the painter matrix, and calls
QGraphicsItem::paint() on all items. Reimplement this function to
provide custom painting of all items for the scene; gaining
complete control over how each item is drawn. In some cases this
can increase drawing performance significantly.
Example:
\snippet doc/src/snippets/graphicssceneadditemsnippet.cpp 0
\sa drawBackground(), drawForeground()
*/
void QGraphicsScene::drawItems(QPainter *painter,
int numItems,
QGraphicsItem *items[],
const QStyleOptionGraphicsItem options[], QWidget *widget)
{
Q_D(QGraphicsScene);
QTransform viewTransform = painter->worldTransform();
Q_UNUSED(options);
// Determine view, expose and flags.
QGraphicsView *view = widget ? qobject_cast<QGraphicsView *>(widget->parentWidget()) : 0;
QRegion *expose = 0;
if (view)
expose = &view->d_func()->exposedRegion;
// Find all toplevels, they are already sorted.
QList<QGraphicsItem *> topLevelItems;
for (int i = 0; i < numItems; ++i) {
QGraphicsItem *item = items[i]->topLevelItem();
if (!item->d_ptr->itemDiscovered) {
topLevelItems << item;
item->d_ptr->itemDiscovered = 1;
d->drawSubtreeRecursive(item, painter, viewTransform, expose, widget);
}
}
// Reset discovery bits.
for (int i = 0; i < topLevelItems.size(); ++i)
topLevelItems.at(i)->d_ptr->itemDiscovered = 0;
painter->setWorldTransform(viewTransform);
}
/*!
\since 4.4
Finds a new widget to give the keyboard focus to, as appropriate for Tab
and Shift+Tab, and returns true if it can find a new widget, or false if
it cannot. If \a next is true, this function searches forward; if \a next
is false, it searches backward.
You can reimplement this function in a subclass of QGraphicsScene to
provide fine-grained control over how tab focus passes inside your
scene. The default implementation is based on the tab focus chain defined
by QGraphicsWidget::setTabOrder().
*/
bool QGraphicsScene::focusNextPrevChild(bool next)
{
Q_D(QGraphicsScene);
QGraphicsItem *item = focusItem();
if (item && !item->isWidget()) {
// Tab out of the scene.
return false;
}
if (!item) {
if (d->lastFocusItem && !d->lastFocusItem->isWidget()) {
// Restore focus to the last focusable non-widget item that had
// focus.
setFocusItem(d->lastFocusItem, next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
return true;
}
}
if (!d->tabFocusFirst) {
// No widgets...
return false;
}
// The item must be a widget.
QGraphicsWidget *widget = 0;
if (!item) {
widget = next ? d->tabFocusFirst : d->tabFocusFirst->d_func()->focusPrev;
} else {
QGraphicsWidget *test = static_cast<QGraphicsWidget *>(item);
widget = next ? test->d_func()->focusNext : test->d_func()->focusPrev;
if ((next && widget == d->tabFocusFirst) || (!next && widget == d->tabFocusFirst->d_func()->focusPrev))
return false;
}
QGraphicsWidget *widgetThatHadFocus = widget;
// Run around the focus chain until we find a widget that can take tab focus.
do {
if (widget->flags() & QGraphicsItem::ItemIsFocusable
&& widget->isEnabled() && widget->isVisibleTo(0)
&& (widget->focusPolicy() & Qt::TabFocus)
&& (!item || !item->isWindow() || item->isAncestorOf(widget))
) {
setFocusItem(widget, next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
return true;
}
widget = next ? widget->d_func()->focusNext : widget->d_func()->focusPrev;
if ((next && widget == d->tabFocusFirst) || (!next && widget == d->tabFocusFirst->d_func()->focusPrev))
return false;
} while (widget != widgetThatHadFocus);
return false;
}
/*!
\fn QGraphicsScene::changed(const QList<QRectF> ®ion)
This signal is emitted by QGraphicsScene when control reaches the
event loop, if the scene content changes. The \a region parameter
contains a list of scene rectangles that indicate the area that
has been changed.
\sa QGraphicsView::updateScene()
*/
/*!
\fn QGraphicsScene::sceneRectChanged(const QRectF &rect)
This signal is emitted by QGraphicsScene whenever the scene rect changes.
The \a rect parameter is the new scene rectangle.
\sa QGraphicsView::updateSceneRect()
*/
/*!
\fn QGraphicsScene::selectionChanged()
\since 4.3
This signal is emitted by QGraphicsScene whenever the selection
changes. You can call selectedItems() to get the new list of selected
items.
The selection changes whenever an item is selected or unselected, a
selection area is set, cleared or otherwise changed, if a preselected item
is added to the scene, or if a selected item is removed from the scene.
QGraphicsScene emits this signal only once for group selection operations.
For example, if you set a selection area, select or unselect a
QGraphicsItemGroup, or if you add or remove from the scene a parent item
that contains several selected items, selectionChanged() is emitted only
once after the operation has completed (instead of once for each item).
\sa setSelectionArea(), selectedItems(), QGraphicsItem::setSelected()
*/
/*!
\since 4.4
Returns the scene's style, or the same as QApplication::style() if the
scene has not been explicitly assigned a style.
\sa setStyle()
*/
QStyle *QGraphicsScene::style() const
{
Q_D(const QGraphicsScene);
// ### This function, and the use of styles in general, is non-reentrant.
return d->style ? d->style : QApplication::style();
}
/*!
\since 4.4
Sets or replaces the style of the scene to \a style, and reparents the
style to this scene. Any previously assigned style is deleted. The scene's
style defaults to QApplication::style(), and serves as the default for all
QGraphicsWidget items in the scene.
Changing the style, either directly by calling this function, or
indirectly by calling QApplication::setStyle(), will automatically update
the style for all widgets in the scene that do not have a style explicitly
assigned to them.
If \a style is 0, QGraphicsScene will revert to QApplication::style().
\sa style()
*/
void QGraphicsScene::setStyle(QStyle *style)
{
Q_D(QGraphicsScene);
// ### This function, and the use of styles in general, is non-reentrant.
if (style == d->style)
return;
// Delete the old style,
delete d->style;
if ((d->style = style))
d->style->setParent(this);
// Notify the scene.
QEvent event(QEvent::StyleChange);
QApplication::sendEvent(this, &event);
// Notify all widgets that don't have a style explicitly set.
foreach (QGraphicsItem *item, items()) {
if (item->isWidget()) {
QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
if (!widget->testAttribute(Qt::WA_SetStyle))
QApplication::sendEvent(widget, &event);
}
}
}
/*!
\property QGraphicsScene::font
\since 4.4
\brief the scene's default font
This property provides the scene's font. The scene font defaults to,
and resolves all its entries from, QApplication::font.
If the scene's font changes, either directly through setFont() or
indirectly when the application font changes, QGraphicsScene first
sends itself a \l{QEvent::FontChange}{FontChange} event, and it then
sends \l{QEvent::FontChange}{FontChange} events to all top-level
widget items in the scene. These items respond by resolving their own
fonts to the scene, and they then notify their children, who again
notify their children, and so on, until all widget items have updated
their fonts.
Changing the scene font, (directly or indirectly through
QApplication::setFont(),) automatically schedules a redraw the entire
scene.
\sa QWidget::font, QApplication::setFont(), palette, style()
*/
QFont QGraphicsScene::font() const
{
Q_D(const QGraphicsScene);
return d->font;
}
void QGraphicsScene::setFont(const QFont &font)
{
Q_D(QGraphicsScene);
QFont naturalFont = QApplication::font();
naturalFont.resolve(0);
QFont resolvedFont = font.resolve(naturalFont);
d->setFont_helper(resolvedFont);
}
/*!
\property QGraphicsScene::palette
\since 4.4
\brief the scene's default palette
This property provides the scene's palette. The scene palette defaults to,
and resolves all its entries from, QApplication::palette.
If the scene's palette changes, either directly through setPalette() or
indirectly when the application palette changes, QGraphicsScene first
sends itself a \l{QEvent::PaletteChange}{PaletteChange} event, and it then
sends \l{QEvent::PaletteChange}{PaletteChange} events to all top-level
widget items in the scene. These items respond by resolving their own
palettes to the scene, and they then notify their children, who again
notify their children, and so on, until all widget items have updated
their palettes.
Changing the scene palette, (directly or indirectly through
QApplication::setPalette(),) automatically schedules a redraw the entire
scene.
\sa QWidget::palette, QApplication::setPalette(), font, style()
*/
QPalette QGraphicsScene::palette() const
{
Q_D(const QGraphicsScene);
return d->palette;
}
void QGraphicsScene::setPalette(const QPalette &palette)
{
Q_D(QGraphicsScene);
QPalette naturalPalette = QApplication::palette();
naturalPalette.resolve(0);
QPalette resolvedPalette = palette.resolve(naturalPalette);
d->setPalette_helper(resolvedPalette);
}
/*!
\since 4.4
Returns the current active window, or 0 if there is no window is currently
active.
\sa QGraphicsScene::setActiveWindow()
*/
QGraphicsWidget *QGraphicsScene::activeWindow() const
{
Q_D(const QGraphicsScene);
return d->activeWindow;
}
/*!
\since 4.4
Activates \a widget, which must be a widget in this scene. You can also
pass 0 for \a widget, in which case QGraphicsScene will deactivate any
currently active window.
\sa activeWindow(), QGraphicsWidget::isActiveWindow()
*/
void QGraphicsScene::setActiveWindow(QGraphicsWidget *widget)
{
Q_D(QGraphicsScene);
if (widget && widget->scene() != this) {
qWarning("QGraphicsScene::setActiveWindow: widget %p must be part of this scene",
widget);
return;
}
// Activate the widget's window.
QGraphicsWidget *window = widget ? widget->window() : 0;
if (window == d->activeWindow)
return;
// Deactivate the last active window.
if (d->activeWindow) {
if (QGraphicsWidget *fw = d->activeWindow->focusWidget()) {
// Remove focus from the current focus item.
if (fw == focusItem())
setFocusItem(0, Qt::ActiveWindowFocusReason);
}
QEvent event(QEvent::WindowDeactivate);
QApplication::sendEvent(d->activeWindow, &event);
}
// Update activate state.
d->activeWindow = window;
QEvent event(QEvent::ActivationChange);
QApplication::sendEvent(this, &event);
// Activate
if (window) {
QEvent event(QEvent::WindowActivate);
QApplication::sendEvent(window, &event);
QList<QGraphicsItem *> siblingWindows;
QGraphicsItem *parent = window->parentItem();
// Raise ### inefficient for toplevels
foreach (QGraphicsItem *sibling, parent ? parent->children() : items()) {
if (sibling != window && sibling->isWidget()
&& static_cast<QGraphicsWidget *>(sibling)->isWindow()) {
siblingWindows << sibling;
}
}
// Find the highest z value.
qreal z = window->zValue();
for (int i = 0; i < siblingWindows.size(); ++i)
z = qMax(z, siblingWindows.at(i)->zValue());
// This will probably never overflow.
const qreal litt = qreal(0.001);
window->setZValue(z + litt);
if (QGraphicsWidget *focusChild = window->focusWidget())
focusChild->setFocus(Qt::ActiveWindowFocusReason);
}
}
QT_END_NAMESPACE
#include "moc_qgraphicsscene.cpp"
#endif // QT_NO_GRAPHICSVIEW
Small optimization to QGraphicsScenePrivate::drawSubtreeRecursive.
We save three function calls by calling item->paint() directly.
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
/*!
\class QGraphicsScene
\brief The QGraphicsScene class provides a surface for managing a large
number of 2D graphical items.
\since 4.2
\ingroup multimedia
\ingroup graphicsview-api
\mainclass
The class serves as a container for QGraphicsItems. It is used together
with QGraphicsView for visualizing graphical items, such as lines,
rectangles, text, or even custom items, on a 2D surface. QGraphicsScene is
part of \l{The Graphics View Framework}.
QGraphicsScene also provides functionality that lets you efficiently
determine both the location of items, and for determining what items are
visible within an arbitrary area on the scene. With the QGraphicsView
widget, you can either visualize the whole scene, or zoom in and view only
parts of the scene.
Example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 0
Note that QGraphicsScene has no visual appearance of its own; it only
manages the items. You need to create a QGraphicsView widget to visualize
the scene.
To add items to a scene, you start off by constructing a QGraphicsScene
object. Then, you have two options: either add your existing QGraphicsItem
objects by calling addItem(), or you can call one of the convenience
functions addEllipse(), addLine(), addPath(), addPixmap(), addPolygon(),
addRect(), or addText(), which all return a pointer to the newly added item.
The dimensions of the items added with these functions are relative to the
item's coordinate system, and the items position is initialized to (0,
0) in the scene.
You can then visualize the scene using QGraphicsView. When the scene
changes, (e.g., when an item moves or is transformed) QGraphicsScene
emits the changed() signal. To remove an item, call removeItem().
QGraphicsScene uses an indexing algorithm to manage the location of items
efficiently. By default, a BSP (Binary Space Partitioning) tree is used; an
algorithm suitable for large scenes where most items remain static (i.e.,
do not move around). You can choose to disable this index by calling
setItemIndexMethod(). For more information about the available indexing
algorithms, see the itemIndexMethod property.
The scene's bounding rect is set by calling setSceneRect(). Items can be
placed at any position on the scene, and the size of the scene is by
default unlimited. The scene rect is used only for internal bookkeeping,
maintaining the scene's item index. If the scene rect is unset,
QGraphicsScene will use the bounding area of all items, as returned by
itemsBoundingRect(), as the scene rect. However, itemsBoundingRect() is a
relatively time consuming function, as it operates by collecting
positional information for every item on the scene. Because of this, you
should always set the scene rect when operating on large scenes.
One of QGraphicsScene's greatest strengths is its ability to efficiently
determine the location of items. Even with millions of items on the scene,
the items() functions can determine the location of an item within few
milliseconds. There are several overloads to items(): one that finds items
at a certain position, one that finds items inside or intersecting with a
polygon or a rectangle, and more. The list of returned items is sorted by
stacking order, with the topmost item being the first item in the list.
For convenience, there is also an itemAt() function that returns the
topmost item at a given position.
QGraphicsScene maintains selection information for the scene. To select
items, call setSelectionArea(), and to clear the current selection, call
clearSelection(). Call selectedItems() to get the list of all selected
items.
\section1 Event Handling and Propagation
Another responsibility that QGraphicsScene has, is to propagate events
from QGraphicsView. To send an event to a scene, you construct an event
that inherits QEvent, and then send it using, for example,
QApplication::sendEvent(). event() is responsible for dispatching
the event to the individual items. Some common events are handled by
convenience event handlers. For example, key press events are handled by
keyPressEvent(), and mouse press events are handled by mousePressEvent().
Key events are delivered to the \e {focus item}. To set the focus item,
you can either call setFocusItem(), passing an item that accepts focus, or
the item itself can call QGraphicsItem::setFocus(). Call focusItem() to
get the current focus item. For compatibility with widgets, the scene also
maintains its own focus information. By default, the scene does not have
focus, and all key events are discarded. If setFocus() is called, or if an
item on the scene gains focus, the scene automatically gains focus. If the
scene has focus, hasFocus() will return true, and key events will be
forwarded to the focus item, if any. If the scene loses focus, (i.e.,
someone calls clearFocus(),) while an item has focus, the scene will
maintain its item focus information, and once the scene regains focus, it
will make sure the last focus item regains focus.
For mouse-over effects, QGraphicsScene dispatches \e {hover
events}. If an item accepts hover events (see
QGraphicsItem::acceptHoverEvents()), it will receive a \l
{QEvent::}{GraphicsSceneHoverEnter} event when the mouse enters
its area. As the mouse continues moving inside the item's area,
QGraphicsScene will send it \l {QEvent::}{GraphicsSceneHoverMove}
events. When the mouse leaves the item's area, the item will
receive a \l {QEvent::}{GraphicsSceneHoverLeave} event.
All mouse events are delivered to the current \e {mouse grabber}
item. An item becomes the scene's mouse grabber if it accepts
mouse events (see QGraphicsItem::acceptedMouseButtons()) and it
receives a mouse press. It stays the mouse grabber until it
receives a mouse release when no other mouse buttons are
pressed. You can call mouseGrabberItem() to determine what item is
currently grabbing the mouse.
\sa QGraphicsItem, QGraphicsView
*/
/*!
\enum QGraphicsScene::SceneLayer
\since 4.3
This enum describes the rendering layers in a QGraphicsScene. When
QGraphicsScene draws the scene contents, it renders each of these layers
separately, in order.
Each layer represents a flag that can be OR'ed together when calling
functions such as invalidate() or QGraphicsView::invalidateScene().
\value ItemLayer The item layer. QGraphicsScene renders all items are in
this layer by calling the virtual function drawItems(). The item layer is
drawn after the background layer, but before the foreground layer.
\value BackgroundLayer The background layer. QGraphicsScene renders the
scene's background in this layer by calling the virtual function
drawBackground(). The background layer is drawn first of all layers.
\value ForegroundLayer The foreground layer. QGraphicsScene renders the
scene's foreground in this layer by calling the virtual function
drawForeground(). The foreground layer is drawn last of all layers.
\value AllLayers All layers; this value represents a combination of all
three layers.
\sa invalidate(), QGraphicsView::invalidateScene()
*/
/*!
\enum QGraphicsScene::ItemIndexMethod
This enum describes the indexing algorithms QGraphicsScene provides for
managing positional information about items on the scene.
\value BspTreeIndex A Binary Space Partitioning tree is applied. All
QGraphicsScene's item location algorithms are of an order close to
logarithmic complexity, by making use of binary search. Adding, moving and
removing items is logarithmic. This approach is best for static scenes
(i.e., scenes where most items do not move).
\value NoIndex No index is applied. Item location is of linear complexity,
as all items on the scene are searched. Adding, moving and removing items,
however, is done in constant time. This approach is ideal for dynamic
scenes, where many items are added, moved or removed continuously.
\sa setItemIndexMethod(), bspTreeDepth
*/
#include "qgraphicsscene.h"
#ifndef QT_NO_GRAPHICSVIEW
#include "qgraphicsitem.h"
#include "qgraphicsitem_p.h"
#include "qgraphicslayout.h"
#include "qgraphicsscene_p.h"
#include "qgraphicssceneevent.h"
#include "qgraphicsview.h"
#include "qgraphicsview_p.h"
#include "qgraphicswidget.h"
#include "qgraphicswidget_p.h"
#include <QtCore/qdebug.h>
#include <QtCore/qlist.h>
#include <QtCore/qmath.h>
#include <QtCore/qrect.h>
#include <QtCore/qset.h>
#include <QtCore/qstack.h>
#include <QtCore/qtimer.h>
#include <QtCore/qvarlengtharray.h>
#include <QtGui/qapplication.h>
#include <QtGui/qdesktopwidget.h>
#include <QtGui/qevent.h>
#include <QtGui/qgraphicslayout.h>
#include <QtGui/qgraphicsproxywidget.h>
#include <QtGui/qgraphicswidget.h>
#include <QtGui/qmatrix.h>
#include <QtGui/qpaintengine.h>
#include <QtGui/qpainter.h>
#include <QtGui/qpixmapcache.h>
#include <QtGui/qpolygon.h>
#include <QtGui/qstyleoption.h>
#include <QtGui/qtooltip.h>
#include <QtGui/qtransform.h>
#include <private/qapplication_p.h>
#include <private/qobject_p.h>
#ifdef Q_WS_X11
#include <private/qt_x11_p.h>
#endif
QT_BEGIN_NAMESPACE
static inline bool qt_notclosestLeaf(const QGraphicsItem *item1, const QGraphicsItem *item2);
static inline bool QRectF_intersects(const QRectF &s, const QRectF &r)
{
qreal xp = s.left();
qreal yp = s.top();
qreal w = s.width();
qreal h = s.height();
qreal l1 = xp;
qreal r1 = xp;
if (w < 0)
l1 += w;
else
r1 += w;
qreal l2 = r.left();
qreal r2 = r.left();
if (w < 0)
l2 += r.width();
else
r2 += r.width();
if (l1 >= r2 || l2 >= r1)
return false;
qreal t1 = yp;
qreal b1 = yp;
if (h < 0)
t1 += h;
else
b1 += h;
qreal t2 = r.top();
qreal b2 = r.top();
if (r.height() < 0)
t2 += r.height();
else
b2 += r.height();
return !(t1 >= b2 || t2 >= b1);
}
// QRectF::intersects() returns false always if either the source or target
// rectangle's width or height are 0. This works around that problem.
static inline void _q_adjustRect(QRectF *rect)
{
Q_ASSERT(rect);
if (!rect->width())
rect->adjust(-0.00001, 0, 0.00001, 0);
if (!rect->height())
rect->adjust(0, -0.00001, 0, 0.00001);
}
static inline QRectF adjustedItemBoundingRect(const QGraphicsItem *item)
{
Q_ASSERT(item);
QRectF boundingRect(item->boundingRect());
_q_adjustRect(&boundingRect);
return boundingRect;
}
static void _q_hoverFromMouseEvent(QGraphicsSceneHoverEvent *hover, const QGraphicsSceneMouseEvent *mouseEvent)
{
hover->setWidget(mouseEvent->widget());
hover->setPos(mouseEvent->pos());
hover->setScenePos(mouseEvent->scenePos());
hover->setScreenPos(mouseEvent->screenPos());
hover->setLastPos(mouseEvent->lastPos());
hover->setLastScenePos(mouseEvent->lastScenePos());
hover->setLastScreenPos(mouseEvent->lastScreenPos());
hover->setModifiers(mouseEvent->modifiers());
hover->setAccepted(mouseEvent->isAccepted());
}
/*!
\internal
*/
QGraphicsScenePrivate::QGraphicsScenePrivate()
: changedSignalMask(0),
indexMethod(QGraphicsScene::BspTreeIndex),
bspTreeDepth(0),
lastItemCount(0),
hasSceneRect(false),
updateAll(false),
calledEmitUpdated(false),
processDirtyItemsEmitted(false),
selectionChanging(0),
needSortTopLevelItems(true),
regenerateIndex(true),
purgePending(false),
indexTimerId(0),
restartIndexTimer(false),
stickyFocus(false),
hasFocus(false),
focusItem(0),
lastFocusItem(0),
tabFocusFirst(0),
activeWindow(0),
activationRefCount(0),
lastMouseGrabberItem(0),
lastMouseGrabberItemHasImplicitMouseGrab(false),
dragDropItem(0),
enterWidget(0),
lastDropAction(Qt::IgnoreAction),
allItemsIgnoreHoverEvents(true),
allItemsUseDefaultCursor(true),
painterStateProtection(true),
sortCacheEnabled(false),
updatingSortCache(false),
style(0)
{
}
/*!
\internal
*/
void QGraphicsScenePrivate::init()
{
Q_Q(QGraphicsScene);
// Keep this index so we can check for connected slots later on.
changedSignalMask = (1 << q->metaObject()->indexOfSignal("changed(QList<QRectF>)"));
qApp->d_func()->scene_list.append(q);
q->update();
}
/*!
\internal
*/
QList<QGraphicsItem *> QGraphicsScenePrivate::estimateItemsInRect(const QRectF &rect) const
{
const_cast<QGraphicsScenePrivate *>(this)->purgeRemovedItems();
const_cast<QGraphicsScenePrivate *>(this)->_q_updateSortCache();
if (indexMethod == QGraphicsScene::BspTreeIndex) {
// ### Only do this once in a while.
QGraphicsScenePrivate *that = const_cast<QGraphicsScenePrivate *>(this);
// Get items from BSP tree
QList<QGraphicsItem *> items = that->bspTree.items(rect);
// Fill in with any unindexed items
for (int i = 0; i < unindexedItems.size(); ++i) {
if (QGraphicsItem *item = unindexedItems.at(i)) {
if (!item->d_ptr->itemDiscovered && item->d_ptr->visible && !(item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)) {
QRectF boundingRect = item->sceneBoundingRect();
if (QRectF_intersects(boundingRect, rect)) {
item->d_ptr->itemDiscovered = 1;
items << item;
}
}
}
}
// Reset the discovered state of all discovered items
for (int i = 0; i < items.size(); ++i)
items.at(i)->d_func()->itemDiscovered = 0;
return items;
}
QList<QGraphicsItem *> itemsInRect;
for (int i = 0; i < unindexedItems.size(); ++i) {
if (QGraphicsItem *item = unindexedItems.at(i)) {
if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)
continue;
if (item->d_ptr->visible && !item->d_ptr->isFullyTransparent())
itemsInRect << item;
}
}
for (int i = 0; i < indexedItems.size(); ++i) {
if (QGraphicsItem *item = indexedItems.at(i)) {
if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)
continue;
if (item->d_ptr->visible && !item->d_ptr->isFullyTransparent())
itemsInRect << item;
}
}
return itemsInRect;
}
/*!
\internal
*/
void QGraphicsScenePrivate::addToIndex(QGraphicsItem *item)
{
if (indexMethod == QGraphicsScene::BspTreeIndex) {
if (item->d_func()->index != -1) {
bspTree.insertItem(item, item->sceneBoundingRect());
foreach (QGraphicsItem *child, item->children())
child->addToIndex();
} else {
// The BSP tree is regenerated if the number of items grows to a
// certain threshold, or if the bounding rect of the graph doubles in
// size.
startIndexTimer();
}
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::removeFromIndex(QGraphicsItem *item)
{
if (indexMethod == QGraphicsScene::BspTreeIndex) {
int index = item->d_func()->index;
if (index != -1) {
bspTree.removeItem(item, item->sceneBoundingRect());
freeItemIndexes << index;
indexedItems[index] = 0;
item->d_func()->index = -1;
unindexedItems << item;
foreach (QGraphicsItem *child, item->children())
child->removeFromIndex();
}
startIndexTimer();
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::resetIndex()
{
purgeRemovedItems();
if (indexMethod == QGraphicsScene::BspTreeIndex) {
for (int i = 0; i < indexedItems.size(); ++i) {
if (QGraphicsItem *item = indexedItems.at(i)) {
item->d_ptr->index = -1;
unindexedItems << item;
}
}
indexedItems.clear();
freeItemIndexes.clear();
regenerateIndex = true;
startIndexTimer();
}
}
static inline int intmaxlog(int n)
{
return (n > 0 ? qMax(qCeil(qLn(qreal(n)) / qLn(qreal(2))), 5) : 0);
}
/*!
\internal
*/
void QGraphicsScenePrivate::_q_updateIndex()
{
if (!indexTimerId)
return;
Q_Q(QGraphicsScene);
q->killTimer(indexTimerId);
indexTimerId = 0;
purgeRemovedItems();
// Add unindexedItems to indexedItems
QRectF unindexedItemsBoundingRect;
for (int i = 0; i < unindexedItems.size(); ++i) {
if (QGraphicsItem *item = unindexedItems.at(i)) {
unindexedItemsBoundingRect |= item->sceneBoundingRect();
if (!freeItemIndexes.isEmpty()) {
int freeIndex = freeItemIndexes.takeFirst();
item->d_func()->index = freeIndex;
indexedItems[freeIndex] = item;
} else {
item->d_func()->index = indexedItems.size();
indexedItems << item;
}
}
}
// Update growing scene rect.
QRectF oldGrowingItemsBoundingRect = growingItemsBoundingRect;
growingItemsBoundingRect |= unindexedItemsBoundingRect;
// Determine whether we should regenerate the BSP tree.
if (indexMethod == QGraphicsScene::BspTreeIndex) {
int depth = bspTreeDepth;
if (depth == 0) {
int oldDepth = intmaxlog(lastItemCount);
depth = intmaxlog(indexedItems.size());
static const int slack = 100;
if (bspTree.leafCount() == 0 || (oldDepth != depth && qAbs(lastItemCount - indexedItems.size()) > slack)) {
// ### Crude algorithm.
regenerateIndex = true;
}
}
// Regenerate the tree.
if (regenerateIndex) {
regenerateIndex = false;
bspTree.initialize(q->sceneRect(), depth);
unindexedItems = indexedItems;
lastItemCount = indexedItems.size();
q->update();
// Take this opportunity to reset our largest-item counter for
// untransformable items. When the items are inserted into the BSP
// tree, we'll get an accurate calculation.
largestUntransformableItem = QRectF();
}
}
// Insert all unindexed items into the tree.
for (int i = 0; i < unindexedItems.size(); ++i) {
if (QGraphicsItem *item = unindexedItems.at(i)) {
QRectF rect = item->sceneBoundingRect();
if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)
continue;
if (indexMethod == QGraphicsScene::BspTreeIndex)
bspTree.insertItem(item, rect);
// If the item ignores view transformations, update our
// largest-item-counter to ensure that the view can accurately
// discover untransformable items when drawing.
if (item->d_ptr->itemIsUntransformable()) {
QGraphicsItem *topmostUntransformable = item;
while (topmostUntransformable && (topmostUntransformable->d_ptr->ancestorFlags
& QGraphicsItemPrivate::AncestorIgnoresTransformations)) {
topmostUntransformable = topmostUntransformable->parentItem();
}
// ### Verify that this is the correct largest untransformable rectangle.
largestUntransformableItem |= item->mapToItem(topmostUntransformable, item->boundingRect()).boundingRect();
}
}
}
unindexedItems.clear();
// Notify scene rect changes.
if (!hasSceneRect && growingItemsBoundingRect != oldGrowingItemsBoundingRect)
emit q->sceneRectChanged(growingItemsBoundingRect);
}
/*!
\internal
*/
void QGraphicsScenePrivate::_q_emitUpdated()
{
Q_Q(QGraphicsScene);
calledEmitUpdated = false;
// Ensure all views are connected if anything is connected. This disables
// the optimization that items send updates directly to the views, but it
// needs to happen in order to keep compatibility with the behavior from
// Qt 4.4 and backward.
if (connectedSignals & changedSignalMask) {
for (int i = 0; i < views.size(); ++i) {
QGraphicsView *view = views.at(i);
if (!view->d_func()->connectedToScene) {
view->d_func()->connectedToScene = true;
q->connect(q, SIGNAL(changed(QList<QRectF>)),
views.at(i), SLOT(updateScene(QList<QRectF>)));
}
}
} else {
updateAll = false;
for (int i = 0; i < views.size(); ++i)
views.at(i)->d_func()->processPendingUpdates();
return;
}
// Notify the changes to anybody interested.
QList<QRectF> oldUpdatedRects;
oldUpdatedRects = updateAll ? (QList<QRectF>() << q->sceneRect()) : updatedRects;
updateAll = false;
updatedRects.clear();
emit q->changed(oldUpdatedRects);
}
/*!
\internal
*/
void QGraphicsScenePrivate::registerTopLevelItem(QGraphicsItem *item)
{
needSortTopLevelItems = true;
topLevelItems.append(item);
}
/*!
\internal
*/
void QGraphicsScenePrivate::unregisterTopLevelItem(QGraphicsItem *item)
{
topLevelItems.removeOne(item);
}
/*!
\internal
Updates all items in the pending update list. At this point, the list is
unlikely to contain partially constructed items.
*/
void QGraphicsScenePrivate::_q_updateLater()
{
foreach (QGraphicsItem *item, pendingUpdateItems)
item->update();
pendingUpdateItems.clear();
}
/*!
\internal
*/
void QGraphicsScenePrivate::_q_polishItems()
{
const QVariant booleanTrueVariant(true);
foreach (QGraphicsItem *item, unpolishedItems) {
if (!item->d_ptr->explicitlyHidden) {
item->itemChange(QGraphicsItem::ItemVisibleChange, booleanTrueVariant);
item->itemChange(QGraphicsItem::ItemVisibleHasChanged, booleanTrueVariant);
}
if (item->isWidget()) {
QEvent event(QEvent::Polish);
QApplication::sendEvent((QGraphicsWidget *)item, &event);
}
}
unpolishedItems.clear();
}
void QGraphicsScenePrivate::_q_processDirtyItems()
{
processDirtyItemsEmitted = false;
const bool wasPendingSceneUpdate = calledEmitUpdated;
const QRectF oldGrowingItemsBoundingRect = growingItemsBoundingRect;
processDirtyItemsRecursive(0);
if (!hasSceneRect && oldGrowingItemsBoundingRect != growingItemsBoundingRect)
emit q_func()->sceneRectChanged(growingItemsBoundingRect);
if (wasPendingSceneUpdate)
return;
for (int i = 0; i < views.size(); ++i)
views.at(i)->d_func()->processPendingUpdates();
if (calledEmitUpdated) {
// We did a compatibility QGraphicsScene::update in processDirtyItemsRecursive
// and we cannot wait for the control to reach the eventloop before the
// changed signal is emitted, so we emit it now.
_q_emitUpdated();
}
// Immediately dispatch all pending update requests on the views.
for (int i = 0; i < views.size(); ++i) {
QWidget *viewport = views.at(i)->d_func()->viewport;
if (qt_widget_private(viewport)->paintOnScreen())
QCoreApplication::sendPostedEvents(viewport, QEvent::UpdateRequest);
else
QCoreApplication::sendPostedEvents(viewport->window(), QEvent::UpdateRequest);
}
}
/*!
\internal
Schedules an item for removal. This function leaves some stale indexes
around in the BSP tree if called from the item's destructor; these will
be cleaned up the next time someone triggers purgeRemovedItems().
Note: This function might get called from QGraphicsItem's destructor. \a item is
being destroyed, so we cannot call any pure virtual functions on it (such
as boundingRect()). Also, it is unnecessary to update the item's own state
in any way.
*/
void QGraphicsScenePrivate::removeItemHelper(QGraphicsItem *item)
{
Q_Q(QGraphicsScene);
// Clear focus on the item to remove any reference in the focusWidget chain.
item->clearFocus();
markDirty(item, QRectF(), false, false, false, false, /*removingItemFromScene=*/true);
if (!item->d_ptr->inDestructor) {
// Can potentially call item->boundingRect() (virtual function), that's why
// we only can call this function if the item is not in its destructor.
removeFromIndex(item);
} else if (item->d_ptr->index != -1) {
// Important: The index is useless until purgeRemovedItems() is called.
indexedItems[item->d_ptr->index] = (QGraphicsItem *)0;
if (!purgePending)
purgePending = true;
removedItems << item;
} else {
// Recently added items are purged immediately. unindexedItems() never
// contains stale items.
unindexedItems.removeAll(item);
}
if (!item->d_ptr->inDestructor && item == tabFocusFirst) {
QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
widget->d_func()->fixFocusChainBeforeReparenting(0, 0);
}
item->d_func()->scene = 0;
// Remove from parent, or unregister from toplevels.
if (QGraphicsItem *parentItem = item->parentItem()) {
if (parentItem->scene()) {
Q_ASSERT_X(parentItem->scene() == q, "QGraphicsScene::removeItem",
"Parent item's scene is different from this item's scene");
item->d_ptr->setParentItemHelper(0);
}
} else {
unregisterTopLevelItem(item);
}
if (!item->d_ptr->inDestructor) {
// Remove from our item lists.
int index = item->d_func()->index;
if (index != -1) {
freeItemIndexes << index;
indexedItems[index] = 0;
} else {
unindexedItems.removeAll(item);
}
}
// Reset the mouse grabber and focus item data.
if (item == focusItem)
focusItem = 0;
if (item == lastFocusItem)
lastFocusItem = 0;
if (item == activeWindow) {
// ### deactivate...
activeWindow = 0;
}
// Disable selectionChanged() for individual items
++selectionChanging;
int oldSelectedItemsSize = selectedItems.size();
// Update selected & hovered item bookkeeping
selectedItems.remove(item);
hoverItems.removeAll(item);
cachedItemsUnderMouse.removeAll(item);
unpolishedItems.removeAll(item);
pendingUpdateItems.removeAll(item);
resetDirtyItem(item);
//We remove all references of item from the sceneEventFilter arrays
QMultiMap<QGraphicsItem*, QGraphicsItem*>::iterator iterator = sceneEventFilters.begin();
while (iterator != sceneEventFilters.end()) {
if (iterator.value() == item || iterator.key() == item)
iterator = sceneEventFilters.erase(iterator);
else
++iterator;
}
if (!item->d_ptr->inDestructor) {
// Remove all children recursively
for (int i = 0; i < item->d_ptr->children.size(); ++i)
q->removeItem(item->d_ptr->children.at(i));
}
// Reset the mouse grabber and focus item data.
if (mouseGrabberItems.contains(item))
ungrabMouse(item, /* item is dying */ item->d_ptr->inDestructor);
// Reset the keyboard grabber
if (keyboardGrabberItems.contains(item))
ungrabKeyboard(item, /* item is dying */ item->d_ptr->inDestructor);
// Reset the last mouse grabber item
if (item == lastMouseGrabberItem)
lastMouseGrabberItem = 0;
// Reenable selectionChanged() for individual items
--selectionChanging;
if (!selectionChanging && selectedItems.size() != oldSelectedItemsSize)
emit q->selectionChanged();
}
/*!
\internal
Removes stale pointers from all data structures.
*/
void QGraphicsScenePrivate::purgeRemovedItems()
{
if (!purgePending && removedItems.isEmpty())
return;
// Remove stale items from the BSP tree.
if (indexMethod != QGraphicsScene::NoIndex)
bspTree.removeItems(removedItems);
// Purge this list.
removedItems.clear();
freeItemIndexes.clear();
for (int i = 0; i < indexedItems.size(); ++i) {
if (!indexedItems.at(i))
freeItemIndexes << i;
}
purgePending = false;
}
/*!
\internal
Starts or restarts the timer used for reindexing unindexed items.
*/
void QGraphicsScenePrivate::startIndexTimer(int interval)
{
Q_Q(QGraphicsScene);
if (indexTimerId) {
restartIndexTimer = true;
} else {
indexTimerId = q->startTimer(interval);
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::addPopup(QGraphicsWidget *widget)
{
Q_ASSERT(widget);
Q_ASSERT(!popupWidgets.contains(widget));
popupWidgets << widget;
if (QGraphicsWidget *focusWidget = widget->focusWidget()) {
focusWidget->setFocus(Qt::PopupFocusReason);
} else {
grabKeyboard((QGraphicsItem *)widget);
if (focusItem && popupWidgets.size() == 1) {
QFocusEvent event(QEvent::FocusOut, Qt::PopupFocusReason);
sendEvent(focusItem, &event);
}
}
grabMouse((QGraphicsItem *)widget);
}
/*!
\internal
Remove \a widget from the popup list. Important notes:
\a widget is guaranteed to be in the list of popups, but it might not be
the last entry; you can hide any item in the pop list before the others,
and this must cause all later mouse grabbers to lose the grab.
*/
void QGraphicsScenePrivate::removePopup(QGraphicsWidget *widget, bool itemIsDying)
{
Q_ASSERT(widget);
int index = popupWidgets.indexOf(widget);
Q_ASSERT(index != -1);
for (int i = popupWidgets.size() - 1; i >= index; --i) {
QGraphicsWidget *widget = popupWidgets.takeLast();
ungrabMouse(widget, itemIsDying);
if (focusItem && popupWidgets.isEmpty()) {
QFocusEvent event(QEvent::FocusIn, Qt::PopupFocusReason);
sendEvent(focusItem, &event);
} else {
ungrabKeyboard((QGraphicsItem *)widget, itemIsDying);
}
if (!itemIsDying && widget->isVisible()) {
widget->hide();
widget->QGraphicsItem::d_ptr->explicitlyHidden = 0;
}
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::grabMouse(QGraphicsItem *item, bool implicit)
{
// Append to list of mouse grabber items, and send a mouse grab event.
if (mouseGrabberItems.contains(item)) {
if (mouseGrabberItems.last() == item) {
Q_ASSERT(!implicit);
if (!lastMouseGrabberItemHasImplicitMouseGrab) {
qWarning("QGraphicsItem::grabMouse: already a mouse grabber");
} else {
// Upgrade to an explicit mouse grab
lastMouseGrabberItemHasImplicitMouseGrab = false;
}
} else {
qWarning("QGraphicsItem::grabMouse: already blocked by mouse grabber: %p",
mouseGrabberItems.last());
}
return;
}
// Send ungrab event to the last grabber.
if (!mouseGrabberItems.isEmpty()) {
QGraphicsItem *last = mouseGrabberItems.last();
if (lastMouseGrabberItemHasImplicitMouseGrab) {
// Implicit mouse grab is immediately lost.
last->ungrabMouse();
} else {
// Just send ungrab event to current grabber.
QEvent ungrabEvent(QEvent::UngrabMouse);
sendEvent(last, &ungrabEvent);
}
}
mouseGrabberItems << item;
lastMouseGrabberItemHasImplicitMouseGrab = implicit;
// Send grab event to current grabber.
QEvent grabEvent(QEvent::GrabMouse);
sendEvent(item, &grabEvent);
}
/*!
\internal
*/
void QGraphicsScenePrivate::ungrabMouse(QGraphicsItem *item, bool itemIsDying)
{
int index = mouseGrabberItems.indexOf(item);
if (index == -1) {
qWarning("QGraphicsItem::ungrabMouse: not a mouse grabber");
return;
}
if (item != mouseGrabberItems.last()) {
// Recursively ungrab the next mouse grabber until we reach this item
// to ensure state consistency.
ungrabMouse(mouseGrabberItems.at(index + 1), itemIsDying);
}
if (!popupWidgets.isEmpty() && item == popupWidgets.last()) {
// If the item is a popup, go via removePopup to ensure state
// consistency and that it gets hidden correctly - beware that
// removePopup() reenters this function to continue removing the grab.
removePopup((QGraphicsWidget *)item, itemIsDying);
return;
}
// Send notification about mouse ungrab.
if (!itemIsDying) {
QEvent event(QEvent::UngrabMouse);
sendEvent(item, &event);
}
// Remove the item from the list of grabbers. Whenever this happens, we
// reset the implicitGrab (there can be only ever be one implicit grabber
// in a scene, and it is always the latest grabber; if the implicit grab
// is lost, it is not automatically regained.
mouseGrabberItems.takeLast();
lastMouseGrabberItemHasImplicitMouseGrab = false;
// Send notification about mouse regrab. ### It's unfortunate that all the
// items get a GrabMouse event, but this is a rare case with a simple
// implementation and it does ensure a consistent state.
if (!itemIsDying && !mouseGrabberItems.isEmpty()) {
QGraphicsItem *last = mouseGrabberItems.last();
QEvent event(QEvent::GrabMouse);
sendEvent(last, &event);
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::clearMouseGrabber()
{
if (!mouseGrabberItems.isEmpty())
mouseGrabberItems.first()->ungrabMouse();
lastMouseGrabberItem = 0;
}
/*!
\internal
*/
void QGraphicsScenePrivate::grabKeyboard(QGraphicsItem *item)
{
if (keyboardGrabberItems.contains(item)) {
if (keyboardGrabberItems.last() == item)
qWarning("QGraphicsItem::grabKeyboard: already a keyboard grabber");
else
qWarning("QGraphicsItem::grabKeyboard: already blocked by keyboard grabber: %p",
keyboardGrabberItems.last());
return;
}
// Send ungrab event to the last grabber.
if (!keyboardGrabberItems.isEmpty()) {
// Just send ungrab event to current grabber.
QEvent ungrabEvent(QEvent::UngrabKeyboard);
sendEvent(keyboardGrabberItems.last(), &ungrabEvent);
}
keyboardGrabberItems << item;
// Send grab event to current grabber.
QEvent grabEvent(QEvent::GrabKeyboard);
sendEvent(item, &grabEvent);
}
/*!
\internal
*/
void QGraphicsScenePrivate::ungrabKeyboard(QGraphicsItem *item, bool itemIsDying)
{
int index = keyboardGrabberItems.lastIndexOf(item);
if (index == -1) {
qWarning("QGraphicsItem::ungrabKeyboard: not a keyboard grabber");
return;
}
if (item != keyboardGrabberItems.last()) {
// Recursively ungrab the topmost keyboard grabber until we reach this
// item to ensure state consistency.
ungrabKeyboard(keyboardGrabberItems.at(index + 1), itemIsDying);
}
// Send notification about keyboard ungrab.
if (!itemIsDying) {
QEvent event(QEvent::UngrabKeyboard);
sendEvent(item, &event);
}
// Remove the item from the list of grabbers.
keyboardGrabberItems.takeLast();
// Send notification about mouse regrab.
if (!itemIsDying && !keyboardGrabberItems.isEmpty()) {
QGraphicsItem *last = keyboardGrabberItems.last();
QEvent event(QEvent::GrabKeyboard);
sendEvent(last, &event);
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::clearKeyboardGrabber()
{
if (!keyboardGrabberItems.isEmpty())
ungrabKeyboard(keyboardGrabberItems.first());
}
void QGraphicsScenePrivate::enableMouseTrackingOnViews()
{
foreach (QGraphicsView *view, views)
view->viewport()->setMouseTracking(true);
}
/*!
Returns all items for the screen position in \a event.
*/
QList<QGraphicsItem *> QGraphicsScenePrivate::itemsAtPosition(const QPoint &screenPos,
const QPointF &scenePos,
QWidget *widget) const
{
Q_Q(const QGraphicsScene);
QGraphicsView *view = widget ? qobject_cast<QGraphicsView *>(widget->parentWidget()) : 0;
QList<QGraphicsItem *> items;
if (view)
items = view->items(view->viewport()->mapFromGlobal(screenPos));
else
items = q->items(scenePos);
return items;
}
/*!
\internal
Checks if item collides with the path and mode, but also checks that if it
doesn't collide, maybe its frame rect will.
*/
bool QGraphicsScenePrivate::itemCollidesWithPath(QGraphicsItem *item,
const QPainterPath &path,
Qt::ItemSelectionMode mode)
{
if (item->collidesWithPath(path, mode))
return true;
if (item->isWidget()) {
// Check if this is a window, and if its frame rect collides.
QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
if (widget->isWindow()) {
QRectF frameRect = widget->windowFrameRect();
QPainterPath framePath;
framePath.addRect(frameRect);
bool intersects = path.intersects(frameRect);
if (mode == Qt::IntersectsItemShape || mode == Qt::IntersectsItemBoundingRect)
return intersects || path.contains(frameRect.topLeft())
|| framePath.contains(path.elementAt(0));
return !intersects && path.contains(frameRect.topLeft());
}
}
return false;
}
/*!
\internal
*/
void QGraphicsScenePrivate::storeMouseButtonsForMouseGrabber(QGraphicsSceneMouseEvent *event)
{
for (int i = 0x1; i <= 0x10; i <<= 1) {
if (event->buttons() & i) {
mouseGrabberButtonDownPos.insert(Qt::MouseButton(i),
mouseGrabberItems.last()->d_ptr->genericMapFromScene(event->scenePos(),
event->widget()));
mouseGrabberButtonDownScenePos.insert(Qt::MouseButton(i), event->scenePos());
mouseGrabberButtonDownScreenPos.insert(Qt::MouseButton(i), event->screenPos());
}
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::installSceneEventFilter(QGraphicsItem *watched, QGraphicsItem *filter)
{
sceneEventFilters.insert(watched, filter);
}
/*!
\internal
*/
void QGraphicsScenePrivate::removeSceneEventFilter(QGraphicsItem *watched, QGraphicsItem *filter)
{
if (!sceneEventFilters.contains(watched))
return;
QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator it = sceneEventFilters.lowerBound(watched);
QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator end = sceneEventFilters.upperBound(watched);
do {
if (it.value() == filter)
it = sceneEventFilters.erase(it);
else
++it;
} while (it != end);
}
/*!
\internal
*/
bool QGraphicsScenePrivate::filterEvent(QGraphicsItem *item, QEvent *event)
{
if (item && !sceneEventFilters.contains(item))
return false;
QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator it = sceneEventFilters.lowerBound(item);
QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator end = sceneEventFilters.upperBound(item);
while (it != end) {
// ### The filterer and filteree might both be deleted.
if (it.value()->sceneEventFilter(it.key(), event))
return true;
++it;
}
return false;
}
/*!
\internal
This is the final dispatch point for any events from the scene to the
item. It filters the event first - if the filter returns true, the event
is considered to have been eaten by the filter, and is therefore stopped
(the default filter returns false). Then/otherwise, if the item is
enabled, the event is sent; otherwise it is stopped.
*/
bool QGraphicsScenePrivate::sendEvent(QGraphicsItem *item, QEvent *event)
{
if (filterEvent(item, event))
return false;
return (item && item->isEnabled()) ? item->sceneEvent(event) : false;
}
/*!
\internal
*/
void QGraphicsScenePrivate::cloneDragDropEvent(QGraphicsSceneDragDropEvent *dest,
QGraphicsSceneDragDropEvent *source)
{
dest->setWidget(source->widget());
dest->setPos(source->pos());
dest->setScenePos(source->scenePos());
dest->setScreenPos(source->screenPos());
dest->setButtons(source->buttons());
dest->setModifiers(source->modifiers());
dest->setPossibleActions(source->possibleActions());
dest->setProposedAction(source->proposedAction());
dest->setDropAction(source->dropAction());
dest->setSource(source->source());
dest->setMimeData(source->mimeData());
}
/*!
\internal
*/
void QGraphicsScenePrivate::sendDragDropEvent(QGraphicsItem *item,
QGraphicsSceneDragDropEvent *dragDropEvent)
{
dragDropEvent->setPos(item->d_ptr->genericMapFromScene(dragDropEvent->scenePos(), dragDropEvent->widget()));
sendEvent(item, dragDropEvent);
}
/*!
\internal
*/
void QGraphicsScenePrivate::sendHoverEvent(QEvent::Type type, QGraphicsItem *item,
QGraphicsSceneHoverEvent *hoverEvent)
{
QGraphicsSceneHoverEvent event(type);
event.setWidget(hoverEvent->widget());
event.setPos(item->d_ptr->genericMapFromScene(hoverEvent->scenePos(), hoverEvent->widget()));
event.setScenePos(hoverEvent->scenePos());
event.setScreenPos(hoverEvent->screenPos());
event.setLastPos(item->d_ptr->genericMapFromScene(hoverEvent->lastScenePos(), hoverEvent->widget()));
event.setLastScenePos(hoverEvent->lastScenePos());
event.setLastScreenPos(hoverEvent->lastScreenPos());
event.setModifiers(hoverEvent->modifiers());
sendEvent(item, &event);
}
/*!
\internal
*/
void QGraphicsScenePrivate::sendMouseEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
if (mouseEvent->button() == 0 && mouseEvent->buttons() == 0 && lastMouseGrabberItemHasImplicitMouseGrab) {
// ### This is a temporary fix for until we get proper mouse
// grab events.
clearMouseGrabber();
return;
}
QGraphicsItem *item = mouseGrabberItems.last();
for (int i = 0x1; i <= 0x10; i <<= 1) {
Qt::MouseButton button = Qt::MouseButton(i);
mouseEvent->setButtonDownPos(button, mouseGrabberButtonDownPos.value(button, item->d_ptr->genericMapFromScene(mouseEvent->scenePos(), mouseEvent->widget())));
mouseEvent->setButtonDownScenePos(button, mouseGrabberButtonDownScenePos.value(button, mouseEvent->scenePos()));
mouseEvent->setButtonDownScreenPos(button, mouseGrabberButtonDownScreenPos.value(button, mouseEvent->screenPos()));
}
mouseEvent->setPos(item->d_ptr->genericMapFromScene(mouseEvent->scenePos(), mouseEvent->widget()));
mouseEvent->setLastPos(item->d_ptr->genericMapFromScene(mouseEvent->lastScenePos(), mouseEvent->widget()));
sendEvent(item, mouseEvent);
}
/*!
\internal
*/
void QGraphicsScenePrivate::mousePressEventHandler(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_Q(QGraphicsScene);
// Ignore by default, unless we find a mouse grabber that accepts it.
mouseEvent->ignore();
// Deliver to any existing mouse grabber.
if (!mouseGrabberItems.isEmpty()) {
// The event is ignored by default, but we disregard the event's
// accepted state after delivery; the mouse is grabbed, after all.
sendMouseEvent(mouseEvent);
return;
}
// Start by determining the number of items at the current position.
// Reuse value from earlier calculations if possible.
if (cachedItemsUnderMouse.isEmpty()) {
cachedItemsUnderMouse = itemsAtPosition(mouseEvent->screenPos(),
mouseEvent->scenePos(),
mouseEvent->widget());
}
// Update window activation.
QGraphicsWidget *newActiveWindow = windowForItem(cachedItemsUnderMouse.value(0));
if (newActiveWindow != activeWindow)
q->setActiveWindow(newActiveWindow);
// Set focus on the topmost enabled item that can take focus.
bool setFocus = false;
foreach (QGraphicsItem *item, cachedItemsUnderMouse) {
if (item->isEnabled() && (item->flags() & QGraphicsItem::ItemIsFocusable)) {
if (!item->isWidget() || ((QGraphicsWidget *)item)->focusPolicy() & Qt::ClickFocus) {
setFocus = true;
if (item != q->focusItem())
q->setFocusItem(item, Qt::MouseFocusReason);
break;
}
}
}
// If nobody could take focus, clear it.
if (!stickyFocus && !setFocus)
q->setFocusItem(0, Qt::MouseFocusReason);
// Find a mouse grabber by sending mouse press events to all mouse grabber
// candidates one at a time, until the event is accepted. It's accepted by
// default, so the receiver has to explicitly ignore it for it to pass
// through.
foreach (QGraphicsItem *item, cachedItemsUnderMouse) {
if (!(item->acceptedMouseButtons() & mouseEvent->button())) {
// Skip items that don't accept the event's mouse button.
continue;
}
grabMouse(item, /* implicit = */ true);
mouseEvent->accept();
// check if the item we are sending to are disabled (before we send the event)
bool disabled = !item->isEnabled();
bool isWindow = item->isWindow();
if (mouseEvent->type() == QEvent::GraphicsSceneMouseDoubleClick
&& item != lastMouseGrabberItem && lastMouseGrabberItem) {
// If this item is different from the item that received the last
// mouse event, and mouseEvent is a doubleclick event, then the
// event is converted to a press. Known limitation:
// Triple-clicking will not generate a doubleclick, though.
QGraphicsSceneMouseEvent mousePress(QEvent::GraphicsSceneMousePress);
mousePress.accept();
mousePress.setButton(mouseEvent->button());
mousePress.setButtons(mouseEvent->buttons());
mousePress.setScreenPos(mouseEvent->screenPos());
mousePress.setScenePos(mouseEvent->scenePos());
mousePress.setModifiers(mouseEvent->modifiers());
mousePress.setWidget(mouseEvent->widget());
mousePress.setButtonDownPos(mouseEvent->button(),
mouseEvent->buttonDownPos(mouseEvent->button()));
mousePress.setButtonDownScenePos(mouseEvent->button(),
mouseEvent->buttonDownScenePos(mouseEvent->button()));
mousePress.setButtonDownScreenPos(mouseEvent->button(),
mouseEvent->buttonDownScreenPos(mouseEvent->button()));
sendMouseEvent(&mousePress);
mouseEvent->setAccepted(mousePress.isAccepted());
} else {
sendMouseEvent(mouseEvent);
}
bool dontSendUngrabEvents = mouseGrabberItems.isEmpty() || mouseGrabberItems.last() != item;
if (disabled) {
ungrabMouse(item, /* itemIsDying = */ dontSendUngrabEvents);
break;
}
if (mouseEvent->isAccepted()) {
if (!mouseGrabberItems.isEmpty())
storeMouseButtonsForMouseGrabber(mouseEvent);
lastMouseGrabberItem = item;
return;
}
ungrabMouse(item, /* itemIsDying = */ dontSendUngrabEvents);
// Don't propagate through windows.
if (isWindow)
break;
}
// Is the event still ignored? Then the mouse press goes to the scene.
// Reset the mouse grabber, clear the selection, clear focus, and leave
// the event ignored so that it can propagate through the originating
// view.
if (!mouseEvent->isAccepted()) {
clearMouseGrabber();
QGraphicsView *view = mouseEvent->widget() ? qobject_cast<QGraphicsView *>(mouseEvent->widget()->parentWidget()) : 0;
bool dontClearSelection = view && view->dragMode() == QGraphicsView::ScrollHandDrag;
if (!dontClearSelection) {
// Clear the selection if the originating view isn't in scroll
// hand drag mode. The view will clear the selection if no drag
// happened.
q->clearSelection();
}
}
}
QGraphicsWidget *QGraphicsScenePrivate::windowForItem(const QGraphicsItem *item) const
{
if (!item)
return 0;
do {
if (item->isWidget())
return static_cast<const QGraphicsWidget *>(item)->window();
item = item->parentItem();
} while (item);
return 0;
}
void QGraphicsScenePrivate::recursive_items_helper(QGraphicsItem *item, QRectF rect,
QList<QGraphicsItem *> *items,
const QTransform &parentTransform,
const QTransform &viewTransform,
Qt::ItemSelectionMode mode, Qt::SortOrder order,
qreal parentOpacity) const
{
// Calculate opacity.
qreal opacity;
if (item) {
if (!item->d_ptr->visible)
return;
QGraphicsItem *p = item->d_ptr->parent;
bool itemIgnoresParentOpacity = item->d_ptr->flags & QGraphicsItem::ItemIgnoresParentOpacity;
bool parentDoesntPropagateOpacity = (p && (p->d_ptr->flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren));
if (!itemIgnoresParentOpacity && !parentDoesntPropagateOpacity) {
opacity = parentOpacity * item->opacity();
} else {
opacity = item->d_ptr->opacity;
}
if (opacity == 0.0 && !(item->d_ptr->flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren))
return;
} else {
opacity = parentOpacity;
}
// Calculate the full transform for this item.
QTransform transform = parentTransform;
bool keep = false;
if (item) {
item->d_ptr->combineTransformFromParent(&transform, &viewTransform);
// ### This does not take the clip into account.
QRectF brect = item->boundingRect();
_q_adjustRect(&brect);
keep = true;
if (mode == Qt::ContainsItemShape || mode == Qt::ContainsItemBoundingRect)
keep = rect.contains(transform.mapRect(brect)) && rect != brect;
else
keep = rect.intersects(transform.mapRect(brect));
if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) {
QPainterPath rectPath;
rectPath.addRect(rect);
keep = itemCollidesWithPath(item, transform.inverted().map(rectPath), mode);
}
}
bool childClip = (item && (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape));
bool dontProcessItem = !item || !keep;
bool dontProcessChildren = item && dontProcessItem && childClip;
// Find and sort children.
QList<QGraphicsItem *> &children = item ? item->d_ptr->children : const_cast<QGraphicsScenePrivate *>(this)->topLevelItems;
if (!dontProcessChildren) {
if (item && item->d_ptr->needSortChildren) {
item->d_ptr->needSortChildren = 0;
qStableSort(children.begin(), children.end(), qt_notclosestLeaf);
} else if (!item && needSortTopLevelItems) {
const_cast<QGraphicsScenePrivate *>(this)->needSortTopLevelItems = false;
qStableSort(children.begin(), children.end(), qt_notclosestLeaf);
}
}
childClip &= !dontProcessChildren & !children.isEmpty();
// Clip.
if (childClip)
rect &= transform.map(item->shape()).controlPointRect();
// Process children behind
int i = 0;
if (!dontProcessChildren) {
for (i = 0; i < children.size(); ++i) {
QGraphicsItem *child = children.at(i);
if (!(child->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent))
break;
recursive_items_helper(child, rect, items, transform, viewTransform,
mode, order, opacity);
}
}
// Process item
if (!dontProcessItem)
items->append(item);
// Process children in front
if (!dontProcessChildren) {
for (; i < children.size(); ++i)
recursive_items_helper(children.at(i), rect, items, transform, viewTransform,
mode, order, opacity);
}
if (!item && order == Qt::AscendingOrder) {
int n = items->size();
for (int i = 0; i < n / 2; ++i) {
QGraphicsItem *tmp = (*items)[n - i - 1];
(*items)[n - i - 1] = (*items)[i];
(*items)[i] = tmp;
}
}
}
QList<QGraphicsItem *> QGraphicsScenePrivate::items_helper(const QPointF &pos) const
{
QList<QGraphicsItem *> items;
// The index returns a rough estimate of what items are inside the rect.
// Refine it by iterating through all returned items.
QRectF adjustedRect = QRectF(pos, QSize(1,1));
foreach (QGraphicsItem *item, estimateItemsInRect(adjustedRect)) {
// Find the item's scene transform in a clever way.
QTransform x = item->sceneTransform();
bool keep = false;
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
const QRectF br(adjustedItemBoundingRect(item));
// Rect intersects/contains item's shape
if (QRectF_intersects(adjustedRect, x.mapRect(br))) {
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
if (item->contains(xinv.map(pos))) {
items << item;
keep = true;
}
}
}
if (keep && (item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) {
// Recurse into children that clip children.
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok)
childItems_helper(&items, item, xinv.map(pos));
}
}
sortItems(&items, Qt::AscendingOrder, sortCacheEnabled);
return items;
}
QList<QGraphicsItem *> QGraphicsScenePrivate::items_helper(const QRectF &rect,
Qt::ItemSelectionMode mode,
Qt::SortOrder order) const
{
QList<QGraphicsItem *> items;
QPainterPath path;
// The index returns a rough estimate of what items are inside the rect.
// Refine it by iterating through all returned items.
QRectF adjustedRect(rect);
_q_adjustRect(&adjustedRect);
foreach (QGraphicsItem *item, estimateItemsInRect(adjustedRect)) {
// Find the item's scene transform in a clever way.
QTransform x = item->sceneTransform();
bool keep = false;
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
const QRectF br(adjustedItemBoundingRect(item));
if (mode >= Qt::ContainsItemBoundingRect) {
// Rect intersects/contains item's bounding rect
QRectF mbr = x.mapRect(br);
if ((mode == Qt::IntersectsItemBoundingRect && QRectF_intersects(rect, mbr))
|| (mode == Qt::ContainsItemBoundingRect && rect != mbr && rect.contains(mbr))) {
items << item;
keep = true;
}
} else {
// Rect intersects/contains item's shape
if (QRectF_intersects(adjustedRect, x.mapRect(br))) {
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
if (path.isEmpty())
path.addRect(rect);
if (itemCollidesWithPath(item, xinv.map(path), mode)) {
items << item;
keep = true;
}
}
}
}
if (keep && (item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) {
// Recurse into children that clip children.
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
if (x.type() <= QTransform::TxScale) {
// Rect
childItems_helper(&items, item, xinv.mapRect(rect), mode);
} else {
// Polygon
childItems_helper(&items, item, xinv.map(rect), mode);
}
}
}
}
if (order != Qt::SortOrder(-1))
sortItems(&items, order, sortCacheEnabled);
return items;
}
QList<QGraphicsItem *> QGraphicsScenePrivate::items_helper(const QPolygonF &polygon,
Qt::ItemSelectionMode mode,
Qt::SortOrder order) const
{
QList<QGraphicsItem *> items;
QRectF polyRect(polygon.boundingRect());
_q_adjustRect(&polyRect);
QPainterPath path;
// The index returns a rough estimate of what items are inside the rect.
// Refine it by iterating through all returned items.
foreach (QGraphicsItem *item, estimateItemsInRect(polyRect)) {
// Find the item's scene transform in a clever way.
QTransform x = item->sceneTransform();
bool keep = false;
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
const QRectF br(adjustedItemBoundingRect(item));
if (mode >= Qt::ContainsItemBoundingRect) {
// Polygon contains/intersects item's bounding rect
if (path == QPainterPath())
path.addPolygon(polygon);
if ((mode == Qt::IntersectsItemBoundingRect && path.intersects(x.mapRect(br)))
|| (mode == Qt::ContainsItemBoundingRect && path.contains(x.mapRect(br)))) {
items << item;
keep = true;
}
} else {
// Polygon contains/intersects item's shape
if (QRectF_intersects(polyRect, x.mapRect(br))) {
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
if (path == QPainterPath())
path.addPolygon(polygon);
if (itemCollidesWithPath(item, xinv.map(path), mode)) {
items << item;
keep = true;
}
}
}
}
if (keep && (item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) {
// Recurse into children that clip children.
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok)
childItems_helper(&items, item, xinv.map(polygon), mode);
}
}
if (order != Qt::SortOrder(-1))
sortItems(&items, order, sortCacheEnabled);
return items;
}
QList<QGraphicsItem *> QGraphicsScenePrivate::items_helper(const QPainterPath &path,
Qt::ItemSelectionMode mode,
Qt::SortOrder order) const
{
QList<QGraphicsItem *> items;
QRectF pathRect(path.controlPointRect());
_q_adjustRect(&pathRect);
// The index returns a rough estimate of what items are inside the rect.
// Refine it by iterating through all returned items.
foreach (QGraphicsItem *item, estimateItemsInRect(pathRect)) {
// Find the item's scene transform in a clever way.
QTransform x = item->sceneTransform();
bool keep = false;
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
const QRectF br(adjustedItemBoundingRect(item));
if (mode >= Qt::ContainsItemBoundingRect) {
// Path contains/intersects item's bounding rect
if ((mode == Qt::IntersectsItemBoundingRect && path.intersects(x.mapRect(br)))
|| (mode == Qt::ContainsItemBoundingRect && path.contains(x.mapRect(br)))) {
items << item;
keep = true;
}
} else {
// Path contains/intersects item's shape
if (QRectF_intersects(pathRect, x.mapRect(br))) {
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
if (itemCollidesWithPath(item, xinv.map(path), mode)) {
items << item;
keep = true;
}
}
}
}
if (keep && (item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) {
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok)
childItems_helper(&items, item, xinv.map(path), mode);
}
}
if (order != Qt::SortOrder(-1))
sortItems(&items, order, sortCacheEnabled);
return items;
}
void QGraphicsScenePrivate::childItems_helper(QList<QGraphicsItem *> *items,
const QGraphicsItem *parent,
const QPointF &pos) const
{
bool parentClip = (parent->flags() & QGraphicsItem::ItemClipsChildrenToShape);
if (parentClip && parent->d_ptr->isClippedAway())
return;
// ### is this needed?
if (parentClip && !parent->boundingRect().contains(pos))
return;
QList<QGraphicsItem *> &children = parent->d_ptr->children;
for (int i = 0; i < children.size(); ++i) {
QGraphicsItem *item = children.at(i);
if (item->d_ptr->transformData && !item->d_ptr->transformData->computedFullTransform().isInvertible())
continue;
// Skip invisible items and all their children.
if (item->d_ptr->isInvisible())
continue;
bool keep = false;
if (!item->d_ptr->isClippedAway()) {
if (item->contains(item->mapFromParent(pos))) {
items->append(item);
keep = true;
}
}
if ((keep || !(item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) && !item->d_ptr->children.isEmpty())
// Recurse into children.
childItems_helper(items, item, item->mapFromParent(pos));
}
}
void QGraphicsScenePrivate::childItems_helper(QList<QGraphicsItem *> *items,
const QGraphicsItem *parent,
const QRectF &rect,
Qt::ItemSelectionMode mode) const
{
bool parentClip = (parent->flags() & QGraphicsItem::ItemClipsChildrenToShape);
if (parentClip && parent->d_ptr->isClippedAway())
return;
QRectF adjustedRect(rect);
_q_adjustRect(&adjustedRect);
QRectF r = !parentClip ? adjustedRect : adjustedRect.intersected(adjustedItemBoundingRect(parent));
if (r.isEmpty())
return;
QPainterPath path;
QList<QGraphicsItem *> &children = parent->d_ptr->children;
for (int i = 0; i < children.size(); ++i) {
QGraphicsItem *item = children.at(i);
if (item->d_ptr->transformData && !item->d_ptr->transformData->computedFullTransform().isInvertible())
continue;
// Skip invisible items and all their children.
if (item->d_ptr->isInvisible())
continue;
bool keep = false;
if (!item->d_ptr->isClippedAway()) {
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
const QRectF br(adjustedItemBoundingRect(item));
QRectF mbr = item->mapRectToParent(br);
if (mode >= Qt::ContainsItemBoundingRect) {
// Rect intersects/contains item's bounding rect
if ((mode == Qt::IntersectsItemBoundingRect && QRectF_intersects(rect, mbr))
|| (mode == Qt::ContainsItemBoundingRect && rect != mbr && rect.contains(br))) {
items->append(item);
keep = true;
}
} else {
// Rect intersects/contains item's shape
if (QRectF_intersects(rect, mbr)) {
if (path == QPainterPath())
path.addRect(rect);
if (itemCollidesWithPath(item, item->mapFromParent(path), mode)) {
items->append(item);
keep = true;
}
}
}
}
if ((keep || !(item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) && !item->d_ptr->children.isEmpty()) {
// Recurse into children.
if (!item->d_ptr->transformData || item->d_ptr->transformData->computedFullTransform().type() <= QTransform::TxScale) {
// Rect
childItems_helper(items, item, item->mapRectFromParent(rect), mode);
} else {
// Polygon
childItems_helper(items, item, item->mapFromParent(rect), mode);
}
}
}
}
void QGraphicsScenePrivate::childItems_helper(QList<QGraphicsItem *> *items,
const QGraphicsItem *parent,
const QPolygonF &polygon,
Qt::ItemSelectionMode mode) const
{
bool parentClip = (parent->flags() & QGraphicsItem::ItemClipsChildrenToShape);
if (parentClip && parent->d_ptr->isClippedAway())
return;
QRectF polyRect(polygon.boundingRect());
_q_adjustRect(&polyRect);
QRectF r = !parentClip ? polyRect : polyRect.intersected(adjustedItemBoundingRect(parent));
if (r.isEmpty())
return;
QPainterPath path;
QList<QGraphicsItem *> &children = parent->d_ptr->children;
for (int i = 0; i < children.size(); ++i) {
QGraphicsItem *item = children.at(i);
if (item->d_ptr->transformData && !item->d_ptr->transformData->computedFullTransform().isInvertible())
continue;
// Skip invisible items.
if (item->d_ptr->isInvisible())
continue;
bool keep = false;
if (!item->d_ptr->isClippedAway()) {
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
const QRectF br(adjustedItemBoundingRect(item));
if (mode >= Qt::ContainsItemBoundingRect) {
// Polygon contains/intersects item's bounding rect
if (path == QPainterPath())
path.addPolygon(polygon);
if ((mode == Qt::IntersectsItemBoundingRect && path.intersects(item->mapRectToParent(br)))
|| (mode == Qt::ContainsItemBoundingRect && path.contains(item->mapRectToParent(br)))) {
items->append(item);
keep = true;
}
} else {
// Polygon contains/intersects item's shape
if (QRectF_intersects(polyRect, item->mapRectToParent(br))) {
if (path == QPainterPath())
path.addPolygon(polygon);
if (itemCollidesWithPath(item, item->mapFromParent(path), mode)) {
items->append(item);
keep = true;
}
}
}
}
if ((keep || !(item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) && !item->d_ptr->children.isEmpty()) {
// Recurse into children that clip children.
childItems_helper(items, item, item->mapFromParent(polygon), mode);
}
}
}
void QGraphicsScenePrivate::childItems_helper(QList<QGraphicsItem *> *items,
const QGraphicsItem *parent,
const QPainterPath &path,
Qt::ItemSelectionMode mode) const
{
bool parentClip = (parent->flags() & QGraphicsItem::ItemClipsChildrenToShape);
if (parentClip && parent->d_ptr->isClippedAway())
return;
QRectF pathRect(path.boundingRect());
_q_adjustRect(&pathRect);
QRectF r = !parentClip ? pathRect : pathRect.intersected(adjustedItemBoundingRect(parent));
if (r.isEmpty())
return;
QList<QGraphicsItem *> &children = parent->d_ptr->children;
for (int i = 0; i < children.size(); ++i) {
QGraphicsItem *item = children.at(i);
if (item->d_ptr->transformData && !item->d_ptr->transformData->computedFullTransform().isInvertible())
continue;
// Skip invisible items.
if (item->d_ptr->isInvisible())
continue;
bool keep = false;
if (!item->d_ptr->isClippedAway()) {
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
const QRectF br(adjustedItemBoundingRect(item));
if (mode >= Qt::ContainsItemBoundingRect) {
// Polygon contains/intersects item's bounding rect
if ((mode == Qt::IntersectsItemBoundingRect && path.intersects(item->mapRectToParent(br)))
|| (mode == Qt::ContainsItemBoundingRect && path.contains(item->mapRectToParent(br)))) {
items->append(item);
keep = true;
}
} else {
// Path contains/intersects item's shape
if (QRectF_intersects(pathRect, item->mapRectToParent(br))) {
if (itemCollidesWithPath(item, item->mapFromParent(path), mode)) {
items->append(item);
keep = true;
}
}
}
}
if ((keep || !(item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) && !item->d_ptr->children.isEmpty()) {
// Recurse into children that clip children.
childItems_helper(items, item, item->mapFromParent(path), mode);
}
}
}
void QGraphicsScenePrivate::invalidateSortCache()
{
Q_Q(QGraphicsScene);
if (!sortCacheEnabled || updatingSortCache)
return;
updatingSortCache = true;
QMetaObject::invokeMethod(q, "_q_updateSortCache", Qt::QueuedConnection);
}
/*!
\internal
Should not be exported, but we can't change that now.
### Qt 5: Remove symbol / make static
*/
inline bool qt_closestLeaf(const QGraphicsItem *item1, const QGraphicsItem *item2)
{
// Return true if sibling item1 is on top of item2.
const QGraphicsItemPrivate *d1 = item1->d_ptr;
const QGraphicsItemPrivate *d2 = item2->d_ptr;
bool f1 = d1->flags & QGraphicsItem::ItemStacksBehindParent;
bool f2 = d2->flags & QGraphicsItem::ItemStacksBehindParent;
if (f1 != f2) return f2;
qreal z1 = d1->z;
qreal z2 = d2->z;
return z1 > z2;
}
static inline bool qt_notclosestLeaf(const QGraphicsItem *item1, const QGraphicsItem *item2)
{
return qt_closestLeaf(item2, item1);
}
/*!
\internal
Should not be exported, but we can't change that now.
*/
inline bool qt_closestItemFirst(const QGraphicsItem *item1, const QGraphicsItem *item2)
{
return QGraphicsScenePrivate::closestItemFirst_withoutCache(item1, item2);
}
/*!
Returns true if \a item1 is on top of \a item2.
\internal
*/
bool QGraphicsScenePrivate::closestItemFirst_withoutCache(const QGraphicsItem *item1, const QGraphicsItem *item2)
{
// Siblings? Just check their z-values.
const QGraphicsItemPrivate *d1 = item1->d_ptr;
const QGraphicsItemPrivate *d2 = item2->d_ptr;
if (d1->parent == d2->parent)
return qt_closestLeaf(item1, item2);
// Find common ancestor, and each item's ancestor closest to the common
// ancestor.
int item1Depth = d1->depth;
int item2Depth = d2->depth;
const QGraphicsItem *p = item1;
const QGraphicsItem *t1 = item1;
while (item1Depth > item2Depth && (p = p->d_ptr->parent)) {
if (p == item2) {
// item2 is one of item1's ancestors; item1 is on top
return !(t1->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent);
}
t1 = p;
--item1Depth;
}
p = item2;
const QGraphicsItem *t2 = item2;
while (item2Depth > item1Depth && (p = p->d_ptr->parent)) {
if (p == item1) {
// item1 is one of item2's ancestors; item1 is not on top
return (t2->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent);
}
t2 = p;
--item2Depth;
}
// item1Ancestor is now at the same level as item2Ancestor, but not the same.
const QGraphicsItem *a1 = t1;
const QGraphicsItem *a2 = t2;
while (a1) {
const QGraphicsItem *p1 = a1;
const QGraphicsItem *p2 = a2;
a1 = a1->parentItem();
a2 = a2->parentItem();
if (a1 && a1 == a2)
return qt_closestLeaf(p1, p2);
}
// No common ancestor? Then just compare the items' toplevels directly.
return qt_closestLeaf(t1->topLevelItem(), t2->topLevelItem());
}
/*!
Returns true if \a item2 is on top of \a item1.
\internal
*/
bool QGraphicsScenePrivate::closestItemLast_withoutCache(const QGraphicsItem *item1, const QGraphicsItem *item2)
{
return closestItemFirst_withoutCache(item2, item1);
}
void QGraphicsScenePrivate::climbTree(QGraphicsItem *item, int *stackingOrder)
{
if (!item->d_ptr->children.isEmpty()) {
QList<QGraphicsItem *> childList = item->d_ptr->children;
qSort(childList.begin(), childList.end(), qt_closestLeaf);
for (int i = 0; i < childList.size(); ++i) {
QGraphicsItem *item = childList.at(i);
if (!(item->flags() & QGraphicsItem::ItemStacksBehindParent))
climbTree(childList.at(i), stackingOrder);
}
item->d_ptr->globalStackingOrder = (*stackingOrder)++;
for (int i = 0; i < childList.size(); ++i) {
QGraphicsItem *item = childList.at(i);
if (item->flags() & QGraphicsItem::ItemStacksBehindParent)
climbTree(childList.at(i), stackingOrder);
}
} else {
item->d_ptr->globalStackingOrder = (*stackingOrder)++;
}
}
void QGraphicsScenePrivate::_q_updateSortCache()
{
_q_updateIndex();
if (!sortCacheEnabled || !updatingSortCache)
return;
updatingSortCache = false;
int stackingOrder = 0;
QList<QGraphicsItem *> topLevels;
for (int i = 0; i < indexedItems.size(); ++i) {
QGraphicsItem *item = indexedItems.at(i);
if (item && item->parentItem() == 0)
topLevels << item;
}
for (int i = 0; i < unindexedItems.size(); ++i) {
QGraphicsItem *item = unindexedItems.at(i);
if (item->parentItem() == 0)
topLevels << item;
}
qSort(topLevels.begin(), topLevels.end(), qt_closestLeaf);
for (int i = 0; i < topLevels.size(); ++i)
climbTree(topLevels.at(i), &stackingOrder);
}
void QGraphicsScenePrivate::sortItems(QList<QGraphicsItem *> *itemList, Qt::SortOrder order,
bool sortCacheEnabled)
{
if (sortCacheEnabled) {
if (order == Qt::AscendingOrder) {
qSort(itemList->begin(), itemList->end(), closestItemFirst_withCache);
} else if (order == Qt::DescendingOrder) {
qSort(itemList->begin(), itemList->end(), closestItemLast_withCache);
}
} else {
if (order == Qt::AscendingOrder) {
qSort(itemList->begin(), itemList->end(), closestItemFirst_withoutCache);
} else if (order == Qt::DescendingOrder) {
qSort(itemList->begin(), itemList->end(), closestItemLast_withoutCache);
}
}
}
/*!
\internal
Set the font and propagate the changes if the font is different from the
current font.
*/
void QGraphicsScenePrivate::setFont_helper(const QFont &font)
{
if (this->font == font && this->font.resolve() == font.resolve())
return;
updateFont(font);
}
/*!
\internal
Resolve the scene's font against the application font, and propagate the
changes too all items in the scene.
*/
void QGraphicsScenePrivate::resolveFont()
{
QFont naturalFont = QApplication::font();
naturalFont.resolve(0);
QFont resolvedFont = font.resolve(naturalFont);
updateFont(resolvedFont);
}
/*!
\internal
Update the font, and whether or not it has changed, reresolve all fonts in
the scene.
*/
void QGraphicsScenePrivate::updateFont(const QFont &font)
{
Q_Q(QGraphicsScene);
// Update local font setting.
this->font = font;
// Resolve the fonts of all top-level widget items, or widget items
// whose parent is not a widget.
foreach (QGraphicsItem *item, q->items()) {
if (!item->parentItem()) {
// Resolvefont for an item is a noop operation, but
// every item can be a widget, or can have a widget
// childre.
item->d_ptr->resolveFont(font.resolve());
}
}
// Send the scene a FontChange event.
QEvent event(QEvent::FontChange);
QApplication::sendEvent(q, &event);
}
/*!
\internal
Set the palette and propagate the changes if the palette is different from
the current palette.
*/
void QGraphicsScenePrivate::setPalette_helper(const QPalette &palette)
{
if (this->palette == palette && this->palette.resolve() == palette.resolve())
return;
updatePalette(palette);
}
/*!
\internal
Resolve the scene's palette against the application palette, and propagate
the changes too all items in the scene.
*/
void QGraphicsScenePrivate::resolvePalette()
{
QPalette naturalPalette = QApplication::palette();
naturalPalette.resolve(0);
QPalette resolvedPalette = palette.resolve(naturalPalette);
updatePalette(resolvedPalette);
}
/*!
\internal
Update the palette, and whether or not it has changed, reresolve all
palettes in the scene.
*/
void QGraphicsScenePrivate::updatePalette(const QPalette &palette)
{
Q_Q(QGraphicsScene);
// Update local palette setting.
this->palette = palette;
// Resolve the palettes of all top-level widget items, or widget items
// whose parent is not a widget.
foreach (QGraphicsItem *item, q->items()) {
if (!item->parentItem()) {
// Resolvefont for an item is a noop operation, but
// every item can be a widget, or can have a widget
// childre.
item->d_ptr->resolvePalette(palette.resolve());
}
}
// Send the scene a PaletteChange event.
QEvent event(QEvent::PaletteChange);
QApplication::sendEvent(q, &event);
}
/*!
Constructs a QGraphicsScene object. The \a parent parameter is
passed to QObject's constructor.
*/
QGraphicsScene::QGraphicsScene(QObject *parent)
: QObject(*new QGraphicsScenePrivate, parent)
{
d_func()->init();
}
/*!
Constructs a QGraphicsScene object, using \a sceneRect for its
scene rectangle. The \a parent parameter is passed to QObject's
constructor.
\sa sceneRect
*/
QGraphicsScene::QGraphicsScene(const QRectF &sceneRect, QObject *parent)
: QObject(*new QGraphicsScenePrivate, parent)
{
setSceneRect(sceneRect);
d_func()->init();
}
/*!
Constructs a QGraphicsScene object, using the rectangle specified
by (\a x, \a y), and the given \a width and \a height for its
scene rectangle. The \a parent parameter is passed to QObject's
constructor.
\sa sceneRect
*/
QGraphicsScene::QGraphicsScene(qreal x, qreal y, qreal width, qreal height, QObject *parent)
: QObject(*new QGraphicsScenePrivate, parent)
{
setSceneRect(x, y, width, height);
d_func()->init();
}
/*!
Destroys the QGraphicsScene object.
*/
QGraphicsScene::~QGraphicsScene()
{
Q_D(QGraphicsScene);
// Remove this scene from qApp's global scene list.
qApp->d_func()->scene_list.removeAll(this);
clear();
// Remove this scene from all associated views.
for (int j = 0; j < d->views.size(); ++j)
d->views.at(j)->setScene(0);
}
/*!
\property QGraphicsScene::sceneRect
\brief the scene rectangle; the bounding rectangle of the scene
The scene rectangle defines the extent of the scene. It is
primarily used by QGraphicsView to determine the view's default
scrollable area, and by QGraphicsScene to manage item indexing.
If unset, or if set to a null QRectF, sceneRect() will return the largest
bounding rect of all items on the scene since the scene was created (i.e.,
a rectangle that grows when items are added to or moved in the scene, but
never shrinks).
\sa width(), height(), QGraphicsView::sceneRect
*/
QRectF QGraphicsScene::sceneRect() const
{
Q_D(const QGraphicsScene);
const_cast<QGraphicsScenePrivate *>(d)->_q_updateIndex();
return d->hasSceneRect ? d->sceneRect : d->growingItemsBoundingRect;
}
void QGraphicsScene::setSceneRect(const QRectF &rect)
{
Q_D(QGraphicsScene);
if (rect != d->sceneRect) {
d->hasSceneRect = !rect.isNull();
d->sceneRect = rect;
d->resetIndex();
emit sceneRectChanged(rect);
}
}
/*!
\fn qreal QGraphicsScene::width() const
This convenience function is equivalent to calling sceneRect().width().
\sa height()
*/
/*!
\fn qreal QGraphicsScene::height() const
This convenience function is equivalent to calling \c sceneRect().height().
\sa width()
*/
/*!
Renders the \a source rect from scene into \a target, using \a painter. This
function is useful for capturing the contents of the scene onto a paint
device, such as a QImage (e.g., to take a screenshot), or for printing
with QPrinter. For example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 1
If \a source is a null rect, this function will use sceneRect() to
determine what to render. If \a target is a null rect, the dimensions of \a
painter's paint device will be used.
The source rect contents will be transformed according to \a
aspectRatioMode to fit into the target rect. By default, the aspect ratio
is kept, and \a source is scaled to fit in \a target.
\sa QGraphicsView::render()
*/
void QGraphicsScene::render(QPainter *painter, const QRectF &target, const QRectF &source,
Qt::AspectRatioMode aspectRatioMode)
{
// Default source rect = scene rect
QRectF sourceRect = source;
if (sourceRect.isNull())
sourceRect = sceneRect();
// Default target rect = device rect
QRectF targetRect = target;
if (targetRect.isNull()) {
if (painter->device()->devType() == QInternal::Picture)
targetRect = sourceRect;
else
targetRect.setRect(0, 0, painter->device()->width(), painter->device()->height());
}
// Find the ideal x / y scaling ratio to fit \a source into \a target.
qreal xratio = targetRect.width() / sourceRect.width();
qreal yratio = targetRect.height() / sourceRect.height();
// Scale according to the aspect ratio mode.
switch (aspectRatioMode) {
case Qt::KeepAspectRatio:
xratio = yratio = qMin(xratio, yratio);
break;
case Qt::KeepAspectRatioByExpanding:
xratio = yratio = qMax(xratio, yratio);
break;
case Qt::IgnoreAspectRatio:
break;
}
// Find all items to draw, and reverse the list (we want to draw
// in reverse order).
QList<QGraphicsItem *> itemList = items(sourceRect, Qt::IntersectsItemBoundingRect);
QGraphicsItem **itemArray = new QGraphicsItem *[itemList.size()];
int numItems = itemList.size();
for (int i = 0; i < numItems; ++i)
itemArray[numItems - i - 1] = itemList.at(i);
itemList.clear();
painter->save();
// Transform the painter.
painter->setClipRect(targetRect);
QTransform painterTransform;
painterTransform *= QTransform()
.translate(targetRect.left(), targetRect.top())
.scale(xratio, yratio)
.translate(-sourceRect.left(), -sourceRect.top());
painter->setWorldTransform(painterTransform, true);
// Two unit vectors.
QLineF v1(0, 0, 1, 0);
QLineF v2(0, 0, 0, 1);
// Generate the style options
QStyleOptionGraphicsItem *styleOptionArray = new QStyleOptionGraphicsItem[numItems];
for (int i = 0; i < numItems; ++i)
itemArray[i]->d_ptr->initStyleOption(&styleOptionArray[i], painterTransform, targetRect.toRect());
// Render the scene.
drawBackground(painter, sourceRect);
drawItems(painter, numItems, itemArray, styleOptionArray);
drawForeground(painter, sourceRect);
delete [] itemArray;
delete [] styleOptionArray;
painter->restore();
}
/*!
\property QGraphicsScene::itemIndexMethod
\brief the item indexing method.
QGraphicsScene applies an indexing algorithm to the scene, to speed up
item discovery functions like items() and itemAt(). Indexing is most
efficient for static scenes (i.e., where items don't move around). For
dynamic scenes, or scenes with many animated items, the index bookkeeping
can outweight the fast lookup speeds.
For the common case, the default index method BspTreeIndex works fine. If
your scene uses many animations and you are experiencing slowness, you can
disable indexing by calling \c setItemIndexMethod(NoIndex).
\sa bspTreeDepth
*/
QGraphicsScene::ItemIndexMethod QGraphicsScene::itemIndexMethod() const
{
Q_D(const QGraphicsScene);
return d->indexMethod;
}
void QGraphicsScene::setItemIndexMethod(ItemIndexMethod method)
{
Q_D(QGraphicsScene);
d->resetIndex();
d->indexMethod = method;
}
/*!
\property QGraphicsScene::bspTreeDepth
\brief the depth of QGraphicsScene's BSP index tree
\since 4.3
This property has no effect when NoIndex is used.
This value determines the depth of QGraphicsScene's BSP tree. The depth
directly affects QGraphicsScene's performance and memory usage; the latter
growing exponentially with the depth of the tree. With an optimal tree
depth, QGraphicsScene can instantly determine the locality of items, even
for scenes with thousands or millions of items. This also greatly improves
rendering performance.
By default, the value is 0, in which case Qt will guess a reasonable
default depth based on the size, location and number of items in the
scene. If these parameters change frequently, however, you may experience
slowdowns as QGraphicsScene retunes the depth internally. You can avoid
potential slowdowns by fixating the tree depth through setting this
property.
The depth of the tree and the size of the scene rectangle decide the
granularity of the scene's partitioning. The size of each scene segment is
determined by the following algorithm:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 2
The BSP tree has an optimal size when each segment contains between 0 and
10 items.
\sa itemIndexMethod
*/
int QGraphicsScene::bspTreeDepth() const
{
Q_D(const QGraphicsScene);
return d->bspTreeDepth;
}
void QGraphicsScene::setBspTreeDepth(int depth)
{
Q_D(QGraphicsScene);
if (d->bspTreeDepth == depth)
return;
if (depth < 0) {
qWarning("QGraphicsScene::setBspTreeDepth: invalid depth %d ignored; must be >= 0", depth);
return;
}
d->bspTreeDepth = depth;
d->resetIndex();
}
/*!
\property QGraphicsScene::sortCacheEnabled
\brief whether sort caching is enabled
\since 4.5
When enabled, this property adds a cache that speeds up sorting and
transformations for scenes with deep hierarchies (i.e., items with many
levels of descendents), at the cost of using more memory (approx. 100 more
bytes of memory per item).
Items that are not part of a deep hierarchy suffer no penalty from this
cache.
*/
bool QGraphicsScene::isSortCacheEnabled() const
{
Q_D(const QGraphicsScene);
return d->sortCacheEnabled;
}
void QGraphicsScene::setSortCacheEnabled(bool enabled)
{
Q_D(QGraphicsScene);
if (enabled == d->sortCacheEnabled)
return;
if ((d->sortCacheEnabled = enabled))
d->invalidateSortCache();
}
/*!
Calculates and returns the bounding rect of all items on the scene. This
function works by iterating over all items, and because if this, it can
be slow for large scenes.
\sa sceneRect()
*/
QRectF QGraphicsScene::itemsBoundingRect() const
{
QRectF boundingRect;
foreach (QGraphicsItem *item, items())
boundingRect |= item->sceneBoundingRect();
return boundingRect;
}
/*!
Returns a list of all items on the scene, in no particular order.
\sa addItem(), removeItem()
*/
QList<QGraphicsItem *> QGraphicsScene::items() const
{
Q_D(const QGraphicsScene);
const_cast<QGraphicsScenePrivate *>(d)->purgeRemovedItems();
// If freeItemIndexes is empty, we know there are no holes in indexedItems and
// unindexedItems.
if (d->freeItemIndexes.isEmpty()) {
if (d->unindexedItems.isEmpty())
return d->indexedItems;
return d->indexedItems + d->unindexedItems;
}
// Rebuild the list of items to avoid holes. ### We could also just
// compress the item lists at this point.
QList<QGraphicsItem *> itemList;
foreach (QGraphicsItem *item, d->indexedItems + d->unindexedItems) {
if (item)
itemList << item;
}
return itemList;
}
/*!
Returns all visible items at position \a pos in the scene. The items are
listed in descending Z order (i.e., the first item in the list is the
top-most item, and the last item is the bottom-most item).
\sa itemAt()
*/
QList<QGraphicsItem *> QGraphicsScene::items(const QPointF &pos) const
{
Q_D(const QGraphicsScene);
return d->items_helper(pos);
}
/*!
\fn QList<QGraphicsItem *> QGraphicsScene::items(const QRectF &rectangle, Qt::ItemSelectionMode mode) const
\overload
Returns all visible items that, depending on \a mode, are either inside or
intersect with the specified \a rectangle.
The default value for \a mode is Qt::IntersectsItemShape; all items whose
exact shape intersects with or is contained by \a rectangle are returned.
\sa itemAt()
*/
QList<QGraphicsItem *> QGraphicsScene::items(const QRectF &rect, Qt::ItemSelectionMode mode) const
{
Q_D(const QGraphicsScene);
QList<QGraphicsItem *> itemList;
d->recursive_items_helper(0, rect, &itemList, QTransform(), QTransform(), mode, Qt::AscendingOrder);
return itemList;
}
/*!
\fn QList<QGraphicsItem *> QGraphicsScene::items(qreal x, qreal y, qreal w, qreal h, Qt::ItemSelectionMode mode) const
\since 4.3
This convenience function is equivalent to calling items(QRectF(\a x, \a y, \a w, \a h), \a mode).
*/
/*!
\overload
Returns all visible items that, depending on \a mode, are either inside or
intersect with the polygon \a polygon.
The default value for \a mode is Qt::IntersectsItemShape; all items whose
exact shape intersects with or is contained by \a polygon are returned.
\sa itemAt()
*/
QList<QGraphicsItem *> QGraphicsScene::items(const QPolygonF &polygon, Qt::ItemSelectionMode mode) const
{
Q_D(const QGraphicsScene);
return d->items_helper(polygon, mode, Qt::AscendingOrder);
}
/*!
\overload
Returns all visible items that, depending on \a path, are either inside or
intersect with the path \a path.
The default value for \a mode is Qt::IntersectsItemShape; all items whose
exact shape intersects with or is contained by \a path are returned.
\sa itemAt()
*/
QList<QGraphicsItem *> QGraphicsScene::items(const QPainterPath &path, Qt::ItemSelectionMode mode) const
{
Q_D(const QGraphicsScene);
return d->items_helper(path, mode, Qt::AscendingOrder);
}
/*!
Returns a list of all items that collide with \a item. Collisions are
determined by calling QGraphicsItem::collidesWithItem(); the collision
detection is determined by \a mode. By default, all items whose shape
intersects \a item or is contained inside \a item's shape are returned.
The items are returned in descending Z order (i.e., the first item in the
list is the top-most item, and the last item is the bottom-most item).
\sa items(), itemAt(), QGraphicsItem::collidesWithItem()
*/
QList<QGraphicsItem *> QGraphicsScene::collidingItems(const QGraphicsItem *item,
Qt::ItemSelectionMode mode) const
{
Q_D(const QGraphicsScene);
if (!item) {
qWarning("QGraphicsScene::collidingItems: cannot find collisions for null item");
return QList<QGraphicsItem *>();
}
QList<QGraphicsItem *> tmp;
foreach (QGraphicsItem *itemInVicinity, d->estimateItemsInRect(item->sceneBoundingRect())) {
if (item != itemInVicinity && item->collidesWithItem(itemInVicinity, mode))
tmp << itemInVicinity;
}
d->sortItems(&tmp, Qt::AscendingOrder, d->sortCacheEnabled);
return tmp;
}
/*!
\fn QGraphicsItem *QGraphicsScene::itemAt(const QPointF &position) const
Returns the topmost visible item at the specified \a position, or 0 if
there are no items at this position.
\note The topmost item is the one with the highest Z-value.
\sa items(), collidingItems(), QGraphicsItem::setZValue()
*/
QGraphicsItem *QGraphicsScene::itemAt(const QPointF &pos) const
{
QList<QGraphicsItem *> itemsAtPoint = items(pos);
return itemsAtPoint.isEmpty() ? 0 : itemsAtPoint.first();
}
/*!
\fn QGraphicsScene::itemAt(qreal x, qreal y) const
\overload
Returns the topmost item at the position specified by (\a x, \a
y), or 0 if there are no items at this position.
This convenience function is equivalent to calling \c
{itemAt(QPointF(x, y))}.
\note The topmost item is the one with the highest Z-value.
*/
/*!
Returns a list of all currently selected items. The items are
returned in no particular order.
\sa setSelectionArea()
*/
QList<QGraphicsItem *> QGraphicsScene::selectedItems() const
{
Q_D(const QGraphicsScene);
// Optimization: Lazily removes items that are not selected.
QGraphicsScene *that = const_cast<QGraphicsScene *>(this);
QSet<QGraphicsItem *> actuallySelectedSet;
foreach (QGraphicsItem *item, that->d_func()->selectedItems) {
if (item->isSelected())
actuallySelectedSet << item;
}
that->d_func()->selectedItems = actuallySelectedSet;
return d->selectedItems.values();
}
/*!
Returns the selection area that was previously set with
setSelectionArea(), or an empty QPainterPath if no selection area has been
set.
\sa setSelectionArea()
*/
QPainterPath QGraphicsScene::selectionArea() const
{
Q_D(const QGraphicsScene);
return d->selectionArea;
}
/*!
Sets the selection area to \a path. All items within this area are
immediately selected, and all items outside are unselected. You can get
the list of all selected items by calling selectedItems().
For an item to be selected, it must be marked as \e selectable
(QGraphicsItem::ItemIsSelectable).
\sa clearSelection(), selectionArea()
*/
void QGraphicsScene::setSelectionArea(const QPainterPath &path)
{
setSelectionArea(path, Qt::IntersectsItemShape);
}
/*!
\overload
\since 4.3
Sets the selection area to \a path using \a mode to determine if items are
included in the selection area.
\sa clearSelection(), selectionArea()
*/
void QGraphicsScene::setSelectionArea(const QPainterPath &path, Qt::ItemSelectionMode mode)
{
Q_D(QGraphicsScene);
// Note: with boolean path operations, we can improve performance here
// quite a lot by "growing" the old path instead of replacing it. That
// allows us to only check the intersect area for changes, instead of
// reevaluating the whole path over again.
d->selectionArea = path;
QSet<QGraphicsItem *> unselectItems = d->selectedItems;
// Disable emitting selectionChanged() for individual items.
++d->selectionChanging;
bool changed = false;
// Set all items in path to selected.
foreach (QGraphicsItem *item, items(path, mode)) {
if (item->flags() & QGraphicsItem::ItemIsSelectable) {
if (!item->isSelected())
changed = true;
unselectItems.remove(item);
item->setSelected(true);
}
}
// Unselect all items outside path.
foreach (QGraphicsItem *item, unselectItems) {
item->setSelected(false);
changed = true;
}
// Reenable emitting selectionChanged() for individual items.
--d->selectionChanging;
if (!d->selectionChanging && changed)
emit selectionChanged();
}
/*!
Clears the current selection.
\sa setSelectionArea(), selectedItems()
*/
void QGraphicsScene::clearSelection()
{
Q_D(QGraphicsScene);
// Disable emitting selectionChanged
++d->selectionChanging;
bool changed = !d->selectedItems.isEmpty();
foreach (QGraphicsItem *item, d->selectedItems)
item->setSelected(false);
d->selectedItems.clear();
// Reenable emitting selectionChanged() for individual items.
--d->selectionChanging;
if (!d->selectionChanging && changed)
emit selectionChanged();
}
/*!
\since 4.4
Removes and deletes all items from the scene, but otherwise leaves the
state of the scene unchanged.
\sa addItem()
*/
void QGraphicsScene::clear()
{
Q_D(QGraphicsScene);
// Recursive descent delete
for (int i = 0; i < d->indexedItems.size(); ++i) {
if (QGraphicsItem *item = d->indexedItems.at(i)) {
if (!item->parentItem())
delete item;
}
}
QList<QGraphicsItem *> unindexedParents;
for (int i = 0; i < d->unindexedItems.size(); ++i) {
QGraphicsItem *item = d->unindexedItems.at(i);
if (!item->parentItem())
unindexedParents << item;
}
d->unindexedItems.clear();
qDeleteAll(unindexedParents);
d->indexedItems.clear();
d->freeItemIndexes.clear();
d->lastItemCount = 0;
d->bspTree.clear();
d->largestUntransformableItem = QRectF();
d->allItemsIgnoreHoverEvents = true;
d->allItemsUseDefaultCursor = true;
}
/*!
Groups all items in \a items into a new QGraphicsItemGroup, and returns a
pointer to the group. The group is created with the common ancestor of \a
items as its parent, and with position (0, 0). The items are all
reparented to the group, and their positions and transformations are
mapped to the group. If \a items is empty, this function will return an
empty top-level QGraphicsItemGroup.
QGraphicsScene has ownership of the group item; you do not need to delete
it. To dismantle (ungroup) a group, call destroyItemGroup().
\sa destroyItemGroup(), QGraphicsItemGroup::addToGroup()
*/
QGraphicsItemGroup *QGraphicsScene::createItemGroup(const QList<QGraphicsItem *> &items)
{
// Build a list of the first item's ancestors
QList<QGraphicsItem *> ancestors;
int n = 0;
if (!items.isEmpty()) {
QGraphicsItem *parent = items.at(n++);
while ((parent = parent->parentItem()))
ancestors.append(parent);
}
// Find the common ancestor for all items
QGraphicsItem *commonAncestor = 0;
if (!ancestors.isEmpty()) {
while (n < items.size()) {
int commonIndex = -1;
QGraphicsItem *parent = items.at(n++);
do {
int index = ancestors.indexOf(parent, qMax(0, commonIndex));
if (index != -1) {
commonIndex = index;
break;
}
} while ((parent = parent->parentItem()));
if (commonIndex == -1) {
commonAncestor = 0;
break;
}
commonAncestor = ancestors.at(commonIndex);
}
}
// Create a new group at that level
QGraphicsItemGroup *group = new QGraphicsItemGroup(commonAncestor);
if (!commonAncestor)
addItem(group);
foreach (QGraphicsItem *item, items)
group->addToGroup(item);
return group;
}
/*!
Reparents all items in \a group to \a group's parent item, then removes \a
group from the scene, and finally deletes it. The items' positions and
transformations are mapped from the group to the group's parent.
\sa createItemGroup(), QGraphicsItemGroup::removeFromGroup()
*/
void QGraphicsScene::destroyItemGroup(QGraphicsItemGroup *group)
{
foreach (QGraphicsItem *item, group->children())
group->removeFromGroup(item);
removeItem(group);
delete group;
}
/*!
Adds or moves the item \a item and all its childen to the scene.
If the item is visible (i.e., QGraphicsItem::isVisible() returns
true), QGraphicsScene will emit changed() once control goes back
to the event loop.
If the item is already in a different scene, it will first be removed from
its old scene, and then added to this scene as a top-level.
QGraphicsScene will send ItemSceneChange notifications to \a item while
it is added to the scene. If item does not currently belong to a scene, only one
notification is sent. If it does belong to scene already (i.e., it is
moved to this scene), QGraphicsScene will send an addition notification as
the item is removed from its previous scene.
\sa removeItem(), addEllipse(), addLine(), addPath(), addPixmap(),
addRect(), addText(), addWidget()
*/
void QGraphicsScene::addItem(QGraphicsItem *item)
{
Q_D(QGraphicsScene);
if (!item) {
qWarning("QGraphicsScene::addItem: cannot add null item");
return;
}
if (item->scene() == this) {
qWarning("QGraphicsScene::addItem: item has already been added to this scene");
return;
}
// Remove this item from its existing scene
if (QGraphicsScene *oldScene = item->scene())
oldScene->removeItem(item);
// Notify the item that its scene is changing, and allow the item to
// react.
const QVariant newSceneVariant(item->itemChange(QGraphicsItem::ItemSceneChange,
qVariantFromValue<QGraphicsScene *>(this)));
QGraphicsScene *targetScene = qVariantValue<QGraphicsScene *>(newSceneVariant);
if (targetScene != this) {
if (targetScene && item->scene() != targetScene)
targetScene->addItem(item);
return;
}
// Prevent reusing a recently deleted pointer: purge all removed items
// from our lists.
d->purgeRemovedItems();
// Invalidate any sort caching; arrival of a new item means we need to
// resort.
d->invalidateSortCache();
// Detach this item from its parent if the parent's scene is different
// from this scene.
if (QGraphicsItem *itemParent = item->parentItem()) {
if (itemParent->scene() != this)
item->setParentItem(0);
}
// Add the item to this scene
item->d_func()->scene = targetScene;
// Indexing requires sceneBoundingRect(), but because \a item might
// not be completely constructed at this point, we need to store it in
// a temporary list and schedule an indexing for later.
d->unindexedItems << item;
item->d_func()->index = -1;
d->startIndexTimer(0);
// Add to list of toplevels if this item is a toplevel.
if (!item->d_ptr->parent)
d->registerTopLevelItem(item);
// Update the scene's sort cache settings.
item->d_ptr->globalStackingOrder = -1;
d->invalidateSortCache();
// Add to list of items that require an update. We cannot assume that the
// item is fully constructed, so calling item->update() can lead to a pure
// virtual function call to boundingRect().
if (!d->updateAll) {
if (d->pendingUpdateItems.isEmpty())
QMetaObject::invokeMethod(this, "_q_updateLater", Qt::QueuedConnection);
d->pendingUpdateItems << item;
}
// Disable selectionChanged() for individual items
++d->selectionChanging;
int oldSelectedItemSize = d->selectedItems.size();
// Enable mouse tracking if the item accepts hover events or has a cursor set.
if (d->allItemsIgnoreHoverEvents && d->itemAcceptsHoverEvents_helper(item)) {
d->allItemsIgnoreHoverEvents = false;
d->enableMouseTrackingOnViews();
}
#ifndef QT_NO_CURSOR
if (d->allItemsUseDefaultCursor && item->hasCursor()) {
d->allItemsUseDefaultCursor = false;
if (d->allItemsIgnoreHoverEvents) // already enabled otherwise
d->enableMouseTrackingOnViews();
}
#endif //QT_NO_CURSOR
// Update selection lists
if (item->isSelected())
d->selectedItems << item;
if (item->isWidget() && item->isVisible() && static_cast<QGraphicsWidget *>(item)->windowType() == Qt::Popup)
d->addPopup(static_cast<QGraphicsWidget *>(item));
// Update creation order focus chain. Make sure to leave the widget's
// internal tab order intact.
if (item->isWidget()) {
QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
if (!d->tabFocusFirst) {
// No first tab focus widget - make this the first tab focus
// widget.
d->tabFocusFirst = widget;
} else if (!widget->parentWidget()) {
// Adding a widget that is not part of a tab focus chain.
QGraphicsWidget *last = d->tabFocusFirst->d_func()->focusPrev;
QGraphicsWidget *lastNew = widget->d_func()->focusPrev;
last->d_func()->focusNext = widget;
widget->d_func()->focusPrev = last;
d->tabFocusFirst->d_func()->focusPrev = lastNew;
lastNew->d_func()->focusNext = d->tabFocusFirst;
}
}
// Add all children recursively
foreach (QGraphicsItem *child, item->children())
addItem(child);
// Resolve font and palette.
item->d_ptr->resolveFont(d->font.resolve());
item->d_ptr->resolvePalette(d->palette.resolve());
if (!item->d_ptr->explicitlyHidden) {
if (d->unpolishedItems.isEmpty())
QMetaObject::invokeMethod(this, "_q_polishItems", Qt::QueuedConnection);
d->unpolishedItems << item;
}
// Reenable selectionChanged() for individual items
--d->selectionChanging;
if (!d->selectionChanging && d->selectedItems.size() != oldSelectedItemSize)
emit selectionChanged();
// Deliver post-change notification
item->itemChange(QGraphicsItem::ItemSceneHasChanged, newSceneVariant);
}
/*!
Creates and adds an ellipse item to the scene, and returns the item
pointer. The geometry of the ellipse is defined by \a rect, and its pen
and brush are initialized to \a pen and \a brush.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addLine(), addPath(), addPixmap(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsEllipseItem *QGraphicsScene::addEllipse(const QRectF &rect, const QPen &pen, const QBrush &brush)
{
QGraphicsEllipseItem *item = new QGraphicsEllipseItem(rect);
item->setPen(pen);
item->setBrush(brush);
addItem(item);
return item;
}
/*!
\fn QGraphicsEllipseItem *QGraphicsScene::addEllipse(qreal x, qreal y, qreal w, qreal h, const QPen &pen, const QBrush &brush)
\since 4.3
This convenience function is equivalent to calling addEllipse(QRectF(\a x,
\a y, \a w, \a h), \a pen, \a brush).
*/
/*!
Creates and adds a line item to the scene, and returns the item
pointer. The geometry of the line is defined by \a line, and its pen
is initialized to \a pen.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addPath(), addPixmap(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsLineItem *QGraphicsScene::addLine(const QLineF &line, const QPen &pen)
{
QGraphicsLineItem *item = new QGraphicsLineItem(line);
item->setPen(pen);
addItem(item);
return item;
}
/*!
\fn QGraphicsLineItem *QGraphicsScene::addLine(qreal x1, qreal y1, qreal x2, qreal y2, const QPen &pen)
\since 4.3
This convenience function is equivalent to calling addLine(QLineF(\a x1,
\a y1, \a x2, \a y2), \a pen).
*/
/*!
Creates and adds a path item to the scene, and returns the item
pointer. The geometry of the path is defined by \a path, and its pen and
brush are initialized to \a pen and \a brush.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPixmap(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsPathItem *QGraphicsScene::addPath(const QPainterPath &path, const QPen &pen, const QBrush &brush)
{
QGraphicsPathItem *item = new QGraphicsPathItem(path);
item->setPen(pen);
item->setBrush(brush);
addItem(item);
return item;
}
/*!
Creates and adds a pixmap item to the scene, and returns the item
pointer. The pixmap is defined by \a pixmap.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPath(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsPixmapItem *QGraphicsScene::addPixmap(const QPixmap &pixmap)
{
QGraphicsPixmapItem *item = new QGraphicsPixmapItem(pixmap);
addItem(item);
return item;
}
/*!
Creates and adds a polygon item to the scene, and returns the item
pointer. The polygon is defined by \a polygon, and its pen and
brush are initialized to \a pen and \a brush.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPath(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsPolygonItem *QGraphicsScene::addPolygon(const QPolygonF &polygon,
const QPen &pen, const QBrush &brush)
{
QGraphicsPolygonItem *item = new QGraphicsPolygonItem(polygon);
item->setPen(pen);
item->setBrush(brush);
addItem(item);
return item;
}
/*!
Creates and adds a rectangle item to the scene, and returns the item
pointer. The geometry of the rectangle is defined by \a rect, and its pen
and brush are initialized to \a pen and \a brush.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0). For example, if a QRect(50, 50, 100,
100) is added, its top-left corner will be at (50, 50) relative to the
origin in the items coordinate system.
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPixmap(), addPixmap(), addText(),
addItem(), addWidget()
*/
QGraphicsRectItem *QGraphicsScene::addRect(const QRectF &rect, const QPen &pen, const QBrush &brush)
{
QGraphicsRectItem *item = new QGraphicsRectItem(rect);
item->setPen(pen);
item->setBrush(brush);
addItem(item);
return item;
}
/*!
\fn QGraphicsRectItem *QGraphicsScene::addRect(qreal x, qreal y, qreal w, qreal h, const QPen &pen, const QBrush &brush)
\since 4.3
This convenience function is equivalent to calling addRect(QRectF(\a x,
\a y, \a w, \a h), \a pen, \a brush).
*/
/*!
Creates and adds a text item to the scene, and returns the item
pointer. The text string is initialized to \a text, and its font
is initialized to \a font.
The item's position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPixmap(), addPixmap(), addRect(),
addItem(), addWidget()
*/
QGraphicsTextItem *QGraphicsScene::addText(const QString &text, const QFont &font)
{
QGraphicsTextItem *item = new QGraphicsTextItem(text);
item->setFont(font);
addItem(item);
return item;
}
/*!
Creates and adds a QGraphicsSimpleTextItem to the scene, and returns the
item pointer. The text string is initialized to \a text, and its font is
initialized to \a font.
The item's position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPixmap(), addPixmap(), addRect(),
addItem(), addWidget()
*/
QGraphicsSimpleTextItem *QGraphicsScene::addSimpleText(const QString &text, const QFont &font)
{
QGraphicsSimpleTextItem *item = new QGraphicsSimpleTextItem(text);
item->setFont(font);
addItem(item);
return item;
}
/*!
Creates a new QGraphicsProxyWidget for \a widget, adds it to the scene,
and returns a pointer to the proxy. \a wFlags set the default window flags
for the embedding proxy widget.
The item's position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
Note that widgets with the Qt::WA_PaintOnScreen widget attribute
set and widgets that wrap an external application or controller
are not supported. Examples are QGLWidget and QAxWidget.
\sa addEllipse(), addLine(), addPixmap(), addPixmap(), addRect(),
addText(), addSimpleText(), addItem()
*/
QGraphicsProxyWidget *QGraphicsScene::addWidget(QWidget *widget, Qt::WindowFlags wFlags)
{
QGraphicsProxyWidget *proxy = new QGraphicsProxyWidget(0, wFlags);
proxy->setWidget(widget);
addItem(proxy);
return proxy;
}
/*!
Removes the item \a item and all its children from the scene. The
ownership of \a item is passed on to the caller (i.e.,
QGraphicsScene will no longer delete \a item when destroyed).
\sa addItem()
*/
void QGraphicsScene::removeItem(QGraphicsItem *item)
{
// ### Refactoring: This function shares much functionality with _q_removeItemLater()
Q_D(QGraphicsScene);
if (!item) {
qWarning("QGraphicsScene::removeItem: cannot remove 0-item");
return;
}
if (item->scene() != this) {
qWarning("QGraphicsScene::removeItem: item %p's scene (%p)"
" is different from this scene (%p)",
item, item->scene(), this);
return;
}
// Notify the item that it's scene is changing to 0, allowing the item to
// react.
const QVariant newSceneVariant(item->itemChange(QGraphicsItem::ItemSceneChange,
qVariantFromValue<QGraphicsScene *>(0)));
QGraphicsScene *targetScene = qVariantValue<QGraphicsScene *>(newSceneVariant);
if (targetScene != 0 && targetScene != this) {
targetScene->addItem(item);
return;
}
d->removeItemHelper(item);
// Deliver post-change notification
item->itemChange(QGraphicsItem::ItemSceneHasChanged, newSceneVariant);
}
/*!
Returns the scene's current focus item, or 0 if no item currently has
focus.
The focus item receives keyboard input when the scene receives a
key event.
\sa setFocusItem(), QGraphicsItem::hasFocus()
*/
QGraphicsItem *QGraphicsScene::focusItem() const
{
Q_D(const QGraphicsScene);
return d->focusItem;
}
/*!
Sets the scene's focus item to \a item, with the focus reason \a
focusReason, after removing focus from any previous item that may have had
focus.
If \a item is 0, or if it either does not accept focus (i.e., it does not
have the QGraphicsItem::ItemIsFocusable flag enabled), or is not visible
or not enabled, this function only removes focus from any previous
focusitem.
If item is not 0, and the scene does not currently have focus (i.e.,
hasFocus() returns false), this function will call setFocus()
automatically.
\sa focusItem(), hasFocus(), setFocus()
*/
void QGraphicsScene::setFocusItem(QGraphicsItem *item, Qt::FocusReason focusReason)
{
Q_D(QGraphicsScene);
if (item == d->focusItem)
return;
if (item && (!(item->flags() & QGraphicsItem::ItemIsFocusable)
|| !item->isVisible() || !item->isEnabled())) {
item = 0;
}
if (item) {
setFocus(focusReason);
if (item == d->focusItem)
return;
}
if (d->focusItem) {
QFocusEvent event(QEvent::FocusOut, focusReason);
d->lastFocusItem = d->focusItem;
d->focusItem = 0;
d->sendEvent(d->lastFocusItem, &event);
}
if (item) {
if (item->isWidget()) {
// Update focus child chain.
static_cast<QGraphicsWidget *>(item)->d_func()->setFocusWidget();
}
d->focusItem = item;
QFocusEvent event(QEvent::FocusIn, focusReason);
d->sendEvent(item, &event);
}
}
/*!
Returns true if the scene has focus; otherwise returns false. If the scene
has focus, it will will forward key events from QKeyEvent to any item that
has focus.
\sa setFocus(), setFocusItem()
*/
bool QGraphicsScene::hasFocus() const
{
Q_D(const QGraphicsScene);
return d->hasFocus;
}
/*!
Sets focus on the scene by sending a QFocusEvent to the scene, passing \a
focusReason as the reason. If the scene regains focus after having
previously lost it while an item had focus, the last focus item will
receive focus with \a focusReason as the reason.
If the scene already has focus, this function does nothing.
\sa hasFocus(), clearFocus(), setFocusItem()
*/
void QGraphicsScene::setFocus(Qt::FocusReason focusReason)
{
Q_D(QGraphicsScene);
if (d->hasFocus)
return;
QFocusEvent event(QEvent::FocusIn, focusReason);
QCoreApplication::sendEvent(this, &event);
}
/*!
Clears focus from the scene. If any item has focus when this function is
called, it will lose focus, and regain focus again once the scene regains
focus.
A scene that does not have focus ignores key events.
\sa hasFocus(), setFocus(), setFocusItem()
*/
void QGraphicsScene::clearFocus()
{
Q_D(QGraphicsScene);
if (d->hasFocus) {
d->hasFocus = false;
setFocusItem(0, Qt::OtherFocusReason);
}
}
/*!
\property QGraphicsScene::stickyFocus
\brief whether or not clicking the scene will clear focus
If this property is false (the default), then clicking on the scene
background or on an item that does not accept focus, will clear
focus. Otherwise, focus will remain unchanged.
The focus change happens in response to a mouse press. You can reimplement
mousePressEvent() in a subclass of QGraphicsScene to toggle this property
based on where the user has clicked.
\sa clearFocus(), setFocusItem()
*/
void QGraphicsScene::setStickyFocus(bool enabled)
{
Q_D(QGraphicsScene);
d->stickyFocus = enabled;
}
bool QGraphicsScene::stickyFocus() const
{
Q_D(const QGraphicsScene);
return d->stickyFocus;
}
/*!
Returns the current mouse grabber item, or 0 if no item is currently
grabbing the mouse. The mouse grabber item is the item that receives all
mouse events sent to the scene.
An item becomes a mouse grabber when it receives and accepts a
mouse press event, and it stays the mouse grabber until either of
the following events occur:
\list
\o If the item receives a mouse release event when there are no other
buttons pressed, it loses the mouse grab.
\o If the item becomes invisible (i.e., someone calls \c {item->setVisible(false))},
or if it becomes disabled (i.e., someone calls \c {item->setEnabled(false))},
it loses the mouse grab.
\o If the item is removed from the scene, it loses the mouse grab.
\endlist
If the item loses its mouse grab, the scene will ignore all mouse events
until a new item grabs the mouse (i.e., until a new item receives a mouse
press event).
*/
QGraphicsItem *QGraphicsScene::mouseGrabberItem() const
{
Q_D(const QGraphicsScene);
return !d->mouseGrabberItems.isEmpty() ? d->mouseGrabberItems.last() : 0;
}
/*!
\property QGraphicsScene::backgroundBrush
\brief the background brush of the scene.
Set this property to changes the scene's background to a different color,
gradient or texture. The default background brush is Qt::NoBrush. The
background is drawn before (behind) the items.
Example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 3
QGraphicsScene::render() calls drawBackground() to draw the scene
background. For more detailed control over how the background is drawn,
you can reimplement drawBackground() in a subclass of QGraphicsScene.
*/
QBrush QGraphicsScene::backgroundBrush() const
{
Q_D(const QGraphicsScene);
return d->backgroundBrush;
}
void QGraphicsScene::setBackgroundBrush(const QBrush &brush)
{
Q_D(QGraphicsScene);
d->backgroundBrush = brush;
foreach (QGraphicsView *view, d->views) {
view->resetCachedContent();
view->viewport()->update();
}
update();
}
/*!
\property QGraphicsScene::foregroundBrush
\brief the foreground brush of the scene.
Change this property to set the scene's foreground to a different
color, gradient or texture.
The foreground is drawn after (on top of) the items. The default
foreground brush is Qt::NoBrush ( i.e. the foreground is not
drawn).
Example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 4
QGraphicsScene::render() calls drawForeground() to draw the scene
foreground. For more detailed control over how the foreground is
drawn, you can reimplement the drawForeground() function in a
QGraphicsScene subclass.
*/
QBrush QGraphicsScene::foregroundBrush() const
{
Q_D(const QGraphicsScene);
return d->foregroundBrush;
}
void QGraphicsScene::setForegroundBrush(const QBrush &brush)
{
Q_D(QGraphicsScene);
d->foregroundBrush = brush;
foreach (QGraphicsView *view, views())
view->viewport()->update();
update();
}
/*!
This method is used by input methods to query a set of properties of
the scene to be able to support complex input method operations as support
for surrounding text and reconversions.
The \a query parameter specifies which property is queried.
\sa QWidget::inputMethodQuery()
*/
QVariant QGraphicsScene::inputMethodQuery(Qt::InputMethodQuery query) const
{
Q_D(const QGraphicsScene);
if (!d->focusItem)
return QVariant();
const QTransform matrix = d->focusItem->sceneTransform();
QVariant value = d->focusItem->inputMethodQuery(query);
if (value.type() == QVariant::RectF)
value = matrix.mapRect(value.toRectF());
else if (value.type() == QVariant::PointF)
value = matrix.map(value.toPointF());
else if (value.type() == QVariant::Rect)
value = matrix.mapRect(value.toRect());
else if (value.type() == QVariant::Point)
value = matrix.map(value.toPoint());
return value;
}
/*!
\fn void QGraphicsScene::update(const QRectF &rect)
Schedules a redraw of the area \a rect on the scene.
\sa sceneRect(), changed()
*/
void QGraphicsScene::update(const QRectF &rect)
{
Q_D(QGraphicsScene);
if (d->updateAll || (rect.isEmpty() && !rect.isNull()))
return;
// Check if anyone's connected; if not, we can send updates directly to
// the views. Otherwise or if there are no views, use old behavior.
bool directUpdates = !(d->connectedSignals & d->changedSignalMask) && !d->views.isEmpty();
if (rect.isNull()) {
d->updateAll = true;
d->updatedRects.clear();
if (directUpdates) {
// Update all views.
for (int i = 0; i < d->views.size(); ++i)
d->views.at(i)->d_func()->updateAll();
}
} else {
if (directUpdates) {
// Update all views.
for (int i = 0; i < d->views.size(); ++i) {
QGraphicsView *view = d->views.at(i);
view->d_func()->updateRegion(QRegion(view->mapFromScene(rect).boundingRect()));
}
} else {
d->updatedRects << rect;
}
}
if (!d->calledEmitUpdated) {
d->calledEmitUpdated = true;
QMetaObject::invokeMethod(this, "_q_emitUpdated", Qt::QueuedConnection);
}
}
/*!
\fn void QGraphicsScene::update(qreal x, qreal y, qreal w, qreal h)
\overload
\since 4.3
This function is equivalent to calling update(QRectF(\a x, \a y, \a w,
\a h));
*/
/*!
Invalidates and schedules a redraw of the \a layers in \a rect on the
scene. Any cached content in \a layers is unconditionally invalidated and
redrawn.
You can use this function overload to notify QGraphicsScene of changes to
the background or the foreground of the scene. This function is commonly
used for scenes with tile-based backgrounds to notify changes when
QGraphicsView has enabled
\l{QGraphicsView::CacheBackground}{CacheBackground}.
Example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 5
Note that QGraphicsView currently supports background caching only (see
QGraphicsView::CacheBackground). This function is equivalent to calling
update() if any layer but BackgroundLayer is passed.
\sa QGraphicsView::resetCachedContent()
*/
void QGraphicsScene::invalidate(const QRectF &rect, SceneLayers layers)
{
foreach (QGraphicsView *view, views())
view->invalidateScene(rect, layers);
update(rect);
}
/*!
\fn void QGraphicsScene::invalidate(qreal x, qreal y, qreal w, qreal h, SceneLayers layers)
\overload
\since 4.3
This convenience function is equivalent to calling invalidate(QRectF(\a x, \a
y, \a w, \a h), \a layers);
*/
/*!
Returns a list of all the views that display this scene.
\sa QGraphicsView::scene()
*/
QList <QGraphicsView *> QGraphicsScene::views() const
{
Q_D(const QGraphicsScene);
return d->views;
}
/*!
This slot \e advances the scene by one step, by calling
QGraphicsItem::advance() for all items on the scene. This is done in two
phases: in the first phase, all items are notified that the scene is about
to change, and in the second phase all items are notified that they can
move. In the first phase, QGraphicsItem::advance() is called passing a
value of 0 as an argument, and 1 is passed in the second phase.
\sa QGraphicsItem::advance(), QGraphicsItemAnimation, QTimeLine
*/
void QGraphicsScene::advance()
{
for (int i = 0; i < 2; ++i) {
foreach (QGraphicsItem *item, items())
item->advance(i);
}
}
/*!
Processes the event \a event, and dispatches it to the respective
event handlers.
In addition to calling the convenience event handlers, this
function is responsible for converting mouse move events to hover
events for when there is no mouse grabber item. Hover events are
delivered directly to items; there is no convenience function for
them.
Unlike QWidget, QGraphicsScene does not have the convenience functions
\l{QWidget::}{enterEvent()} and \l{QWidget::}{leaveEvent()}. Use this
function to obtain those events instead.
\sa contextMenuEvent(), keyPressEvent(), keyReleaseEvent(),
mousePressEvent(), mouseMoveEvent(), mouseReleaseEvent(),
mouseDoubleClickEvent(), focusInEvent(), focusOutEvent()
*/
bool QGraphicsScene::event(QEvent *event)
{
Q_D(QGraphicsScene);
switch (event->type()) {
case QEvent::GraphicsSceneMousePress:
case QEvent::GraphicsSceneMouseMove:
case QEvent::GraphicsSceneMouseRelease:
case QEvent::GraphicsSceneMouseDoubleClick:
case QEvent::GraphicsSceneHoverEnter:
case QEvent::GraphicsSceneHoverLeave:
case QEvent::GraphicsSceneHoverMove:
// Reset the under-mouse list to ensure that this event gets fresh
// item-under-mouse data. Be careful about this list; if people delete
// items from inside event handlers, this list can quickly end up
// having stale pointers in it. We need to clear it before dispatching
// events that use it.
// ### this should only be cleared if we received a new mouse move event,
// which relies on us fixing the replay mechanism in QGraphicsView.
d->cachedItemsUnderMouse.clear();
default:
break;
}
switch (event->type()) {
case QEvent::GraphicsSceneDragEnter:
dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
break;
case QEvent::GraphicsSceneDragMove:
dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
break;
case QEvent::GraphicsSceneDragLeave:
dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
break;
case QEvent::GraphicsSceneDrop:
dropEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
break;
case QEvent::GraphicsSceneContextMenu:
contextMenuEvent(static_cast<QGraphicsSceneContextMenuEvent *>(event));
break;
case QEvent::KeyPress:
if (!d->focusItem) {
QKeyEvent *k = static_cast<QKeyEvent *>(event);
if (k->key() == Qt::Key_Tab || k->key() == Qt::Key_Backtab) {
if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier?
bool res = false;
if (k->key() == Qt::Key_Backtab
|| (k->key() == Qt::Key_Tab && (k->modifiers() & Qt::ShiftModifier))) {
res = focusNextPrevChild(false);
} else if (k->key() == Qt::Key_Tab) {
res = focusNextPrevChild(true);
}
if (!res)
event->ignore();
return true;
}
}
}
keyPressEvent(static_cast<QKeyEvent *>(event));
break;
case QEvent::KeyRelease:
keyReleaseEvent(static_cast<QKeyEvent *>(event));
break;
case QEvent::ShortcutOverride: {
QGraphicsItem *parent = focusItem();
while (parent) {
d->sendEvent(parent, event);
if (event->isAccepted())
return true;
parent = parent->parentItem();
}
}
return false;
case QEvent::GraphicsSceneMouseMove:
mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
break;
case QEvent::GraphicsSceneMousePress:
mousePressEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
break;
case QEvent::GraphicsSceneMouseRelease:
mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
break;
case QEvent::GraphicsSceneMouseDoubleClick:
mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
break;
case QEvent::GraphicsSceneWheel:
wheelEvent(static_cast<QGraphicsSceneWheelEvent *>(event));
break;
case QEvent::FocusIn:
focusInEvent(static_cast<QFocusEvent *>(event));
break;
case QEvent::FocusOut:
focusOutEvent(static_cast<QFocusEvent *>(event));
break;
case QEvent::GraphicsSceneHoverEnter:
case QEvent::GraphicsSceneHoverLeave:
case QEvent::GraphicsSceneHoverMove:
d->dispatchHoverEvent(static_cast<QGraphicsSceneHoverEvent *>(event));
break;
case QEvent::Leave:
d->leaveScene();
break;
case QEvent::GraphicsSceneHelp:
helpEvent(static_cast<QGraphicsSceneHelpEvent *>(event));
break;
case QEvent::InputMethod:
inputMethodEvent(static_cast<QInputMethodEvent *>(event));
break;
case QEvent::WindowActivate: {
if (!d->activationRefCount++) {
// Notify all non-window widgets.
foreach (QGraphicsItem *item, items()) {
if (item->isWidget() && item->isVisible() && !item->isWindow() && !item->parentWidget()) {
QEvent event(QEvent::WindowActivate);
QApplication::sendEvent(static_cast<QGraphicsWidget *>(item), &event);
}
}
// Restore window activation.
QGraphicsItem *nextFocusItem = d->focusItem ? d->focusItem : d->lastFocusItem;
if (nextFocusItem && nextFocusItem->window())
setActiveWindow(static_cast<QGraphicsWidget *>(nextFocusItem));
else if (d->tabFocusFirst && d->tabFocusFirst->isWindow())
setActiveWindow(d->tabFocusFirst);
}
break;
}
case QEvent::WindowDeactivate: {
if (!--d->activationRefCount) {
// Remove window activation.
setActiveWindow(0);
// Notify all non-window widgets.
foreach (QGraphicsItem *item, items()) {
if (item->isWidget() && item->isVisible() && !item->isWindow() && !item->parentWidget()) {
QEvent event(QEvent::WindowDeactivate);
QApplication::sendEvent(static_cast<QGraphicsWidget *>(item), &event);
}
}
}
break;
}
case QEvent::ApplicationFontChange: {
// Resolve the existing scene font.
d->resolveFont();
break;
}
case QEvent::FontChange:
// Update the entire scene when the font changes.
update();
break;
case QEvent::ApplicationPaletteChange: {
// Resolve the existing scene palette.
d->resolvePalette();
break;
}
case QEvent::PaletteChange:
// Update the entire scene when the palette changes.
update();
break;
case QEvent::StyleChange:
// Reresolve all widgets' styles. Update all top-level widgets'
// geometries that do not have an explicit style set.
update();
break;
case QEvent::Timer:
if (d->indexTimerId && static_cast<QTimerEvent *>(event)->timerId() == d->indexTimerId) {
if (d->restartIndexTimer) {
d->restartIndexTimer = false;
} else {
// this call will kill the timer
d->_q_updateIndex();
}
}
// Fallthrough intended - support timers in subclasses.
default:
return QObject::event(event);
}
return true;
}
/*!
\reimp
QGraphicsScene filters QApplication's events to detect palette and font
changes.
*/
bool QGraphicsScene::eventFilter(QObject *watched, QEvent *event)
{
if (watched != qApp)
return false;
switch (event->type()) {
case QEvent::ApplicationPaletteChange:
QApplication::postEvent(this, new QEvent(QEvent::ApplicationPaletteChange));
break;
case QEvent::ApplicationFontChange:
QApplication::postEvent(this, new QEvent(QEvent::ApplicationFontChange));
break;
default:
break;
}
return false;
}
/*!
This event handler, for event \a contextMenuEvent, can be reimplemented in
a subclass to receive context menu events. The default implementation
forwards the event to the topmost item that accepts context menu events at
the position of the event. If no items accept context menu events at this
position, the event is ignored.
\sa QGraphicsItem::contextMenuEvent()
*/
void QGraphicsScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *contextMenuEvent)
{
Q_D(QGraphicsScene);
// Ignore by default.
contextMenuEvent->ignore();
// Send the event to all items at this position until one item accepts the
// event.
foreach (QGraphicsItem *item, d->itemsAtPosition(contextMenuEvent->screenPos(),
contextMenuEvent->scenePos(),
contextMenuEvent->widget())) {
contextMenuEvent->setPos(item->d_ptr->genericMapFromScene(contextMenuEvent->scenePos(),
contextMenuEvent->widget()));
contextMenuEvent->accept();
if (!d->sendEvent(item, contextMenuEvent))
break;
if (contextMenuEvent->isAccepted())
break;
}
}
/*!
This event handler, for event \a event, can be reimplemented in a subclass
to receive drag enter events for the scene.
The default implementation accepts the event and prepares the scene to
accept drag move events.
\sa QGraphicsItem::dragEnterEvent(), dragMoveEvent(), dragLeaveEvent(),
dropEvent()
*/
void QGraphicsScene::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
{
Q_D(QGraphicsScene);
d->dragDropItem = 0;
d->lastDropAction = Qt::IgnoreAction;
event->accept();
}
/*!
This event handler, for event \a event, can be reimplemented in a subclass
to receive drag move events for the scene.
\sa QGraphicsItem::dragMoveEvent(), dragEnterEvent(), dragLeaveEvent(),
dropEvent()
*/
void QGraphicsScene::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
{
Q_D(QGraphicsScene);
event->ignore();
if (!d->mouseGrabberItems.isEmpty()) {
// Mouse grabbers that start drag events lose the mouse grab.
d->clearMouseGrabber();
d->mouseGrabberButtonDownPos.clear();
d->mouseGrabberButtonDownScenePos.clear();
d->mouseGrabberButtonDownScreenPos.clear();
}
bool eventDelivered = false;
// Find the topmost enabled items under the cursor. They are all
// candidates for accepting drag & drop events.
foreach (QGraphicsItem *item, d->itemsAtPosition(event->screenPos(),
event->scenePos(),
event->widget())) {
if (!item->isEnabled() || !item->acceptDrops())
continue;
if (item != d->dragDropItem) {
// Enter the new drag drop item. If it accepts the event, we send
// the leave to the parent item.
QGraphicsSceneDragDropEvent dragEnter(QEvent::GraphicsSceneDragEnter);
d->cloneDragDropEvent(&dragEnter, event);
dragEnter.setDropAction(event->proposedAction());
d->sendDragDropEvent(item, &dragEnter);
event->setAccepted(dragEnter.isAccepted());
event->setDropAction(dragEnter.dropAction());
if (!event->isAccepted()) {
// Propagate to the item under
continue;
}
d->lastDropAction = event->dropAction();
if (d->dragDropItem) {
// Leave the last drag drop item. A perfect implementation
// would set the position of this event to the point where
// this event and the last event intersect with the item's
// shape, but that's not easy to do. :-)
QGraphicsSceneDragDropEvent dragLeave(QEvent::GraphicsSceneDragLeave);
d->cloneDragDropEvent(&dragLeave, event);
d->sendDragDropEvent(d->dragDropItem, &dragLeave);
}
// We've got a new drag & drop item
d->dragDropItem = item;
}
// Send the move event.
event->setDropAction(d->lastDropAction);
event->accept();
d->sendDragDropEvent(item, event);
if (event->isAccepted())
d->lastDropAction = event->dropAction();
eventDelivered = true;
break;
}
if (!eventDelivered) {
if (d->dragDropItem) {
// Leave the last drag drop item
QGraphicsSceneDragDropEvent dragLeave(QEvent::GraphicsSceneDragLeave);
d->cloneDragDropEvent(&dragLeave, event);
d->sendDragDropEvent(d->dragDropItem, &dragLeave);
d->dragDropItem = 0;
}
// Propagate
event->setDropAction(Qt::IgnoreAction);
}
}
/*!
This event handler, for event \a event, can be reimplemented in a subclass
to receive drag leave events for the scene.
\sa QGraphicsItem::dragLeaveEvent(), dragEnterEvent(), dragMoveEvent(),
dropEvent()
*/
void QGraphicsScene::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
{
Q_D(QGraphicsScene);
if (d->dragDropItem) {
// Leave the last drag drop item
d->sendDragDropEvent(d->dragDropItem, event);
d->dragDropItem = 0;
}
}
/*!
This event handler, for event \a event, can be reimplemented in a subclass
to receive drop events for the scene.
\sa QGraphicsItem::dropEvent(), dragEnterEvent(), dragMoveEvent(),
dragLeaveEvent()
*/
void QGraphicsScene::dropEvent(QGraphicsSceneDragDropEvent *event)
{
Q_UNUSED(event);
Q_D(QGraphicsScene);
if (d->dragDropItem) {
// Drop on the last drag drop item
d->sendDragDropEvent(d->dragDropItem, event);
d->dragDropItem = 0;
}
}
/*!
This event handler, for event \a focusEvent, can be reimplemented in a
subclass to receive focus in events.
The default implementation sets focus on the scene, and then on the last
focus item.
\sa QGraphicsItem::focusOutEvent()
*/
void QGraphicsScene::focusInEvent(QFocusEvent *focusEvent)
{
Q_D(QGraphicsScene);
d->hasFocus = true;
switch (focusEvent->reason()) {
case Qt::TabFocusReason:
if (!focusNextPrevChild(true))
focusEvent->ignore();
break;
case Qt::BacktabFocusReason:
if (!focusNextPrevChild(false))
focusEvent->ignore();
break;
default:
if (d->lastFocusItem) {
// Set focus on the last focus item
setFocusItem(d->lastFocusItem, focusEvent->reason());
}
break;
}
}
/*!
This event handler, for event \a focusEvent, can be reimplemented in a
subclass to receive focus out events.
The default implementation removes focus from any focus item, then removes
focus from the scene.
\sa QGraphicsItem::focusInEvent()
*/
void QGraphicsScene::focusOutEvent(QFocusEvent *focusEvent)
{
Q_D(QGraphicsScene);
d->hasFocus = false;
setFocusItem(0, focusEvent->reason());
// Remove all popups when the scene loses focus.
if (!d->popupWidgets.isEmpty())
d->removePopup(d->popupWidgets.first());
}
/*!
This event handler, for event \a helpEvent, can be
reimplemented in a subclass to receive help events. The events
are of type QEvent::ToolTip, which are created when a tooltip is
requested.
The default implementation shows the tooltip of the topmost
item, i.e., the item with the highest z-value, at the mouse
cursor position. If no item has a tooltip set, this function
does nothing.
\sa QGraphicsItem::toolTip(), QGraphicsSceneHelpEvent
*/
void QGraphicsScene::helpEvent(QGraphicsSceneHelpEvent *helpEvent)
{
#ifdef QT_NO_TOOLTIP
Q_UNUSED(helpEvent);
#else
// Find the first item that does tooltips
Q_D(QGraphicsScene);
QList<QGraphicsItem *> itemsAtPos = d->itemsAtPosition(helpEvent->screenPos(),
helpEvent->scenePos(),
helpEvent->widget());
QGraphicsItem *toolTipItem = 0;
for (int i = 0; i < itemsAtPos.size(); ++i) {
QGraphicsItem *tmp = itemsAtPos.at(i);
if (!tmp->toolTip().isEmpty()) {
toolTipItem = tmp;
break;
}
}
// Show or hide the tooltip
QString text;
QPoint point;
if (toolTipItem && !toolTipItem->toolTip().isEmpty()) {
text = toolTipItem->toolTip();
point = helpEvent->screenPos();
}
QToolTip::showText(point, text);
helpEvent->setAccepted(!text.isEmpty());
#endif
}
bool QGraphicsScenePrivate::itemAcceptsHoverEvents_helper(const QGraphicsItem *item) const
{
return item->acceptHoverEvents()
|| (item->isWidget() && static_cast<const QGraphicsWidget *>(item)->d_func()->hasDecoration());
}
/*!
This event handler, for event \a hoverEvent, can be reimplemented in a
subclass to receive hover enter events. The default implementation
forwards the event to the topmost item that accepts hover events at the
scene position from the event.
\sa QGraphicsItem::hoverEvent(), QGraphicsItem::setAcceptHoverEvents()
*/
bool QGraphicsScenePrivate::dispatchHoverEvent(QGraphicsSceneHoverEvent *hoverEvent)
{
if (allItemsIgnoreHoverEvents)
return false;
// Find the first item that accepts hover events, reusing earlier
// calculated data is possible.
if (cachedItemsUnderMouse.isEmpty()) {
cachedItemsUnderMouse = itemsAtPosition(hoverEvent->screenPos(),
hoverEvent->scenePos(),
hoverEvent->widget());
}
QGraphicsItem *item = 0;
for (int i = 0; i < cachedItemsUnderMouse.size(); ++i) {
QGraphicsItem *tmp = cachedItemsUnderMouse.at(i);
if (itemAcceptsHoverEvents_helper(tmp)) {
item = tmp;
break;
}
}
// Find the common ancestor item for the new topmost hoverItem and the
// last item in the hoverItem list.
QGraphicsItem *commonAncestorItem = (item && !hoverItems.isEmpty()) ? item->commonAncestorItem(hoverItems.last()) : 0;
while (commonAncestorItem && !itemAcceptsHoverEvents_helper(commonAncestorItem))
commonAncestorItem = commonAncestorItem->parentItem();
if (commonAncestorItem && commonAncestorItem->window() != item->window()) {
// The common ancestor isn't in the same window as the two hovered
// items.
commonAncestorItem = 0;
}
// Check if the common ancestor item is known.
int index = commonAncestorItem ? hoverItems.indexOf(commonAncestorItem) : -1;
// Send hover leaves to any existing hovered children of the common
// ancestor item.
for (int i = hoverItems.size() - 1; i > index; --i) {
QGraphicsItem *lastItem = hoverItems.takeLast();
if (itemAcceptsHoverEvents_helper(lastItem))
sendHoverEvent(QEvent::GraphicsSceneHoverLeave, lastItem, hoverEvent);
}
// Item is a child of a known item. Generate enter events for the
// missing links.
QList<QGraphicsItem *> parents;
QGraphicsItem *parent = item;
while (parent && parent != commonAncestorItem) {
parents.prepend(parent);
if (parent->isWindow()) {
// Stop at the window - we don't deliver beyond this point.
break;
}
parent = parent->parentItem();
}
for (int i = 0; i < parents.size(); ++i) {
parent = parents.at(i);
hoverItems << parent;
if (itemAcceptsHoverEvents_helper(parent))
sendHoverEvent(QEvent::GraphicsSceneHoverEnter, parent, hoverEvent);
}
// Generate a move event for the item itself
if (item && !hoverItems.isEmpty() && item == hoverItems.last()) {
sendHoverEvent(QEvent::GraphicsSceneHoverMove, item, hoverEvent);
return true;
}
return false;
}
/*!
\internal
Handles all actions necessary to clean up the scene when the mouse leaves
the view.
*/
void QGraphicsScenePrivate::leaveScene()
{
Q_Q(QGraphicsScene);
#ifndef QT_NO_TOOLTIP
// Remove any tooltips
QToolTip::showText(QPoint(), QString());
#endif
// Send HoverLeave events to all existing hover items, topmost first.
QGraphicsView *senderWidget = qobject_cast<QGraphicsView *>(q->sender());
QGraphicsSceneHoverEvent hoverEvent;
hoverEvent.setWidget(senderWidget);
if (senderWidget) {
QPoint cursorPos = QCursor::pos();
hoverEvent.setScenePos(senderWidget->mapToScene(senderWidget->mapFromGlobal(cursorPos)));
hoverEvent.setLastScenePos(hoverEvent.scenePos());
hoverEvent.setScreenPos(cursorPos);
hoverEvent.setLastScreenPos(hoverEvent.screenPos());
}
while (!hoverItems.isEmpty()) {
QGraphicsItem *lastItem = hoverItems.takeLast();
if (lastItem->acceptHoverEvents()
|| (lastItem->isWidget() && static_cast<QGraphicsWidget*>(lastItem)->d_func()->hasDecoration()))
sendHoverEvent(QEvent::GraphicsSceneHoverLeave, lastItem, &hoverEvent);
}
}
/*!
This event handler, for event \a keyEvent, can be reimplemented in a
subclass to receive keypress events. The default implementation forwards
the event to current focus item.
\sa QGraphicsItem::keyPressEvent(), focusItem()
*/
void QGraphicsScene::keyPressEvent(QKeyEvent *keyEvent)
{
// ### Merge this function with keyReleaseEvent; they are identical
// ### (except this comment).
Q_D(QGraphicsScene);
QGraphicsItem *item = !d->keyboardGrabberItems.isEmpty() ? d->keyboardGrabberItems.last() : 0;
if (!item)
item = focusItem();
if (item) {
QGraphicsItem *p = item;
do {
// Accept the event by default
keyEvent->accept();
// Send it; QGraphicsItem::keyPressEvent ignores it. If the event
// is filtered out, stop propagating it.
if (!d->sendEvent(p, keyEvent))
break;
} while (!keyEvent->isAccepted() && !p->isWindow() && (p = p->parentItem()));
} else {
keyEvent->ignore();
}
}
/*!
This event handler, for event \a keyEvent, can be reimplemented in a
subclass to receive key release events. The default implementation
forwards the event to current focus item.
\sa QGraphicsItem::keyReleaseEvent(), focusItem()
*/
void QGraphicsScene::keyReleaseEvent(QKeyEvent *keyEvent)
{
// ### Merge this function with keyPressEvent; they are identical (except
// ### this comment).
Q_D(QGraphicsScene);
QGraphicsItem *item = !d->keyboardGrabberItems.isEmpty() ? d->keyboardGrabberItems.last() : 0;
if (!item)
item = focusItem();
if (item) {
QGraphicsItem *p = item;
do {
// Accept the event by default
keyEvent->accept();
// Send it; QGraphicsItem::keyPressEvent ignores it. If the event
// is filtered out, stop propagating it.
if (!d->sendEvent(p, keyEvent))
break;
} while (!keyEvent->isAccepted() && !p->isWindow() && (p = p->parentItem()));
} else {
keyEvent->ignore();
}
}
/*!
This event handler, for event \a mouseEvent, can be reimplemented
in a subclass to receive mouse press events for the scene.
The default implementation depends on the state of the scene. If
there is a mouse grabber item, then the event is sent to the mouse
grabber. Otherwise, it is forwarded to the topmost item that
accepts mouse events at the scene position from the event, and
that item promptly becomes the mouse grabber item.
If there is no item at the given position on the scene, the
selection area is reset, any focus item loses its input focus, and
the event is then ignored.
\sa QGraphicsItem::mousePressEvent(),
QGraphicsItem::setAcceptedMouseButtons()
*/
void QGraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_D(QGraphicsScene);
d->mousePressEventHandler(mouseEvent);
}
/*!
This event handler, for event \a mouseEvent, can be reimplemented
in a subclass to receive mouse move events for the scene.
The default implementation depends on the mouse grabber state. If there is
a mouse grabber item, the event is sent to the mouse grabber. If there
are any items that accept hover events at the current position, the event
is translated into a hover event and accepted; otherwise it's ignored.
\sa QGraphicsItem::mousePressEvent(), QGraphicsItem::mouseReleaseEvent(),
QGraphicsItem::mouseDoubleClickEvent(), QGraphicsItem::setAcceptedMouseButtons()
*/
void QGraphicsScene::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_D(QGraphicsScene);
if (d->mouseGrabberItems.isEmpty()) {
if (mouseEvent->buttons())
return;
QGraphicsSceneHoverEvent hover;
_q_hoverFromMouseEvent(&hover, mouseEvent);
mouseEvent->setAccepted(d->dispatchHoverEvent(&hover));
return;
}
// Forward the event to the mouse grabber
d->sendMouseEvent(mouseEvent);
mouseEvent->accept();
}
/*!
This event handler, for event \a mouseEvent, can be reimplemented
in a subclass to receive mouse release events for the scene.
The default implementation depends on the mouse grabber state. If
there is no mouse grabber, the event is ignored. Otherwise, if
there is a mouse grabber item, the event is sent to the mouse
grabber. If this mouse release represents the last pressed button
on the mouse, the mouse grabber item then loses the mouse grab.
\sa QGraphicsItem::mousePressEvent(), QGraphicsItem::mouseMoveEvent(),
QGraphicsItem::mouseDoubleClickEvent(), QGraphicsItem::setAcceptedMouseButtons()
*/
void QGraphicsScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_D(QGraphicsScene);
if (d->mouseGrabberItems.isEmpty()) {
mouseEvent->ignore();
return;
}
// Forward the event to the mouse grabber
d->sendMouseEvent(mouseEvent);
mouseEvent->accept();
// Reset the mouse grabber when the last mouse button has been released.
if (!mouseEvent->buttons()) {
if (!d->mouseGrabberItems.isEmpty()) {
d->lastMouseGrabberItem = d->mouseGrabberItems.last();
if (d->lastMouseGrabberItemHasImplicitMouseGrab)
d->mouseGrabberItems.last()->ungrabMouse();
} else {
d->lastMouseGrabberItem = 0;
}
// Generate a hoverevent
QGraphicsSceneHoverEvent hoverEvent;
_q_hoverFromMouseEvent(&hoverEvent, mouseEvent);
d->dispatchHoverEvent(&hoverEvent);
}
}
/*!
This event handler, for event \a mouseEvent, can be reimplemented
in a subclass to receive mouse doubleclick events for the scene.
If someone doubleclicks on the scene, the scene will first receive
a mouse press event, followed by a release event (i.e., a click),
then a doubleclick event, and finally a release event. If the
doubleclick event is delivered to a different item than the one
that received the first press and release, it will be delivered as
a press event. However, tripleclick events are not delivered as
doubleclick events in this case.
The default implementation is similar to mousePressEvent().
\sa QGraphicsItem::mousePressEvent(), QGraphicsItem::mouseMoveEvent(),
QGraphicsItem::mouseReleaseEvent(), QGraphicsItem::setAcceptedMouseButtons()
*/
void QGraphicsScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_D(QGraphicsScene);
d->mousePressEventHandler(mouseEvent);
}
/*!
This event handler, for event \a wheelEvent, can be reimplemented in a
subclass to receive mouse wheel events for the scene.
By default, the event is delivered to the topmost visible item under the
cursor. If ignored, the event propagates to the item beneath, and again
until the event is accepted, or it reaches the scene. If no items accept
the event, it is ignored.
\sa QGraphicsItem::wheelEvent()
*/
void QGraphicsScene::wheelEvent(QGraphicsSceneWheelEvent *wheelEvent)
{
Q_D(QGraphicsScene);
QList<QGraphicsItem *> wheelCandidates = d->itemsAtPosition(wheelEvent->screenPos(),
wheelEvent->scenePos(),
wheelEvent->widget());
bool hasSetFocus = false;
foreach (QGraphicsItem *item, wheelCandidates) {
if (!hasSetFocus && item->isEnabled() && (item->flags() & QGraphicsItem::ItemIsFocusable)) {
if (item->isWidget() && static_cast<QGraphicsWidget *>(item)->focusPolicy() == Qt::WheelFocus) {
hasSetFocus = true;
if (item != focusItem())
setFocusItem(item, Qt::MouseFocusReason);
}
}
wheelEvent->setPos(item->d_ptr->genericMapFromScene(wheelEvent->scenePos(),
wheelEvent->widget()));
wheelEvent->accept();
bool isWindow = item->isWindow();
d->sendEvent(item, wheelEvent);
if (isWindow || wheelEvent->isAccepted())
break;
}
}
/*!
This event handler, for event \a event, can be reimplemented in a
subclass to receive input method events for the scene.
The default implementation forwards the event to the focusItem().
If no item currently has focus, this function does nothing.
\sa QGraphicsItem::inputMethodEvent()
*/
void QGraphicsScene::inputMethodEvent(QInputMethodEvent *event)
{
Q_D(QGraphicsScene);
if (!d->focusItem)
return;
d->sendEvent(d->focusItem, event);
}
/*!
Draws the background of the scene using \a painter, before any items and
the foreground are drawn. Reimplement this function to provide a custom
background for the scene.
All painting is done in \e scene coordinates. The \a rect
parameter is the exposed rectangle.
If all you want is to define a color, texture, or gradient for the
background, you can call setBackgroundBrush() instead.
\sa drawForeground(), drawItems()
*/
void QGraphicsScene::drawBackground(QPainter *painter, const QRectF &rect)
{
Q_D(QGraphicsScene);
if (d->backgroundBrush.style() != Qt::NoBrush) {
if (d->painterStateProtection)
painter->save();
painter->setBrushOrigin(0, 0);
painter->fillRect(rect, backgroundBrush());
if (d->painterStateProtection)
painter->restore();
}
}
/*!
Draws the foreground of the scene using \a painter, after the background
and all items have been drawn. Reimplement this function to provide a
custom foreground for the scene.
All painting is done in \e scene coordinates. The \a rect
parameter is the exposed rectangle.
If all you want is to define a color, texture or gradient for the
foreground, you can call setForegroundBrush() instead.
\sa drawBackground(), drawItems()
*/
void QGraphicsScene::drawForeground(QPainter *painter, const QRectF &rect)
{
Q_D(QGraphicsScene);
if (d->foregroundBrush.style() != Qt::NoBrush) {
if (d->painterStateProtection)
painter->save();
painter->setBrushOrigin(0, 0);
painter->fillRect(rect, foregroundBrush());
if (d->painterStateProtection)
painter->restore();
}
}
static void _q_paintItem(QGraphicsItem *item, QPainter *painter,
const QStyleOptionGraphicsItem *option, QWidget *widget,
bool useWindowOpacity, bool painterStateProtection)
{
if (!item->isWidget()) {
item->paint(painter, option, widget);
return;
}
QGraphicsWidget *widgetItem = static_cast<QGraphicsWidget *>(item);
QGraphicsProxyWidget *proxy = qobject_cast<QGraphicsProxyWidget *>(widgetItem);
const qreal windowOpacity = (proxy && proxy->widget() && useWindowOpacity)
? proxy->widget()->windowOpacity() : 1.0;
const qreal oldPainterOpacity = painter->opacity();
if (qFuzzyIsNull(windowOpacity))
return;
// Set new painter opacity.
if (windowOpacity < 1.0)
painter->setOpacity(oldPainterOpacity * windowOpacity);
// set layoutdirection on the painter
Qt::LayoutDirection oldLayoutDirection = painter->layoutDirection();
painter->setLayoutDirection(widgetItem->layoutDirection());
if (widgetItem->isWindow() && widgetItem->windowType() != Qt::Popup && widgetItem->windowType() != Qt::ToolTip
&& !(widgetItem->windowFlags() & Qt::FramelessWindowHint)) {
if (painterStateProtection)
painter->save();
widgetItem->paintWindowFrame(painter, option, widget);
if (painterStateProtection)
painter->restore();
}
widgetItem->paint(painter, option, widget);
// Restore layoutdirection on the painter.
painter->setLayoutDirection(oldLayoutDirection);
// Restore painter opacity.
if (windowOpacity < 1.0)
painter->setOpacity(oldPainterOpacity);
}
static void _q_paintIntoCache(QPixmap *pix, QGraphicsItem *item, const QRegion &pixmapExposed,
const QTransform &itemToPixmap, QPainter::RenderHints renderHints,
const QStyleOptionGraphicsItem *option, bool painterStateProtection)
{
QPixmap subPix;
QPainter pixmapPainter;
QRect br = pixmapExposed.boundingRect();
// Don't use subpixmap if we get a full update.
if (pixmapExposed.isEmpty() || (pixmapExposed.numRects() == 1 && br.contains(pix->rect()))) {
pix->fill(Qt::transparent);
pixmapPainter.begin(pix);
} else {
subPix = QPixmap(br.size());
subPix.fill(Qt::transparent);
pixmapPainter.begin(&subPix);
pixmapPainter.translate(-br.topLeft());
if (!pixmapExposed.isEmpty()) {
// Applied to subPix; paint is adjusted to the coordinate space is
// correct.
pixmapPainter.setClipRegion(pixmapExposed);
}
}
pixmapPainter.setRenderHints(pixmapPainter.renderHints(), false);
pixmapPainter.setRenderHints(renderHints, true);
pixmapPainter.setWorldTransform(itemToPixmap, true);
// Render.
_q_paintItem(item, &pixmapPainter, option, 0, false, painterStateProtection);
pixmapPainter.end();
if (!subPix.isNull()) {
// Blit the subpixmap into the main pixmap.
pixmapPainter.begin(pix);
pixmapPainter.setCompositionMode(QPainter::CompositionMode_Source);
pixmapPainter.setClipRegion(pixmapExposed);
pixmapPainter.drawPixmap(br.topLeft(), subPix);
pixmapPainter.end();
}
}
/*!
\internal
Draws items directly, or using cache.
*/
void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painter,
const QStyleOptionGraphicsItem *option, QWidget *widget,
bool painterStateProtection)
{
QGraphicsItemPrivate *itemd = item->d_ptr;
QGraphicsItem::CacheMode cacheMode = QGraphicsItem::CacheMode(itemd->cacheMode);
// Render directly, using no cache.
if (cacheMode == QGraphicsItem::NoCache
#ifdef Q_WS_X11
|| !X11->use_xrender
#endif
) {
_q_paintItem(static_cast<QGraphicsWidget *>(item), painter, option, widget, true, painterStateProtection);
return;
}
const qreal oldPainterOpacity = painter->opacity();
qreal newPainterOpacity = oldPainterOpacity;
QGraphicsProxyWidget *proxy = item->isWidget() ? qobject_cast<QGraphicsProxyWidget *>(static_cast<QGraphicsWidget *>(item)) : 0;
if (proxy && proxy->widget()) {
const qreal windowOpacity = proxy->widget()->windowOpacity();
if (windowOpacity < 1.0)
newPainterOpacity *= windowOpacity;
}
// Item's (local) bounding rect
QRectF brect = item->boundingRect();
QRectF adjustedBrect(brect);
_q_adjustRect(&adjustedBrect);
if (adjustedBrect.isEmpty())
return;
// Fetch the off-screen transparent buffer and exposed area info.
QPixmapCache::Key pixmapKey;
QPixmap pix;
bool pixmapFound;
QGraphicsItemCache *itemCache = itemd->extraItemCache();
if (cacheMode == QGraphicsItem::ItemCoordinateCache) {
if (itemCache->boundingRect != brect.toRect()) {
itemCache->boundingRect = brect.toRect();
itemCache->allExposed = true;
itemCache->exposed.clear();
}
pixmapKey = itemCache->key;
} else {
pixmapKey = itemCache->deviceData.value(widget).key;
}
// Find pixmap in cache.
pixmapFound = QPixmapCache::find(pixmapKey, &pix);
// Render using item coordinate cache mode.
if (cacheMode == QGraphicsItem::ItemCoordinateCache) {
QSize pixmapSize;
bool fixedCacheSize = false;
QRectF brectAligned = brect.toAlignedRect();
if ((fixedCacheSize = itemCache->fixedSize.isValid())) {
pixmapSize = itemCache->fixedSize;
} else {
pixmapSize = brectAligned.size().toSize();
}
// Create or recreate the pixmap.
int adjust = itemCache->fixedSize.isValid() ? 0 : 2;
QSize adjustSize(adjust*2, adjust*2);
QRectF br = brectAligned.adjusted(-adjust, -adjust, adjust, adjust);
if (pix.isNull() || (!fixedCacheSize && (pixmapSize + adjustSize) != pix.size())) {
pix = QPixmap(pixmapSize + adjustSize);
itemCache->exposed.clear();
itemCache->allExposed = true;
}
// Redraw any newly exposed areas.
if (itemCache->allExposed || !itemCache->exposed.isEmpty()) {
//We know that we will modify the pixmap, removing it from the cache
//will detach the one we have and avoid a deep copy
if (pixmapFound)
QPixmapCache::remove(pixmapKey);
// Fit the item's bounding rect into the pixmap's coordinates.
QTransform itemToPixmap;
if (fixedCacheSize) {
const QPointF scale(pixmapSize.width() / brect.width(), pixmapSize.height() / brect.height());
itemToPixmap.scale(scale.x(), scale.y());
}
itemToPixmap.translate(-br.x(), -br.y());
// Generate the item's exposedRect and map its list of expose
// rects to device coordinates.
styleOptionTmp = *option;
QRegion pixmapExposed;
QRectF exposedRect;
if (!itemCache->allExposed) {
for (int i = 0; i < itemCache->exposed.size(); ++i) {
QRectF r = itemCache->exposed.at(i);
exposedRect |= r;
pixmapExposed += itemToPixmap.mapRect(r).toAlignedRect();
}
} else {
exposedRect = brect;
}
styleOptionTmp.exposedRect = exposedRect;
// Render.
_q_paintIntoCache(&pix, item, pixmapExposed, itemToPixmap, painter->renderHints(),
&styleOptionTmp, painterStateProtection);
// insert this pixmap into the cache.
itemCache->key = QPixmapCache::insert(pix);
// Reset expose data.
itemCache->allExposed = false;
itemCache->exposed.clear();
}
// Redraw the exposed area using the transformed painter. Depending on
// the hardware, this may be a server-side operation, or an expensive
// qpixmap-image-transform-pixmap roundtrip.
if (newPainterOpacity != oldPainterOpacity) {
painter->setOpacity(newPainterOpacity);
painter->drawPixmap(br, pix, QRectF(QPointF(), pix.size()));
painter->setOpacity(oldPainterOpacity);
} else {
painter->drawPixmap(br, pix, QRectF(QPointF(), pix.size()));
}
return;
}
// Render using device coordinate cache mode.
if (cacheMode == QGraphicsItem::DeviceCoordinateCache) {
// Find the item's bounds in device coordinates.
QRectF deviceBounds = painter->worldTransform().mapRect(brect);
QRect deviceRect = deviceBounds.toRect().adjusted(-1, -1, 1, 1);
if (deviceRect.isEmpty())
return;
QRect viewRect = widget ? widget->rect() : QRect();
if (widget && !viewRect.intersects(deviceRect))
return;
// Resort to direct rendering if the device rect exceeds the
// (optional) maximum bounds. (QGraphicsSvgItem uses this).
QSize maximumCacheSize =
itemd->extra(QGraphicsItemPrivate::ExtraMaxDeviceCoordCacheSize).toSize();
if (!maximumCacheSize.isEmpty()
&& (deviceRect.width() > maximumCacheSize.width()
|| deviceRect.height() > maximumCacheSize.height())) {
_q_paintItem(static_cast<QGraphicsWidget *>(item), painter, option, widget,
oldPainterOpacity != newPainterOpacity, painterStateProtection);
return;
}
// Create or reuse offscreen pixmap, possibly scroll/blit from the old one.
bool pixModified = false;
QGraphicsItemCache::DeviceData *deviceData = &itemCache->deviceData[widget];
bool invertable = true;
QTransform diff = deviceData->lastTransform.inverted(&invertable);
if (invertable)
diff *= painter->worldTransform();
deviceData->lastTransform = painter->worldTransform();
if (!invertable || diff.type() > QTransform::TxTranslate) {
pixModified = true;
itemCache->allExposed = true;
itemCache->exposed.clear();
pix = QPixmap();
}
// ### This is a pretty bad way to determine when to start partial
// exposure for DeviceCoordinateCache but it's the least intrusive
// approach for now.
#if 0
// Only if the device rect isn't fully contained.
bool allowPartialCacheExposure = !viewRect.contains(deviceRect);
#else
// Only if deviceRect is 20% taller or wider than the desktop.
QRect desktopRect = QApplication::desktop()->availableGeometry(widget);
bool allowPartialCacheExposure = (desktopRect.width() * 1.2 < deviceRect.width()
|| desktopRect.height() * 1.2 < deviceRect.height());
#endif
QRegion scrollExposure;
if (deviceData->cacheIndent != QPoint() || allowPartialCacheExposure) {
// Part of pixmap is drawn. Either device contains viewrect (big
// item covers whole screen) or parts of device are outside the
// viewport. In either case the device rect must be the intersect
// between the two.
int dx = deviceRect.left() < viewRect.left() ? viewRect.left() - deviceRect.left() : 0;
int dy = deviceRect.top() < viewRect.top() ? viewRect.top() - deviceRect.top() : 0;
QPoint newCacheIndent(dx, dy);
deviceRect &= viewRect;
if (pix.isNull()) {
deviceData->cacheIndent = QPoint();
itemCache->allExposed = true;
itemCache->exposed.clear();
pixModified = true;
}
// Copy / "scroll" the old pixmap onto the new ole and calculate
// scrolled exposure.
if (newCacheIndent != deviceData->cacheIndent || deviceRect.size() != pix.size()) {
QPoint diff = newCacheIndent - deviceData->cacheIndent;
QPixmap newPix(deviceRect.size());
// ### Investigate removing this fill (test with Plasma and
// graphicssystem raster).
newPix.fill(Qt::transparent);
if (!pix.isNull()) {
QPainter newPixPainter(&newPix);
newPixPainter.drawPixmap(-diff, pix);
newPixPainter.end();
}
QRegion exposed;
exposed += newPix.rect();
if (!pix.isNull())
exposed -= QRect(-diff, pix.size());
scrollExposure = exposed;
pix = newPix;
pixModified = true;
}
deviceData->cacheIndent = newCacheIndent;
} else {
// Full pixmap is drawn.
deviceData->cacheIndent = QPoint();
// Auto-adjust the pixmap size.
if (deviceRect.size() != pix.size()) {
// exposed needs to cover the whole pixmap
pix = QPixmap(deviceRect.size());
pixModified = true;
itemCache->allExposed = true;
itemCache->exposed.clear();
}
}
// Check for newly invalidated areas.
if (itemCache->allExposed || !itemCache->exposed.isEmpty() || !scrollExposure.isEmpty()) {
//We know that we will modify the pixmap, removing it from the cache
//will detach the one we have and avoid a deep copy
if (pixmapFound)
QPixmapCache::remove(pixmapKey);
// Construct an item-to-pixmap transform.
QPointF p = deviceRect.topLeft();
QTransform itemToPixmap = painter->worldTransform();
if (!p.isNull())
itemToPixmap *= QTransform::fromTranslate(-p.x(), -p.y());
// Map the item's logical expose to pixmap coordinates.
QRegion pixmapExposed = scrollExposure;
if (!itemCache->allExposed) {
const QVector<QRectF> &exposed = itemCache->exposed;
for (int i = 0; i < exposed.size(); ++i)
pixmapExposed += itemToPixmap.mapRect(exposed.at(i)).toRect().adjusted(-1, -1, 1, 1);
}
// Calculate the style option's exposedRect.
QRectF br;
if (itemCache->allExposed) {
br = item->boundingRect();
} else {
const QVector<QRectF> &exposed = itemCache->exposed;
for (int i = 0; i < exposed.size(); ++i)
br |= exposed.at(i);
QTransform pixmapToItem = itemToPixmap.inverted();
foreach (QRect r, scrollExposure.rects())
br |= pixmapToItem.mapRect(r);
}
styleOptionTmp = *option;
styleOptionTmp.exposedRect = br.adjusted(-1, -1, 1, 1);
// Render the exposed areas.
_q_paintIntoCache(&pix, item, pixmapExposed, itemToPixmap, painter->renderHints(),
&styleOptionTmp, painterStateProtection);
// Reset expose data.
pixModified = true;
itemCache->allExposed = false;
itemCache->exposed.clear();
}
if (pixModified) {
// Insert this pixmap into the cache.
deviceData->key = QPixmapCache::insert(pix);
}
// Redraw the exposed area using an untransformed painter. This
// effectively becomes a bitblit that does not transform the cache.
QTransform restoreTransform = painter->worldTransform();
painter->setWorldTransform(QTransform());
if (newPainterOpacity != oldPainterOpacity) {
painter->setOpacity(newPainterOpacity);
painter->drawPixmap(deviceRect.topLeft(), pix);
painter->setOpacity(oldPainterOpacity);
} else {
painter->drawPixmap(deviceRect.topLeft(), pix);
}
painter->setWorldTransform(restoreTransform);
return;
}
}
void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter,
const QTransform &viewTransform,
QRegion *exposedRegion, QWidget *widget,
QList<QGraphicsItem *> *topLevelItems,
qreal parentOpacity)
{
// Calculate opacity.
qreal opacity;
bool invisibleButChildIgnoresParentOpacity = false;
if (item) {
if (!item->d_ptr->visible)
return;
opacity = item->d_ptr->combineOpacityFromParent(parentOpacity);
if (opacity == 0.0 && !(item->d_ptr->flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)) {
invisibleButChildIgnoresParentOpacity = !item->d_ptr->childrenCombineOpacity();
if (!invisibleButChildIgnoresParentOpacity)
return;
}
} else {
opacity = parentOpacity;
}
// Item is invisible.
bool hasContents = item && !(item->d_ptr->flags & QGraphicsItem::ItemHasNoContents);
bool invisible = !hasContents || invisibleButChildIgnoresParentOpacity;
// Calculate the full transform for this item.
bool wasDirtyParentSceneTransform = false;
bool dontDrawItem = true;
QTransform transform;
if (item) {
if (item->d_ptr->itemIsUntransformable()) {
transform = item->deviceTransform(viewTransform);
} else {
if (item->d_ptr->dirtySceneTransform) {
item->d_ptr->sceneTransform = item->d_ptr->parent ? item->d_ptr->parent->d_ptr->sceneTransform
: QTransform();
item->d_ptr->combineTransformFromParent(&item->d_ptr->sceneTransform);
item->d_ptr->dirtySceneTransform = 0;
wasDirtyParentSceneTransform = true;
}
transform = item->d_ptr->sceneTransform;
transform *= viewTransform;
}
if (!invisible) {
QRectF brect = item->boundingRect();
// ### This does not take the clip into account.
_q_adjustRect(&brect);
QRect viewBoundingRect = transform.mapRect(brect).toRect();
item->d_ptr->paintedViewBoundingRects.insert(widget, viewBoundingRect);
viewBoundingRect.adjust(-1, -1, 1, 1);
if (exposedRegion)
dontDrawItem = !exposedRegion->intersects(viewBoundingRect);
else
dontDrawItem = viewBoundingRect.isEmpty();
}
}
// Find and sort children.
QList<QGraphicsItem *> tmp;
QList<QGraphicsItem *> *children = 0;
if (item) {
children = &item->d_ptr->children;
} else if (topLevelItems) {
children = topLevelItems;
} else if (indexMethod == QGraphicsScene::NoIndex || !exposedRegion) {
children = &this->topLevelItems;
} else {
QRectF sceneRect = viewTransform.inverted().mapRect(QRectF(exposedRegion->boundingRect().adjusted(-1, -1, 1, 1)));
if (!largestUntransformableItem.isEmpty()) {
// ### Nuke this when we move the indexing code into a separate
// class. All the largestUntransformableItem code should then go
// away, and the estimate function should return untransformable
// items as well.
QRectF untr = largestUntransformableItem;
QRectF ltri = viewTransform.inverted().mapRect(untr);
ltri.adjust(-untr.width(), -untr.height(), untr.width(), untr.height());
sceneRect.adjust(-ltri.width(), -ltri.height(), ltri.width(), ltri.height());
}
tmp = estimateItemsInRect(sceneRect);
QList<QGraphicsItem *> tli;
for (int i = 0; i < tmp.size(); ++i)
tmp.at(i)->topLevelItem()->d_ptr->itemDiscovered = 1;
// Sort if the toplevel list is unsorted.
if (needSortTopLevelItems) {
needSortTopLevelItems = false;
qStableSort(this->topLevelItems.begin(),
this->topLevelItems.end(), qt_notclosestLeaf);
}
for (int i = 0; i < this->topLevelItems.size(); ++i) {
// ### Investigate smarter ways. Looping through all top level
// items is not optimal. If the BSP tree is to have maximum
// effect, it should be possible to sort the subset of items
// quickly. We must use this approach for now, as it's the only
// current way to keep the stable sorting order (insertion order).
QGraphicsItem *item = this->topLevelItems.at(i);
if (item->d_ptr->itemDiscovered) {
item->d_ptr->itemDiscovered = 0;
tli << item;
}
}
tmp = tli;
children = &tmp;
}
bool childClip = (item && (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape));
bool dontDrawChildren = item && hasContents && dontDrawItem && childClip;
childClip &= !dontDrawChildren && !children->isEmpty();
if (item && invisible)
dontDrawItem = true;
// Clip children.
if (childClip) {
painter->save();
painter->setWorldTransform(transform);
painter->setClipPath(item->shape(), Qt::IntersectClip);
}
if (!dontDrawChildren) {
if (item && item->d_ptr->needSortChildren) {
item->d_ptr->needSortChildren = 0;
qStableSort(children->begin(), children->end(), qt_notclosestLeaf);
} else if (!item && needSortTopLevelItems && children != &tmp) {
needSortTopLevelItems = false;
qStableSort(children->begin(), children->end(), qt_notclosestLeaf);
}
}
// Draw children behind
int i = 0;
if (!dontDrawChildren) {
// ### Don't visit children that don't ignore parent opacity if this
// item is invisible.
for (i = 0; i < children->size(); ++i) {
QGraphicsItem *child = children->at(i);
if (wasDirtyParentSceneTransform)
child->d_ptr->dirtySceneTransform = 1;
if (!(child->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent))
break;
drawSubtreeRecursive(child, painter, viewTransform, exposedRegion, widget,
0, opacity);
}
}
// Draw item
if (!dontDrawItem) {
item->d_ptr->initStyleOption(&styleOptionTmp, transform, exposedRegion ? *exposedRegion : QRegion(), exposedRegion == 0);
bool clipsToShape = (item->d_ptr->flags & QGraphicsItem::ItemClipsToShape);
bool savePainter = clipsToShape || painterStateProtection;
if (savePainter)
painter->save();
if (!childClip)
painter->setWorldTransform(transform);
if (clipsToShape)
painter->setClipPath(item->shape(), Qt::IntersectClip);
painter->setOpacity(opacity);
if (!item->d_ptr->cacheMode && !item->d_ptr->isWidget)
item->paint(painter, &styleOptionTmp, widget);
else
drawItemHelper(item, painter, &styleOptionTmp, widget, painterStateProtection);
if (savePainter)
painter->restore();
}
// Draw children in front
if (!dontDrawChildren) {
// ### Don't visit children that don't ignore parent opacity if this
// item is invisible.
for (; i < children->size(); ++i) {
QGraphicsItem *child = children->at(i);
if (wasDirtyParentSceneTransform)
child->d_ptr->dirtySceneTransform = 1;
drawSubtreeRecursive(child, painter, viewTransform, exposedRegion,
widget, 0, opacity);
}
} else if (wasDirtyParentSceneTransform) {
item->d_ptr->invalidateChildrenSceneTransform();
}
// Restore child clip
if (childClip)
painter->restore();
}
void QGraphicsScenePrivate::markDirty(QGraphicsItem *item, const QRectF &rect, bool invalidateChildren,
bool maybeDirtyClipPath, bool force, bool ignoreOpacity,
bool removingItemFromScene)
{
Q_ASSERT(item);
if (updateAll)
return;
if (item->d_ptr->discardUpdateRequest(/*ignoreClipping=*/maybeDirtyClipPath,
/*ignoreVisibleBit=*/force,
/*ignoreDirtyBit=*/removingItemFromScene || invalidateChildren,
/*ignoreOpacity=*/ignoreOpacity)) {
return;
}
const bool fullItemUpdate = rect.isNull();
if (!fullItemUpdate && rect.isEmpty())
return;
if (!processDirtyItemsEmitted) {
QMetaObject::invokeMethod(q_ptr, "_q_processDirtyItems", Qt::QueuedConnection);
processDirtyItemsEmitted = true;
}
if (removingItemFromScene) {
// Note that this function can be called from the item's destructor, so
// do NOT call any virtual functions on it within this block.
if ((connectedSignals & changedSignalMask) || views.isEmpty()) {
// This block of code is kept for compatibility. Since 4.5, by default
// QGraphicsView does not connect the signal and we use the below
// method of delivering updates.
q_func()->update();
return;
}
for (int i = 0; i < views.size(); ++i) {
QGraphicsViewPrivate *viewPrivate = views.at(i)->d_func();
QRect rect = item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport);
rect.translate(viewPrivate->dirtyScrollOffset);
viewPrivate->updateRect(rect);
}
return;
}
bool hasNoContents = item->d_ptr->flags & QGraphicsItem::ItemHasNoContents;
if (!hasNoContents) {
item->d_ptr->dirty = 1;
if (fullItemUpdate)
item->d_ptr->fullUpdatePending = 1;
else if (!item->d_ptr->fullUpdatePending)
item->d_ptr->needsRepaint |= rect;
}
if (invalidateChildren) {
item->d_ptr->allChildrenDirty = 1;
item->d_ptr->dirtyChildren = 1;
}
if (force)
item->d_ptr->ignoreVisible = 1;
if (ignoreOpacity)
item->d_ptr->ignoreOpacity = 1;
QGraphicsItem *p = item->d_ptr->parent;
while (p && !p->d_ptr->dirtyChildren) {
p->d_ptr->dirtyChildren = 1;
p = p->d_ptr->parent;
}
}
void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool dirtyAncestorContainsChildren,
qreal parentOpacity)
{
Q_Q(QGraphicsScene);
bool wasDirtyParentViewBoundingRects = false;
bool wasDirtyParentSceneTransform = false;
qreal opacity = parentOpacity;
if (item) {
wasDirtyParentViewBoundingRects = item->d_ptr->paintedViewBoundingRectsNeedRepaint;
opacity = item->d_ptr->combineOpacityFromParent(parentOpacity);
const bool itemIsHidden = !item->d_ptr->ignoreVisible && !item->d_ptr->visible;
const bool itemIsFullyTransparent = !item->d_ptr->ignoreOpacity && opacity == 0.0;
if (item->d_ptr->dirtySceneTransform && !itemIsHidden && !item->d_ptr->itemIsUntransformable()
&& !(itemIsFullyTransparent && item->d_ptr->childrenCombineOpacity())) {
// Calculate the full scene transform for this item.
item->d_ptr->sceneTransform = item->d_ptr->parent ? item->d_ptr->parent->d_ptr->sceneTransform
: QTransform();
item->d_ptr->combineTransformFromParent(&item->d_ptr->sceneTransform);
item->d_ptr->dirtySceneTransform = 0;
wasDirtyParentSceneTransform = true;
}
if (itemIsHidden || itemIsFullyTransparent || (item->d_ptr->flags & QGraphicsItem::ItemHasNoContents)) {
// Make sure we don't process invisible items or items with no content.
item->d_ptr->dirty = 0;
item->d_ptr->paintedViewBoundingRectsNeedRepaint = 0;
}
}
// Process item.
if (item && (item->d_ptr->dirty || item->d_ptr->paintedViewBoundingRectsNeedRepaint)) {
const bool useCompatUpdate = views.isEmpty() || (connectedSignals & changedSignalMask);
const bool untransformableItem = item->d_ptr->itemIsUntransformable();
const QRectF itemBoundingRect = adjustedItemBoundingRect(item);
if (item->d_ptr->geometryChanged) {
// Update growingItemsBoundingRect.
if (!hasSceneRect)
growingItemsBoundingRect |= item->d_ptr->sceneTransform.mapRect(itemBoundingRect);
item->d_ptr->geometryChanged = 0;
}
if (useCompatUpdate && !untransformableItem && qFuzzyIsNull(item->boundingRegionGranularity())) {
// This block of code is kept for compatibility. Since 4.5, by default
// QGraphicsView does not connect the signal and we use the below
// method of delivering updates.
q->update(item->d_ptr->sceneTransform.mapRect(itemBoundingRect));
} else {
QRectF dirtyRect;
bool uninitializedDirtyRect = true;
for (int j = 0; j < views.size(); ++j) {
QGraphicsView *view = views.at(j);
QGraphicsViewPrivate *viewPrivate = view->d_func();
if (viewPrivate->fullUpdatePending)
continue;
switch (viewPrivate->viewportUpdateMode) {
case QGraphicsView::NoViewportUpdate:
continue;
case QGraphicsView::FullViewportUpdate:
view->viewport()->update();
viewPrivate->fullUpdatePending = 1;
continue;
default:
break;
}
QRect &paintedViewBoundingRect = item->d_ptr->paintedViewBoundingRects[viewPrivate->viewport];
if (item->d_ptr->paintedViewBoundingRectsNeedRepaint) {
wasDirtyParentViewBoundingRects = true;
paintedViewBoundingRect.translate(viewPrivate->dirtyScrollOffset);
if (!viewPrivate->updateRect(paintedViewBoundingRect))
paintedViewBoundingRect = QRect();
}
if (!item->d_ptr->dirty)
continue;
if (uninitializedDirtyRect) {
dirtyRect = itemBoundingRect;
if (!item->d_ptr->fullUpdatePending) {
_q_adjustRect(&item->d_ptr->needsRepaint);
dirtyRect &= item->d_ptr->needsRepaint;
}
uninitializedDirtyRect = false;
}
if (dirtyRect.isEmpty())
continue; // Discard updates outside the bounding rect.
bool valid = false;
if (untransformableItem) {
valid = item->d_ptr->updateHelper(viewPrivate, dirtyRect,
item->deviceTransform(view->viewportTransform()));
} else if (!view->isTransformed()) {
valid = item->d_ptr->updateHelper(viewPrivate, dirtyRect, item->d_ptr->sceneTransform);
} else {
QTransform deviceTransform = item->d_ptr->sceneTransform;
deviceTransform *= view->viewportTransform();
valid = !item->d_ptr->updateHelper(viewPrivate, dirtyRect, deviceTransform);
}
if (!valid)
paintedViewBoundingRect = QRect();
}
}
}
// Process root items / children.
if (!item || item->d_ptr->dirtyChildren) {
QList<QGraphicsItem *> *children = item ? &item->d_ptr->children : &topLevelItems;
const bool allChildrenDirty = item && item->d_ptr->allChildrenDirty;
if (!dirtyAncestorContainsChildren) {
dirtyAncestorContainsChildren = item && item->d_ptr->fullUpdatePending
&& (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape);
}
const bool parentIgnoresVisible = item && item->d_ptr->ignoreVisible;
const bool parentIgnoresOpacity = item && item->d_ptr->ignoreOpacity;
for (int i = 0; i < children->size(); ++i) {
QGraphicsItem *child = children->at(i);
if (wasDirtyParentSceneTransform)
child->d_ptr->dirtySceneTransform = 1;
if (wasDirtyParentViewBoundingRects)
child->d_ptr->paintedViewBoundingRectsNeedRepaint = 1;
if (parentIgnoresVisible)
child->d_ptr->ignoreVisible = 1;
if (parentIgnoresOpacity)
child->d_ptr->ignoreOpacity = 1;
if (allChildrenDirty) {
child->d_ptr->dirty = 1;
child->d_ptr->fullUpdatePending = 1;
child->d_ptr->dirtyChildren = 1;
child->d_ptr->allChildrenDirty = 1;
} else if (!child->d_ptr->dirty && !child->d_ptr->dirtyChildren) {
resetDirtyItem(child);
continue;
}
if (dirtyAncestorContainsChildren || updateAll) {
// No need to process this child's dirty rect, hence reset the dirty state.
// However, we have to continue the recursion because it might have a dirty
// view bounding rect that needs repaint. We also have to reset the dirty
// state of its descendants.
child->d_ptr->dirty = 0;
child->d_ptr->fullUpdatePending = 0;
if (updateAll)
child->d_ptr->paintedViewBoundingRectsNeedRepaint = 0;
}
processDirtyItemsRecursive(child, dirtyAncestorContainsChildren, opacity);
}
} else if (wasDirtyParentSceneTransform) {
item->d_ptr->invalidateChildrenSceneTransform();
}
if (item)
resetDirtyItem(item);
}
/*!
Paints the given \a items using the provided \a painter, after the
background has been drawn, and before the foreground has been
drawn. All painting is done in \e scene coordinates. Before
drawing each item, the painter must be transformed using
QGraphicsItem::sceneMatrix().
The \a options parameter is the list of style option objects for
each item in \a items. The \a numItems parameter is the number of
items in \a items and options in \a options. The \a widget
parameter is optional; if specified, it should point to the widget
that is being painted on.
The default implementation prepares the painter matrix, and calls
QGraphicsItem::paint() on all items. Reimplement this function to
provide custom painting of all items for the scene; gaining
complete control over how each item is drawn. In some cases this
can increase drawing performance significantly.
Example:
\snippet doc/src/snippets/graphicssceneadditemsnippet.cpp 0
\sa drawBackground(), drawForeground()
*/
void QGraphicsScene::drawItems(QPainter *painter,
int numItems,
QGraphicsItem *items[],
const QStyleOptionGraphicsItem options[], QWidget *widget)
{
Q_D(QGraphicsScene);
QTransform viewTransform = painter->worldTransform();
Q_UNUSED(options);
// Determine view, expose and flags.
QGraphicsView *view = widget ? qobject_cast<QGraphicsView *>(widget->parentWidget()) : 0;
QRegion *expose = 0;
if (view)
expose = &view->d_func()->exposedRegion;
// Find all toplevels, they are already sorted.
QList<QGraphicsItem *> topLevelItems;
for (int i = 0; i < numItems; ++i) {
QGraphicsItem *item = items[i]->topLevelItem();
if (!item->d_ptr->itemDiscovered) {
topLevelItems << item;
item->d_ptr->itemDiscovered = 1;
d->drawSubtreeRecursive(item, painter, viewTransform, expose, widget);
}
}
// Reset discovery bits.
for (int i = 0; i < topLevelItems.size(); ++i)
topLevelItems.at(i)->d_ptr->itemDiscovered = 0;
painter->setWorldTransform(viewTransform);
}
/*!
\since 4.4
Finds a new widget to give the keyboard focus to, as appropriate for Tab
and Shift+Tab, and returns true if it can find a new widget, or false if
it cannot. If \a next is true, this function searches forward; if \a next
is false, it searches backward.
You can reimplement this function in a subclass of QGraphicsScene to
provide fine-grained control over how tab focus passes inside your
scene. The default implementation is based on the tab focus chain defined
by QGraphicsWidget::setTabOrder().
*/
bool QGraphicsScene::focusNextPrevChild(bool next)
{
Q_D(QGraphicsScene);
QGraphicsItem *item = focusItem();
if (item && !item->isWidget()) {
// Tab out of the scene.
return false;
}
if (!item) {
if (d->lastFocusItem && !d->lastFocusItem->isWidget()) {
// Restore focus to the last focusable non-widget item that had
// focus.
setFocusItem(d->lastFocusItem, next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
return true;
}
}
if (!d->tabFocusFirst) {
// No widgets...
return false;
}
// The item must be a widget.
QGraphicsWidget *widget = 0;
if (!item) {
widget = next ? d->tabFocusFirst : d->tabFocusFirst->d_func()->focusPrev;
} else {
QGraphicsWidget *test = static_cast<QGraphicsWidget *>(item);
widget = next ? test->d_func()->focusNext : test->d_func()->focusPrev;
if ((next && widget == d->tabFocusFirst) || (!next && widget == d->tabFocusFirst->d_func()->focusPrev))
return false;
}
QGraphicsWidget *widgetThatHadFocus = widget;
// Run around the focus chain until we find a widget that can take tab focus.
do {
if (widget->flags() & QGraphicsItem::ItemIsFocusable
&& widget->isEnabled() && widget->isVisibleTo(0)
&& (widget->focusPolicy() & Qt::TabFocus)
&& (!item || !item->isWindow() || item->isAncestorOf(widget))
) {
setFocusItem(widget, next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
return true;
}
widget = next ? widget->d_func()->focusNext : widget->d_func()->focusPrev;
if ((next && widget == d->tabFocusFirst) || (!next && widget == d->tabFocusFirst->d_func()->focusPrev))
return false;
} while (widget != widgetThatHadFocus);
return false;
}
/*!
\fn QGraphicsScene::changed(const QList<QRectF> ®ion)
This signal is emitted by QGraphicsScene when control reaches the
event loop, if the scene content changes. The \a region parameter
contains a list of scene rectangles that indicate the area that
has been changed.
\sa QGraphicsView::updateScene()
*/
/*!
\fn QGraphicsScene::sceneRectChanged(const QRectF &rect)
This signal is emitted by QGraphicsScene whenever the scene rect changes.
The \a rect parameter is the new scene rectangle.
\sa QGraphicsView::updateSceneRect()
*/
/*!
\fn QGraphicsScene::selectionChanged()
\since 4.3
This signal is emitted by QGraphicsScene whenever the selection
changes. You can call selectedItems() to get the new list of selected
items.
The selection changes whenever an item is selected or unselected, a
selection area is set, cleared or otherwise changed, if a preselected item
is added to the scene, or if a selected item is removed from the scene.
QGraphicsScene emits this signal only once for group selection operations.
For example, if you set a selection area, select or unselect a
QGraphicsItemGroup, or if you add or remove from the scene a parent item
that contains several selected items, selectionChanged() is emitted only
once after the operation has completed (instead of once for each item).
\sa setSelectionArea(), selectedItems(), QGraphicsItem::setSelected()
*/
/*!
\since 4.4
Returns the scene's style, or the same as QApplication::style() if the
scene has not been explicitly assigned a style.
\sa setStyle()
*/
QStyle *QGraphicsScene::style() const
{
Q_D(const QGraphicsScene);
// ### This function, and the use of styles in general, is non-reentrant.
return d->style ? d->style : QApplication::style();
}
/*!
\since 4.4
Sets or replaces the style of the scene to \a style, and reparents the
style to this scene. Any previously assigned style is deleted. The scene's
style defaults to QApplication::style(), and serves as the default for all
QGraphicsWidget items in the scene.
Changing the style, either directly by calling this function, or
indirectly by calling QApplication::setStyle(), will automatically update
the style for all widgets in the scene that do not have a style explicitly
assigned to them.
If \a style is 0, QGraphicsScene will revert to QApplication::style().
\sa style()
*/
void QGraphicsScene::setStyle(QStyle *style)
{
Q_D(QGraphicsScene);
// ### This function, and the use of styles in general, is non-reentrant.
if (style == d->style)
return;
// Delete the old style,
delete d->style;
if ((d->style = style))
d->style->setParent(this);
// Notify the scene.
QEvent event(QEvent::StyleChange);
QApplication::sendEvent(this, &event);
// Notify all widgets that don't have a style explicitly set.
foreach (QGraphicsItem *item, items()) {
if (item->isWidget()) {
QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
if (!widget->testAttribute(Qt::WA_SetStyle))
QApplication::sendEvent(widget, &event);
}
}
}
/*!
\property QGraphicsScene::font
\since 4.4
\brief the scene's default font
This property provides the scene's font. The scene font defaults to,
and resolves all its entries from, QApplication::font.
If the scene's font changes, either directly through setFont() or
indirectly when the application font changes, QGraphicsScene first
sends itself a \l{QEvent::FontChange}{FontChange} event, and it then
sends \l{QEvent::FontChange}{FontChange} events to all top-level
widget items in the scene. These items respond by resolving their own
fonts to the scene, and they then notify their children, who again
notify their children, and so on, until all widget items have updated
their fonts.
Changing the scene font, (directly or indirectly through
QApplication::setFont(),) automatically schedules a redraw the entire
scene.
\sa QWidget::font, QApplication::setFont(), palette, style()
*/
QFont QGraphicsScene::font() const
{
Q_D(const QGraphicsScene);
return d->font;
}
void QGraphicsScene::setFont(const QFont &font)
{
Q_D(QGraphicsScene);
QFont naturalFont = QApplication::font();
naturalFont.resolve(0);
QFont resolvedFont = font.resolve(naturalFont);
d->setFont_helper(resolvedFont);
}
/*!
\property QGraphicsScene::palette
\since 4.4
\brief the scene's default palette
This property provides the scene's palette. The scene palette defaults to,
and resolves all its entries from, QApplication::palette.
If the scene's palette changes, either directly through setPalette() or
indirectly when the application palette changes, QGraphicsScene first
sends itself a \l{QEvent::PaletteChange}{PaletteChange} event, and it then
sends \l{QEvent::PaletteChange}{PaletteChange} events to all top-level
widget items in the scene. These items respond by resolving their own
palettes to the scene, and they then notify their children, who again
notify their children, and so on, until all widget items have updated
their palettes.
Changing the scene palette, (directly or indirectly through
QApplication::setPalette(),) automatically schedules a redraw the entire
scene.
\sa QWidget::palette, QApplication::setPalette(), font, style()
*/
QPalette QGraphicsScene::palette() const
{
Q_D(const QGraphicsScene);
return d->palette;
}
void QGraphicsScene::setPalette(const QPalette &palette)
{
Q_D(QGraphicsScene);
QPalette naturalPalette = QApplication::palette();
naturalPalette.resolve(0);
QPalette resolvedPalette = palette.resolve(naturalPalette);
d->setPalette_helper(resolvedPalette);
}
/*!
\since 4.4
Returns the current active window, or 0 if there is no window is currently
active.
\sa QGraphicsScene::setActiveWindow()
*/
QGraphicsWidget *QGraphicsScene::activeWindow() const
{
Q_D(const QGraphicsScene);
return d->activeWindow;
}
/*!
\since 4.4
Activates \a widget, which must be a widget in this scene. You can also
pass 0 for \a widget, in which case QGraphicsScene will deactivate any
currently active window.
\sa activeWindow(), QGraphicsWidget::isActiveWindow()
*/
void QGraphicsScene::setActiveWindow(QGraphicsWidget *widget)
{
Q_D(QGraphicsScene);
if (widget && widget->scene() != this) {
qWarning("QGraphicsScene::setActiveWindow: widget %p must be part of this scene",
widget);
return;
}
// Activate the widget's window.
QGraphicsWidget *window = widget ? widget->window() : 0;
if (window == d->activeWindow)
return;
// Deactivate the last active window.
if (d->activeWindow) {
if (QGraphicsWidget *fw = d->activeWindow->focusWidget()) {
// Remove focus from the current focus item.
if (fw == focusItem())
setFocusItem(0, Qt::ActiveWindowFocusReason);
}
QEvent event(QEvent::WindowDeactivate);
QApplication::sendEvent(d->activeWindow, &event);
}
// Update activate state.
d->activeWindow = window;
QEvent event(QEvent::ActivationChange);
QApplication::sendEvent(this, &event);
// Activate
if (window) {
QEvent event(QEvent::WindowActivate);
QApplication::sendEvent(window, &event);
QList<QGraphicsItem *> siblingWindows;
QGraphicsItem *parent = window->parentItem();
// Raise ### inefficient for toplevels
foreach (QGraphicsItem *sibling, parent ? parent->children() : items()) {
if (sibling != window && sibling->isWidget()
&& static_cast<QGraphicsWidget *>(sibling)->isWindow()) {
siblingWindows << sibling;
}
}
// Find the highest z value.
qreal z = window->zValue();
for (int i = 0; i < siblingWindows.size(); ++i)
z = qMax(z, siblingWindows.at(i)->zValue());
// This will probably never overflow.
const qreal litt = qreal(0.001);
window->setZValue(z + litt);
if (QGraphicsWidget *focusChild = window->focusWidget())
focusChild->setFocus(Qt::ActiveWindowFocusReason);
}
}
QT_END_NAMESPACE
#include "moc_qgraphicsscene.cpp"
#endif // QT_NO_GRAPHICSVIEW
|
#include "p2Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Input.h"
#include "j1Textures.h"
#include "j1Audio.h"
#include "j1Render.h"
#include "j1Window.h"
#include "j1Scene.h"
#include "j1Gui.h"
#include "j1GuiEntity.h"
#include "j1GuiElements.h"
#include "j1Player.h"
#include "j1FileSystem.h"
#include "j1AnimationManager.h"
#include "Golem.h"
#include "j1Collision.h"
#include "j1InputManager.h"
#include "Soldier.h"
#include "j1Item.h"
#include "j1DynamicObjects.h"
#include "j1Creature.h"
#include "j1Weapon.h"
#include "Animation.h"
#include "Pokemon.h"
//Constructor
Player::Player() : Creature()
{
type = CREATURE;
name = "Link";
hp_hearts = { 6,6 };
}
// Destructor
Player::~Player()
{}
// Called before render is available
bool Player::Awake(pugi::xml_node& conf)
{
LOG("Loading Texture Player");
bool ret = true;
hp = conf.child("stats").attribute("hp").as_int(0);
attack = conf.child("stats").attribute("attack").as_int(0);
speed = conf.child("stats").attribute("speed").as_int(0);
position.x = conf.child("stats").attribute("pos_x").as_int(0);
position.y = conf.child("stats").attribute("pos_y").as_int(0);
return ret;
}
// Called before the first frame
bool Player::Start()
{
bool ret = true;
changeResolution = false;
attacker = false;
direction = DOWN;
state = IDLE;
scale = App->win->GetScale();
offset_x = 7;
offset_y = 10;
gamestate = TIMETOPLAY;
timetoplay = SDL_GetTicks();
canSwitchMap = true;
black = 0;
collision_feet = App->collision->AddCollider({ position.x - offset_x, position.y - offset_y, 14, 14 }, COLLIDER_PLAYER, this);
App->input_manager->AddListener(this);
return ret;
}
bool Player::PreUpdate()
{
BROFILER_CATEGORY("PreUpdate_Player", Profiler::Color::RosyBrown)
bool ret = true;
return ret;
}
bool Player::Update()//TODO HIGH -> I delete dt but i thing that we need.
{
BROFILER_CATEGORY("DoUpdate_Player", Profiler::Color::Red)
bool ret = true;
//if you dead, you appear on the Link House
if (hp_hearts.y == 0)
{
hp_hearts = { 6,6 };
if (App->map->CleanUp())
{
App->collision->EreseAllColiderPlayer();
App->entity_elements->DelteElements();
if (App->scene->enemy.size() > 0)
{
App->scene->enemy.clear();
}
if (App->scene->items.size() > 0)
{
App->scene->items.clear();
}
if (App->scene->dynobjects.size() > 0)
{
App->scene->dynobjects.clear();
}
if (App->scene->pokemons.size() > 0)
{
App->scene->pokemons.clear();
}
App->scene->Load_new_map(1);
}
}
// STATE MACHINE ------------------
if (gamestate == INGAME)
{
switch (state)
{
case IDLE:
{
Idle();
break;
}
case WALKING:
{
Walking();
break;
}
case ATTACKING:
{
Attack();
break;
}
case INTERACTING:
{
Interact();
break;
}
case HOOKTHROWN:
{
Hooking();
break;
}
default:
{
break;
}
}
}
else if (gamestate == INMENU)
{
}
else if (gamestate == TIMETOPLAY)
{
if (SDL_GetTicks() - timetoplay > 1000)
{
gamestate = INGAME;
}
}
//CHARGE BAR --------------
if (equiped_item != nullptr && equiped_item == hook)
{
if ((App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::BUTTON_B) == EVENTSTATE::E_REPEAT) && charge <= 34)
{
charge++;
}
else if (App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_UP)
{
state = HOOKTHROWN;
ThrowHookshot(charge);
}
else if (charge > 0)
{
charge--;
}
}
if (equiped_item != nullptr && equiped_item == bombmanager && App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_UP)
{
bombmanager->Drop(position);
App->audio->PlayFx(6);
}
if (App->input->GetKey(SDL_SCANCODE_B) == KEY_REPEAT && gems<999)
{
gems++;
}
if (App->input->GetKey(SDL_SCANCODE_M) == KEY_REPEAT && bombs<99)
{
bombs++;
}
if (App->input->GetKey(SDL_SCANCODE_N) == KEY_REPEAT && arrows<99)
{
arrows++;
}
if (App->input->GetKey(SDL_SCANCODE_Z) == KEY_DOWN)
{
//App->scene->dialog->PushLine(true);
}
if (App->input->GetKey(SDL_SCANCODE_RETURN) == KEY_DOWN)
{
if (App->scene->inventory) //TODO LOW -> If pres to fast you can lisen 2.
{
App->audio->PlayFx(3);
}
else
{
App->audio->PlayFx(2);
}
App->scene->switch_menu = true;
gamestate = INMENU;
}
//Collision follow the player
collision_feet->SetPos(position.x - offset_x, position.y - offset_y);
if (App->input_manager->EventPressed(INPUTEVENT::BUTTON_A) == EVENTSTATE::E_DOWN)
{
if (dialog == nullptr)
{
// dialog = App->gui->CreateDialogue("> Allahuakbar LOREM IPSUM,main nemim i spotato nintendo switch nontendoo SL maoeraoern ayylmao olaefc bruh. THE END");
}
else if (dialog->end == false)
{
// dialog->PushLine(true);
}
}
return ret;
}
void Player::Draw()
{
//Draw player
App->anim_manager->Drawing_Manager(state, direction, position, 0); //TODO LOW-> ID magic number, need change!!
}
bool Player::CleanUp()
{
bool ret = true;
return ret;
}
bool Player::Save()
{
App->entity_elements->XML.child("config").child("Link").child("stats").attribute("hp").set_value(hp);
App->entity_elements->XML.save_file("config.xml");
return true;
}
void Player::OnCollision(Collider* c1, Collider* c2)
{
if (c1 != nullptr && c2 != nullptr)
{
if (c1 == collision_attack && c2->type == COLLIDER_DYNOBJECT && c2->callback->name != "chest" && c2->callback->name != "bigchest")
{
iPoint pos_dyn = App->map->WorldToMap(c2->callback->position.x, c2->callback->position.y);
//srand(time(NULL)); int canDrop = rand() % 5 + 1;
int canDrop = 1;
if (canDrop == 1)
{
iPoint position;
position.x = c2->callback->position.x + 4;
position.y = c2->callback->position.y;
DynamicObjects* temp = (DynamicObjects*)c2->callback;
App->scene->items.push_back(App->entity_elements->CreateItem(temp->item_id, position));
}
App->map->EditCost(pos_dyn.x, pos_dyn.y, App->map->data.tilesets[1]->firstgid);
App->map->EditCost(pos_dyn.x + 1, pos_dyn.y, App->map->data.tilesets[1]->firstgid);
App->map->EditCost(pos_dyn.x, pos_dyn.y + 1, App->map->data.tilesets[1]->firstgid);
App->map->EditCost(pos_dyn.x + 1, pos_dyn.y + 1, App->map->data.tilesets[1]->firstgid);
App->entity_elements->DeleteDynObject((DynamicObjects*)c2->callback);
//App->collision->EraseCollider(c2);
}
if (c1 == collision_interact && c2->type == COLLIDER_DYNOBJECT)
{
if (c2->callback->name == "chest" || c2->callback->name == "bigchest")
{
iPoint pos_dyn = App->map->WorldToMap(c2->callback->position.x, c2->callback->position.y);
//srand(time(NULL)); int canDrop = rand() % 5 + 1;
int canDrop = 1;
if (canDrop == 1)
{
iPoint position;
position.x = c2->callback->position.x + c2->rect.w*0.5;
position.y = c2->callback->position.y + c2->rect.h;
DynamicObjects* temp = (DynamicObjects*)c2->callback;
App->scene->items.push_back(App->entity_elements->CreateItem(temp->item_id, position)); //TODO LOW call Drop item() function
}
App->entity_elements->DeleteDynObject((DynamicObjects*)c2->callback);
//App->collision->EraseCollider(c2);
}
}
if (c1 == collision_feet && c2->type == COLLIDER_ITEM)
{
if (c2->callback->name == "rupee")
{
App->audio->PlayFx(4);
gems++;
App->entity_elements->DeleteItem((Item*)c2->callback);
//App->collision->EraseCollider(c2);
}
if (c2->callback->name == "bomb")
{
if (bombmanager == nullptr)
{
bombmanager = App->entity_elements->CreateBombContainer();
}
App->entity_elements->DeleteItem((Item*)c2->callback);
bombs++;
//App->collision->EraseCollider(c2);
}
if (c2->callback->name == "hookshot")
{
if (hook == nullptr)
{
hook = App->entity_elements->CreateHookshot();
}
App->entity_elements->DeleteItem((Item*)c2->callback);
//App->collision->EraseCollider(c2);
}
if (c2->callback->name == "heart")
{
AddHeartContainer();
App->entity_elements->DeleteItem((Item*)c2->callback);
//App->collision->EraseCollider(c2);
}
}
if (c1 == collision_feet && c2->type == COLLIDER_ENEMY)
{
if (hurt == false)
{
timer.Start();
hurt = true;
hp_hearts.y--;
if (direction == UP)
{
if (App->map->MovementCost(position.x, position.y + 15, offset_x, offset_y, DOWN) == 0) //magic numbers 20 -> this is the distance you will move
{
position.y += 15;
}
}
if (direction == DOWN)
{
if (App->map->MovementCost(position.x, position.y - 15, offset_x, offset_y, UP) == 0) //magic numbers 20 -> this is the distance you will move
{
position.y -= 15;
}
}
if (direction == LEFT)
{
if (App->map->MovementCost(position.x + 15, position.y, offset_x, offset_y, RIGHT) == 0) //magic numbers 20 -> this is the distance you will move
{
position.x += 15;
}
}
if (direction == RIGHT)
{
if (App->map->MovementCost(position.x - 15, position.y, offset_x, offset_y, LEFT) == 0) //magic numbers 20 -> this is the distance you will move
{
position.x -= 15;
}
}
}
else
{
if (timer.ReadSec() >= 1)
{
hurt = false;
}
}
}
if (c1 == collision_attack && c2->type == COLLIDER_ENEMY)
{
Soldier* soldier = (Soldier*)c2->callback;
soldier->hp--;
if (soldier->hp == 0)
{
if (soldier->destructible)
{
c2->callback->state = DYING;
}
}
else
{
if (soldier->destructible)
{
soldier->state = HIT;
soldier->dir_hit = c1->callback->direction;
soldier->previus_position = soldier->position;
}
}
}
if (c1 == collision_feet && c2->type == COLLIDER_SWITCH_MAP)
{
if (canSwitchMap == false)
{
canSwitchMap = true;
}
else
{
iPoint temp_meta = App->map->WorldToMap(position.x, position.y); //central position
MapLayer* meta_ = App->map->data.layers[1];
int id_meta = meta_->Get(temp_meta.x, temp_meta.y);
for (int i = 0; i < App->map->directMap.size(); i++)
{
if (App->map->directMap[i].id_tile == id_meta)
{
canSwitchMap = false;
App->scene->switch_map = App->map->directMap[i].id_map;
App->scene->newPosition = App->map->directMap[i].position;
}
}
}
}
if (c1 == collision_attack && c2->type == COLLIDER_POKEMON)
{
if (c2->callback->name == "Golem" && c2->callback->state == HIT)
{
c2->callback->state = AWAKENING;
}
}
if (c1 == collision_feet && c2->type == COLLIDER_BOMB)
{
if (hurt == false)
{
GetDamage();
hurt = true;
}
}
}
}
bool Player::Camera_inside()
{
//256x224
if (camera_follow == true)
{
iPoint camera_pos(-App->render->camera.x / 2, -App->render->camera.y / 2);
iPoint size_map = App->map->MapToWorld(App->map->data.width, App->map->data.height);
if (direction == UP)
{
if (camera_pos.y == 0)
{
return false;
}
else
{
if (position.y > size_map.y - (App->win->GetHeight() / scale) / 2)
{
return false;
}
}
}
if (direction == DOWN)
{
if (camera_pos.y + (App->win->GetHeight() / scale) >= size_map.y)
{
return false;
}
else
{
if (position.y < (App->win->GetHeight() / scale) / 2)
{
return false;
}
}
}
if (direction == LEFT)
{
if (camera_pos.x == 0)
{
return false;
}
else
{
if (position.x > size_map.x - (App->win->GetWidth() / scale) / 2)
{
return false;
}
}
}
if (direction == RIGHT)
{
if (camera_pos.x + (App->win->GetWidth() / scale) >= size_map.x)
{
return false;
}
else
{
if (position.x < (App->win->GetWidth() / scale) / 2)
{
return false;
}
}
}
}
else
{
return false;
}
return true;
}
bool Player::Idle()
{
//TEST MOVE LINK
if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT ||
App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MDOWN) == EVENTSTATE::E_REPEAT ||
App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT ||
App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MUP) == EVENTSTATE::E_REPEAT)
{
state = WALKING;
CheckOrientation();
}
else if (App->input->GetKey(SDL_SCANCODE_E) == KEY_DOWN)
{
state = ATTACKING;
current_animation = App->anim_manager->GetAnimation(state, direction, 0);
current_animation->Reset();
}
else if (App->input->GetKey(SDL_SCANCODE_Q) == KEY_DOWN)
{
state = INTERACTING;
//current_animation = App->anim_manager->GetAnimation(state, direction, 0);
//current_animation->Reset();
}
else
{
state = IDLE;
}
return true;
}
bool Player::Walking()
{
walking = false;
Move();
if (walking == false)
{
state = IDLE;
}
else if (App->input->GetKey(SDL_SCANCODE_E) == KEY_DOWN)
{
state = ATTACKING;
current_animation = App->anim_manager->GetAnimation(state, direction, 0);
current_animation->Reset();
}
else if (App->input->GetKey(SDL_SCANCODE_Q) == KEY_DOWN)
{
state = INTERACTING;
//current_animation = App->anim_manager->GetAnimation(state, direction, 0);
//current_animation->Reset();
}
else
{
state = WALKING;
}
return false;
}
bool Player::Attack()
{
if (attacker)
{
if (current_animation->Finished())
{
App->collision->EraseCollider(collision_attack);
attacker = false;
current_animation->Reset();
current_animation = nullptr;
state = IDLE;
}
}
else
{
attacker = true;
if (direction == UP)
{
App->audio->PlayFx(5);
collision_attack = App->collision->AddCollider({ position.x - 4, position.y - offset_y - 18, 8, 20 }, COLLIDER_PLAYER, this);
}
else if (direction == RIGHT)
{
App->audio->PlayFx(5);
collision_attack = App->collision->AddCollider({ position.x + 3, position.y - 8, 20, 8 }, COLLIDER_PLAYER, this);
}
else if (direction == DOWN)
{
App->audio->PlayFx(5);
collision_attack = App->collision->AddCollider({ position.x - 4, position.y - 6, 8, 20 }, COLLIDER_PLAYER, this);
}
else if (direction == LEFT)
{
App->audio->PlayFx(5);
collision_attack = App->collision->AddCollider({ position.x - 22, position.y - 7, 20, 8 }, COLLIDER_PLAYER, this);
}
}
return true;
}
bool Player::Interact()
{
if (interaction)
{
if (timer.ReadSec() >= 0.3) // change to animation.finished
{
//if (current_animation->Finished())
//{
App->collision->EraseCollider(collision_interact);
interaction = false;
//current_animation->Reset();
//current_animation = nullptr;
state = IDLE;
//}
}
}
else
{
timer.Start();
interaction = true;
if (direction == UP)
{
collision_interact = App->collision->AddCollider({ position.x - 8, position.y - 14, 16, 5 }, COLLIDER_PLAYER, this);
}
else if (direction == RIGHT)
{
collision_interact = App->collision->AddCollider({ position.x + offset_x - 1, position.y - offset_y - 1, 5, 16 }, COLLIDER_PLAYER, this);
}
else if (direction == DOWN)
{
collision_interact = App->collision->AddCollider({ position.x - 8, position.y + 3, 16, 5 }, COLLIDER_PLAYER, this);
}
else if (direction == LEFT)
{
collision_interact = App->collision->AddCollider({ position.x - offset_x - 4, position.y - offset_y - 1, 5, 16 }, COLLIDER_PLAYER, this);
}
}
return true;
}
bool Player::Equip(Weapon* to_equip)
{
if (to_equip != nullptr)
{
if (equiped_item != to_equip && to_equip->equipable == true)
{
equiped_item = to_equip;
equiped_item->equiped = true;
LOG("Equiped %s", equiped_item->name.c_str());
return true;
}
}
LOG("Can't equip item");
return false;
}
bool Player::Unequip()
{
bool ret = false;
if (equiped_item == nullptr)
{
LOG("Nothing equiped");
}
else
{
LOG("Unequiped %s", equiped_item->name.c_str());
equiped_item->equiped = false;
equiped_item = nullptr;
}
return ret;
}
void Player::OnInputCallback(INPUTEVENT action, EVENTSTATE e_state)
{
switch (action)
{
if (gamestate == INGAME)
{
case BUTTON_X:
{
if (e_state == E_DOWN)
{
state = ATTACKING;
current_animation = App->anim_manager->GetAnimation(state, direction, 0);
current_animation->Reset();
}
break;
}
case BUTTON_A:
{
if (e_state == E_DOWN)
{
state = INTERACTING;;
//current_animation = App->anim_manager->GetAnimation(state, direction, 0);
//current_animation->Reset();
}
break;
}
case BUTTON_B:
if (hook != nullptr && equiped_item == hook)
{
if (e_state == E_UP)
{
state = HOOKTHROWN;
ThrowHookshot(charge);
}
}
else if (bombmanager != nullptr && equiped_item == bombmanager)
{
if (e_state == E_UP)
{
bombmanager->Drop(position);
}
}
break;
}
case BUTTON_START:
{
if (App->scene->inventory)
{
App->audio->PlayFx(2);
}
else
{
App->audio->PlayFx(3);
}
App->scene->switch_menu = true;
gamestate = INMENU;
break;
}
}
}
int Player::GetnuminputUse()
{
int ret = 0;
if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT)
{
ret++;
}
if (App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MDOWN) == EVENTSTATE::E_REPEAT)
{
ret++;
}
if (App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT)
{
ret++;
}
if (App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MUP) == EVENTSTATE::E_REPEAT)
{
ret++;
}
return ret;
}
void Player::ThrowHookshot(uint charge)
{
hook->in_use = true;
//CHECK DIRECTION
if (direction == UP)
{
iPoint pos(position.x, position.y - 3);
hook->SetPos(pos);
hook->offset_x = 6;
hook->offset_y = 4;
hook->collision = App->collision->AddCollider({ pos.x - hook->offset_x, pos.y - hook->offset_y, 12, 8 }, COLLIDER_HOOKSHOT, hook);
hook->direction = UP;
}
else if (direction == RIGHT)
{
iPoint pos(position.x, position.y - 3);
hook->SetPos(pos);
hook->offset_x = 4;
hook->offset_y = 6;
hook->collision = App->collision->AddCollider({ pos.x + offset_x, pos.y - hook->offset_y, 8, 12 }, COLLIDER_HOOKSHOT, hook);
hook->direction = RIGHT;
}
else if (direction == DOWN)
{
iPoint pos(position.x, position.y);
hook->SetPos(pos);
hook->offset_x = 6;
hook->offset_y = 4;
hook->collision = App->collision->AddCollider({ pos.x - hook->offset_x, pos.y + hook->offset_y, 12, 8 }, COLLIDER_HOOKSHOT, hook);
hook->direction = DOWN;
}
else if (direction == LEFT)
{
iPoint pos(position.x, position.y - 3);
hook->SetPos(pos);
hook->offset_x = 4;
hook->offset_y = 6;
hook->collision = App->collision->AddCollider({ pos.x - hook->offset_x, pos.y - hook->offset_y, 8, 12 }, COLLIDER_HOOKSHOT, hook);
hook->direction = LEFT;
}
//SET MAX RANGE
hook->SetRange((float)charge);
}
bool Player::Hooking()
{
//collider follows the hookshot
hook->collision->SetPos(hook->position.x - hook->offset_x, hook->position.y - hook->offset_y);
HookState stat = hook->GetState();
if (hook->actual_range_pos < hook->range)
{
if (stat == MISS)
{
HookState stat = hook->ReachObjective(actual_floor);
KeepGoing();
hook->actual_range_pos++;
}
else if (hook->GetState() == TARGET)
{
MoveTo(hook->position);
}
else if (hook->GetState() == OBSTACLE)
{
PickUpHook();
}
}
else
{
PickUpHook();
}
return true;
}
void Player::KeepGoing()
{
switch (direction)
{
case UP:
hook->position.y-= hook->speed;
break;
case DOWN:
hook->position.y += hook->speed;
break;
case LEFT:
hook->position.x -= hook->speed;
break;
case RIGHT:
hook->position.x += hook->speed;
break;
default:
break;
}
}
void Player::PickUpHook()
{
switch (direction)
{
case UP:
hook->position.y += hook->speed;
if (hook->position.y + hook->offset_y >= collision_feet->rect.y)
{
hook->Reset();
state = IDLE;
}
break;
case DOWN:
hook->position.y -= hook->speed;
if (hook->position.y <= collision_feet->rect.y + collision_feet->rect.h)
{
hook->Reset();
state = IDLE;
}
break;
case LEFT:
hook->position.x += hook->speed;
if (hook->position.x + hook->offset_x >= collision_feet->rect.x)
{
hook->Reset();
state = IDLE;
}
break;
case RIGHT:
hook->position.x -= hook->speed;
if (hook->position.x <= collision_feet->rect.x + collision_feet->rect.w)
{
hook->Reset();
state = IDLE;
}
break;
default:
break;
}
}
void Player::MoveTo(const iPoint& pos)
{
switch (direction)
{
case UP:
{
//int temp = App->map->MovementCost(position.x, position.y - hook->speed, UP);
if (Camera_inside())
App->render->camera.y += hook->speed * scale;
position.y -= hook->speed;
if (hook->position.y >= position.y)
{
hook->Reset();
state = IDLE;
}
break;
}
case DOWN:
{
//int temp = App->map->MovementCost(position.x, position.y + (hook->speed + height), DOWN
if (Camera_inside())
App->render->camera.y -= hook->speed * scale;
position.y += hook->speed;
if (hook->position.y <= position.y)
{
hook->Reset();
state = IDLE;
}
break;
}
case LEFT:
{
//int temp = App->map->MovementCost(position.x - hook->speed, position.y, LEFT);
if (Camera_inside())
App->render->camera.x += hook->speed * scale;
position.x -= hook->speed;
if (hook->position.x >= position.x)
{
hook->Reset();
state = IDLE;
}
break;
}
case RIGHT:
{
//int temp = App->map->MovementCost(position.x + (hook->speed + width), position.y, RIGHT
if (Camera_inside())
App->render->camera.x -= hook->speed * scale;
position.x += hook->speed;
if (hook->position.x <= position.x)
{
hook->Reset();
state = IDLE;
}
break;
}
default:
break;
}
}
bool Player::Move()
{
int keysuse = GetnuminputUse();
if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT)
{
direction = LEFT;
//int temp = App->map->MovementCost(position.x - speed, position.y, LEFT
int temp = App->map->MovementCost(collision_feet->rect.x - speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, LEFT);
if (temp == T_CONTINUE)
{
if (Camera_inside())
App->render->camera.x += speed * scale;
position.x -= speed;
}
if (keysuse == 1) //if you pres a key left and up this if will do that dont move more fast
{
if (temp == T_UP)//up
{
direction = UP;
if (Camera_inside())
App->render->camera.y += speed * scale;
position.y -= speed;
direction = LEFT;
}
if (temp == T_DOWN)//down
{
direction = DOWN;
if (Camera_inside())
App->render->camera.y -= speed * scale;
position.y += speed;
direction = LEFT;
}
}
walking = true;
}
if (App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MDOWN) == EVENTSTATE::E_REPEAT)
{
direction = DOWN;
//int temp = App->map->MovementCost(position.x, position.y + (speed + height), DOWN);
int temp = App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y + collision_feet->rect.h + speed, collision_feet->rect.w, collision_feet->rect.h, DOWN);
if (temp == T_CONTINUE)
{
if (Camera_inside())
App->render->camera.y -= speed * scale;
position.y += speed;
}
if (keysuse == 1)
{
if (temp == T_LEFT)//left
{
direction = LEFT;
if (Camera_inside())
App->render->camera.x += speed * scale;
position.x -= speed;
direction = DOWN;
}
if (temp == T_RIGHT)//right
{
direction = RIGHT;
if (Camera_inside())
App->render->camera.x -= speed * scale;
position.x += speed;
direction = DOWN;
}
}
walking = true;
}
if (App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT)
{
direction = RIGHT;
//int temp = App->map->MovementCost(position.x + (speed + width), position.y, RIGHT);
int temp = App->map->MovementCost(collision_feet->rect.x + collision_feet->rect.w + speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, RIGHT);
if (temp == T_CONTINUE)
{
if (Camera_inside())
App->render->camera.x -= speed * scale;
position.x += speed;
}
if (keysuse == 1)
{
if (temp == T_UP)//up
{
direction = UP;
if (Camera_inside())
App->render->camera.y += speed * scale;
position.y -= speed;
direction = RIGHT;
}
if (temp == T_DOWN)//down
{
direction = DOWN;
if (Camera_inside())
App->render->camera.y -= speed * scale;
position.y += speed;
direction = RIGHT;
}
}
walking = true;
}
if (App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MUP) == EVENTSTATE::E_REPEAT)
{
direction = UP;
//int temp = App->map->MovementCost(position.x, position.y - speed, UP);
int temp = App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y - speed, collision_feet->rect.w, collision_feet->rect.h, UP);
if (temp == T_CONTINUE)
{
if (Camera_inside())
App->render->camera.y += speed * scale;
position.y -= speed;
}
if (keysuse == 1)
{
if (temp == T_LEFT)//left
{
direction = LEFT;
if (Camera_inside())
App->render->camera.x += speed * scale;
position.x -= speed;
direction = UP;
}
if (temp == T_RIGHT)//right
{
direction = RIGHT;
if (Camera_inside())
App->render->camera.x -= speed * scale;
position.x += speed;
direction = UP;
}
}
walking = true;
}
//Set the actual floor of the player
if (App->map->data.layers.size() >= 3)
{
GetfloorLvl(position);
}
return walking;
}
void Player::GetfloorLvl(iPoint pos)
{
const MapLayer* meta_layer = App->map->data.layers[2];
iPoint map_pos = App->map->WorldToMap(pos.x, pos.y);
int player_lvl = meta_layer->Get(map_pos.x, map_pos.y);
const TileSet* tileset = App->map->data.tilesets[1];
int first_floor = tileset->firstgid + 1; // RED TILE
int second_floor = tileset->firstgid + 2; // YELLOW TILE
int third_floor = tileset->firstgid ; // GREEN TILE
if (first_floor == player_lvl)
{
actual_floor = 0;
}
else if (second_floor == player_lvl)
{
actual_floor = 1;
}
else if (third_floor == player_lvl)
{
actual_floor = 2;
}
LOG("Link is in floor %i", actual_floor);
}
bool Player::CheckOrientation()
{
if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT)
{
direction = LEFT;
}
else if (App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT)
{
direction = RIGHT;
}
else if (App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MUP) == EVENTSTATE::E_REPEAT)
{
direction = UP;
}
else if (App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MDOWN) == EVENTSTATE::E_REPEAT)
{
direction = DOWN;
}
return true;
}
void Player::AddHeartContainer()
{
iPoint last_heart_pos = App->scene->hp->elements.back()->position - App->scene->hp->position;
Image* newhp = App->gui->CreateImage({ 177,24,7,7 }, { last_heart_pos.x + 9,last_heart_pos.y }, "hp_add");
App->scene->hp->elements.push_back(newhp);
newhp->parent = App->scene->hp;
newhp->CalculateDiferential();
hp_hearts.x += 2;
hp_hearts.y = hp_hearts.x;
}
void Player::ShowHearts()
{
int addheart = hp_hearts.y;
for (int i = 0; i < App->scene->hp->elements.size(); i++)
{
if (addheart - 2 >= 0)
{
App->scene->hp->elements[i]->Hitbox.x = 161;
addheart -= 2;
}
else if (addheart - 1 >= 0)
{
App->scene->hp->elements[i]->Hitbox.x = 169;
addheart--;
}
else if (addheart == 0)
{
App->scene->hp->elements[i]->Hitbox.x = 177;
}
}
}
void Player::GetDamage()
{
if (hp_hearts.y>0)
hp_hearts.y--;
}
Fixed Collider Attack Link
#include "p2Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Input.h"
#include "j1Textures.h"
#include "j1Audio.h"
#include "j1Render.h"
#include "j1Window.h"
#include "j1Scene.h"
#include "j1Gui.h"
#include "j1GuiEntity.h"
#include "j1GuiElements.h"
#include "j1Player.h"
#include "j1FileSystem.h"
#include "j1AnimationManager.h"
#include "Golem.h"
#include "j1Collision.h"
#include "j1InputManager.h"
#include "Soldier.h"
#include "j1Item.h"
#include "j1DynamicObjects.h"
#include "j1Creature.h"
#include "j1Weapon.h"
#include "Animation.h"
#include "Pokemon.h"
//Constructor
Player::Player() : Creature()
{
type = CREATURE;
name = "Link";
hp_hearts = { 6,6 };
}
// Destructor
Player::~Player()
{}
// Called before render is available
bool Player::Awake(pugi::xml_node& conf)
{
LOG("Loading Texture Player");
bool ret = true;
hp = conf.child("stats").attribute("hp").as_int(0);
attack = conf.child("stats").attribute("attack").as_int(0);
speed = conf.child("stats").attribute("speed").as_int(0);
position.x = conf.child("stats").attribute("pos_x").as_int(0);
position.y = conf.child("stats").attribute("pos_y").as_int(0);
return ret;
}
// Called before the first frame
bool Player::Start()
{
bool ret = true;
changeResolution = false;
attacker = false;
direction = DOWN;
state = IDLE;
scale = App->win->GetScale();
offset_x = 7;
offset_y = 10;
gamestate = TIMETOPLAY;
timetoplay = SDL_GetTicks();
canSwitchMap = true;
black = 0;
collision_feet = App->collision->AddCollider({ position.x - offset_x, position.y - offset_y, 14, 14 }, COLLIDER_PLAYER, this);
App->input_manager->AddListener(this);
return ret;
}
bool Player::PreUpdate()
{
BROFILER_CATEGORY("PreUpdate_Player", Profiler::Color::RosyBrown)
bool ret = true;
return ret;
}
bool Player::Update()//TODO HIGH -> I delete dt but i thing that we need.
{
BROFILER_CATEGORY("DoUpdate_Player", Profiler::Color::Red)
bool ret = true;
//if you dead, you appear on the Link House
if (hp_hearts.y == 0)
{
hp_hearts = { 6,6 };
if (App->map->CleanUp())
{
App->collision->EreseAllColiderPlayer();
App->entity_elements->DelteElements();
if (App->scene->enemy.size() > 0)
{
App->scene->enemy.clear();
}
if (App->scene->items.size() > 0)
{
App->scene->items.clear();
}
if (App->scene->dynobjects.size() > 0)
{
App->scene->dynobjects.clear();
}
if (App->scene->pokemons.size() > 0)
{
App->scene->pokemons.clear();
}
App->scene->Load_new_map(1);
}
}
// STATE MACHINE ------------------
if (gamestate == INGAME)
{
switch (state)
{
case IDLE:
{
Idle();
break;
}
case WALKING:
{
Walking();
break;
}
case ATTACKING:
{
Attack();
break;
}
case INTERACTING:
{
Interact();
break;
}
case HOOKTHROWN:
{
Hooking();
break;
}
default:
{
break;
}
}
}
else if (gamestate == INMENU)
{
}
else if (gamestate == TIMETOPLAY)
{
if (SDL_GetTicks() - timetoplay > 1000)
{
gamestate = INGAME;
}
}
//CHARGE BAR --------------
if (equiped_item != nullptr && equiped_item == hook)
{
if ((App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::BUTTON_B) == EVENTSTATE::E_REPEAT) && charge <= 34)
{
charge++;
}
else if (App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_UP)
{
state = HOOKTHROWN;
ThrowHookshot(charge);
}
else if (charge > 0)
{
charge--;
}
}
if (equiped_item != nullptr && equiped_item == bombmanager && App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_UP)
{
bombmanager->Drop(position);
App->audio->PlayFx(6);
}
if (App->input->GetKey(SDL_SCANCODE_B) == KEY_REPEAT && gems<999)
{
gems++;
}
if (App->input->GetKey(SDL_SCANCODE_M) == KEY_REPEAT && bombs<99)
{
bombs++;
}
if (App->input->GetKey(SDL_SCANCODE_N) == KEY_REPEAT && arrows<99)
{
arrows++;
}
if (App->input->GetKey(SDL_SCANCODE_Z) == KEY_DOWN)
{
//App->scene->dialog->PushLine(true);
}
if (App->input->GetKey(SDL_SCANCODE_RETURN) == KEY_DOWN)
{
if (App->scene->inventory) //TODO LOW -> If pres to fast you can lisen 2.
{
App->audio->PlayFx(3);
}
else
{
App->audio->PlayFx(2);
}
App->scene->switch_menu = true;
gamestate = INMENU;
}
//Collision follow the player
collision_feet->SetPos(position.x - offset_x, position.y - offset_y);
if (App->input_manager->EventPressed(INPUTEVENT::BUTTON_A) == EVENTSTATE::E_DOWN)
{
if (dialog == nullptr)
{
// dialog = App->gui->CreateDialogue("> Allahuakbar LOREM IPSUM,main nemim i spotato nintendo switch nontendoo SL maoeraoern ayylmao olaefc bruh. THE END");
}
else if (dialog->end == false)
{
// dialog->PushLine(true);
}
}
return ret;
}
void Player::Draw()
{
//Draw player
App->anim_manager->Drawing_Manager(state, direction, position, 0); //TODO LOW-> ID magic number, need change!!
}
bool Player::CleanUp()
{
bool ret = true;
return ret;
}
bool Player::Save()
{
App->entity_elements->XML.child("config").child("Link").child("stats").attribute("hp").set_value(hp);
App->entity_elements->XML.save_file("config.xml");
return true;
}
void Player::OnCollision(Collider* c1, Collider* c2)
{
if (c1 != nullptr && c2 != nullptr)
{
if (c1 == collision_attack && c2->type == COLLIDER_DYNOBJECT && c2->callback->name != "chest" && c2->callback->name != "bigchest")
{
iPoint pos_dyn = App->map->WorldToMap(c2->callback->position.x, c2->callback->position.y);
//srand(time(NULL)); int canDrop = rand() % 5 + 1;
int canDrop = 1;
if (canDrop == 1)
{
iPoint position;
position.x = c2->callback->position.x + 4;
position.y = c2->callback->position.y;
DynamicObjects* temp = (DynamicObjects*)c2->callback;
App->scene->items.push_back(App->entity_elements->CreateItem(temp->item_id, position));
}
App->map->EditCost(pos_dyn.x, pos_dyn.y, App->map->data.tilesets[1]->firstgid);
App->map->EditCost(pos_dyn.x + 1, pos_dyn.y, App->map->data.tilesets[1]->firstgid);
App->map->EditCost(pos_dyn.x, pos_dyn.y + 1, App->map->data.tilesets[1]->firstgid);
App->map->EditCost(pos_dyn.x + 1, pos_dyn.y + 1, App->map->data.tilesets[1]->firstgid);
App->entity_elements->DeleteDynObject((DynamicObjects*)c2->callback);
//App->collision->EraseCollider(c2);
}
if (c1 == collision_interact && c2->type == COLLIDER_DYNOBJECT)
{
if (c2->callback->name == "chest" || c2->callback->name == "bigchest")
{
iPoint pos_dyn = App->map->WorldToMap(c2->callback->position.x, c2->callback->position.y);
//srand(time(NULL)); int canDrop = rand() % 5 + 1;
int canDrop = 1;
if (canDrop == 1)
{
iPoint position;
position.x = c2->callback->position.x + c2->rect.w*0.5;
position.y = c2->callback->position.y + c2->rect.h;
DynamicObjects* temp = (DynamicObjects*)c2->callback;
App->scene->items.push_back(App->entity_elements->CreateItem(temp->item_id, position)); //TODO LOW call Drop item() function
}
App->entity_elements->DeleteDynObject((DynamicObjects*)c2->callback);
//App->collision->EraseCollider(c2);
}
}
if (c1 == collision_feet && c2->type == COLLIDER_ITEM)
{
if (c2->callback->name == "rupee")
{
App->audio->PlayFx(4);
gems++;
App->entity_elements->DeleteItem((Item*)c2->callback);
//App->collision->EraseCollider(c2);
}
if (c2->callback->name == "bomb")
{
if (bombmanager == nullptr)
{
bombmanager = App->entity_elements->CreateBombContainer();
}
App->entity_elements->DeleteItem((Item*)c2->callback);
bombs++;
//App->collision->EraseCollider(c2);
}
if (c2->callback->name == "hookshot")
{
if (hook == nullptr)
{
hook = App->entity_elements->CreateHookshot();
}
App->entity_elements->DeleteItem((Item*)c2->callback);
//App->collision->EraseCollider(c2);
}
if (c2->callback->name == "heart")
{
AddHeartContainer();
App->entity_elements->DeleteItem((Item*)c2->callback);
//App->collision->EraseCollider(c2);
}
}
if (c1 == collision_feet && c2->type == COLLIDER_ENEMY)
{
if (hurt == false)
{
timer.Start();
hurt = true;
hp_hearts.y--;
if (direction == UP)
{
if (App->map->MovementCost(position.x, position.y + 15, offset_x, offset_y, DOWN) == 0) //magic numbers 20 -> this is the distance you will move
{
position.y += 15;
}
}
if (direction == DOWN)
{
if (App->map->MovementCost(position.x, position.y - 15, offset_x, offset_y, UP) == 0) //magic numbers 20 -> this is the distance you will move
{
position.y -= 15;
}
}
if (direction == LEFT)
{
if (App->map->MovementCost(position.x + 15, position.y, offset_x, offset_y, RIGHT) == 0) //magic numbers 20 -> this is the distance you will move
{
position.x += 15;
}
}
if (direction == RIGHT)
{
if (App->map->MovementCost(position.x - 15, position.y, offset_x, offset_y, LEFT) == 0) //magic numbers 20 -> this is the distance you will move
{
position.x -= 15;
}
}
}
else
{
if (timer.ReadSec() >= 1)
{
hurt = false;
}
}
}
if (c1 == collision_attack && c2->type == COLLIDER_ENEMY)
{
Soldier* soldier = (Soldier*)c2->callback;
soldier->hp--;
if (soldier->hp == 0)
{
if (soldier->destructible)
{
c2->callback->state = DYING;
}
}
else
{
if (soldier->destructible)
{
soldier->state = HIT;
soldier->dir_hit = c1->callback->direction;
soldier->previus_position = soldier->position;
}
}
}
if (c1 == collision_feet && c2->type == COLLIDER_SWITCH_MAP)
{
if (canSwitchMap == false)
{
canSwitchMap = true;
}
else
{
iPoint temp_meta = App->map->WorldToMap(position.x, position.y); //central position
MapLayer* meta_ = App->map->data.layers[1];
int id_meta = meta_->Get(temp_meta.x, temp_meta.y);
for (int i = 0; i < App->map->directMap.size(); i++)
{
if (App->map->directMap[i].id_tile == id_meta)
{
canSwitchMap = false;
App->scene->switch_map = App->map->directMap[i].id_map;
App->scene->newPosition = App->map->directMap[i].position;
}
}
}
}
if (c1 == collision_attack && c2->type == COLLIDER_POKEMON)
{
if (c2->callback->name == "Golem" && c2->callback->state == HIT)
{
c2->callback->state = AWAKENING;
}
}
if (c1 == collision_feet && c2->type == COLLIDER_BOMB)
{
if (hurt == false)
{
GetDamage();
hurt = true;
}
}
}
}
bool Player::Camera_inside()
{
//256x224
if (camera_follow == true)
{
iPoint camera_pos(-App->render->camera.x / 2, -App->render->camera.y / 2);
iPoint size_map = App->map->MapToWorld(App->map->data.width, App->map->data.height);
if (direction == UP)
{
if (camera_pos.y == 0)
{
return false;
}
else
{
if (position.y > size_map.y - (App->win->GetHeight() / scale) / 2)
{
return false;
}
}
}
if (direction == DOWN)
{
if (camera_pos.y + (App->win->GetHeight() / scale) >= size_map.y)
{
return false;
}
else
{
if (position.y < (App->win->GetHeight() / scale) / 2)
{
return false;
}
}
}
if (direction == LEFT)
{
if (camera_pos.x == 0)
{
return false;
}
else
{
if (position.x > size_map.x - (App->win->GetWidth() / scale) / 2)
{
return false;
}
}
}
if (direction == RIGHT)
{
if (camera_pos.x + (App->win->GetWidth() / scale) >= size_map.x)
{
return false;
}
else
{
if (position.x < (App->win->GetWidth() / scale) / 2)
{
return false;
}
}
}
}
else
{
return false;
}
return true;
}
bool Player::Idle()
{
//TEST MOVE LINK
if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT ||
App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MDOWN) == EVENTSTATE::E_REPEAT ||
App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT ||
App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MUP) == EVENTSTATE::E_REPEAT)
{
state = WALKING;
CheckOrientation();
}
else if (App->input->GetKey(SDL_SCANCODE_E) == KEY_DOWN)
{
state = ATTACKING;
current_animation = App->anim_manager->GetAnimation(state, direction, 0);
current_animation->Reset();
}
else if (App->input->GetKey(SDL_SCANCODE_Q) == KEY_DOWN)
{
state = INTERACTING;
//current_animation = App->anim_manager->GetAnimation(state, direction, 0);
//current_animation->Reset();
}
else
{
state = IDLE;
}
return true;
}
bool Player::Walking()
{
walking = false;
Move();
if (walking == false)
{
state = IDLE;
}
else if (App->input->GetKey(SDL_SCANCODE_E) == KEY_DOWN)
{
state = ATTACKING;
current_animation = App->anim_manager->GetAnimation(state, direction, 0);
current_animation->Reset();
}
else if (App->input->GetKey(SDL_SCANCODE_Q) == KEY_DOWN)
{
state = INTERACTING;
//current_animation = App->anim_manager->GetAnimation(state, direction, 0);
//current_animation->Reset();
}
else
{
state = WALKING;
}
return false;
}
bool Player::Attack()
{
if (attacker)
{
if (current_animation->Finished())
{
App->collision->EraseCollider(collision_attack);
attacker = false;
current_animation->Reset();
current_animation = nullptr;
state = IDLE;
}
}
else
{
attacker = true;
if (direction == UP)
{
App->audio->PlayFx(5);
collision_attack = App->collision->AddCollider({ position.x - 4, position.y - offset_y - 13, 8, 20 }, COLLIDER_PLAYER, this);
}
else if (direction == RIGHT)
{
App->audio->PlayFx(5);
collision_attack = App->collision->AddCollider({ position.x + 3, position.y - 8, 20, 8 }, COLLIDER_PLAYER, this);
}
else if (direction == DOWN)
{
App->audio->PlayFx(5);
collision_attack = App->collision->AddCollider({ position.x - 4, position.y - 6, 8, 16 }, COLLIDER_PLAYER, this);
}
else if (direction == LEFT)
{
App->audio->PlayFx(5);
collision_attack = App->collision->AddCollider({ position.x - 22, position.y - 7, 20, 8 }, COLLIDER_PLAYER, this);
}
}
return true;
}
bool Player::Interact()
{
if (interaction)
{
if (timer.ReadSec() >= 0.3) // change to animation.finished
{
//if (current_animation->Finished())
//{
App->collision->EraseCollider(collision_interact);
interaction = false;
//current_animation->Reset();
//current_animation = nullptr;
state = IDLE;
//}
}
}
else
{
timer.Start();
interaction = true;
if (direction == UP)
{
collision_interact = App->collision->AddCollider({ position.x - 8, position.y - 14, 16, 5 }, COLLIDER_PLAYER, this);
}
else if (direction == RIGHT)
{
collision_interact = App->collision->AddCollider({ position.x + offset_x - 1, position.y - offset_y - 1, 5, 16 }, COLLIDER_PLAYER, this);
}
else if (direction == DOWN)
{
collision_interact = App->collision->AddCollider({ position.x - 8, position.y + 3, 16, 5 }, COLLIDER_PLAYER, this);
}
else if (direction == LEFT)
{
collision_interact = App->collision->AddCollider({ position.x - offset_x - 4, position.y - offset_y - 1, 5, 16 }, COLLIDER_PLAYER, this);
}
}
return true;
}
bool Player::Equip(Weapon* to_equip)
{
if (to_equip != nullptr)
{
if (equiped_item != to_equip && to_equip->equipable == true)
{
equiped_item = to_equip;
equiped_item->equiped = true;
LOG("Equiped %s", equiped_item->name.c_str());
return true;
}
}
LOG("Can't equip item");
return false;
}
bool Player::Unequip()
{
bool ret = false;
if (equiped_item == nullptr)
{
LOG("Nothing equiped");
}
else
{
LOG("Unequiped %s", equiped_item->name.c_str());
equiped_item->equiped = false;
equiped_item = nullptr;
}
return ret;
}
void Player::OnInputCallback(INPUTEVENT action, EVENTSTATE e_state)
{
switch (action)
{
if (gamestate == INGAME)
{
case BUTTON_X:
{
if (e_state == E_DOWN)
{
state = ATTACKING;
current_animation = App->anim_manager->GetAnimation(state, direction, 0);
current_animation->Reset();
}
break;
}
case BUTTON_A:
{
if (e_state == E_DOWN)
{
state = INTERACTING;;
//current_animation = App->anim_manager->GetAnimation(state, direction, 0);
//current_animation->Reset();
}
break;
}
case BUTTON_B:
if (hook != nullptr && equiped_item == hook)
{
if (e_state == E_UP)
{
state = HOOKTHROWN;
ThrowHookshot(charge);
}
}
else if (bombmanager != nullptr && equiped_item == bombmanager)
{
if (e_state == E_UP)
{
bombmanager->Drop(position);
}
}
break;
}
case BUTTON_START:
{
if (App->scene->inventory)
{
App->audio->PlayFx(2);
}
else
{
App->audio->PlayFx(3);
}
App->scene->switch_menu = true;
gamestate = INMENU;
break;
}
}
}
int Player::GetnuminputUse()
{
int ret = 0;
if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT)
{
ret++;
}
if (App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MDOWN) == EVENTSTATE::E_REPEAT)
{
ret++;
}
if (App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT)
{
ret++;
}
if (App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MUP) == EVENTSTATE::E_REPEAT)
{
ret++;
}
return ret;
}
void Player::ThrowHookshot(uint charge)
{
hook->in_use = true;
//CHECK DIRECTION
if (direction == UP)
{
iPoint pos(position.x, position.y - 3);
hook->SetPos(pos);
hook->offset_x = 6;
hook->offset_y = 4;
hook->collision = App->collision->AddCollider({ pos.x - hook->offset_x, pos.y - hook->offset_y, 12, 8 }, COLLIDER_HOOKSHOT, hook);
hook->direction = UP;
}
else if (direction == RIGHT)
{
iPoint pos(position.x, position.y - 3);
hook->SetPos(pos);
hook->offset_x = 4;
hook->offset_y = 6;
hook->collision = App->collision->AddCollider({ pos.x + offset_x, pos.y - hook->offset_y, 8, 12 }, COLLIDER_HOOKSHOT, hook);
hook->direction = RIGHT;
}
else if (direction == DOWN)
{
iPoint pos(position.x, position.y);
hook->SetPos(pos);
hook->offset_x = 6;
hook->offset_y = 4;
hook->collision = App->collision->AddCollider({ pos.x - hook->offset_x, pos.y + hook->offset_y, 12, 8 }, COLLIDER_HOOKSHOT, hook);
hook->direction = DOWN;
}
else if (direction == LEFT)
{
iPoint pos(position.x, position.y - 3);
hook->SetPos(pos);
hook->offset_x = 4;
hook->offset_y = 6;
hook->collision = App->collision->AddCollider({ pos.x - hook->offset_x, pos.y - hook->offset_y, 8, 12 }, COLLIDER_HOOKSHOT, hook);
hook->direction = LEFT;
}
//SET MAX RANGE
hook->SetRange((float)charge);
}
bool Player::Hooking()
{
//collider follows the hookshot
hook->collision->SetPos(hook->position.x - hook->offset_x, hook->position.y - hook->offset_y);
HookState stat = hook->GetState();
if (hook->actual_range_pos < hook->range)
{
if (stat == MISS)
{
HookState stat = hook->ReachObjective(actual_floor);
KeepGoing();
hook->actual_range_pos++;
}
else if (hook->GetState() == TARGET)
{
MoveTo(hook->position);
}
else if (hook->GetState() == OBSTACLE)
{
PickUpHook();
}
}
else
{
PickUpHook();
}
return true;
}
void Player::KeepGoing()
{
switch (direction)
{
case UP:
hook->position.y-= hook->speed;
break;
case DOWN:
hook->position.y += hook->speed;
break;
case LEFT:
hook->position.x -= hook->speed;
break;
case RIGHT:
hook->position.x += hook->speed;
break;
default:
break;
}
}
void Player::PickUpHook()
{
switch (direction)
{
case UP:
hook->position.y += hook->speed;
if (hook->position.y + hook->offset_y >= collision_feet->rect.y)
{
hook->Reset();
state = IDLE;
}
break;
case DOWN:
hook->position.y -= hook->speed;
if (hook->position.y <= collision_feet->rect.y + collision_feet->rect.h)
{
hook->Reset();
state = IDLE;
}
break;
case LEFT:
hook->position.x += hook->speed;
if (hook->position.x + hook->offset_x >= collision_feet->rect.x)
{
hook->Reset();
state = IDLE;
}
break;
case RIGHT:
hook->position.x -= hook->speed;
if (hook->position.x <= collision_feet->rect.x + collision_feet->rect.w)
{
hook->Reset();
state = IDLE;
}
break;
default:
break;
}
}
void Player::MoveTo(const iPoint& pos)
{
switch (direction)
{
case UP:
{
//int temp = App->map->MovementCost(position.x, position.y - hook->speed, UP);
if (Camera_inside())
App->render->camera.y += hook->speed * scale;
position.y -= hook->speed;
if (hook->position.y >= position.y)
{
hook->Reset();
state = IDLE;
}
break;
}
case DOWN:
{
//int temp = App->map->MovementCost(position.x, position.y + (hook->speed + height), DOWN
if (Camera_inside())
App->render->camera.y -= hook->speed * scale;
position.y += hook->speed;
if (hook->position.y <= position.y)
{
hook->Reset();
state = IDLE;
}
break;
}
case LEFT:
{
//int temp = App->map->MovementCost(position.x - hook->speed, position.y, LEFT);
if (Camera_inside())
App->render->camera.x += hook->speed * scale;
position.x -= hook->speed;
if (hook->position.x >= position.x)
{
hook->Reset();
state = IDLE;
}
break;
}
case RIGHT:
{
//int temp = App->map->MovementCost(position.x + (hook->speed + width), position.y, RIGHT
if (Camera_inside())
App->render->camera.x -= hook->speed * scale;
position.x += hook->speed;
if (hook->position.x <= position.x)
{
hook->Reset();
state = IDLE;
}
break;
}
default:
break;
}
}
bool Player::Move()
{
int keysuse = GetnuminputUse();
if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT)
{
direction = LEFT;
//int temp = App->map->MovementCost(position.x - speed, position.y, LEFT
int temp = App->map->MovementCost(collision_feet->rect.x - speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, LEFT);
if (temp == T_CONTINUE)
{
if (Camera_inside())
App->render->camera.x += speed * scale;
position.x -= speed;
}
if (keysuse == 1) //if you pres a key left and up this if will do that dont move more fast
{
if (temp == T_UP)//up
{
direction = UP;
if (Camera_inside())
App->render->camera.y += speed * scale;
position.y -= speed;
direction = LEFT;
}
if (temp == T_DOWN)//down
{
direction = DOWN;
if (Camera_inside())
App->render->camera.y -= speed * scale;
position.y += speed;
direction = LEFT;
}
}
walking = true;
}
if (App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MDOWN) == EVENTSTATE::E_REPEAT)
{
direction = DOWN;
//int temp = App->map->MovementCost(position.x, position.y + (speed + height), DOWN);
int temp = App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y + collision_feet->rect.h + speed, collision_feet->rect.w, collision_feet->rect.h, DOWN);
if (temp == T_CONTINUE)
{
if (Camera_inside())
App->render->camera.y -= speed * scale;
position.y += speed;
}
if (keysuse == 1)
{
if (temp == T_LEFT)//left
{
direction = LEFT;
if (Camera_inside())
App->render->camera.x += speed * scale;
position.x -= speed;
direction = DOWN;
}
if (temp == T_RIGHT)//right
{
direction = RIGHT;
if (Camera_inside())
App->render->camera.x -= speed * scale;
position.x += speed;
direction = DOWN;
}
}
walking = true;
}
if (App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT)
{
direction = RIGHT;
//int temp = App->map->MovementCost(position.x + (speed + width), position.y, RIGHT);
int temp = App->map->MovementCost(collision_feet->rect.x + collision_feet->rect.w + speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, RIGHT);
if (temp == T_CONTINUE)
{
if (Camera_inside())
App->render->camera.x -= speed * scale;
position.x += speed;
}
if (keysuse == 1)
{
if (temp == T_UP)//up
{
direction = UP;
if (Camera_inside())
App->render->camera.y += speed * scale;
position.y -= speed;
direction = RIGHT;
}
if (temp == T_DOWN)//down
{
direction = DOWN;
if (Camera_inside())
App->render->camera.y -= speed * scale;
position.y += speed;
direction = RIGHT;
}
}
walking = true;
}
if (App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MUP) == EVENTSTATE::E_REPEAT)
{
direction = UP;
//int temp = App->map->MovementCost(position.x, position.y - speed, UP);
int temp = App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y - speed, collision_feet->rect.w, collision_feet->rect.h, UP);
if (temp == T_CONTINUE)
{
if (Camera_inside())
App->render->camera.y += speed * scale;
position.y -= speed;
}
if (keysuse == 1)
{
if (temp == T_LEFT)//left
{
direction = LEFT;
if (Camera_inside())
App->render->camera.x += speed * scale;
position.x -= speed;
direction = UP;
}
if (temp == T_RIGHT)//right
{
direction = RIGHT;
if (Camera_inside())
App->render->camera.x -= speed * scale;
position.x += speed;
direction = UP;
}
}
walking = true;
}
//Set the actual floor of the player
if (App->map->data.layers.size() >= 3)
{
GetfloorLvl(position);
}
return walking;
}
void Player::GetfloorLvl(iPoint pos)
{
const MapLayer* meta_layer = App->map->data.layers[2];
iPoint map_pos = App->map->WorldToMap(pos.x, pos.y);
int player_lvl = meta_layer->Get(map_pos.x, map_pos.y);
const TileSet* tileset = App->map->data.tilesets[1];
int first_floor = tileset->firstgid + 1; // RED TILE
int second_floor = tileset->firstgid + 2; // YELLOW TILE
int third_floor = tileset->firstgid ; // GREEN TILE
if (first_floor == player_lvl)
{
actual_floor = 0;
}
else if (second_floor == player_lvl)
{
actual_floor = 1;
}
else if (third_floor == player_lvl)
{
actual_floor = 2;
}
LOG("Link is in floor %i", actual_floor);
}
bool Player::CheckOrientation()
{
if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT)
{
direction = LEFT;
}
else if (App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT)
{
direction = RIGHT;
}
else if (App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MUP) == EVENTSTATE::E_REPEAT)
{
direction = UP;
}
else if (App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MDOWN) == EVENTSTATE::E_REPEAT)
{
direction = DOWN;
}
return true;
}
void Player::AddHeartContainer()
{
iPoint last_heart_pos = App->scene->hp->elements.back()->position - App->scene->hp->position;
Image* newhp = App->gui->CreateImage({ 177,24,7,7 }, { last_heart_pos.x + 9,last_heart_pos.y }, "hp_add");
App->scene->hp->elements.push_back(newhp);
newhp->parent = App->scene->hp;
newhp->CalculateDiferential();
hp_hearts.x += 2;
hp_hearts.y = hp_hearts.x;
}
void Player::ShowHearts()
{
int addheart = hp_hearts.y;
for (int i = 0; i < App->scene->hp->elements.size(); i++)
{
if (addheart - 2 >= 0)
{
App->scene->hp->elements[i]->Hitbox.x = 161;
addheart -= 2;
}
else if (addheart - 1 >= 0)
{
App->scene->hp->elements[i]->Hitbox.x = 169;
addheart--;
}
else if (addheart == 0)
{
App->scene->hp->elements[i]->Hitbox.x = 177;
}
}
}
void Player::GetDamage()
{
if (hp_hearts.y>0)
hp_hearts.y--;
} |
#include "MasterManagerBase.h"
#include "SuperNodeManager.h"
#include "NodeManagerBase.h"
#include "ZooKeeperNamespace.h"
#include "DistributeTest.hpp"
#include <boost/lexical_cast.hpp>
using namespace sf1r;
// note lock:
// you should never sync call the interface which may hold a lock in the NodeManagerBase .
//
MasterManagerBase::MasterManagerBase()
: isDistributeEnable_(false)
, masterState_(MASTER_STATE_INIT)
, stopping_(false)
, write_prepared_(false)
, new_write_disabled_(false)
, CLASSNAME("MasterManagerBase")
{
}
bool MasterManagerBase::init()
{
// initialize zookeeper client
topologyPath_ = ZooKeeperNamespace::getTopologyPath();
serverParentPath_ = ZooKeeperNamespace::getServerParentPath();
serverPath_ = ZooKeeperNamespace::getServerPath();
zookeeper_ = ZooKeeperManager::get()->createClient(this);
if (!zookeeper_)
return false;
sf1rTopology_ = NodeManagerBase::get()->getSf1rTopology();
write_req_queue_ = ZooKeeperNamespace::getWriteReqQueueNode(sf1rTopology_.curNode_.nodeId_);
write_req_queue_parent_ = ZooKeeperNamespace::getCurrWriteReqQueueParent(sf1rTopology_.curNode_.nodeId_);
write_req_queue_root_parent_ = ZooKeeperNamespace::getRootWriteReqQueueParent();
stopping_ = false;
return true;
}
void MasterManagerBase::start()
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
stopping_ = false;
if (masterState_ == MASTER_STATE_INIT)
{
masterState_ = MASTER_STATE_STARTING;
if (!init())
{
throw std::runtime_error(std::string("failed to initialize ") + CLASSNAME);
}
if (!checkZooKeeperService())
{
masterState_ = MASTER_STATE_STARTING_WAIT_ZOOKEEPER;
LOG (ERROR) << CLASSNAME << " waiting for ZooKeeper Service...";
return;
}
doStart();
}
// call init for all service.
ServiceMapT::const_iterator cit = all_distributed_services_.begin();
while(cit != all_distributed_services_.end())
{
cit->second->initMaster();
++cit;
}
}
void MasterManagerBase::stop()
{
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
stopping_ = true;
}
if (zookeeper_ && zookeeper_->isConnected())
{
std::vector<std::string> childrenList;
zookeeper_->deleteZNode(serverRealPath_);
zookeeper_->getZNodeChildren(serverParentPath_, childrenList, ZooKeeper::NOT_WATCH, false);
if (childrenList.size() == 0)
{
zookeeper_->deleteZNode(serverParentPath_);
}
childrenList.clear();
zookeeper_->isZNodeExists(write_req_queue_parent_, ZooKeeper::NOT_WATCH);
zookeeper_->isZNodeExists(write_req_queue_root_parent_, ZooKeeper::NOT_WATCH);
// disconnect will wait other ZooKeeper event finished,
// so we can not do it in state_mutex_ lock.
zookeeper_->disconnect();
}
boost::lock_guard<boost::mutex> lock(state_mutex_);
masterState_ = MASTER_STATE_INIT;
}
bool MasterManagerBase::getShardReceiver(
unsigned int shardid,
std::string& host,
unsigned int& recvPort)
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
WorkerMapT::iterator it = workerMap_.find(shardid);
if (it != workerMap_.end())
{
host = it->second->host_;
recvPort = it->second->dataPort_;
return true;
}
else
{
return false;
}
}
bool MasterManagerBase::getCollectionShardids(const std::string& service, const std::string& collection, std::vector<shardid_t>& shardidList)
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
return sf1rTopology_.curNode_.master_.getShardidList(service, collection, shardidList);
}
bool MasterManagerBase::checkCollectionShardid(const std::string& service, const std::string& collection, unsigned int shardid)
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
return sf1rTopology_.curNode_.master_.checkCollectionWorker(service, collection, shardid);
}
void MasterManagerBase::registerIndexStatus(const std::string& collection, bool isIndexing)
{
std::string indexStatus = isIndexing ? "indexing" : "notindexing";
std::string data;
if (zookeeper_ && zookeeper_->getZNodeData(serverRealPath_, data))
{
ZNode znode;
znode.loadKvString(data);
znode.setValue(collection, indexStatus);
}
std::string nodePath = getNodePath(sf1rTopology_.curNode_.replicaId_, sf1rTopology_.curNode_.nodeId_);
if (zookeeper_ && zookeeper_->getZNodeData(nodePath, data, ZooKeeper::WATCH))
{
ZNode znode;
znode.loadKvString(data);
znode.setValue(collection, indexStatus);
}
}
void MasterManagerBase::process(ZooKeeperEvent& zkEvent)
{
LOG(INFO) << CLASSNAME << ", "<< state2string(masterState_) <<", "<<zkEvent.toString();
if (stopping_)
return;
if (zkEvent.type_ == ZOO_SESSION_EVENT && zkEvent.state_ == ZOO_CONNECTED_STATE)
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
if (masterState_ == MASTER_STATE_STARTING_WAIT_ZOOKEEPER)
{
masterState_ = MASTER_STATE_STARTING;
doStart();
}
else
{
watchAll();
checkForWriteReq();
}
}
else if (zkEvent.type_ == ZOO_SESSION_EVENT && zkEvent.state_ == ZOO_EXPIRED_SESSION_STATE)
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
LOG(WARNING) << "master node disconnected by zookeeper, state : " << zookeeper_->getStateString();
LOG(WARNING) << "try reconnect: " << sf1rTopology_.curNode_.toString();
stopping_ = true;
zookeeper_->disconnect();
masterState_ = MASTER_STATE_STARTING;
if (!checkZooKeeperService())
{
masterState_ = MASTER_STATE_STARTING_WAIT_ZOOKEEPER;
LOG (ERROR) << CLASSNAME << " waiting for ZooKeeper Service...";
return;
}
doStart();
LOG (WARNING) << " restarted in MasterManagerBase for ZooKeeper Service finished";
}
}
void MasterManagerBase::onNodeCreated(const std::string& path)
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
if (stopping_)
return;
if (path.find(topologyPath_) == std::string::npos)
{
LOG(INFO) << "created path not care :" << path;
return;
}
if (masterState_ == MASTER_STATE_STARTING_WAIT_WORKERS)
{
// try detect workers
masterState_ = MASTER_STATE_STARTING;
detectWorkers();
}
else if (masterState_ == MASTER_STATE_STARTED)
{
// try recover
recover(path);
}
//else if (masterState_ == MASTER_STATE_STARTED
// && masterState_ != MASTER_STATE_FAILOVERING)
//{
// // try recover
// failover(path);
//}
}
void MasterManagerBase::onNodeDeleted(const std::string& path)
{
LOG(INFO) << "node deleted: " << path;
boost::lock_guard<boost::mutex> lock(state_mutex_);
if (stopping_)
return;
if (masterState_ == MASTER_STATE_STARTED ||
masterState_ == MASTER_STATE_STARTING_WAIT_WORKERS)
{
if (path.find(topologyPath_) != std::string::npos)
{
// try failover
failover(path);
// reset watch.
std::string sdata;
zookeeper_->getZNodeData(path, sdata, ZooKeeper::WATCH);
}
}
checkForWriteReq();
}
void MasterManagerBase::onChildrenChanged(const std::string& path)
{
LOG(INFO) << "node children changed : " << path;
boost::lock_guard<boost::mutex> lock(state_mutex_);
if (stopping_)
return;
if (masterState_ > MASTER_STATE_STARTING_WAIT_ZOOKEEPER)
{
if (path.find(topologyPath_) != std::string::npos)
{
// reset watch.
std::string sdata;
zookeeper_->getZNodeData(path, sdata, ZooKeeper::WATCH);
detectReplicaSet(path);
}
}
checkForWriteReq();
}
void MasterManagerBase::onDataChanged(const std::string& path)
{
LOG(INFO) << "node data changed : " << path;
boost::lock_guard<boost::mutex> lock(state_mutex_);
if (stopping_)
return;
if (masterState_ == MASTER_STATE_STARTING_WAIT_WORKERS)
{
if (path.find(topologyPath_) != std::string::npos)
{
// try detect workers
masterState_ = MASTER_STATE_STARTING;
detectWorkers();
}
}
// reset watch.
if (path.find(topologyPath_) != std::string::npos)
zookeeper_->isZNodeExists(path, ZooKeeper::WATCH);
checkForWriteReq();
}
bool MasterManagerBase::prepareWriteReq()
{
if (!isDistributeEnable_)
return true;
if (stopping_)
return false;
if (!zookeeper_ || !zookeeper_->isConnected())
return false;
if (!isMinePrimary())
{
LOG(WARNING) << "non-primary master can not prepare a write request!";
zookeeper_->isZNodeExists(ZooKeeperNamespace::getWriteReqPrepareNode(), ZooKeeper::WATCH);
return false;
}
if (new_write_disabled_)
{
LOG(INFO) << "prepare a write request failed for new write temporal disabled!";
return false;
}
ZNode znode;
znode.setValue(ZNode::KEY_MASTER_SERVER_REAL_PATH, serverRealPath_);
//znode.setValue(ZNode::KEY_MASTER_STATE, MASTER_STATE_WAIT_WORKER_FINISH_REQ);
if (!zookeeper_->createZNode(ZooKeeperNamespace::getWriteReqPrepareNode(), znode.serialize(), ZooKeeper::ZNODE_EPHEMERAL))
{
if (zookeeper_->getErrorCode() == ZooKeeper::ZERR_ZNODEEXISTS)
{
LOG(INFO) << "There is another write request running, prepareWriteReq failed on server: " << serverRealPath_;
}
else
{
LOG (ERROR) <<" Failed to prepare write request for (" << zookeeper_->getErrorString()
<< "), please retry. on server : " << serverRealPath_;
}
zookeeper_->isZNodeExists(ZooKeeperNamespace::getWriteReqPrepareNode(), ZooKeeper::WATCH);
return false;
}
LOG(INFO) << "prepareWriteReq success on server : " << serverRealPath_;
write_prepared_ = true;
DistributeTestSuit::testFail(PrimaryFail_At_Master_PrepareWrite);
return true;
}
bool MasterManagerBase::getWriteReqNodeData(ZNode& znode)
{
if (!zookeeper_->isZNodeExists(ZooKeeperNamespace::getWriteReqPrepareNode()))
{
LOG(INFO) << "There is no any write request";
return true;
}
std::string sdata;
if (zookeeper_->getZNodeData(ZooKeeperNamespace::getWriteReqPrepareNode(), sdata))
{
ZNode znode;
znode.loadKvString(sdata);
}
else
{
LOG(WARNING) << "get write request data failed on :" << serverRealPath_;
}
return false;
}
void MasterManagerBase::checkForWriteReq()
{
DistributeTestSuit::loadTestConf();
if (!isDistributeEnable_)
return;
if (!zookeeper_ || !zookeeper_->isConnected())
return;
if (!isMinePrimary())
{
if (!cached_write_reqlist_.empty())
{
LOG(ERROR) << "non primary master but has cached write request, these request will be ignored !!!!!! " << serverRealPath_;
cached_write_reqlist_ = std::queue<std::pair<std::string, std::string> >();
}
LOG(INFO) << "not a primary master while check write request, ignore." << serverRealPath_;
return;
}
switch(masterState_)
{
//case MASTER_STATE_WAIT_WORKER_FINISH_REQ:
// checkForWriteReqFinished();
// break;
case MASTER_STATE_STARTED:
case MASTER_STATE_STARTING_WAIT_WORKERS:
checkForNewWriteReq();
break;
default:
break;
}
}
// check if last request finished
//void MasterManagerBase::checkForWriteReqFinished()
//{
// if (masterState_ != MASTER_STATE_WAIT_WORKER_FINISH_REQ)
// {
// LOG(ERROR) << "master is not waiting worker finish request while check finish, state:" << masterState_;
// return;
// }
// if (!isAllWorkerFinished())
// {
// LOG(INFO) << "not all worker finished current request, keep waiting.";
// return;
// }
// masterState_ = MASTER_STATE_STARTED;
// // update write request state to notify all primary worker.
// ZNode znode;
// if (getWriteReqNodeData(znode))
// {
// std::string write_server = znode.getStrValue(ZNode::KEY_MASTER_SERVER_REAL_PATH);
// if (write_server != serverRealPath_)
// {
// LOG(WARNING) << "change write request state mismatch server. " << write_server << " vs " << serverRealPath_;
// return;
// }
// znode.setValue(ZNode::KEY_MASTER_STATE, masterState_);
// zookeeper_->setZNodeData(ZooKeeperNamespace::getWriteReqPrepareNode(), znode.serialize());
// LOG(INFO) << "write request state changed success on server : " << serverRealPath_;
// }
//}
bool MasterManagerBase::cacheNewWriteFromZNode()
{
std::vector<std::string> reqchild;
zookeeper_->getZNodeChildren(write_req_queue_parent_, reqchild, ZooKeeper::NOT_WATCH);
if (reqchild.empty())
{
LOG(INFO) << "no write request anymore while check request on server: " << serverRealPath_;
zookeeper_->getZNodeChildren(write_req_queue_parent_, reqchild, ZooKeeper::WATCH);
return false;
}
LOG(INFO) << "there are some write request waiting: " << reqchild.size();
size_t pop_num = reqchild.size() > 1000 ? 1000:reqchild.size();
for(size_t i = 0; i < pop_num; ++i)
{
ZNode znode;
std::string sdata;
zookeeper_->getZNodeData(reqchild[i], sdata);
znode.loadKvString(sdata);
LOG(INFO) << "a request poped : " << reqchild[i] << " on the server: " << serverRealPath_;
cached_write_reqlist_.push(std::make_pair(znode.getStrValue(ZNode::KEY_REQ_DATA),
znode.getStrValue(ZNode::KEY_REQ_TYPE)));
zookeeper_->deleteZNode(reqchild[i]);
}
return true;
}
// check if any new request can be processed.
void MasterManagerBase::checkForNewWriteReq()
{
if (masterState_ != MASTER_STATE_STARTED && masterState_ != MASTER_STATE_STARTING_WAIT_WORKERS)
{
LOG(INFO) << "current master state is not ready while check write, state:" << masterState_;
return;
}
if (write_prepared_)
{
LOG(INFO) << "a prepared write is still waiting worker ";
return;
}
if (!isAllWorkerIdle())
{
return;
}
if (!endWriteReq())
{
zookeeper_->isZNodeExists(ZooKeeperNamespace::getWriteReqPrepareNode(), ZooKeeper::WATCH);
return;
}
if (cached_write_reqlist_.empty())
{
if (!cacheNewWriteFromZNode())
return;
}
if (!cached_write_reqlist_.empty())
{
LOG(INFO) << "there are some cached write request : " << cached_write_reqlist_.size();
DistributeTestSuit::testFail(PrimaryFail_At_Master_checkForNewWrite);
if (on_new_req_available_)
{
bool ret = on_new_req_available_();
if (!ret)
{
LOG(ERROR) << "the write request handler return failed.";
write_prepared_ = false;
endWriteReq();
}
else
{
LOG(INFO) << "all new write requests have been delivered success.";
}
}
else
{
LOG(ERROR) << "the new request handler not set!!";
return;
}
}
}
// make sure prepare success before call this.
bool MasterManagerBase::popWriteReq(std::string& reqdata, std::string& type)
{
if (!isDistributeEnable_)
return false;
if (!zookeeper_ || !zookeeper_->isConnected())
return false;
if (cached_write_reqlist_.empty())
{
if (!cacheNewWriteFromZNode())
return false;
}
reqdata = cached_write_reqlist_.front().first;
type = cached_write_reqlist_.front().second;
cached_write_reqlist_.pop();
return true;
}
void MasterManagerBase::pushWriteReq(const std::string& reqdata, const std::string& type)
{
if (!isDistributeEnable_)
{
LOG(ERROR) << "Master is not configured as distributed, write request pushed failed." <<
"," << reqdata;
return;
}
if (stopping_)
{
LOG(ERROR) << "Master is stopping, write request pushed failed." <<
"," << reqdata;
return;
}
// boost::lock_guard<boost::mutex> lock(state_mutex_);
if (!zookeeper_ || !zookeeper_->isConnected())
{
LOG(ERROR) << "Master is not connecting to ZooKeeper, write request pushed failed." <<
"," << reqdata;
return;
}
ZNode znode;
//znode.setValue(ZNode::KEY_REQ_CONTROLLER, controller_name);
znode.setValue(ZNode::KEY_REQ_TYPE, type);
znode.setValue(ZNode::KEY_REQ_DATA, reqdata);
if(zookeeper_->createZNode(write_req_queue_, znode.serialize(), ZooKeeper::ZNODE_SEQUENCE))
{
LOG(INFO) << "a write request pushed to the queue : " << zookeeper_->getLastCreatedNodePath();
}
else
{
LOG(ERROR) << "write request pushed failed." <<
"," << reqdata;
}
}
bool MasterManagerBase::disableNewWrite()
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
if (write_prepared_)
{
LOG(INFO) << "disable write failed for already prepared : ";
return false;
}
new_write_disabled_ = true;
return true;
}
void MasterManagerBase::enableNewWrite()
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
new_write_disabled_ = false;
}
void MasterManagerBase::endPreparedWrite()
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
write_prepared_ = false;
}
bool MasterManagerBase::endWriteReq()
{
if (!isMinePrimary())
{
LOG(INFO) << "non-primary master can not end a write request.";
return false;
}
if (!zookeeper_->isZNodeExists(ZooKeeperNamespace::getWriteReqPrepareNode()))
{
LOG(INFO) << "There is no any write request while end request";
return true;
}
std::string sdata;
if (zookeeper_->getZNodeData(ZooKeeperNamespace::getWriteReqPrepareNode(), sdata))
{
ZNode znode;
znode.loadKvString(sdata);
std::string write_server = znode.getStrValue(ZNode::KEY_MASTER_SERVER_REAL_PATH);
if (write_server != serverRealPath_)
{
LOG(WARNING) << "end request mismatch server. " << write_server << " vs " << serverRealPath_;
return false;
}
zookeeper_->deleteZNode(ZooKeeperNamespace::getWriteReqPrepareNode());
LOG(INFO) << "end write request success on server : " << serverRealPath_;
}
else
{
LOG(WARNING) << "get write request data failed while end request on server :" << serverRealPath_;
return false;
}
return true;
}
//bool MasterManagerBase::isAllWorkerFinished()
//{
// if (!isAllWorkerInState(NodeManagerBase::NODE_STATE_WAIT_MASTER_FINISH_REQ))
// {
// LOG(INFO) << "one of primary worker not finish write request : ";
// return false;
// }
// return true;
//}
bool MasterManagerBase::isAllWorkerIdle()
{
if (!isAllWorkerInState(NodeManagerBase::NODE_STATE_STARTED))
{
LOG(INFO) << "one of primary worker not ready for new write request.";
return false;
}
return true;
}
bool MasterManagerBase::isAllWorkerInState(int state)
{
WorkerMapT::iterator it;
for (it = workerMap_.begin(); it != workerMap_.end(); it++)
{
std::string nodepath = getNodePath(it->second->replicaId_, it->first);
std::string sdata;
if (zookeeper_->getZNodeData(nodepath, sdata, ZooKeeper::WATCH))
{
ZNode nodedata;
nodedata.loadKvString(sdata);
if (nodedata.getUInt32Value(ZNode::KEY_NODE_STATE) != (uint32_t)state)
{
return false;
}
}
}
return true;
}
bool MasterManagerBase::isBusy()
{
if (!isDistributeEnable_)
return false;
boost::lock_guard<boost::mutex> lock(state_mutex_);
if (stopping_ || !zookeeper_ || !zookeeper_->isConnected())
return true;
if (zookeeper_->isZNodeExists(ZooKeeperNamespace::getWriteReqPrepareNode()))
{
LOG(INFO) << "Master is busy because there is another write request running";
return true;
}
return !isAllWorkerIdle();
}
void MasterManagerBase::showWorkers()
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
WorkerMapT::iterator it;
for (it = workerMap_.begin(); it != workerMap_.end(); it++)
{
cout << it->second->toString() ;
}
}
/// protected ////////////////////////////////////////////////////////////////////
std::string MasterManagerBase::state2string(MasterStateType e)
{
std::stringstream ss;
switch (e)
{
case MASTER_STATE_INIT:
return "MASTER_STATE_INIT";
break;
case MASTER_STATE_STARTING:
return "MASTER_STATE_STARTING";
break;
case MASTER_STATE_STARTING_WAIT_ZOOKEEPER:
return "MASTER_STATE_STARTING_WAIT_ZOOKEEPER";
break;
case MASTER_STATE_STARTING_WAIT_WORKERS:
return "MASTER_STATE_STARTING_WAIT_WORKERS";
break;
case MASTER_STATE_STARTED:
return "MASTER_STATE_STARTED";
break;
//case MASTER_STATE_FAILOVERING:
// return "MASTER_STATE_FAILOVERING";
// break;
//case MASTER_STATE_RECOVERING:
// return "MASTER_STATE_RECOVERING";
// break;
}
return "UNKNOWN";
}
void MasterManagerBase::watchAll()
{
// for replica change
std::vector<std::string> childrenList;
zookeeper_->getZNodeChildren(topologyPath_, childrenList, ZooKeeper::WATCH);
for (size_t i = 0; i < childrenList.size(); i++)
{
std::vector<std::string> chchList;
zookeeper_->getZNodeChildren(childrenList[i], chchList, ZooKeeper::WATCH);
}
// for nodes change
for (uint32_t nodeid = 1; nodeid <= sf1rTopology_.nodeNum_; nodeid++)
{
std::string nodePath = getNodePath(sf1rTopology_.curNode_.replicaId_, nodeid);
zookeeper_->isZNodeExists(nodePath, ZooKeeper::WATCH);
}
}
bool MasterManagerBase::checkZooKeeperService()
{
if (!zookeeper_->isConnected())
{
zookeeper_->connect(true);
if (!zookeeper_->isConnected())
{
return false;
}
}
return true;
}
void MasterManagerBase::doStart()
{
stopping_ = false;
detectReplicaSet();
detectWorkers();
// Each Master serves as a Search Server, register it without waiting for all workers to be ready.
registerServiceServer();
}
int MasterManagerBase::detectWorkersInReplica(replicaid_t replicaId, size_t& detected, size_t& good)
{
bool mine_primary = isMinePrimary();
if (mine_primary)
LOG(INFO) << "I am primary master ";
for (uint32_t nodeid = 1; nodeid <= sf1rTopology_.nodeNum_; nodeid++)
{
std::string data;
std::string nodePath = getNodePath(replicaId, nodeid);
if (zookeeper_->getZNodeData(nodePath, data, ZooKeeper::WATCH))
{
ZNode znode;
znode.loadKvString(data);
// if this sf1r node provides worker server
if (znode.hasKey(ZNode::KEY_WORKER_PORT))
{
if (mine_primary)
{
if(!isPrimaryWorker(replicaId, nodeid))
{
LOG(INFO) << "primary master need detect primary worker, ignore non-primary worker";
LOG (INFO) << "node " << nodeid << ", replica: " << replicaId;
continue;
}
}
if (nodeid > 0 && nodeid <= sf1rTopology_.nodeNum_)
{
if (workerMap_.find(nodeid) != workerMap_.end())
{
if (workerMap_[nodeid]->worker_.isGood_)
continue;
workerMap_[nodeid]->worker_.isGood_ = true;
}
else
{
// insert new worker
boost::shared_ptr<Sf1rNode> sf1rNode(new Sf1rNode);
sf1rNode->worker_.isGood_ = true;
workerMap_[nodeid] = sf1rNode;
}
// update worker info
boost::shared_ptr<Sf1rNode>& workerNode = workerMap_[nodeid];
workerNode->nodeId_ = nodeid;
updateWorkerNode(workerNode, znode);
detected ++;
if (workerNode->worker_.isGood_)
{
good ++;
}
}
else
{
std::stringstream ss;
ss << "in node[" << nodeid << "] @ " << znode.getStrValue(ZNode::KEY_HOST)
<< " is out of range for current master (max is " << sf1rTopology_.nodeNum_ << ")";
LOG (WARNING) << ss.str();
throw std::runtime_error(ss.str());
}
}
}
else
{
// reset watcher
zookeeper_->isZNodeExists(nodePath, ZooKeeper::WATCH);
}
}
if (detected >= sf1rTopology_.nodeNum_)
{
masterState_ = MASTER_STATE_STARTED;
LOG (INFO) << CLASSNAME << " detected " << sf1rTopology_.nodeNum_
<< " all workers (good " << good << ")" << std::endl;
}
else
{
masterState_ = MASTER_STATE_STARTING_WAIT_WORKERS;
LOG (INFO) << CLASSNAME << " detected " << detected << " workers (good " << good
<< "), all " << sf1rTopology_.nodeNum_ << std::endl;
}
return good;
}
int MasterManagerBase::detectWorkers()
{
size_t detected = 0;
size_t good = 0;
workerMap_.clear();
// detect workers from "current" replica first
replicaid_t replicaId = sf1rTopology_.curNode_.replicaId_;
detectWorkersInReplica(replicaId, detected, good);
for (size_t i = 0; i < replicaIdList_.size(); i++)
{
if (masterState_ != MASTER_STATE_STARTING_WAIT_WORKERS)
{
LOG(INFO) << "detected worker enough, stop detect other replica.";
break;
}
if (replicaId == replicaIdList_[i])
continue;
// not enough, check other replica
LOG(INFO) << "begin detect workers in other replica : " << replicaIdList_[i];
detectWorkersInReplica(replicaIdList_[i], detected, good);
}
//
// update workers' info to aggregators
resetAggregatorConfig();
return good;
}
void MasterManagerBase::updateWorkerNode(boost::shared_ptr<Sf1rNode>& workerNode, ZNode& znode)
{
workerNode->replicaId_ = sf1rTopology_.curNode_.replicaId_;
workerNode->host_ = znode.getStrValue(ZNode::KEY_HOST);
//workerNode->port_ = znode.getUInt32Value(ZNode::KEY_WORKER_PORT);
try
{
workerNode->worker_.port_ =
boost::lexical_cast<port_t>(znode.getStrValue(ZNode::KEY_WORKER_PORT));
}
catch (std::exception& e)
{
workerNode->worker_.isGood_ = false;
LOG (ERROR) << "failed to convert workerPort \"" << znode.getStrValue(ZNode::KEY_WORKER_PORT)
<< "\" got from worker on node " << workerNode->nodeId_
<< " @" << workerNode->host_;
}
try
{
workerNode->dataPort_ =
boost::lexical_cast<port_t>(znode.getStrValue(ZNode::KEY_DATA_PORT));
}
catch (std::exception& e)
{
workerNode->worker_.isGood_ = false;
LOG (ERROR) << "failed to convert dataPort \"" << znode.getStrValue(ZNode::KEY_DATA_PORT)
<< "\" got from worker on node " << workerNode->nodeId_
<< " @" << workerNode->host_;
}
LOG (INFO) << CLASSNAME << " detected worker on (node" << workerNode->nodeId_ <<") "
<< workerNode->host_ << ":" << workerNode->worker_.port_ << std::endl;
}
void MasterManagerBase::detectReplicaSet(const std::string& zpath)
{
// find replications
std::vector<std::string> childrenList;
zookeeper_->getZNodeChildren(topologyPath_, childrenList, ZooKeeper::WATCH);
replicaIdList_.clear();
for (size_t i = 0; i < childrenList.size(); i++)
{
std::string sreplicaId;
zookeeper_->getZNodeData(childrenList[i], sreplicaId);
try
{
replicaIdList_.push_back(boost::lexical_cast<replicaid_t>(sreplicaId));
LOG (INFO) << " detected replica id \"" << sreplicaId
<< "\" for " << childrenList[i];
}
catch (std::exception& e) {
LOG (ERROR) << CLASSNAME << " failed to parse replica id \"" << sreplicaId
<< "\" for " << childrenList[i];
}
// watch for nodes change
std::vector<std::string> chchList;
zookeeper_->getZNodeChildren(childrenList[i], chchList, ZooKeeper::WATCH);
zookeeper_->isZNodeExists(childrenList[i], ZooKeeper::WATCH);
}
// try to detect workers again while waiting for some of the workers
if (masterState_ == MASTER_STATE_STARTING_WAIT_WORKERS)
{
detectWorkers();
}
WorkerMapT::iterator it;
for (it = workerMap_.begin(); it != workerMap_.end(); it++)
{
boost::shared_ptr<Sf1rNode>& sf1rNode = it->second;
if (!sf1rNode->worker_.isGood_)
{
// try failover
if (!failover(sf1rNode))
{
LOG(WARNING) << "one of worker failed and can not cover this failure.";
masterState_ = MASTER_STATE_STARTING_WAIT_WORKERS;
}
}
}
}
void MasterManagerBase::failover(const std::string& zpath)
{
// check path
WorkerMapT::iterator it;
for (it = workerMap_.begin(); it != workerMap_.end(); it++)
{
boost::shared_ptr<Sf1rNode>& sf1rNode = it->second;
std::string nodePath = getNodePath(sf1rNode->replicaId_, sf1rNode->nodeId_);
if (zpath == nodePath)
{
LOG (WARNING) << "[node " << sf1rNode->nodeId_ << "]@" << sf1rNode->host_ << " was broken down, in "
<< "[replica " << sf1rNode->replicaId_ << "]";
if (failover(sf1rNode))
{
LOG (INFO) << "failover: finished.";
return;
}
else
{
LOG (INFO) << "failover: failed to cover this failure.";
masterState_ = MASTER_STATE_STARTING_WAIT_WORKERS;
return;
}
}
}
}
bool MasterManagerBase::failover(boost::shared_ptr<Sf1rNode>& sf1rNode)
{
sf1rNode->worker_.isGood_ = false;
bool mine_primary = isMinePrimary();
if (mine_primary)
LOG(INFO) << "I am primary master ";
for (size_t i = 0; i < replicaIdList_.size(); i++)
{
if (replicaIdList_[i] != sf1rNode->replicaId_)
{
// try to switch to replicaIdList_[i]
ZNode znode;
std::string sdata;
std::string nodePath = getNodePath(replicaIdList_[i], sf1rNode->nodeId_);
// get node data
if (zookeeper_->getZNodeData(nodePath, sdata, ZooKeeper::WATCH))
{
if (mine_primary)
{
if(!isPrimaryWorker(replicaIdList_[i], sf1rNode->nodeId_))
{
LOG(INFO) << "primary master need failover to primary worker, ignore non-primary worker";
LOG (INFO) << "node " << sf1rNode->nodeId_ << " ,replica: " << replicaIdList_[i];
continue;
}
}
znode.loadKvString(sdata);
if (znode.hasKey(ZNode::KEY_WORKER_PORT))
{
LOG (INFO) << "switching node " << sf1rNode->nodeId_ << " from replica " << sf1rNode->replicaId_
<<" to " << replicaIdList_[i];
sf1rNode->replicaId_ = replicaIdList_[i]; // new replica
sf1rNode->host_ = znode.getStrValue(ZNode::KEY_HOST);
try
{
sf1rNode->worker_.port_ =
boost::lexical_cast<port_t>(znode.getStrValue(ZNode::KEY_WORKER_PORT));
}
catch (std::exception& e)
{
LOG (ERROR) << "failed to convert workerPort \"" << znode.getStrValue(ZNode::KEY_WORKER_PORT)
<< "\" got from node " << sf1rNode->nodeId_ << " at " << znode.getStrValue(ZNode::KEY_HOST)
<< ", in replica " << replicaIdList_[i];
continue;
}
// succeed to failover
sf1rNode->worker_.isGood_ = true;
break;
}
else
{
LOG (ERROR) << "[Replica " << replicaIdList_[i] << "] [Node " << sf1rNode->nodeId_
<< "] did not enable worker server, this happened because of the mismatch configuration.";
LOG (ERROR) << "In the same cluster, the sf1r node with the same nodeid must have the same configuration.";
throw std::runtime_error("error configuration : mismatch with the same nodeid.");
}
}
}
}
// notify aggregators
resetAggregatorConfig();
// Watch current replica, waiting for node recover
zookeeper_->isZNodeExists(getNodePath(sf1rNode->replicaId_, sf1rNode->nodeId_), ZooKeeper::WATCH);
return sf1rNode->worker_.isGood_;
}
void MasterManagerBase::recover(const std::string& zpath)
{
WorkerMapT::iterator it;
bool mine_primary = isMinePrimary();
if (mine_primary)
LOG(INFO) << "I am primary master ";
for (it = workerMap_.begin(); it != workerMap_.end(); it++)
{
boost::shared_ptr<Sf1rNode>& sf1rNode = it->second;
if (zpath == getNodePath(sf1rTopology_.curNode_.replicaId_, sf1rNode->nodeId_))
{
if (mine_primary)
{
if(!isPrimaryWorker(sf1rTopology_.curNode_.replicaId_, sf1rNode->nodeId_))
{
LOG(INFO) << "primary master need recover to primary worker, ignore non-primary worker";
LOG (INFO) << "node " << sf1rNode->nodeId_ << " ,replica: " << sf1rTopology_.curNode_.replicaId_;
continue;
}
}
LOG (INFO) << "recover: node " << sf1rNode->nodeId_
<< " recovered in current replica " << sf1rTopology_.curNode_.replicaId_;
ZNode znode;
std::string sdata;
if (zookeeper_->getZNodeData(zpath, sdata, ZooKeeper::WATCH))
{
// try to recover
znode.loadKvString(sdata);
try
{
sf1rNode->worker_.port_ =
boost::lexical_cast<port_t>(znode.getStrValue(ZNode::KEY_WORKER_PORT));
}
catch (std::exception& e)
{
LOG (ERROR) << "failed to convert workerPort \"" << znode.getStrValue(ZNode::KEY_WORKER_PORT)
<< "\" got from node " << sf1rNode->nodeId_ << " at " << znode.getStrValue(ZNode::KEY_HOST)
<< ", in replica " << sf1rTopology_.curNode_.replicaId_;
continue;
}
sf1rNode->replicaId_ = sf1rTopology_.curNode_.replicaId_; // new replica
sf1rNode->host_ = znode.getStrValue(ZNode::KEY_HOST);
// recovered, and notify aggregators
sf1rNode->worker_.isGood_ = true;
break;
}
}
}
resetAggregatorConfig();
}
void MasterManagerBase::setServicesData(ZNode& znode)
{
// write service name to server node.
std::string services;
ServiceMapT::const_iterator cit = all_distributed_services_.begin();
while(cit != all_distributed_services_.end())
{
if (services.empty())
services = cit->first;
else
services += "," + cit->first;
std::string collections;
std::vector<MasterCollection>& collectionList = sf1rTopology_.curNode_.master_.masterServices_[cit->first].collectionList_;
for (std::vector<MasterCollection>::iterator it = collectionList.begin();
it != collectionList.end(); it++)
{
if (collections.empty())
collections = (*it).name_;
else
collections += "," + (*it).name_;
}
znode.setValue(cit->first + ZNode::KEY_COLLECTION, collections);
++cit;
}
znode.setValue(ZNode::KEY_SERVICE_NAMES, services);
}
void MasterManagerBase::initServices()
{
}
bool MasterManagerBase::isServiceReadyForRead(bool include_self)
{
// service is ready for read means all shard workers current master connected are ready for read.
boost::lock_guard<boost::mutex> lock(state_mutex_);
WorkerMapT::const_iterator it = workerMap_.begin();
for ( ; it != workerMap_.end(); ++it)
{
if (it->second->nodeId_ == sf1rTopology_.curNode_.nodeId_)
{
if (!include_self)
continue;
}
std::string nodepath = getNodePath(it->second->replicaId_, it->second->nodeId_);
std::string sdata;
if (zookeeper_->getZNodeData(nodepath, sdata, ZooKeeper::WATCH))
{
ZNode znode;
znode.loadKvString(sdata);
std::string value = znode.getStrValue(ZNode::KEY_SERVICE_STATE);
if (value != "ReadyForRead" && value != "BusyForShard")
{
LOG(INFO) << "one shard of master service is not ready for read:" << nodepath;
return false;
}
}
}
return true;
}
void MasterManagerBase::registerDistributeServiceMaster(boost::shared_ptr<IDistributeService> sp_service, bool enable_master)
{
if (enable_master)
{
if (all_distributed_services_.find(sp_service->getServiceName()) !=
all_distributed_services_.end() )
{
LOG(WARNING) << "duplicate service name!!!!!!!";
throw std::runtime_error("duplicate service!");
}
LOG(INFO) << "registering service master: " << sp_service->getServiceName();
all_distributed_services_[sp_service->getServiceName()] = sp_service;
}
}
bool MasterManagerBase::findServiceMasterAddress(const std::string& service, std::string& host, uint32_t& port)
{
if (!zookeeper_ || !zookeeper_->isConnected())
return false;
std::vector<std::string> children;
zookeeper_->getZNodeChildren(serverParentPath_, children);
for (size_t i = 0; i < children.size(); ++i)
{
std::string serviceMasterPath = children[i];
std::string data;
if (zookeeper_->getZNodeData(serviceMasterPath, data))
{
ZNode znode;
znode.loadKvString(data);
std::string service_names = znode.getStrValue(ZNode::KEY_SERVICE_NAMES);
if (service_names.find(service) == std::string::npos)
continue;
LOG(INFO) << "find service master address success : " << service << ", on server :" << serviceMasterPath;
host = znode.getStrValue(ZNode::KEY_HOST);
port = znode.getUInt32Value(ZNode::KEY_MASTER_PORT);
return true;
}
}
return false;
}
void MasterManagerBase::registerServiceServer()
{
// Master server provide search service
if (!zookeeper_->isZNodeExists(serverParentPath_))
{
zookeeper_->createZNode(serverParentPath_);
}
initServices();
ZNode znode;
znode.setValue(ZNode::KEY_HOST, sf1rTopology_.curNode_.host_);
znode.setValue(ZNode::KEY_BA_PORT, sf1rTopology_.curNode_.baPort_);
znode.setValue(ZNode::KEY_MASTER_PORT, SuperNodeManager::get()->getMasterPort());
setServicesData(znode);
if (zookeeper_->createZNode(serverPath_, znode.serialize(), ZooKeeper::ZNODE_EPHEMERAL_SEQUENCE))
{
serverRealPath_ = zookeeper_->getLastCreatedNodePath();
}
if (!zookeeper_->isZNodeExists(write_req_queue_root_parent_, ZooKeeper::WATCH))
{
zookeeper_->createZNode(write_req_queue_root_parent_);
}
if (!zookeeper_->isZNodeExists(write_req_queue_parent_, ZooKeeper::WATCH))
{
zookeeper_->createZNode(write_req_queue_parent_);
}
std::vector<string> reqchild;
zookeeper_->getZNodeChildren(write_req_queue_parent_, reqchild, ZooKeeper::WATCH);
}
void MasterManagerBase::resetAggregatorConfig()
{
std::vector<boost::shared_ptr<AggregatorBase> >::iterator agg_it;
for (agg_it = aggregatorList_.begin(); agg_it != aggregatorList_.end(); agg_it++)
{
boost::shared_ptr<AggregatorBase>& aggregator = *agg_it;
// get shardids for collection of aggregator
std::vector<shardid_t> shardidList;
if (!sf1rTopology_.curNode_.master_.getShardidList(aggregator->service(),
aggregator->collection(), shardidList))
{
continue;
}
// set workers for aggregator
AggregatorConfig aggregatorConfig;
for (size_t i = 0; i < shardidList.size(); i++)
{
WorkerMapT::iterator it = workerMap_.find(shardidList[i]);
if (it != workerMap_.end())
{
if(!it->second->worker_.isGood_)
{
LOG(INFO) << "worker_ : " << it->second->nodeId_ << " is not good, so do not added to aggregator.";
continue;
}
bool isLocal = (it->second->nodeId_ == sf1rTopology_.curNode_.nodeId_);
aggregatorConfig.addWorker(it->second->host_, it->second->worker_.port_, shardidList[i], isLocal);
}
else
{
LOG (ERROR) << "worker " << shardidList[i] << " was not found for Aggregator of "
<< aggregator->collection() << " in service " << aggregator->service();
}
}
//std::cout << aggregator->collection() << ":" << std::endl << aggregatorConfig.toString();
aggregator->setAggregatorConfig(aggregatorConfig);
}
}
bool MasterManagerBase::isPrimaryWorker(replicaid_t replicaId, nodeid_t nodeId)
{
std::string nodepath = getNodePath(replicaId, nodeId);
std::string sdata;
if (zookeeper_->getZNodeData(nodepath, sdata, ZooKeeper::WATCH))
{
ZNode znode;
znode.loadKvString(sdata);
std::string self_reg_primary = znode.getStrValue(ZNode::KEY_SELF_REG_PRIMARY_PATH);
std::vector<std::string> node_list;
zookeeper_->getZNodeChildren(getPrimaryNodeParentPath(nodeId), node_list);
if (node_list.empty())
{
LOG(INFO) << "no any primary node for node id: " << nodeId;
return false;
}
return self_reg_primary == node_list[0];
}
else
return false;
}
bool MasterManagerBase::isMinePrimary()
{
if(!isDistributeEnable_)
return true;
if (!zookeeper_ || !zookeeper_->isConnected())
return false;
return isPrimaryWorker(sf1rTopology_.curNode_.replicaId_, sf1rTopology_.curNode_.nodeId_);
}
tiny fix
#include "MasterManagerBase.h"
#include "SuperNodeManager.h"
#include "NodeManagerBase.h"
#include "ZooKeeperNamespace.h"
#include "DistributeTest.hpp"
#include <boost/lexical_cast.hpp>
using namespace sf1r;
// note lock:
// you should never sync call the interface which may hold a lock in the NodeManagerBase .
//
MasterManagerBase::MasterManagerBase()
: isDistributeEnable_(false)
, masterState_(MASTER_STATE_INIT)
, stopping_(false)
, write_prepared_(false)
, new_write_disabled_(false)
, CLASSNAME("MasterManagerBase")
{
}
bool MasterManagerBase::init()
{
// initialize zookeeper client
topologyPath_ = ZooKeeperNamespace::getTopologyPath();
serverParentPath_ = ZooKeeperNamespace::getServerParentPath();
serverPath_ = ZooKeeperNamespace::getServerPath();
zookeeper_ = ZooKeeperManager::get()->createClient(this);
if (!zookeeper_)
return false;
sf1rTopology_ = NodeManagerBase::get()->getSf1rTopology();
write_req_queue_ = ZooKeeperNamespace::getWriteReqQueueNode(sf1rTopology_.curNode_.nodeId_);
write_req_queue_parent_ = ZooKeeperNamespace::getCurrWriteReqQueueParent(sf1rTopology_.curNode_.nodeId_);
write_req_queue_root_parent_ = ZooKeeperNamespace::getRootWriteReqQueueParent();
stopping_ = false;
return true;
}
void MasterManagerBase::start()
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
stopping_ = false;
if (masterState_ == MASTER_STATE_INIT)
{
masterState_ = MASTER_STATE_STARTING;
if (!init())
{
throw std::runtime_error(std::string("failed to initialize ") + CLASSNAME);
}
if (!checkZooKeeperService())
{
masterState_ = MASTER_STATE_STARTING_WAIT_ZOOKEEPER;
LOG (ERROR) << CLASSNAME << " waiting for ZooKeeper Service...";
return;
}
doStart();
}
// call init for all service.
ServiceMapT::const_iterator cit = all_distributed_services_.begin();
while(cit != all_distributed_services_.end())
{
cit->second->initMaster();
++cit;
}
}
void MasterManagerBase::stop()
{
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
stopping_ = true;
}
if (zookeeper_ && zookeeper_->isConnected())
{
std::vector<std::string> childrenList;
zookeeper_->deleteZNode(serverRealPath_);
zookeeper_->getZNodeChildren(serverParentPath_, childrenList, ZooKeeper::NOT_WATCH, false);
if (childrenList.size() == 0)
{
zookeeper_->deleteZNode(serverParentPath_);
}
childrenList.clear();
zookeeper_->isZNodeExists(write_req_queue_parent_, ZooKeeper::NOT_WATCH);
zookeeper_->isZNodeExists(write_req_queue_root_parent_, ZooKeeper::NOT_WATCH);
// disconnect will wait other ZooKeeper event finished,
// so we can not do it in state_mutex_ lock.
zookeeper_->disconnect();
}
boost::lock_guard<boost::mutex> lock(state_mutex_);
masterState_ = MASTER_STATE_INIT;
}
bool MasterManagerBase::getShardReceiver(
unsigned int shardid,
std::string& host,
unsigned int& recvPort)
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
WorkerMapT::iterator it = workerMap_.find(shardid);
if (it != workerMap_.end())
{
host = it->second->host_;
recvPort = it->second->dataPort_;
return true;
}
else
{
return false;
}
}
bool MasterManagerBase::getCollectionShardids(const std::string& service, const std::string& collection, std::vector<shardid_t>& shardidList)
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
return sf1rTopology_.curNode_.master_.getShardidList(service, collection, shardidList);
}
bool MasterManagerBase::checkCollectionShardid(const std::string& service, const std::string& collection, unsigned int shardid)
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
return sf1rTopology_.curNode_.master_.checkCollectionWorker(service, collection, shardid);
}
void MasterManagerBase::registerIndexStatus(const std::string& collection, bool isIndexing)
{
std::string indexStatus = isIndexing ? "indexing" : "notindexing";
std::string data;
if (zookeeper_ && zookeeper_->getZNodeData(serverRealPath_, data))
{
ZNode znode;
znode.loadKvString(data);
znode.setValue(collection, indexStatus);
}
std::string nodePath = getNodePath(sf1rTopology_.curNode_.replicaId_, sf1rTopology_.curNode_.nodeId_);
if (zookeeper_ && zookeeper_->getZNodeData(nodePath, data, ZooKeeper::WATCH))
{
ZNode znode;
znode.loadKvString(data);
znode.setValue(collection, indexStatus);
}
}
void MasterManagerBase::process(ZooKeeperEvent& zkEvent)
{
LOG(INFO) << CLASSNAME << ", "<< state2string(masterState_) <<", "<<zkEvent.toString();
if (stopping_)
return;
if (zkEvent.type_ == ZOO_SESSION_EVENT && zkEvent.state_ == ZOO_CONNECTED_STATE)
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
if (masterState_ == MASTER_STATE_STARTING_WAIT_ZOOKEEPER)
{
masterState_ = MASTER_STATE_STARTING;
doStart();
}
else
{
watchAll();
checkForWriteReq();
}
}
else if (zkEvent.type_ == ZOO_SESSION_EVENT && zkEvent.state_ == ZOO_EXPIRED_SESSION_STATE)
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
LOG(WARNING) << "master node disconnected by zookeeper, state : " << zookeeper_->getStateString();
LOG(WARNING) << "try reconnect: " << sf1rTopology_.curNode_.toString();
stopping_ = true;
zookeeper_->disconnect();
masterState_ = MASTER_STATE_STARTING;
if (!checkZooKeeperService())
{
masterState_ = MASTER_STATE_STARTING_WAIT_ZOOKEEPER;
LOG (ERROR) << CLASSNAME << " waiting for ZooKeeper Service...";
return;
}
doStart();
LOG (WARNING) << " restarted in MasterManagerBase for ZooKeeper Service finished";
}
}
void MasterManagerBase::onNodeCreated(const std::string& path)
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
if (stopping_)
return;
if (path.find(topologyPath_) == std::string::npos)
{
LOG(INFO) << "created path not care :" << path;
return;
}
if (masterState_ == MASTER_STATE_STARTING_WAIT_WORKERS)
{
// try detect workers
masterState_ = MASTER_STATE_STARTING;
detectWorkers();
}
else if (masterState_ == MASTER_STATE_STARTED)
{
// try recover
recover(path);
}
//else if (masterState_ == MASTER_STATE_STARTED
// && masterState_ != MASTER_STATE_FAILOVERING)
//{
// // try recover
// failover(path);
//}
}
void MasterManagerBase::onNodeDeleted(const std::string& path)
{
LOG(INFO) << "node deleted: " << path;
boost::lock_guard<boost::mutex> lock(state_mutex_);
if (stopping_)
return;
if (masterState_ == MASTER_STATE_STARTED ||
masterState_ == MASTER_STATE_STARTING_WAIT_WORKERS)
{
if (path.find(topologyPath_) != std::string::npos)
{
// try failover
failover(path);
// reset watch.
std::string sdata;
zookeeper_->getZNodeData(path, sdata, ZooKeeper::WATCH);
}
}
checkForWriteReq();
}
void MasterManagerBase::onChildrenChanged(const std::string& path)
{
LOG(INFO) << "node children changed : " << path;
boost::lock_guard<boost::mutex> lock(state_mutex_);
if (stopping_)
return;
if (masterState_ > MASTER_STATE_STARTING_WAIT_ZOOKEEPER)
{
if (path.find(topologyPath_) != std::string::npos)
{
// reset watch.
std::string sdata;
zookeeper_->getZNodeData(path, sdata, ZooKeeper::WATCH);
detectReplicaSet(path);
}
}
checkForWriteReq();
}
void MasterManagerBase::onDataChanged(const std::string& path)
{
LOG(INFO) << "node data changed : " << path;
boost::lock_guard<boost::mutex> lock(state_mutex_);
if (stopping_)
return;
if (masterState_ == MASTER_STATE_STARTING_WAIT_WORKERS)
{
if (path.find(topologyPath_) != std::string::npos)
{
// try detect workers
masterState_ = MASTER_STATE_STARTING;
detectWorkers();
}
}
// reset watch.
if (path.find(topologyPath_) != std::string::npos)
zookeeper_->isZNodeExists(path, ZooKeeper::WATCH);
checkForWriteReq();
}
bool MasterManagerBase::prepareWriteReq()
{
if (!isDistributeEnable_)
return true;
if (stopping_)
return false;
if (!zookeeper_ || !zookeeper_->isConnected())
return false;
if (!isMinePrimary())
{
LOG(WARNING) << "non-primary master can not prepare a write request!";
zookeeper_->isZNodeExists(ZooKeeperNamespace::getWriteReqPrepareNode(), ZooKeeper::WATCH);
return false;
}
if (new_write_disabled_)
{
LOG(INFO) << "prepare a write request failed for new write temporal disabled!";
return false;
}
ZNode znode;
znode.setValue(ZNode::KEY_MASTER_SERVER_REAL_PATH, serverRealPath_);
//znode.setValue(ZNode::KEY_MASTER_STATE, MASTER_STATE_WAIT_WORKER_FINISH_REQ);
if (!zookeeper_->createZNode(ZooKeeperNamespace::getWriteReqPrepareNode(), znode.serialize(), ZooKeeper::ZNODE_EPHEMERAL))
{
if (zookeeper_->getErrorCode() == ZooKeeper::ZERR_ZNODEEXISTS)
{
LOG(INFO) << "There is another write request running, prepareWriteReq failed on server: " << serverRealPath_;
}
else
{
LOG (ERROR) <<" Failed to prepare write request for (" << zookeeper_->getErrorString()
<< "), please retry. on server : " << serverRealPath_;
}
zookeeper_->isZNodeExists(ZooKeeperNamespace::getWriteReqPrepareNode(), ZooKeeper::WATCH);
return false;
}
LOG(INFO) << "prepareWriteReq success on server : " << serverRealPath_;
write_prepared_ = true;
DistributeTestSuit::testFail(PrimaryFail_At_Master_PrepareWrite);
return true;
}
bool MasterManagerBase::getWriteReqNodeData(ZNode& znode)
{
if (!zookeeper_->isZNodeExists(ZooKeeperNamespace::getWriteReqPrepareNode()))
{
LOG(INFO) << "There is no any write request";
return true;
}
std::string sdata;
if (zookeeper_->getZNodeData(ZooKeeperNamespace::getWriteReqPrepareNode(), sdata))
{
ZNode znode;
znode.loadKvString(sdata);
}
else
{
LOG(WARNING) << "get write request data failed on :" << serverRealPath_;
}
return false;
}
void MasterManagerBase::checkForWriteReq()
{
DistributeTestSuit::loadTestConf();
if (!isDistributeEnable_)
return;
if (!zookeeper_ || !zookeeper_->isConnected())
return;
if (!isMinePrimary())
{
if (!cached_write_reqlist_.empty())
{
LOG(ERROR) << "non primary master but has cached write request, these request will be ignored !!!!!! " << serverRealPath_;
cached_write_reqlist_ = std::queue<std::pair<std::string, std::string> >();
}
LOG(INFO) << "not a primary master while check write request, ignore." << serverRealPath_;
return;
}
switch(masterState_)
{
//case MASTER_STATE_WAIT_WORKER_FINISH_REQ:
// checkForWriteReqFinished();
// break;
case MASTER_STATE_STARTED:
case MASTER_STATE_STARTING_WAIT_WORKERS:
checkForNewWriteReq();
break;
default:
break;
}
}
// check if last request finished
//void MasterManagerBase::checkForWriteReqFinished()
//{
// if (masterState_ != MASTER_STATE_WAIT_WORKER_FINISH_REQ)
// {
// LOG(ERROR) << "master is not waiting worker finish request while check finish, state:" << masterState_;
// return;
// }
// if (!isAllWorkerFinished())
// {
// LOG(INFO) << "not all worker finished current request, keep waiting.";
// return;
// }
// masterState_ = MASTER_STATE_STARTED;
// // update write request state to notify all primary worker.
// ZNode znode;
// if (getWriteReqNodeData(znode))
// {
// std::string write_server = znode.getStrValue(ZNode::KEY_MASTER_SERVER_REAL_PATH);
// if (write_server != serverRealPath_)
// {
// LOG(WARNING) << "change write request state mismatch server. " << write_server << " vs " << serverRealPath_;
// return;
// }
// znode.setValue(ZNode::KEY_MASTER_STATE, masterState_);
// zookeeper_->setZNodeData(ZooKeeperNamespace::getWriteReqPrepareNode(), znode.serialize());
// LOG(INFO) << "write request state changed success on server : " << serverRealPath_;
// }
//}
bool MasterManagerBase::cacheNewWriteFromZNode()
{
std::vector<std::string> reqchild;
zookeeper_->getZNodeChildren(write_req_queue_parent_, reqchild, ZooKeeper::NOT_WATCH);
if (reqchild.empty())
{
LOG(INFO) << "no write request anymore while check request on server: " << serverRealPath_;
zookeeper_->getZNodeChildren(write_req_queue_parent_, reqchild, ZooKeeper::WATCH);
return false;
}
LOG(INFO) << "there are some write request waiting: " << reqchild.size();
size_t pop_num = reqchild.size() > 1000 ? 1000:reqchild.size();
for(size_t i = 0; i < pop_num; ++i)
{
ZNode znode;
std::string sdata;
zookeeper_->getZNodeData(reqchild[i], sdata);
znode.loadKvString(sdata);
LOG(INFO) << "a request poped : " << reqchild[i] << " on the server: " << serverRealPath_;
cached_write_reqlist_.push(std::make_pair(znode.getStrValue(ZNode::KEY_REQ_DATA),
znode.getStrValue(ZNode::KEY_REQ_TYPE)));
zookeeper_->deleteZNode(reqchild[i]);
}
return true;
}
// check if any new request can be processed.
void MasterManagerBase::checkForNewWriteReq()
{
if (masterState_ != MASTER_STATE_STARTED && masterState_ != MASTER_STATE_STARTING_WAIT_WORKERS)
{
LOG(INFO) << "current master state is not ready while check write, state:" << masterState_;
return;
}
if (write_prepared_)
{
LOG(INFO) << "a prepared write is still waiting worker ";
return;
}
if (!isAllWorkerIdle())
{
return;
}
if (!endWriteReq())
{
zookeeper_->isZNodeExists(ZooKeeperNamespace::getWriteReqPrepareNode(), ZooKeeper::WATCH);
return;
}
if (cached_write_reqlist_.empty())
{
if (!cacheNewWriteFromZNode())
return;
}
if (!cached_write_reqlist_.empty())
{
LOG(INFO) << "there are some cached write request : " << cached_write_reqlist_.size();
DistributeTestSuit::testFail(PrimaryFail_At_Master_checkForNewWrite);
if (on_new_req_available_)
{
bool ret = on_new_req_available_();
if (!ret)
{
LOG(ERROR) << "the write request handler return failed.";
write_prepared_ = false;
endWriteReq();
}
else
{
LOG(INFO) << "all new write requests have been delivered success.";
}
}
else
{
LOG(ERROR) << "the new request handler not set!!";
return;
}
}
}
// make sure prepare success before call this.
bool MasterManagerBase::popWriteReq(std::string& reqdata, std::string& type)
{
if (!isDistributeEnable_)
return false;
if (!zookeeper_ || !zookeeper_->isConnected())
return false;
if (cached_write_reqlist_.empty())
{
if (!cacheNewWriteFromZNode())
return false;
}
reqdata = cached_write_reqlist_.front().first;
type = cached_write_reqlist_.front().second;
cached_write_reqlist_.pop();
return true;
}
void MasterManagerBase::pushWriteReq(const std::string& reqdata, const std::string& type)
{
if (!isDistributeEnable_)
{
LOG(ERROR) << "Master is not configured as distributed, write request pushed failed." <<
"," << reqdata;
return;
}
if (stopping_)
{
LOG(ERROR) << "Master is stopping, write request pushed failed." <<
"," << reqdata;
return;
}
// boost::lock_guard<boost::mutex> lock(state_mutex_);
if (!zookeeper_ || !zookeeper_->isConnected())
{
LOG(ERROR) << "Master is not connecting to ZooKeeper, write request pushed failed." <<
"," << reqdata;
return;
}
ZNode znode;
//znode.setValue(ZNode::KEY_REQ_CONTROLLER, controller_name);
znode.setValue(ZNode::KEY_REQ_TYPE, type);
znode.setValue(ZNode::KEY_REQ_DATA, reqdata);
if(zookeeper_->createZNode(write_req_queue_, znode.serialize(), ZooKeeper::ZNODE_SEQUENCE))
{
LOG(INFO) << "a write request pushed to the queue : " << zookeeper_->getLastCreatedNodePath();
}
else
{
LOG(ERROR) << "write request pushed failed." <<
"," << reqdata;
}
}
bool MasterManagerBase::disableNewWrite()
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
if (write_prepared_)
{
LOG(INFO) << "disable write failed for already prepared : ";
return false;
}
new_write_disabled_ = true;
return true;
}
void MasterManagerBase::enableNewWrite()
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
new_write_disabled_ = false;
}
void MasterManagerBase::endPreparedWrite()
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
write_prepared_ = false;
}
bool MasterManagerBase::endWriteReq()
{
if (!isMinePrimary())
{
LOG(INFO) << "non-primary master can not end a write request.";
return false;
}
if (!zookeeper_->isZNodeExists(ZooKeeperNamespace::getWriteReqPrepareNode()))
{
LOG(INFO) << "There is no any write request while end request";
return true;
}
std::string sdata;
if (zookeeper_->getZNodeData(ZooKeeperNamespace::getWriteReqPrepareNode(), sdata))
{
ZNode znode;
znode.loadKvString(sdata);
std::string write_server = znode.getStrValue(ZNode::KEY_MASTER_SERVER_REAL_PATH);
if (write_server != serverRealPath_)
{
LOG(WARNING) << "end request mismatch server. " << write_server << " vs " << serverRealPath_;
return false;
}
zookeeper_->deleteZNode(ZooKeeperNamespace::getWriteReqPrepareNode());
LOG(INFO) << "end write request success on server : " << serverRealPath_;
}
else
{
LOG(WARNING) << "get write request data failed while end request on server :" << serverRealPath_;
return false;
}
return true;
}
//bool MasterManagerBase::isAllWorkerFinished()
//{
// if (!isAllWorkerInState(NodeManagerBase::NODE_STATE_WAIT_MASTER_FINISH_REQ))
// {
// LOG(INFO) << "one of primary worker not finish write request : ";
// return false;
// }
// return true;
//}
bool MasterManagerBase::isAllWorkerIdle()
{
if (!isAllWorkerInState(NodeManagerBase::NODE_STATE_STARTED))
{
LOG(INFO) << "one of primary worker not ready for new write request.";
return false;
}
return true;
}
bool MasterManagerBase::isAllWorkerInState(int state)
{
WorkerMapT::iterator it;
for (it = workerMap_.begin(); it != workerMap_.end(); it++)
{
std::string nodepath = getNodePath(it->second->replicaId_, it->first);
std::string sdata;
if (zookeeper_->getZNodeData(nodepath, sdata, ZooKeeper::WATCH))
{
ZNode nodedata;
nodedata.loadKvString(sdata);
if (nodedata.getUInt32Value(ZNode::KEY_NODE_STATE) != (uint32_t)state)
{
return false;
}
}
}
return true;
}
bool MasterManagerBase::isBusy()
{
if (!isDistributeEnable_)
return false;
boost::lock_guard<boost::mutex> lock(state_mutex_);
if (stopping_ || !zookeeper_ || !zookeeper_->isConnected())
return true;
if (zookeeper_->isZNodeExists(ZooKeeperNamespace::getWriteReqPrepareNode()))
{
LOG(INFO) << "Master is busy because there is another write request running";
return true;
}
return !isAllWorkerIdle();
}
void MasterManagerBase::showWorkers()
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
WorkerMapT::iterator it;
for (it = workerMap_.begin(); it != workerMap_.end(); it++)
{
cout << it->second->toString() ;
}
}
/// protected ////////////////////////////////////////////////////////////////////
std::string MasterManagerBase::state2string(MasterStateType e)
{
std::stringstream ss;
switch (e)
{
case MASTER_STATE_INIT:
return "MASTER_STATE_INIT";
break;
case MASTER_STATE_STARTING:
return "MASTER_STATE_STARTING";
break;
case MASTER_STATE_STARTING_WAIT_ZOOKEEPER:
return "MASTER_STATE_STARTING_WAIT_ZOOKEEPER";
break;
case MASTER_STATE_STARTING_WAIT_WORKERS:
return "MASTER_STATE_STARTING_WAIT_WORKERS";
break;
case MASTER_STATE_STARTED:
return "MASTER_STATE_STARTED";
break;
//case MASTER_STATE_FAILOVERING:
// return "MASTER_STATE_FAILOVERING";
// break;
//case MASTER_STATE_RECOVERING:
// return "MASTER_STATE_RECOVERING";
// break;
}
return "UNKNOWN";
}
void MasterManagerBase::watchAll()
{
// for replica change
std::vector<std::string> childrenList;
zookeeper_->getZNodeChildren(topologyPath_, childrenList, ZooKeeper::WATCH);
for (size_t i = 0; i < childrenList.size(); i++)
{
std::vector<std::string> chchList;
zookeeper_->getZNodeChildren(childrenList[i], chchList, ZooKeeper::WATCH);
}
// for nodes change
for (uint32_t nodeid = 1; nodeid <= sf1rTopology_.nodeNum_; nodeid++)
{
std::string nodePath = getNodePath(sf1rTopology_.curNode_.replicaId_, nodeid);
zookeeper_->isZNodeExists(nodePath, ZooKeeper::WATCH);
}
}
bool MasterManagerBase::checkZooKeeperService()
{
if (!zookeeper_->isConnected())
{
zookeeper_->connect(true);
if (!zookeeper_->isConnected())
{
return false;
}
}
return true;
}
void MasterManagerBase::doStart()
{
stopping_ = false;
detectReplicaSet();
detectWorkers();
// Each Master serves as a Search Server, register it without waiting for all workers to be ready.
registerServiceServer();
}
int MasterManagerBase::detectWorkersInReplica(replicaid_t replicaId, size_t& detected, size_t& good)
{
bool mine_primary = isMinePrimary();
if (mine_primary)
LOG(INFO) << "I am primary master ";
for (uint32_t nodeid = 1; nodeid <= sf1rTopology_.nodeNum_; nodeid++)
{
std::string data;
std::string nodePath = getNodePath(replicaId, nodeid);
if (zookeeper_->getZNodeData(nodePath, data, ZooKeeper::WATCH))
{
ZNode znode;
znode.loadKvString(data);
// if this sf1r node provides worker server
if (znode.hasKey(ZNode::KEY_WORKER_PORT))
{
if (mine_primary)
{
if(!isPrimaryWorker(replicaId, nodeid))
{
LOG(INFO) << "primary master need detect primary worker, ignore non-primary worker";
LOG (INFO) << "node " << nodeid << ", replica: " << replicaId;
continue;
}
}
if (nodeid > 0 && nodeid <= sf1rTopology_.nodeNum_)
{
if (workerMap_.find(nodeid) != workerMap_.end())
{
if (workerMap_[nodeid]->worker_.isGood_)
continue;
workerMap_[nodeid]->worker_.isGood_ = true;
}
else
{
// insert new worker
boost::shared_ptr<Sf1rNode> sf1rNode(new Sf1rNode);
sf1rNode->worker_.isGood_ = true;
workerMap_[nodeid] = sf1rNode;
}
// update worker info
boost::shared_ptr<Sf1rNode>& workerNode = workerMap_[nodeid];
workerNode->nodeId_ = nodeid;
updateWorkerNode(workerNode, znode);
workerNode->replicaId_ = replicaId;
detected ++;
if (workerNode->worker_.isGood_)
{
good ++;
}
}
else
{
std::stringstream ss;
ss << "in node[" << nodeid << "] @ " << znode.getStrValue(ZNode::KEY_HOST)
<< " is out of range for current master (max is " << sf1rTopology_.nodeNum_ << ")";
LOG (WARNING) << ss.str();
throw std::runtime_error(ss.str());
}
}
}
else
{
// reset watcher
zookeeper_->isZNodeExists(nodePath, ZooKeeper::WATCH);
}
}
if (detected >= sf1rTopology_.nodeNum_)
{
masterState_ = MASTER_STATE_STARTED;
LOG (INFO) << CLASSNAME << " detected " << sf1rTopology_.nodeNum_
<< " all workers (good " << good << ")" << std::endl;
}
else
{
masterState_ = MASTER_STATE_STARTING_WAIT_WORKERS;
LOG (INFO) << CLASSNAME << " detected " << detected << " workers (good " << good
<< "), all " << sf1rTopology_.nodeNum_ << std::endl;
}
return good;
}
int MasterManagerBase::detectWorkers()
{
size_t detected = 0;
size_t good = 0;
workerMap_.clear();
// detect workers from "current" replica first
replicaid_t replicaId = sf1rTopology_.curNode_.replicaId_;
detectWorkersInReplica(replicaId, detected, good);
for (size_t i = 0; i < replicaIdList_.size(); i++)
{
if (masterState_ != MASTER_STATE_STARTING_WAIT_WORKERS)
{
LOG(INFO) << "detected worker enough, stop detect other replica.";
break;
}
if (replicaId == replicaIdList_[i])
continue;
// not enough, check other replica
LOG(INFO) << "begin detect workers in other replica : " << replicaIdList_[i];
detectWorkersInReplica(replicaIdList_[i], detected, good);
}
//
// update workers' info to aggregators
resetAggregatorConfig();
return good;
}
void MasterManagerBase::updateWorkerNode(boost::shared_ptr<Sf1rNode>& workerNode, ZNode& znode)
{
workerNode->replicaId_ = sf1rTopology_.curNode_.replicaId_;
workerNode->host_ = znode.getStrValue(ZNode::KEY_HOST);
//workerNode->port_ = znode.getUInt32Value(ZNode::KEY_WORKER_PORT);
try
{
workerNode->worker_.port_ =
boost::lexical_cast<port_t>(znode.getStrValue(ZNode::KEY_WORKER_PORT));
}
catch (std::exception& e)
{
workerNode->worker_.isGood_ = false;
LOG (ERROR) << "failed to convert workerPort \"" << znode.getStrValue(ZNode::KEY_WORKER_PORT)
<< "\" got from worker on node " << workerNode->nodeId_
<< " @" << workerNode->host_;
}
try
{
workerNode->dataPort_ =
boost::lexical_cast<port_t>(znode.getStrValue(ZNode::KEY_DATA_PORT));
}
catch (std::exception& e)
{
workerNode->worker_.isGood_ = false;
LOG (ERROR) << "failed to convert dataPort \"" << znode.getStrValue(ZNode::KEY_DATA_PORT)
<< "\" got from worker on node " << workerNode->nodeId_
<< " @" << workerNode->host_;
}
LOG (INFO) << CLASSNAME << " detected worker on (node" << workerNode->nodeId_ <<") "
<< workerNode->host_ << ":" << workerNode->worker_.port_ << std::endl;
}
void MasterManagerBase::detectReplicaSet(const std::string& zpath)
{
// find replications
std::vector<std::string> childrenList;
zookeeper_->getZNodeChildren(topologyPath_, childrenList, ZooKeeper::WATCH);
replicaIdList_.clear();
for (size_t i = 0; i < childrenList.size(); i++)
{
std::string sreplicaId;
zookeeper_->getZNodeData(childrenList[i], sreplicaId);
try
{
replicaIdList_.push_back(boost::lexical_cast<replicaid_t>(sreplicaId));
LOG (INFO) << " detected replica id \"" << sreplicaId
<< "\" for " << childrenList[i];
}
catch (std::exception& e) {
LOG (ERROR) << CLASSNAME << " failed to parse replica id \"" << sreplicaId
<< "\" for " << childrenList[i];
}
// watch for nodes change
std::vector<std::string> chchList;
zookeeper_->getZNodeChildren(childrenList[i], chchList, ZooKeeper::WATCH);
zookeeper_->isZNodeExists(childrenList[i], ZooKeeper::WATCH);
}
// try to detect workers again while waiting for some of the workers
if (masterState_ == MASTER_STATE_STARTING_WAIT_WORKERS)
{
detectWorkers();
}
WorkerMapT::iterator it;
for (it = workerMap_.begin(); it != workerMap_.end(); it++)
{
boost::shared_ptr<Sf1rNode>& sf1rNode = it->second;
if (!sf1rNode->worker_.isGood_)
{
// try failover
if (!failover(sf1rNode))
{
LOG(WARNING) << "one of worker failed and can not cover this failure.";
masterState_ = MASTER_STATE_STARTING_WAIT_WORKERS;
}
}
}
}
void MasterManagerBase::failover(const std::string& zpath)
{
// check path
WorkerMapT::iterator it;
for (it = workerMap_.begin(); it != workerMap_.end(); it++)
{
boost::shared_ptr<Sf1rNode>& sf1rNode = it->second;
std::string nodePath = getNodePath(sf1rNode->replicaId_, sf1rNode->nodeId_);
if (zpath == nodePath)
{
LOG (WARNING) << "[node " << sf1rNode->nodeId_ << "]@" << sf1rNode->host_ << " was broken down, in "
<< "[replica " << sf1rNode->replicaId_ << "]";
if (failover(sf1rNode))
{
LOG (INFO) << "failover: finished.";
return;
}
else
{
LOG (INFO) << "failover: failed to cover this failure.";
masterState_ = MASTER_STATE_STARTING_WAIT_WORKERS;
return;
}
}
}
LOG (INFO) << "failed node is not in my watching workers . " << zpath;
}
bool MasterManagerBase::failover(boost::shared_ptr<Sf1rNode>& sf1rNode)
{
sf1rNode->worker_.isGood_ = false;
bool mine_primary = isMinePrimary();
if (mine_primary)
LOG(INFO) << "I am primary master ";
for (size_t i = 0; i < replicaIdList_.size(); i++)
{
if (replicaIdList_[i] != sf1rNode->replicaId_)
{
// try to switch to replicaIdList_[i]
ZNode znode;
std::string sdata;
std::string nodePath = getNodePath(replicaIdList_[i], sf1rNode->nodeId_);
// get node data
if (zookeeper_->getZNodeData(nodePath, sdata, ZooKeeper::WATCH))
{
if (mine_primary)
{
if(!isPrimaryWorker(replicaIdList_[i], sf1rNode->nodeId_))
{
LOG(INFO) << "primary master need failover to primary worker, ignore non-primary worker";
LOG (INFO) << "node " << sf1rNode->nodeId_ << " ,replica: " << replicaIdList_[i];
continue;
}
}
znode.loadKvString(sdata);
if (znode.hasKey(ZNode::KEY_WORKER_PORT))
{
LOG (INFO) << "switching node " << sf1rNode->nodeId_ << " from replica " << sf1rNode->replicaId_
<<" to " << replicaIdList_[i];
sf1rNode->replicaId_ = replicaIdList_[i]; // new replica
sf1rNode->host_ = znode.getStrValue(ZNode::KEY_HOST);
try
{
sf1rNode->worker_.port_ =
boost::lexical_cast<port_t>(znode.getStrValue(ZNode::KEY_WORKER_PORT));
}
catch (std::exception& e)
{
LOG (ERROR) << "failed to convert workerPort \"" << znode.getStrValue(ZNode::KEY_WORKER_PORT)
<< "\" got from node " << sf1rNode->nodeId_ << " at " << znode.getStrValue(ZNode::KEY_HOST)
<< ", in replica " << replicaIdList_[i];
continue;
}
// succeed to failover
sf1rNode->worker_.isGood_ = true;
break;
}
else
{
LOG (ERROR) << "[Replica " << replicaIdList_[i] << "] [Node " << sf1rNode->nodeId_
<< "] did not enable worker server, this happened because of the mismatch configuration.";
LOG (ERROR) << "In the same cluster, the sf1r node with the same nodeid must have the same configuration.";
throw std::runtime_error("error configuration : mismatch with the same nodeid.");
}
}
}
}
// notify aggregators
resetAggregatorConfig();
// Watch current replica, waiting for node recover
zookeeper_->isZNodeExists(getNodePath(sf1rNode->replicaId_, sf1rNode->nodeId_), ZooKeeper::WATCH);
return sf1rNode->worker_.isGood_;
}
void MasterManagerBase::recover(const std::string& zpath)
{
WorkerMapT::iterator it;
bool mine_primary = isMinePrimary();
if (mine_primary)
LOG(INFO) << "I am primary master ";
for (it = workerMap_.begin(); it != workerMap_.end(); it++)
{
boost::shared_ptr<Sf1rNode>& sf1rNode = it->second;
if (zpath == getNodePath(sf1rTopology_.curNode_.replicaId_, sf1rNode->nodeId_))
{
if (mine_primary)
{
if(!isPrimaryWorker(sf1rTopology_.curNode_.replicaId_, sf1rNode->nodeId_))
{
LOG(INFO) << "primary master need recover to primary worker, ignore non-primary worker";
LOG (INFO) << "node " << sf1rNode->nodeId_ << " ,replica: " << sf1rTopology_.curNode_.replicaId_;
continue;
}
}
LOG (INFO) << "recover: node " << sf1rNode->nodeId_
<< " recovered in current replica " << sf1rTopology_.curNode_.replicaId_;
ZNode znode;
std::string sdata;
if (zookeeper_->getZNodeData(zpath, sdata, ZooKeeper::WATCH))
{
// try to recover
znode.loadKvString(sdata);
try
{
sf1rNode->worker_.port_ =
boost::lexical_cast<port_t>(znode.getStrValue(ZNode::KEY_WORKER_PORT));
}
catch (std::exception& e)
{
LOG (ERROR) << "failed to convert workerPort \"" << znode.getStrValue(ZNode::KEY_WORKER_PORT)
<< "\" got from node " << sf1rNode->nodeId_ << " at " << znode.getStrValue(ZNode::KEY_HOST)
<< ", in replica " << sf1rTopology_.curNode_.replicaId_;
continue;
}
sf1rNode->replicaId_ = sf1rTopology_.curNode_.replicaId_; // new replica
sf1rNode->host_ = znode.getStrValue(ZNode::KEY_HOST);
// recovered, and notify aggregators
sf1rNode->worker_.isGood_ = true;
break;
}
}
}
resetAggregatorConfig();
}
void MasterManagerBase::setServicesData(ZNode& znode)
{
// write service name to server node.
std::string services;
ServiceMapT::const_iterator cit = all_distributed_services_.begin();
while(cit != all_distributed_services_.end())
{
if (services.empty())
services = cit->first;
else
services += "," + cit->first;
std::string collections;
std::vector<MasterCollection>& collectionList = sf1rTopology_.curNode_.master_.masterServices_[cit->first].collectionList_;
for (std::vector<MasterCollection>::iterator it = collectionList.begin();
it != collectionList.end(); it++)
{
if (collections.empty())
collections = (*it).name_;
else
collections += "," + (*it).name_;
}
znode.setValue(cit->first + ZNode::KEY_COLLECTION, collections);
++cit;
}
znode.setValue(ZNode::KEY_SERVICE_NAMES, services);
}
void MasterManagerBase::initServices()
{
}
bool MasterManagerBase::isServiceReadyForRead(bool include_self)
{
// service is ready for read means all shard workers current master connected are ready for read.
boost::lock_guard<boost::mutex> lock(state_mutex_);
WorkerMapT::const_iterator it = workerMap_.begin();
for ( ; it != workerMap_.end(); ++it)
{
if (it->second->nodeId_ == sf1rTopology_.curNode_.nodeId_)
{
if (!include_self)
continue;
}
std::string nodepath = getNodePath(it->second->replicaId_, it->second->nodeId_);
std::string sdata;
if (zookeeper_->getZNodeData(nodepath, sdata, ZooKeeper::WATCH))
{
ZNode znode;
znode.loadKvString(sdata);
std::string value = znode.getStrValue(ZNode::KEY_SERVICE_STATE);
if (value != "ReadyForRead" && value != "BusyForShard")
{
LOG(INFO) << "one shard of master service is not ready for read:" << nodepath;
return false;
}
}
}
return true;
}
void MasterManagerBase::registerDistributeServiceMaster(boost::shared_ptr<IDistributeService> sp_service, bool enable_master)
{
if (enable_master)
{
if (all_distributed_services_.find(sp_service->getServiceName()) !=
all_distributed_services_.end() )
{
LOG(WARNING) << "duplicate service name!!!!!!!";
throw std::runtime_error("duplicate service!");
}
LOG(INFO) << "registering service master: " << sp_service->getServiceName();
all_distributed_services_[sp_service->getServiceName()] = sp_service;
}
}
bool MasterManagerBase::findServiceMasterAddress(const std::string& service, std::string& host, uint32_t& port)
{
if (!zookeeper_ || !zookeeper_->isConnected())
return false;
std::vector<std::string> children;
zookeeper_->getZNodeChildren(serverParentPath_, children);
for (size_t i = 0; i < children.size(); ++i)
{
std::string serviceMasterPath = children[i];
std::string data;
if (zookeeper_->getZNodeData(serviceMasterPath, data))
{
ZNode znode;
znode.loadKvString(data);
std::string service_names = znode.getStrValue(ZNode::KEY_SERVICE_NAMES);
if (service_names.find(service) == std::string::npos)
continue;
LOG(INFO) << "find service master address success : " << service << ", on server :" << serviceMasterPath;
host = znode.getStrValue(ZNode::KEY_HOST);
port = znode.getUInt32Value(ZNode::KEY_MASTER_PORT);
return true;
}
}
return false;
}
void MasterManagerBase::registerServiceServer()
{
// Master server provide search service
if (!zookeeper_->isZNodeExists(serverParentPath_))
{
zookeeper_->createZNode(serverParentPath_);
}
initServices();
ZNode znode;
znode.setValue(ZNode::KEY_HOST, sf1rTopology_.curNode_.host_);
znode.setValue(ZNode::KEY_BA_PORT, sf1rTopology_.curNode_.baPort_);
znode.setValue(ZNode::KEY_MASTER_PORT, SuperNodeManager::get()->getMasterPort());
setServicesData(znode);
if (zookeeper_->createZNode(serverPath_, znode.serialize(), ZooKeeper::ZNODE_EPHEMERAL_SEQUENCE))
{
serverRealPath_ = zookeeper_->getLastCreatedNodePath();
}
if (!zookeeper_->isZNodeExists(write_req_queue_root_parent_, ZooKeeper::WATCH))
{
zookeeper_->createZNode(write_req_queue_root_parent_);
}
if (!zookeeper_->isZNodeExists(write_req_queue_parent_, ZooKeeper::WATCH))
{
zookeeper_->createZNode(write_req_queue_parent_);
}
std::vector<string> reqchild;
zookeeper_->getZNodeChildren(write_req_queue_parent_, reqchild, ZooKeeper::WATCH);
}
void MasterManagerBase::resetAggregatorConfig()
{
std::vector<boost::shared_ptr<AggregatorBase> >::iterator agg_it;
for (agg_it = aggregatorList_.begin(); agg_it != aggregatorList_.end(); agg_it++)
{
boost::shared_ptr<AggregatorBase>& aggregator = *agg_it;
// get shardids for collection of aggregator
std::vector<shardid_t> shardidList;
if (!sf1rTopology_.curNode_.master_.getShardidList(aggregator->service(),
aggregator->collection(), shardidList))
{
continue;
}
// set workers for aggregator
AggregatorConfig aggregatorConfig;
for (size_t i = 0; i < shardidList.size(); i++)
{
WorkerMapT::iterator it = workerMap_.find(shardidList[i]);
if (it != workerMap_.end())
{
if(!it->second->worker_.isGood_)
{
LOG(INFO) << "worker_ : " << it->second->nodeId_ << " is not good, so do not added to aggregator.";
continue;
}
bool isLocal = (it->second->nodeId_ == sf1rTopology_.curNode_.nodeId_);
aggregatorConfig.addWorker(it->second->host_, it->second->worker_.port_, shardidList[i], isLocal);
}
else
{
LOG (ERROR) << "worker " << shardidList[i] << " was not found for Aggregator of "
<< aggregator->collection() << " in service " << aggregator->service();
}
}
//std::cout << aggregator->collection() << ":" << std::endl << aggregatorConfig.toString();
aggregator->setAggregatorConfig(aggregatorConfig);
}
}
bool MasterManagerBase::isPrimaryWorker(replicaid_t replicaId, nodeid_t nodeId)
{
std::string nodepath = getNodePath(replicaId, nodeId);
std::string sdata;
if (zookeeper_->getZNodeData(nodepath, sdata, ZooKeeper::WATCH))
{
ZNode znode;
znode.loadKvString(sdata);
std::string self_reg_primary = znode.getStrValue(ZNode::KEY_SELF_REG_PRIMARY_PATH);
std::vector<std::string> node_list;
zookeeper_->getZNodeChildren(getPrimaryNodeParentPath(nodeId), node_list);
if (node_list.empty())
{
LOG(INFO) << "no any primary node for node id: " << nodeId;
return false;
}
return self_reg_primary == node_list[0];
}
else
return false;
}
bool MasterManagerBase::isMinePrimary()
{
if(!isDistributeEnable_)
return true;
if (!zookeeper_ || !zookeeper_->isConnected())
return false;
return isPrimaryWorker(sf1rTopology_.curNode_.replicaId_, sf1rTopology_.curNode_.nodeId_);
}
|
#include "ui_SimpleView.h"
#include "SimpleView.h"
// Qt
#include <QSettings>
#include <QDockWidget>
#include <QFileDialog>
#include <QProgressDialog.h>
// dicom net
#include "dcmtkEchoScu.h"
#include "dcmtkFindScu.h"
#include "dcmtkMoveScu.h"
#include "dcmtkStoreScp.h"
#include "dcmtkStoreScu.h"
#include "dcmtkResultDataset.h"
// logger
#include "dcmtkLogger.h"
#include "LoggerFileOutput.h"
#include "LoggerConsoleOutput.h"
#include "LoggerWidgetOutput.h"
#include "LoggerWidget.h"
// utilities
#include "dcmtkDump.h"
#include <sstream>
//---------------------------------------------------------------------------------------------
// Constructor
SimpleView::SimpleView()
{
//initialize logger
dcmtkLogger::startUp();
// create and show LoggerWidget
this->ui = new Ui_SimpleView;
this->ui->setupUi(this);
QStringList labels;
labels << "Patient name" << "Description" << "ID/Number" << "Modality/Type";
ui->treeWidget->setHeaderLabels(labels);
ui->treeWidget->setHeaderHidden(false);
m_echoScu = new dcmtkEchoScu();
m_findScu = new dcmtkFindScu();
m_serverThread = new dcmtkStoreScp();
m_sendThread = new dcmtkStoreScu();
m_moveThread = new dcmtkMoveScu();
m_shellOut = new LoggerConsoleOutput();
m_fileOut = new LoggerFileOutput();
m_loggerWidget = new LoggerWidget(this);
m_widgetOut = new LoggerWidgetOutput(m_loggerWidget);
connect(this->ui->actionExit, SIGNAL(triggered()), this, SLOT(quit()));
connect(this->ui->searchField, SIGNAL(returnPressed()), this, SLOT(findStudyLevel()));
connect(this->ui->treeWidget, SIGNAL(itemDoubleClicked ( QTreeWidgetItem* , int )), this, SLOT(move(QTreeWidgetItem *, int)));
connect(this->ui->treeWidget, SIGNAL(itemExpanded ( QTreeWidgetItem* )), this, SLOT(findSeriesLevel(QTreeWidgetItem *)));
connect(this->ui->echoButton, SIGNAL(clicked()), this, SLOT(echo()));
connect(this->ui->applySettingsButton, SIGNAL(clicked()), this, SLOT(applySettingsSlot()));
connect(this->ui->cbFileTarget, SIGNAL(stateChanged(int)), this, SLOT(fileAppender(int)));
connect(this->ui->cbShellTarget, SIGNAL(stateChanged(int)), this, SLOT(shellAppender(int)));
connect(this->ui->cbWidgetTarget, SIGNAL(stateChanged(int)), this, SLOT(widgetAppender(int)));
connect(this->ui->cbLogLevel, SIGNAL(currentIndexChanged(int)), this, SLOT(changeLogLevel(int)));
connect(this->ui->serverRestartButton, SIGNAL(clicked()), this, SLOT(restartServer()));
connect(this->ui->dirButton, SIGNAL(clicked()),this,SLOT(setSendDirectory()));
connect(this->ui->dirbutton2, SIGNAL(clicked()), this, SLOT(setArchiveDirectory()));
connect(this->ui->diredit2, SIGNAL(editingFinished()), this, SLOT(updateServerDir()));
connect(this->ui->sendButton, SIGNAL(clicked()),this,SLOT(store()));
connect(this->ui->addButton, SIGNAL(clicked()), this, SLOT(addConn()));
connect(this->ui->connTableWidget, SIGNAL(itemSelectionChanged()), this, SLOT(handleConnSelection()));
connect(this->ui->peerTitleEdit, SIGNAL(textChanged(QString)), this, SLOT(inputChanged()));
connect(this->ui->peerIPEdit, SIGNAL(textChanged(QString)), this, SLOT(inputChanged()));
connect(this->ui->peerPortEdit, SIGNAL(textChanged(QString)), this, SLOT(inputChanged()));
connect(m_findScu,SIGNAL(finished()), this, SLOT(fillTreeStudy()));
retrieveSettings();
setConnectionParams();
//set logger defaults
ui->cbWidgetTarget->setChecked(true);
ui->cbLogLevel->setCurrentIndex(2);
QDockWidget* loggerDock = new QDockWidget(this);
loggerDock->setWidget(m_loggerWidget);
this->addDockWidget(Qt::BottomDockWidgetArea, loggerDock);
// start the threaded server
startServer();
};
//---------------------------------------------------------------------------------------------
SimpleView::~SimpleView()
{
dcmtkLogger::shutDown();
stopServer();
delete m_findScu;
delete m_echoScu;
delete m_sendThread;
delete m_moveThread;
delete m_shellOut;
delete m_fileOut;
delete m_widgetOut;
if(ui != NULL) delete ui;
}
//---------------------------------------------------------------------------------------------
void SimpleView::changeLogLevel(int index)
{
LoggerLogLevel::LogLevel logLevel;
switch(index)
{
case 0:
logLevel = LoggerLogLevel::NOLOG;
break;
case 1:
logLevel = LoggerLogLevel::ERRORLOG;
break;
case 2:
logLevel = LoggerLogLevel::WARNINGLOG;
break;
case 3:
logLevel = LoggerLogLevel::INFOLOG;
break;
case 4:
logLevel = LoggerLogLevel::DEBUGLOG;
break;
default:
logLevel = LoggerLogLevel::INFOLOG;
break;
}
m_fileOut->setLogLevel(logLevel);
m_shellOut->setLogLevel(logLevel);
m_widgetOut->setLogLevel(logLevel);
}
//---------------------------------------------------------------------------------------------
void SimpleView::setConnectionParams()
{
m_ourTitle = ui->ourTitleEdit->text().toStdString();
m_ourIP = ui->ourIPEdit->text().toStdString();
m_peerTitle = ui->peerTitleEdit->text().toStdString();
m_peerIP = ui->peerIPEdit->text().toStdString();
try
{
m_peerPort = ui->peerPortEdit->text().toInt();
}
catch(...)
{
ui->peerPortEdit->setText("");
}
try
{
m_ourPort = ui->ourPortEdit->text().toInt();
}
catch(...)
{
ui->ourPortEdit->setText("9999");
}
m_echoScu->setConnectionParams(m_peerTitle.c_str(), m_peerIP.c_str(), m_peerPort, m_ourTitle.c_str(), m_ourIP.c_str(), m_ourPort);
m_serverThread->setConnectionParams(m_ourTitle.c_str(), m_ourIP.c_str(), m_ourPort);
}
//---------------------------------------------------------------------------------------------
// Action to be taken upon file open
void SimpleView::findStudyLevel()
{
// get selected nodes
dcmtkContainer<dcmtkNode*>* selectedNodes = getSelectedNodes();
QString patientName = ui->searchField->text();
patientName.append("*");
// clear previous results
m_findScu->clearAllQueryAttributes();
// set up search criteria
m_findScu->setQueryLevel(dcmtkFindScu::STUDY);
m_findScu->addQueryAttribute(0x0010,0x0010,patientName.toLatin1()); // patient name
m_findScu->addQueryAttribute(0x0008,0x0030,"\0"); // study date
m_findScu->addQueryAttribute(0x0008,0x0050,"\0"); // accession no
m_findScu->addQueryAttribute(0x0008,0x0061,"\0"); // modalities in study
m_findScu->addQueryAttribute(0x0008,0x0090,"\0"); // ref physician
m_findScu->addQueryAttribute(0x0008,0x1030,"\0"); // study description
m_findScu->addQueryAttribute(0x0010,0x0020,"\0"); // patient ID
m_findScu->addQueryAttribute(0x0010,0x0030,"\0"); // patient BD
m_findScu->addQueryAttribute(0x0010,0x0040,"\0"); // sex
m_findScu->addQueryAttribute(0x0020,0x000D,"\0"); // studyInstanceUID
m_findScu->addQueryAttribute(0x0020,0x0010,"\0"); // study ID
// we repeat the find process with the data from all selected nodes
dcmtkNode* selNode = selectedNodes->getFirst();
while (selectedNodes->isValid())
{
QProgressDialog* progress = new QProgressDialog("Looking for images...", "Cancel", 0, 100);
progress->setWindowModality(Qt::WindowModal);
connect(m_findScu,SIGNAL(progressed(int)), progress,SLOT(setValue(int)));
connect(progress,SIGNAL(canceled()),m_findScu,SLOT(sendCancelRequest()));
progress->show();
progress->repaint();
// do the work
m_findScu->wait();
m_findScu->setConnectionParams(selNode->title().c_str(),selNode->ip().c_str(),selNode->port(),m_ourTitle.c_str(), m_ourIP.c_str(), m_ourPort);
m_findScu->start();
selNode = selectedNodes->getNext();
}
// clean up
delete selectedNodes;
}
//---------------------------------------------------------------------------------------------
void SimpleView::findSeriesLevel(QTreeWidgetItem * item)
{
// check if its a top level item
if (item->parent() != NULL)
{
if (item->parent()->parent() != NULL)
{
findImageLevel(item); // forward to image level
return;
}
} else return;
// check if the item alread has children (don't query again)
if (item->child(0) != NULL) return;
// retrieve data
int nodeIndex = item->data(0,Qt::UserRole).toInt();
QPoint tag = item->data(1,Qt::UserRole).toPoint();
QString searchStr = item->data(2,Qt::UserRole).toString();
dcmtkContainer<dcmtkNode*>* mainNodeCont = m_findScu->getNodeContainer();
dcmtkConnectionData cdata;
dcmtkNode* node = mainNodeCont->getAtPos(nodeIndex);
cdata.title = node->title();
cdata.ip = node->ip();
cdata.port = node->port();
// clear previous results
dcmtkFindScu* findScu = new dcmtkFindScu;
// set up search criteria
findScu->setQueryLevel(dcmtkFindScu::SERIES);
findScu->addQueryAttribute(tag.x(),tag.y(),searchStr.toLatin1()); // studyInstanceUID
findScu->addQueryAttribute(0x0008,0x0021,"\0"); // series date
findScu->addQueryAttribute(0x0008,0x0031,"\0"); // series time
findScu->addQueryAttribute(0x0008,0x0060,"\0"); // series modality
findScu->addQueryAttribute(0x0008,0x103E,"\0"); // series description
findScu->addQueryAttribute(0x0018,0x0015,"\0"); // body part
findScu->addQueryAttribute(0x0018,0x1030,"\0"); // protocol name
findScu->addQueryAttribute(0x0018,0x5100,"\0"); // patient position
findScu->addQueryAttribute(0x0020,0x000E,"\0"); // series instance UID
findScu->addQueryAttribute(0x0020,0x0011,"\0"); // series number
findScu->addQueryAttribute(0x0020,0x0052,"\0"); // frame of reference
// do the work
findScu->sendFindRequest(cdata.title.c_str(),cdata.ip.c_str(),cdata.port,m_ourTitle.c_str(), m_ourIP.c_str(), m_ourPort);
// now extract information from datasets and build a visual list
int sum = 0;
dcmtkContainer<dcmtkNode*>* resNodeCont = findScu->getNodeContainer();
dcmtkNode* myNode = resNodeCont->getFirst();
if (resNodeCont->isValid())
{
dcmtkContainer<dcmtkResultDataset*>* resCont = myNode->getResultDatasetContainer();
dcmtkResultDataset* resDs = resCont->getFirst();
while (resCont->isValid())
{
// add result to list
QTreeWidgetItem *pItem = new QTreeWidgetItem(item);
pItem->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator);
pItem->setData(0,Qt::UserRole, nodeIndex); //forwarding node index
pItem->setData(1,Qt::UserRole, QPoint(0x0020,0x000E)); // tag
pItem->setData(2,Qt::UserRole, QString(resDs->getSeriesInstanceUID())); // search value
pItem->setText(0,">>");
pItem->setText(1,resDs->findKeyValue(0x0008,0x103E));
pItem->setText(2,resDs->findKeyValue(0x0020,0x0011)); // series number
item->addChild(pItem);
resDs = resCont->getNext();
}
sum = resCont->size();
myNode = resNodeCont->getNext();
}
// print to logwindow
printResults(sum,"series");
// clean up
delete findScu;
}
//---------------------------------------------------------------------------------------------
void SimpleView::findImageLevel(QTreeWidgetItem * item)
{
// check if the item already has children (don't query again)
if (item->child(0) != NULL) return;
// retrieve data
int nodeIndex = item->data(0,Qt::UserRole).toInt(); // node index
QString searchStr = item->data(2,Qt::UserRole).toString(); // search value
dcmtkContainer<dcmtkNode*>* mainNodeCont = m_findScu->getNodeContainer();
dcmtkConnectionData cdata;
dcmtkNode* myNode = mainNodeCont->getAtPos(nodeIndex);
cdata.title = myNode->title();
cdata.ip = myNode->ip();
cdata.port = myNode->port();
// clear previous results
dcmtkFindScu* findScu = new dcmtkFindScu;
// set up search criteria
findScu->setQueryLevel(dcmtkFindScu::IMAGE);
findScu->addQueryAttribute(0x0020,0x000E,searchStr.toLatin1()); // series instance UID
findScu->addQueryAttribute(0x0008,0x0008,"\0"); // image type
findScu->addQueryAttribute(0x0008,0x0012,"\0"); // instance creation date
findScu->addQueryAttribute(0x0008,0x0013,"\0"); // instance creation time
findScu->addQueryAttribute(0x0008,0x0016,"\0"); // SOP class UID
findScu->addQueryAttribute(0x0008,0x0018,"\0"); // SOP instance UID
findScu->addQueryAttribute(0x0008,0x0022,"\0"); // image date
findScu->addQueryAttribute(0x0008,0x0032,"\0"); // image time
findScu->addQueryAttribute(0x0020,0x0012,"\0"); // acquisition number
findScu->addQueryAttribute(0x0020,0x000D,"\0"); // study instance UID
findScu->addQueryAttribute(0x0020,0x0013,"\0"); // instance time
findScu->addQueryAttribute(0x0020,0x0032,"\0"); // image position patient
findScu->addQueryAttribute(0x0020,0x0037,"\0"); // image orientation patient
findScu->addQueryAttribute(0x0020,0x1041,"\0"); // slice location
findScu->addQueryAttribute(0x0028,0x0008,"\0"); // number of frames
// do the work
findScu->sendFindRequest(cdata.title.c_str(),cdata.ip.c_str(),cdata.port,m_ourTitle.c_str(), m_ourIP.c_str(), m_ourPort);
// now extract information from datasets and build a visual list
int sum = 0;
dcmtkContainer<dcmtkNode*>* resNodeCont = findScu->getNodeContainer();
dcmtkNode* node = resNodeCont->getFirst();
if (resNodeCont->isValid())
{
dcmtkContainer<dcmtkResultDataset*>* resCont = node->getResultDatasetContainer();
dcmtkResultDataset* resDs = resCont->getFirst();
while (resCont->isValid())
{
// add result to list
QTreeWidgetItem *pItem = new QTreeWidgetItem(item);
pItem->setData(0,Qt::UserRole, nodeIndex); //forwarding node index
pItem->setData(1,Qt::UserRole, QPoint(0x0008,0x0018)); // tag
pItem->setData(2,Qt::UserRole, QString(resDs->getSOPInstanceUID())); // search value
pItem->setText(0,">>");
pItem->setText(2,resDs->findKeyValue(0x0020,0x0012)); // aqu. number
pItem->setText(3,resDs->findKeyValue(0x0008,0x0008)); // image type
item->addChild(pItem);
resDs = resCont->getNext();
}
sum = resCont->size();
}
// print to logwindow
printResults(sum,"images");
// clean up
delete findScu;
}
//---------------------------------------------------------------------------------------------
void SimpleView::move(QTreeWidgetItem * item, int column)
{
dcmtkContainer<dcmtkNode*>* mainNodeCont = m_findScu->getNodeContainer();
// retrieve data
int nodeIndex = item->data(0,Qt::UserRole).toInt();
QPoint tag = item->data(1,Qt::UserRole).toPoint();
QString searchStr = item->data(2,Qt::UserRole).toString();
ui->logWindow->append(tr("Fetching data..."));
ui->logWindow->repaint();
// set up search criteria
m_moveThread->clearAllQueryAttributes();
// find out which query level should be used
int elem = tag.y();
switch(elem)
{
case 0x0018:
m_moveThread->setQueryLevel(dcmtkMoveScu::IMAGE);
break;
case 0x000E:
m_moveThread->setQueryLevel(dcmtkMoveScu::SERIES);
break;
case 0x000D:
m_moveThread->setQueryLevel(dcmtkMoveScu::STUDY);
break;
default:
ui->logWindow->append(tr("Could not determine query level."));
}
m_moveThread->addQueryAttribute(tag.x(), tag.y(), searchStr.toLatin1());
// send the move request using the search crits
dcmtkNode* myNode = mainNodeCont->getAtPos(nodeIndex);
QProgressDialog* progress = new QProgressDialog("Fetching data...", "Cancel", 0, 100);
progress->setWindowModality(Qt::WindowModal);
connect(m_moveThread,SIGNAL(progressed(int)), progress,SLOT(setValue(int)));
connect(progress,SIGNAL(canceled()),m_moveThread,SLOT(sendCancelRequest()));
progress->show();
m_moveThread->setConnectionParams(myNode->title().c_str(),myNode->ip().c_str(),myNode->port(),m_ourTitle.c_str(), m_ourIP.c_str(), m_ourPort);
m_moveThread->start();
}
//---------------------------------------------------------------------------------------------
void SimpleView::echo()
{
// update params
setConnectionParams();
// now send the echo
if ( m_echoScu->sendEchoRequest() == 0 )
{
ui->logWindow->append(tr("Connection verified successfully"));
}
else
ui->logWindow->append(tr("No response from peer. Check your connection"));
}
//---------------------------------------------------------------------------------------------
void SimpleView::store()
{
// set the current node params first
dcmtkConnectionData* cb = &(m_nodes.at(ui->sendToNodeCB->currentIndex()));
m_sendThread->setConnectionParams(cb->title.c_str(), cb->ip.c_str(), cb->port, m_ourTitle.c_str(), m_ourIP.c_str(), m_ourPort);
QDir testDir;
testDir.setPath(ui->directoryLE->text());
if ( testDir.isReadable() )
{
m_sendThread->setScanDirectory(ui->directoryLE->text().toLatin1());
m_sendThread->start();
}
else
{
ui->logWindow->append("This is not a valid import directory!");
}
}
//---------------------------------------------------------------------------------------------
void SimpleView::setSendDirectory()
{
QDir selDir;
QFileDialog dialog(this);
dialog.setFileMode(QFileDialog::DirectoryOnly);
if (dialog.exec())
{
selDir = dialog.directory();
this->ui->directoryLE->setText(selDir.path());
}
}
//---------------------------------------------------------------------------------------------
void SimpleView::applySettingsSlot()
{
storeSettings(1);
setConnectionParams();
restartServer();
}
//---------------------------------------------------------------------------------------------
void SimpleView::storeSettings(int type)
{
QSettings settings("INRIA", "DCMTKTOOL");
std::vector<dcmtkConnectionData>::iterator iter;
int count = 0;
QString countString;
switch(type)
{
case 0:
settings.beginGroup("Connection");
for( iter = m_nodes.begin(); iter != m_nodes.end(); iter++)
{
countString.setNum(count);
QString port;
port.setNum((*iter).port);
settings.setValue(QString("PEER_AET" + countString), QString::fromStdString((*iter).title));
settings.setValue(QString("PEER_IP" + countString), QString::fromStdString((*iter).ip));
settings.setValue(QString("PEER_PORT" + countString), port);
count++;
}
// remove all items coming after the last one
countString.setNum(count);
while (settings.contains(QString("PEER_IP" + countString)))
{
settings.remove(QString("PEER_AET" + countString));
settings.remove(QString("PEER_IP" + countString));
settings.remove(QString("PEER_PORT" + countString));
}
settings.endGroup();
break;
case 1:
settings.beginGroup("Connection");
settings.setValue("OUR_AET", ui->ourTitleEdit->text());
settings.setValue("OUR_IP", ui->ourIPEdit->text());
settings.setValue("OUR_PORT", ui->ourPortEdit->text());
settings.endGroup();
break;
case 2:
settings.beginGroup("Server");
settings.setValue("ARCHIVE_DIR", ui->diredit2->text());
settings.endGroup();
break;
default:
std::cout << "switch error" << std::endl;
break;
}
}
//---------------------------------------------------------------------------------------------
void SimpleView::retrieveSettings()
{
QString ourTitle, ourIP, ourPort;
QString peerTitle, peerIP, peerPort;
QString archiveDir;
int count = 0;
QString countString;
countString.setNum(count);
QSettings settings("INRIA", "DCMTKTOOL");
settings.beginGroup("Connection");
while (settings.contains(QString("PEER_IP" + countString)))
{
peerTitle = settings.value("PEER_AET" + countString).value<QString>();
peerIP = settings.value("PEER_IP" + countString).value<QString>();
peerPort = settings.value("PEER_PORT" + countString).value<QString>();
this->addConnection(peerTitle, peerIP, peerPort);
count++;
countString.setNum(count);
}
ourTitle = settings.value("OUR_AET").value<QString>();
ourIP = settings.value("OUR_IP").value<QString>();
ourPort = settings.value("OUR_PORT").value<QString>();
settings.endGroup();
settings.beginGroup("Server");
archiveDir = settings.value("ARCHIVE_DIR").value<QString>();
settings.endGroup();
ui->peerTitleEdit->setText(peerTitle);
ui->peerIPEdit->setText(peerIP);
ui->peerPortEdit->setText(peerPort);
// apply only if none-empty
if(!ourTitle.isEmpty()) ui->ourTitleEdit->setText(ourTitle);
if(!ourIP.isEmpty()) ui->ourIPEdit->setText(ourIP);
if(!ourPort.isEmpty()) ui->ourPortEdit->setText(ourPort);
if(!archiveDir.isEmpty())
{
ui->diredit2->setText(archiveDir);
updateServerDir();
}
}
//---------------------------------------------------------------------------------------------
void SimpleView::fileAppender(int state)
{
switch(state)
{
case 0:
BaseLogger::removeOutput(m_fileOut);
break;
case 2:
BaseLogger::addOutput(m_fileOut);
break;
default:
std::cout << "switch error" << std::endl;
break;
}
}
//---------------------------------------------------------------------------------------------
void SimpleView::shellAppender(int state)
{
switch(state)
{
case 0:
BaseLogger::removeOutput(m_shellOut);
break;
case 2:
BaseLogger::addOutput(m_shellOut);
break;
default:
std::cout << "switch error" << std::endl;
break;
}
}
//---------------------------------------------------------------------------------------------
void SimpleView::widgetAppender(int state)
{
switch(state)
{
case 0:
BaseLogger::removeOutput(m_widgetOut);
break;
case 2:
BaseLogger::addOutput(m_widgetOut);
break;
default:
std::cout << "switch error" << std::endl;
break;
}
}
//---------------------------------------------------------------------------------------------
void SimpleView::startServer()
{
ui->logWindow->append(tr("Server started."));
m_serverThread->start();
}
//---------------------------------------------------------------------------------------------
void SimpleView::stopServer()
{
if (m_serverThread->isRunning())
{
m_serverThread->stopService();
m_serverThread->exit();
m_serverThread->wait();
}
ui->logWindow->append(tr("Server stopped."));
}
//---------------------------------------------------------------------------------------------
void SimpleView::restartServer()
{
stopServer();
startServer();
}
//---------------------------------------------------------------------------------------------
void SimpleView::quit()
{
qApp->quit();
}
//---------------------------------------------------------------------------------------------
void SimpleView::addConn()
{
if (ui->addButton->text() == "Add")
{
addConnection(ui->peerTitleEdit->text(), ui->peerIPEdit->text(), ui->peerPortEdit->text());
}
else
{
removeConnection(ui->connTableWidget->currentRow());
}
storeSettings(0);
}
//---------------------------------------------------------------------------------------------
void SimpleView::addConnection(QString peer, QString ip, QString port)
{
int row = ui->connTableWidget->rowCount();
ui->connTableWidget->insertRow(row);
ui->connTableWidget->setColumnCount(3);
ui->connTableWidget->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
QStringList horHeaders;
horHeaders << "AET" << "IP" << "PORT";
ui->connTableWidget->setHorizontalHeaderLabels(horHeaders);
QTableWidgetItem *aetItem = new QTableWidgetItem(peer);
ui->connTableWidget->setItem(row, 0, aetItem);
QTableWidgetItem *ipItem = new QTableWidgetItem(ip);
ui->connTableWidget->setItem(row, 1, ipItem);
QTableWidgetItem *portItem = new QTableWidgetItem(port);
ui->connTableWidget->setItem(row, 2, portItem);
dcmtkConnectionData cdata;
cdata.title = peer.toStdString();
cdata.ip = ip.toStdString();
cdata.port = port.toInt();
m_nodes.push_back(cdata);
QListWidgetItem* myItem = new QListWidgetItem(peer,ui->nodeSelectionLW);
myItem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
myItem->setCheckState(Qt::Unchecked);
// add available dicom nodes to cb, for the moment only one..
ui->sendToNodeCB->addItem(peer);
}
//---------------------------------------------------------------------------------------------
void SimpleView::removeConnection(int index)
{
ui->connTableWidget->removeRow(index);
m_nodes.erase(m_nodes.begin()+index);
ui->nodeSelectionLW->takeItem(index);
ui->sendToNodeCB->removeItem(index);
}
//---------------------------------------------------------------------------------------------
void SimpleView::handleConnSelection()
{
int row = this->ui->connTableWidget->currentRow();
if ( row < (int)m_nodes.size())
{
ui->peerTitleEdit->setText(QString::fromStdString(m_nodes.at(row).title));
ui->peerIPEdit->setText(QString::fromStdString(m_nodes.at(row).ip));
QString mystring;
ui->peerPortEdit->setText(mystring.setNum(m_nodes.at(row).port));
}
//change add button to remove
ui->addButton->setText("Remove");
}
//---------------------------------------------------------------------------------------------
void SimpleView::inputChanged()
{
ui->addButton->setText("Add");
}
//---------------------------------------------------------------------------------------------
dcmtkContainer<dcmtkNode*>* SimpleView::getSelectedNodes()
{
//build selected node container
dcmtkContainer<dcmtkNode*>* selectedNodes = new dcmtkContainer<dcmtkNode*>;
for(int i=0; i < ui->nodeSelectionLW->count(); i++)
{
QListWidgetItem *item = ui->nodeSelectionLW->item(i);
if( item->checkState() == Qt::Checked)
{
dcmtkNode* node = new dcmtkNode;
node->setTitle(m_nodes.at(i).title);
node->setIp(m_nodes.at(i).ip);
node->setPort(m_nodes.at(i).port);
selectedNodes->add(node);
}
}
return selectedNodes;
}
//---------------------------------------------------------------------------------------------
void SimpleView::printResults(int sum, const char* type)
{
QString number;
number.setNum(sum);
QString stype = type;
ui->logWindow->append(number + " " + stype + " found.");
}
//---------------------------------------------------------------------------------------------
void SimpleView::fillTreeStudy()
{
QString patientName = ui->searchField->text();
patientName.append("*");
// now extract information from datasets and build a visual list
int sum = 0;
ui->treeWidget->clear();
dcmtkContainer<dcmtkNode*>* resNodeCont = m_findScu->getNodeContainer();
dcmtkNode* myNode = resNodeCont->getFirst();
while (resNodeCont->isValid())
{
dcmtkContainer<dcmtkResultDataset*>* resCont = myNode->getResultDatasetContainer();
dcmtkResultDataset* resDs = resCont->getFirst();
// add the root node containing the name of the DICOM NODE
QTreeWidgetItem *topLevelItem = new QTreeWidgetItem();
ui->treeWidget->addTopLevelItem(topLevelItem);
topLevelItem->setData(0,Qt::UserRole, resNodeCont->index()); //node index
topLevelItem->setData(1,Qt::UserRole, QPoint(0x0010,0x0010)); // tag
topLevelItem->setData(2,Qt::UserRole, patientName); // search value
topLevelItem->setText(0,myNode->title().c_str());
while ( resCont->isValid())
{
// add result to list
QTreeWidgetItem *pItem = new QTreeWidgetItem(topLevelItem);
pItem->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator);
pItem->setData(0,Qt::UserRole, resNodeCont->index()); //node index
pItem->setData(1,Qt::UserRole, QPoint(0x0020,0x000D)); // tag
pItem->setData(2,Qt::UserRole, QString(resDs->getStudyInstanceUID())); // search value
pItem->setText(0,resDs->findKeyValue(0x0010,0x0010)); // patient name
ui->treeWidget->insertTopLevelItem(0,pItem);
resDs = resCont->getNext();
}
sum = sum + resCont->size();
myNode = resNodeCont->getNext();
topLevelItem->setExpanded(true);
}
// print to logwindow
printResults(sum,"studies");
}
//---------------------------------------------------------------------------------------------
void SimpleView::setArchiveDirectory()
{
QDir selDir;
QFileDialog dialog(this);
dialog.setFileMode(QFileDialog::DirectoryOnly);
if (dialog.exec())
{
selDir = dialog.directory();
this->ui->diredit2->setText(selDir.path());
updateServerDir();
}
}
//---------------------------------------------------------------------------------------------
void SimpleView::updateServerDir()
{
m_serverThread->setStorageDirectory(ui->diredit2->text().latin1());
restartServer();
storeSettings(2);
}
//---------------------------------------------------------------------------------------------
Fixing a problem retrieving lists of studies
#include "ui_SimpleView.h"
#include "SimpleView.h"
// Qt
#include <QSettings>
#include <QDockWidget>
#include <QFileDialog>
#include <QProgressDialog>
// dicom net
#include "dcmtkEchoScu.h"
#include "dcmtkFindScu.h"
#include "dcmtkMoveScu.h"
#include "dcmtkStoreScp.h"
#include "dcmtkStoreScu.h"
#include "dcmtkResultDataset.h"
// logger
#include "dcmtkLogger.h"
#include "LoggerFileOutput.h"
#include "LoggerConsoleOutput.h"
#include "LoggerWidgetOutput.h"
#include "LoggerWidget.h"
// utilities
#include "dcmtkDump.h"
#include <sstream>
//---------------------------------------------------------------------------------------------
// Constructor
SimpleView::SimpleView()
{
//initialize logger
dcmtkLogger::startUp();
// create and show LoggerWidget
this->ui = new Ui_SimpleView;
this->ui->setupUi(this);
QStringList labels;
labels << "Patient name" << "Description" << "ID/Number" << "Modality/Type";
ui->treeWidget->setHeaderLabels(labels);
ui->treeWidget->setHeaderHidden(false);
m_echoScu = new dcmtkEchoScu();
m_findScu = new dcmtkFindScu();
m_serverThread = new dcmtkStoreScp();
m_sendThread = new dcmtkStoreScu();
m_moveThread = new dcmtkMoveScu();
m_shellOut = new LoggerConsoleOutput();
m_fileOut = new LoggerFileOutput();
m_loggerWidget = new LoggerWidget(this);
m_widgetOut = new LoggerWidgetOutput(m_loggerWidget);
connect(this->ui->actionExit, SIGNAL(triggered()), this, SLOT(quit()));
connect(this->ui->searchField, SIGNAL(returnPressed()), this, SLOT(findStudyLevel()));
connect(this->ui->treeWidget, SIGNAL(itemDoubleClicked ( QTreeWidgetItem* , int )), this, SLOT(move(QTreeWidgetItem *, int)));
connect(this->ui->treeWidget, SIGNAL(itemExpanded ( QTreeWidgetItem* )), this, SLOT(findSeriesLevel(QTreeWidgetItem *)));
connect(this->ui->echoButton, SIGNAL(clicked()), this, SLOT(echo()));
connect(this->ui->applySettingsButton, SIGNAL(clicked()), this, SLOT(applySettingsSlot()));
connect(this->ui->cbFileTarget, SIGNAL(stateChanged(int)), this, SLOT(fileAppender(int)));
connect(this->ui->cbShellTarget, SIGNAL(stateChanged(int)), this, SLOT(shellAppender(int)));
connect(this->ui->cbWidgetTarget, SIGNAL(stateChanged(int)), this, SLOT(widgetAppender(int)));
connect(this->ui->cbLogLevel, SIGNAL(currentIndexChanged(int)), this, SLOT(changeLogLevel(int)));
connect(this->ui->serverRestartButton, SIGNAL(clicked()), this, SLOT(restartServer()));
connect(this->ui->dirButton, SIGNAL(clicked()),this,SLOT(setSendDirectory()));
connect(this->ui->dirbutton2, SIGNAL(clicked()), this, SLOT(setArchiveDirectory()));
connect(this->ui->diredit2, SIGNAL(editingFinished()), this, SLOT(updateServerDir()));
connect(this->ui->sendButton, SIGNAL(clicked()),this,SLOT(store()));
connect(this->ui->addButton, SIGNAL(clicked()), this, SLOT(addConn()));
connect(this->ui->connTableWidget, SIGNAL(itemSelectionChanged()), this, SLOT(handleConnSelection()));
connect(this->ui->peerTitleEdit, SIGNAL(textChanged(QString)), this, SLOT(inputChanged()));
connect(this->ui->peerIPEdit, SIGNAL(textChanged(QString)), this, SLOT(inputChanged()));
connect(this->ui->peerPortEdit, SIGNAL(textChanged(QString)), this, SLOT(inputChanged()));
connect(m_findScu,SIGNAL(finished()), this, SLOT(fillTreeStudy()));
retrieveSettings();
setConnectionParams();
//set logger defaults
ui->cbWidgetTarget->setChecked(true);
ui->cbLogLevel->setCurrentIndex(2);
QDockWidget* loggerDock = new QDockWidget(this);
loggerDock->setWidget(m_loggerWidget);
this->addDockWidget(Qt::BottomDockWidgetArea, loggerDock);
// start the threaded server
startServer();
};
//---------------------------------------------------------------------------------------------
SimpleView::~SimpleView()
{
dcmtkLogger::shutDown();
stopServer();
delete m_findScu;
delete m_echoScu;
delete m_sendThread;
delete m_moveThread;
delete m_shellOut;
delete m_fileOut;
delete m_widgetOut;
if(ui != NULL) delete ui;
}
//---------------------------------------------------------------------------------------------
void SimpleView::changeLogLevel(int index)
{
LoggerLogLevel::LogLevel logLevel;
switch(index)
{
case 0:
logLevel = LoggerLogLevel::NOLOG;
break;
case 1:
logLevel = LoggerLogLevel::ERRORLOG;
break;
case 2:
logLevel = LoggerLogLevel::WARNINGLOG;
break;
case 3:
logLevel = LoggerLogLevel::INFOLOG;
break;
case 4:
logLevel = LoggerLogLevel::DEBUGLOG;
break;
default:
logLevel = LoggerLogLevel::INFOLOG;
break;
}
m_fileOut->setLogLevel(logLevel);
m_shellOut->setLogLevel(logLevel);
m_widgetOut->setLogLevel(logLevel);
}
//---------------------------------------------------------------------------------------------
void SimpleView::setConnectionParams()
{
m_ourTitle = ui->ourTitleEdit->text().toStdString();
m_ourIP = ui->ourIPEdit->text().toStdString();
m_peerTitle = ui->peerTitleEdit->text().toStdString();
m_peerIP = ui->peerIPEdit->text().toStdString();
try
{
m_peerPort = ui->peerPortEdit->text().toInt();
}
catch(...)
{
ui->peerPortEdit->setText("");
}
try
{
m_ourPort = ui->ourPortEdit->text().toInt();
}
catch(...)
{
ui->ourPortEdit->setText("9999");
}
m_echoScu->setConnectionParams(m_peerTitle.c_str(), m_peerIP.c_str(), m_peerPort, m_ourTitle.c_str(), m_ourIP.c_str(), m_ourPort);
m_serverThread->setConnectionParams(m_ourTitle.c_str(), m_ourIP.c_str(), m_ourPort);
}
//---------------------------------------------------------------------------------------------
// Action to be taken upon file open
void SimpleView::findStudyLevel()
{
// get selected nodes
dcmtkContainer<dcmtkNode*>* selectedNodes = getSelectedNodes();
QString patientName = ui->searchField->text();
patientName.append("*");
// clear previous results
m_findScu->clearAllQueryAttributes();
// set up search criteria
m_findScu->setQueryLevel(dcmtkFindScu::STUDY);
m_findScu->addQueryAttribute(0x0010,0x0010,patientName.toLatin1()); // patient name
m_findScu->addQueryAttribute(0x0008,0x0030,"\0"); // study date
m_findScu->addQueryAttribute(0x0008,0x0050,"\0"); // accession no
m_findScu->addQueryAttribute(0x0008,0x0061,"\0"); // modalities in study
m_findScu->addQueryAttribute(0x0008,0x0090,"\0"); // ref physician
m_findScu->addQueryAttribute(0x0008,0x1030,"\0"); // study description
m_findScu->addQueryAttribute(0x0010,0x0020,"\0"); // patient ID
m_findScu->addQueryAttribute(0x0010,0x0030,"\0"); // patient BD
m_findScu->addQueryAttribute(0x0010,0x0040,"\0"); // sex
m_findScu->addQueryAttribute(0x0020,0x000D,"\0"); // studyInstanceUID
m_findScu->addQueryAttribute(0x0020,0x0010,"\0"); // study ID
// we repeat the find process with the data from all selected nodes
dcmtkNode* selNode = selectedNodes->getFirst();
while (selectedNodes->isValid())
{
QProgressDialog* progress = new QProgressDialog("Looking for images...", "Cancel", 0, 100);
progress->setWindowModality(Qt::WindowModal);
connect(m_findScu,SIGNAL(progressed(int)), progress,SLOT(setValue(int)));
connect(progress,SIGNAL(canceled()),m_findScu,SLOT(sendCancelRequest()));
progress->show();
progress->repaint();
// do the work
m_findScu->wait();
m_findScu->setConnectionParams(selNode->title().c_str(),selNode->ip().c_str(),selNode->port(),m_ourTitle.c_str(), m_ourIP.c_str(), m_ourPort);
m_findScu->start();
selNode = selectedNodes->getNext();
}
// clean up
delete selectedNodes;
}
//---------------------------------------------------------------------------------------------
void SimpleView::findSeriesLevel(QTreeWidgetItem * item)
{
// check if its a top level item
if (item->parent() != NULL)
{
if (item->parent()->parent() != NULL)
{
findImageLevel(item); // forward to image level
return;
}
} else return;
// check if the item alread has children (don't query again)
if (item->child(0) != NULL) return;
// retrieve data
int nodeIndex = item->data(0,Qt::UserRole).toInt();
QPoint tag = item->data(1,Qt::UserRole).toPoint();
QString searchStr = item->data(2,Qt::UserRole).toString();
dcmtkContainer<dcmtkNode*>* mainNodeCont = m_findScu->getNodeContainer();
dcmtkConnectionData cdata;
dcmtkNode* node = mainNodeCont->getAtPos(nodeIndex);
cdata.title = node->title();
cdata.ip = node->ip();
cdata.port = node->port();
// clear previous results
dcmtkFindScu* findScu = new dcmtkFindScu;
// set up search criteria
findScu->setQueryLevel(dcmtkFindScu::SERIES);
findScu->addQueryAttribute(tag.x(),tag.y(),searchStr.toLatin1()); // studyInstanceUID
findScu->addQueryAttribute(0x0008,0x0021,"\0"); // series date
findScu->addQueryAttribute(0x0008,0x0031,"\0"); // series time
findScu->addQueryAttribute(0x0008,0x0060,"\0"); // series modality
findScu->addQueryAttribute(0x0008,0x103E,"\0"); // series description
findScu->addQueryAttribute(0x0018,0x0015,"\0"); // body part
findScu->addQueryAttribute(0x0018,0x1030,"\0"); // protocol name
findScu->addQueryAttribute(0x0018,0x5100,"\0"); // patient position
findScu->addQueryAttribute(0x0020,0x000E,"\0"); // series instance UID
findScu->addQueryAttribute(0x0020,0x0011,"\0"); // series number
findScu->addQueryAttribute(0x0020,0x0052,"\0"); // frame of reference
// do the work
findScu->sendFindRequest(cdata.title.c_str(),cdata.ip.c_str(),cdata.port,m_ourTitle.c_str(), m_ourIP.c_str(), m_ourPort);
// now extract information from datasets and build a visual list
int sum = 0;
dcmtkContainer<dcmtkNode*>* resNodeCont = findScu->getNodeContainer();
dcmtkNode* myNode = resNodeCont->getFirst();
if (resNodeCont->isValid())
{
dcmtkContainer<dcmtkResultDataset*>* resCont = myNode->getResultDatasetContainer();
dcmtkResultDataset* resDs = resCont->getFirst();
while (resCont->isValid())
{
// add result to list
QTreeWidgetItem *pItem = new QTreeWidgetItem(item);
pItem->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator);
pItem->setData(0,Qt::UserRole, nodeIndex); //forwarding node index
pItem->setData(1,Qt::UserRole, QPoint(0x0020,0x000E)); // tag
pItem->setData(2,Qt::UserRole, QString(resDs->getSeriesInstanceUID())); // search value
pItem->setText(0,">>");
pItem->setText(1,resDs->findKeyValue(0x0008,0x103E));
pItem->setText(2,resDs->findKeyValue(0x0020,0x0011)); // series number
item->addChild(pItem);
resDs = resCont->getNext();
}
sum = resCont->size();
myNode = resNodeCont->getNext();
}
// print to logwindow
printResults(sum,"series");
// clean up
delete findScu;
}
//---------------------------------------------------------------------------------------------
void SimpleView::findImageLevel(QTreeWidgetItem * item)
{
// check if the item already has children (don't query again)
if (item->child(0) != NULL) return;
// retrieve data
int nodeIndex = item->data(0,Qt::UserRole).toInt(); // node index
QString searchStr = item->data(2,Qt::UserRole).toString(); // search value
dcmtkContainer<dcmtkNode*>* mainNodeCont = m_findScu->getNodeContainer();
dcmtkConnectionData cdata;
dcmtkNode* myNode = mainNodeCont->getAtPos(nodeIndex);
cdata.title = myNode->title();
cdata.ip = myNode->ip();
cdata.port = myNode->port();
// clear previous results
dcmtkFindScu* findScu = new dcmtkFindScu;
// set up search criteria
findScu->setQueryLevel(dcmtkFindScu::IMAGE);
findScu->addQueryAttribute(0x0020,0x000E,searchStr.toLatin1()); // series instance UID
findScu->addQueryAttribute(0x0008,0x0008,"\0"); // image type
findScu->addQueryAttribute(0x0008,0x0012,"\0"); // instance creation date
findScu->addQueryAttribute(0x0008,0x0013,"\0"); // instance creation time
findScu->addQueryAttribute(0x0008,0x0016,"\0"); // SOP class UID
findScu->addQueryAttribute(0x0008,0x0018,"\0"); // SOP instance UID
findScu->addQueryAttribute(0x0008,0x0022,"\0"); // image date
findScu->addQueryAttribute(0x0008,0x0032,"\0"); // image time
findScu->addQueryAttribute(0x0020,0x0012,"\0"); // acquisition number
findScu->addQueryAttribute(0x0020,0x000D,"\0"); // study instance UID
findScu->addQueryAttribute(0x0020,0x0013,"\0"); // instance time
findScu->addQueryAttribute(0x0020,0x0032,"\0"); // image position patient
findScu->addQueryAttribute(0x0020,0x0037,"\0"); // image orientation patient
findScu->addQueryAttribute(0x0020,0x1041,"\0"); // slice location
findScu->addQueryAttribute(0x0028,0x0008,"\0"); // number of frames
// do the work
findScu->sendFindRequest(cdata.title.c_str(),cdata.ip.c_str(),cdata.port,m_ourTitle.c_str(), m_ourIP.c_str(), m_ourPort);
// now extract information from datasets and build a visual list
int sum = 0;
dcmtkContainer<dcmtkNode*>* resNodeCont = findScu->getNodeContainer();
dcmtkNode* node = resNodeCont->getFirst();
if (resNodeCont->isValid())
{
dcmtkContainer<dcmtkResultDataset*>* resCont = node->getResultDatasetContainer();
dcmtkResultDataset* resDs = resCont->getFirst();
while (resCont->isValid())
{
// add result to list
QTreeWidgetItem *pItem = new QTreeWidgetItem(item);
pItem->setData(0,Qt::UserRole, nodeIndex); //forwarding node index
pItem->setData(1,Qt::UserRole, QPoint(0x0008,0x0018)); // tag
pItem->setData(2,Qt::UserRole, QString(resDs->getSOPInstanceUID())); // search value
pItem->setText(0,">>");
pItem->setText(2,resDs->findKeyValue(0x0020,0x0012)); // aqu. number
pItem->setText(3,resDs->findKeyValue(0x0008,0x0008)); // image type
item->addChild(pItem);
resDs = resCont->getNext();
}
sum = resCont->size();
}
// print to logwindow
printResults(sum,"images");
// clean up
delete findScu;
}
//---------------------------------------------------------------------------------------------
void SimpleView::move(QTreeWidgetItem * item, int column)
{
dcmtkContainer<dcmtkNode*>* mainNodeCont = m_findScu->getNodeContainer();
// retrieve data
int nodeIndex = item->data(0,Qt::UserRole).toInt();
QPoint tag = item->data(1,Qt::UserRole).toPoint();
QString searchStr = item->data(2,Qt::UserRole).toString();
ui->logWindow->append(tr("Fetching data..."));
ui->logWindow->repaint();
// set up search criteria
m_moveThread->clearAllQueryAttributes();
// find out which query level should be used
int elem = tag.y();
switch(elem)
{
case 0x0018:
m_moveThread->setQueryLevel(dcmtkMoveScu::IMAGE);
break;
case 0x000E:
m_moveThread->setQueryLevel(dcmtkMoveScu::SERIES);
break;
case 0x000D:
m_moveThread->setQueryLevel(dcmtkMoveScu::STUDY);
break;
default:
ui->logWindow->append(tr("Could not determine query level."));
}
m_moveThread->addQueryAttribute(tag.x(), tag.y(), searchStr.toLatin1());
// send the move request using the search crits
dcmtkNode* myNode = mainNodeCont->getAtPos(nodeIndex);
QProgressDialog* progress = new QProgressDialog("Fetching data...", "Cancel", 0, 100);
progress->setWindowModality(Qt::WindowModal);
connect(m_moveThread,SIGNAL(progressed(int)), progress,SLOT(setValue(int)));
connect(progress,SIGNAL(canceled()),m_moveThread,SLOT(sendCancelRequest()));
progress->show();
m_moveThread->setConnectionParams(myNode->title().c_str(),myNode->ip().c_str(),myNode->port(),m_ourTitle.c_str(), m_ourIP.c_str(), m_ourPort);
m_moveThread->start();
}
//---------------------------------------------------------------------------------------------
void SimpleView::echo()
{
// update params
setConnectionParams();
// now send the echo
if ( m_echoScu->sendEchoRequest() == 0 )
{
ui->logWindow->append(tr("Connection verified successfully"));
}
else
ui->logWindow->append(tr("No response from peer. Check your connection"));
}
//---------------------------------------------------------------------------------------------
void SimpleView::store()
{
// set the current node params first
dcmtkConnectionData* cb = &(m_nodes.at(ui->sendToNodeCB->currentIndex()));
m_sendThread->setConnectionParams(cb->title.c_str(), cb->ip.c_str(), cb->port, m_ourTitle.c_str(), m_ourIP.c_str(), m_ourPort);
QDir testDir;
testDir.setPath(ui->directoryLE->text());
if ( testDir.isReadable() )
{
m_sendThread->setScanDirectory(ui->directoryLE->text().toLatin1());
m_sendThread->start();
}
else
{
ui->logWindow->append("This is not a valid import directory!");
}
}
//---------------------------------------------------------------------------------------------
void SimpleView::setSendDirectory()
{
QDir selDir;
QFileDialog dialog(this);
dialog.setFileMode(QFileDialog::DirectoryOnly);
if (dialog.exec())
{
selDir = dialog.directory();
this->ui->directoryLE->setText(selDir.path());
}
}
//---------------------------------------------------------------------------------------------
void SimpleView::applySettingsSlot()
{
storeSettings(1);
setConnectionParams();
restartServer();
}
//---------------------------------------------------------------------------------------------
void SimpleView::storeSettings(int type)
{
QSettings settings("INRIA", "DCMTKTOOL");
std::vector<dcmtkConnectionData>::iterator iter;
int count = 0;
QString countString;
switch(type)
{
case 0:
settings.beginGroup("Connection");
for( iter = m_nodes.begin(); iter != m_nodes.end(); iter++)
{
countString.setNum(count);
QString port;
port.setNum((*iter).port);
settings.setValue(QString("PEER_AET" + countString), QString::fromStdString((*iter).title));
settings.setValue(QString("PEER_IP" + countString), QString::fromStdString((*iter).ip));
settings.setValue(QString("PEER_PORT" + countString), port);
count++;
}
// remove all items coming after the last one
countString.setNum(count);
while (settings.contains(QString("PEER_IP" + countString)))
{
settings.remove(QString("PEER_AET" + countString));
settings.remove(QString("PEER_IP" + countString));
settings.remove(QString("PEER_PORT" + countString));
}
settings.endGroup();
break;
case 1:
settings.beginGroup("Connection");
settings.setValue("OUR_AET", ui->ourTitleEdit->text());
settings.setValue("OUR_IP", ui->ourIPEdit->text());
settings.setValue("OUR_PORT", ui->ourPortEdit->text());
settings.endGroup();
break;
case 2:
settings.beginGroup("Server");
settings.setValue("ARCHIVE_DIR", ui->diredit2->text());
settings.endGroup();
break;
default:
std::cout << "switch error" << std::endl;
break;
}
}
//---------------------------------------------------------------------------------------------
void SimpleView::retrieveSettings()
{
QString ourTitle, ourIP, ourPort;
QString peerTitle, peerIP, peerPort;
QString archiveDir;
int count = 0;
QString countString;
countString.setNum(count);
QSettings settings("INRIA", "DCMTKTOOL");
settings.beginGroup("Connection");
while (settings.contains(QString("PEER_IP" + countString)))
{
peerTitle = settings.value("PEER_AET" + countString).value<QString>();
peerIP = settings.value("PEER_IP" + countString).value<QString>();
peerPort = settings.value("PEER_PORT" + countString).value<QString>();
this->addConnection(peerTitle, peerIP, peerPort);
count++;
countString.setNum(count);
}
ourTitle = settings.value("OUR_AET").value<QString>();
ourIP = settings.value("OUR_IP").value<QString>();
ourPort = settings.value("OUR_PORT").value<QString>();
settings.endGroup();
settings.beginGroup("Server");
archiveDir = settings.value("ARCHIVE_DIR").value<QString>();
settings.endGroup();
ui->peerTitleEdit->setText(peerTitle);
ui->peerIPEdit->setText(peerIP);
ui->peerPortEdit->setText(peerPort);
// apply only if none-empty
if(!ourTitle.isEmpty()) ui->ourTitleEdit->setText(ourTitle);
if(!ourIP.isEmpty()) ui->ourIPEdit->setText(ourIP);
if(!ourPort.isEmpty()) ui->ourPortEdit->setText(ourPort);
if(!archiveDir.isEmpty())
{
ui->diredit2->setText(archiveDir);
updateServerDir();
}
}
//---------------------------------------------------------------------------------------------
void SimpleView::fileAppender(int state)
{
switch(state)
{
case 0:
BaseLogger::removeOutput(m_fileOut);
break;
case 2:
BaseLogger::addOutput(m_fileOut);
break;
default:
std::cout << "switch error" << std::endl;
break;
}
}
//---------------------------------------------------------------------------------------------
void SimpleView::shellAppender(int state)
{
switch(state)
{
case 0:
BaseLogger::removeOutput(m_shellOut);
break;
case 2:
BaseLogger::addOutput(m_shellOut);
break;
default:
std::cout << "switch error" << std::endl;
break;
}
}
//---------------------------------------------------------------------------------------------
void SimpleView::widgetAppender(int state)
{
switch(state)
{
case 0:
BaseLogger::removeOutput(m_widgetOut);
break;
case 2:
BaseLogger::addOutput(m_widgetOut);
break;
default:
std::cout << "switch error" << std::endl;
break;
}
}
//---------------------------------------------------------------------------------------------
void SimpleView::startServer()
{
ui->logWindow->append(tr("Server started."));
m_serverThread->start();
}
//---------------------------------------------------------------------------------------------
void SimpleView::stopServer()
{
if (m_serverThread->isRunning())
{
m_serverThread->stopService();
m_serverThread->exit();
m_serverThread->wait();
}
ui->logWindow->append(tr("Server stopped."));
}
//---------------------------------------------------------------------------------------------
void SimpleView::restartServer()
{
stopServer();
startServer();
}
//---------------------------------------------------------------------------------------------
void SimpleView::quit()
{
qApp->quit();
}
//---------------------------------------------------------------------------------------------
void SimpleView::addConn()
{
if (ui->addButton->text() == "Add")
{
addConnection(ui->peerTitleEdit->text(), ui->peerIPEdit->text(), ui->peerPortEdit->text());
}
else
{
removeConnection(ui->connTableWidget->currentRow());
}
storeSettings(0);
}
//---------------------------------------------------------------------------------------------
void SimpleView::addConnection(QString peer, QString ip, QString port)
{
int row = ui->connTableWidget->rowCount();
ui->connTableWidget->insertRow(row);
ui->connTableWidget->setColumnCount(3);
ui->connTableWidget->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
QStringList horHeaders;
horHeaders << "AET" << "IP" << "PORT";
ui->connTableWidget->setHorizontalHeaderLabels(horHeaders);
QTableWidgetItem *aetItem = new QTableWidgetItem(peer);
ui->connTableWidget->setItem(row, 0, aetItem);
QTableWidgetItem *ipItem = new QTableWidgetItem(ip);
ui->connTableWidget->setItem(row, 1, ipItem);
QTableWidgetItem *portItem = new QTableWidgetItem(port);
ui->connTableWidget->setItem(row, 2, portItem);
dcmtkConnectionData cdata;
cdata.title = peer.toStdString();
cdata.ip = ip.toStdString();
cdata.port = port.toInt();
m_nodes.push_back(cdata);
QListWidgetItem* myItem = new QListWidgetItem(peer,ui->nodeSelectionLW);
myItem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
myItem->setCheckState(Qt::Unchecked);
// add available dicom nodes to cb, for the moment only one..
ui->sendToNodeCB->addItem(peer);
}
//---------------------------------------------------------------------------------------------
void SimpleView::removeConnection(int index)
{
ui->connTableWidget->removeRow(index);
m_nodes.erase(m_nodes.begin()+index);
ui->nodeSelectionLW->takeItem(index);
ui->sendToNodeCB->removeItem(index);
}
//---------------------------------------------------------------------------------------------
void SimpleView::handleConnSelection()
{
int row = this->ui->connTableWidget->currentRow();
if ( row < (int)m_nodes.size())
{
ui->peerTitleEdit->setText(QString::fromStdString(m_nodes.at(row).title));
ui->peerIPEdit->setText(QString::fromStdString(m_nodes.at(row).ip));
QString mystring;
ui->peerPortEdit->setText(mystring.setNum(m_nodes.at(row).port));
}
//change add button to remove
ui->addButton->setText("Remove");
}
//---------------------------------------------------------------------------------------------
void SimpleView::inputChanged()
{
ui->addButton->setText("Add");
}
//---------------------------------------------------------------------------------------------
dcmtkContainer<dcmtkNode*>* SimpleView::getSelectedNodes()
{
//build selected node container
dcmtkContainer<dcmtkNode*>* selectedNodes = new dcmtkContainer<dcmtkNode*>;
for(int i=0; i < ui->nodeSelectionLW->count(); i++)
{
QListWidgetItem *item = ui->nodeSelectionLW->item(i);
if( item->checkState() == Qt::Checked)
{
dcmtkNode* node = new dcmtkNode;
node->setTitle(m_nodes.at(i).title);
node->setIp(m_nodes.at(i).ip);
node->setPort(m_nodes.at(i).port);
selectedNodes->add(node);
}
}
return selectedNodes;
}
//---------------------------------------------------------------------------------------------
void SimpleView::printResults(int sum, const char* type)
{
QString number;
number.setNum(sum);
QString stype = type;
ui->logWindow->append(number + " " + stype + " found.");
}
//---------------------------------------------------------------------------------------------
void SimpleView::fillTreeStudy()
{
QString concatStudInstUID;
// now extract information from datasets and build a visual list
int sum = 0;
ui->treeWidget->clear();
dcmtkContainer<dcmtkNode*>* resNodeCont = m_findScu->getNodeContainer();
dcmtkNode* myNode = resNodeCont->getFirst();
while (resNodeCont->isValid())
{
dcmtkContainer<dcmtkResultDataset*>* resCont = myNode->getResultDatasetContainer();
dcmtkResultDataset* resDs = resCont->getFirst();
// add the root node containing the name of the DICOM NODE
QTreeWidgetItem *topLevelItem = new QTreeWidgetItem();
ui->treeWidget->addTopLevelItem(topLevelItem);
topLevelItem->setText(0,myNode->title().c_str());
while ( resCont->isValid())
{
// add result to list
QTreeWidgetItem *pItem = new QTreeWidgetItem(topLevelItem);
pItem->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator);
pItem->setData(0,Qt::UserRole, resNodeCont->index()); //node index
pItem->setData(1,Qt::UserRole, QPoint(0x0020,0x000D)); // tag
pItem->setData(2,Qt::UserRole, QString(resDs->getStudyInstanceUID())); // search value
pItem->setText(0,resDs->findKeyValue(0x0010,0x0010)); // patient name
ui->treeWidget->insertTopLevelItem(0,pItem);
// concatenate all studyInstUIDs belonging to this node
concatStudInstUID = QString(resDs->getStudyInstanceUID()) +"\\"+ concatStudInstUID;
resDs = resCont->getNext();
}
// now we add the list of studies to the top-level-item
topLevelItem->setData(0,Qt::UserRole, resNodeCont->index()); //node index
topLevelItem->setData(1,Qt::UserRole, QPoint(0x0020,0x0020)); // tag (studyInstanceUID)
topLevelItem->setData(2,Qt::UserRole, concatStudInstUID); // search value
topLevelItem->setExpanded(true);
sum = sum + resCont->size();
myNode = resNodeCont->getNext();
}
// print to logwindow
printResults(sum,"studies");
}
//---------------------------------------------------------------------------------------------
void SimpleView::setArchiveDirectory()
{
QDir selDir;
QFileDialog dialog(this);
dialog.setFileMode(QFileDialog::DirectoryOnly);
if (dialog.exec())
{
selDir = dialog.directory();
this->ui->diredit2->setText(selDir.path());
updateServerDir();
}
}
//---------------------------------------------------------------------------------------------
void SimpleView::updateServerDir()
{
m_serverThread->setStorageDirectory(ui->diredit2->text().latin1());
restartServer();
storeSettings(2);
}
//---------------------------------------------------------------------------------------------
|
/*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include <sys/types.h>
#include <net/ethernet.h>
#include <boost/uuid/uuid_io.hpp>
#include "base/logging.h"
#include "db/db.h"
#include "db/db_entry.h"
#include "db/db_table.h"
#include "ifmap/ifmap_node.h"
#include "net/address_util.h"
#include <cfg/cfg_init.h>
#include <cfg/cfg_interface.h>
#include <cmn/agent.h>
#include <init/agent_param.h>
#include <oper/operdb_init.h>
#include <oper/ifmap_dependency_manager.h>
#include <oper/config_manager.h>
#include <oper/route_common.h>
#include <oper/vm.h>
#include <oper/vn.h>
#include <oper/vrf.h>
#include <oper/nexthop.h>
#include <oper/mpls.h>
#include <oper/mirror_table.h>
#include <oper/interface_common.h>
#include <oper/vrf_assign.h>
#include <oper/vxlan.h>
#include <oper/oper_dhcp_options.h>
#include <oper/inet_unicast_route.h>
#include <oper/physical_device_vn.h>
#include <oper/ifmap_dependency_manager.h>
#include <bgp_schema_types.h>
#include <vnc_cfg_types.h>
#include <oper/agent_sandesh.h>
#include <oper/sg.h>
#include "sandesh/sandesh_trace.h"
#include "sandesh/common/vns_types.h"
#include "sandesh/common/vns_constants.h"
#include <filter/acl.h>
using namespace std;
using namespace boost::uuids;
using namespace autogen;
VmInterface::VmInterface(const boost::uuids::uuid &uuid) :
Interface(Interface::VM_INTERFACE, uuid, "", NULL), vm_(NULL),
vn_(NULL), primary_ip_addr_(0), mdata_addr_(0), subnet_bcast_addr_(0),
primary_ip6_addr_(), vm_mac_(""), policy_enabled_(false),
mirror_entry_(NULL), mirror_direction_(MIRROR_RX_TX), cfg_name_(""),
fabric_port_(true), need_linklocal_ip_(false), dhcp_enable_(true),
do_dhcp_relay_(false), vm_name_(),
vm_project_uuid_(nil_uuid()), vxlan_id_(0), bridging_(true),
layer3_forwarding_(true), flood_unknown_unicast_(false),
mac_set_(false), ecmp_(false),
tx_vlan_id_(kInvalidVlanId), rx_vlan_id_(kInvalidVlanId), parent_(NULL),
local_preference_(VmInterface::INVALID), oper_dhcp_options_(),
sg_list_(), floating_ip_list_(), service_vlan_list_(), static_route_list_(),
allowed_address_pair_list_(), vrf_assign_rule_list_(),
vrf_assign_acl_(NULL), vm_ip_gw_addr_(0), vm_ip6_gw_addr_(),
device_type_(VmInterface::DEVICE_TYPE_INVALID),
vmi_type_(VmInterface::VMI_TYPE_INVALID),
configurer_(0), subnet_(0), subnet_plen_(0), ethernet_tag_(0),
logical_interface_(nil_uuid()), nova_ip_addr_(0), nova_ip6_addr_(),
dhcp_addr_(0) {
ipv4_active_ = false;
ipv6_active_ = false;
l2_active_ = false;
}
VmInterface::VmInterface(const boost::uuids::uuid &uuid,
const std::string &name,
const Ip4Address &addr, const std::string &mac,
const std::string &vm_name,
const boost::uuids::uuid &vm_project_uuid,
uint16_t tx_vlan_id, uint16_t rx_vlan_id,
Interface *parent, const Ip6Address &a6,
DeviceType device_type, VmiType vmi_type) :
Interface(Interface::VM_INTERFACE, uuid, name, NULL), vm_(NULL),
vn_(NULL), primary_ip_addr_(addr), mdata_addr_(0), subnet_bcast_addr_(0),
primary_ip6_addr_(a6), vm_mac_(mac), policy_enabled_(false),
mirror_entry_(NULL), mirror_direction_(MIRROR_RX_TX), cfg_name_(""),
fabric_port_(true), need_linklocal_ip_(false), dhcp_enable_(true),
do_dhcp_relay_(false), vm_name_(vm_name),
vm_project_uuid_(vm_project_uuid), vxlan_id_(0),
bridging_(true), layer3_forwarding_(true),
flood_unknown_unicast_(false), mac_set_(false),
ecmp_(false), tx_vlan_id_(tx_vlan_id), rx_vlan_id_(rx_vlan_id),
parent_(parent), local_preference_(VmInterface::INVALID), oper_dhcp_options_(),
sg_list_(), floating_ip_list_(), service_vlan_list_(), static_route_list_(),
allowed_address_pair_list_(), vrf_assign_rule_list_(),
vrf_assign_acl_(NULL), device_type_(device_type),
vmi_type_(vmi_type), configurer_(0), subnet_(0),
subnet_plen_(0), ethernet_tag_(0), logical_interface_(nil_uuid()),
nova_ip_addr_(0), nova_ip6_addr_(), dhcp_addr_(0) {
ipv4_active_ = false;
ipv6_active_ = false;
l2_active_ = false;
}
VmInterface::~VmInterface() {
}
bool VmInterface::CmpInterface(const DBEntry &rhs) const {
const VmInterface &intf=static_cast<const VmInterface &>(rhs);
return uuid_ < intf.uuid_;
}
/////////////////////////////////////////////////////////////////////////////
// Template function to audit two lists. This is used to synchronize the
// operational and config list for Floating-IP, Service-Vlans, Static Routes
// and SG List
/////////////////////////////////////////////////////////////////////////////
template<class List, class Iterator>
bool AuditList(List &list, Iterator old_first, Iterator old_last,
Iterator new_first, Iterator new_last) {
bool ret = false;
Iterator old_iterator = old_first;
Iterator new_iterator = new_first;
while (old_iterator != old_last && new_iterator != new_last) {
if (old_iterator->IsLess(new_iterator.operator->())) {
Iterator bkp = old_iterator++;
list.Remove(bkp);
ret = true;
} else if (new_iterator->IsLess(old_iterator.operator->())) {
Iterator bkp = new_iterator++;
list.Insert(bkp.operator->());
ret = true;
} else {
Iterator old_bkp = old_iterator++;
Iterator new_bkp = new_iterator++;
list.Update(old_bkp.operator->(), new_bkp.operator->());
ret = true;
}
}
while (old_iterator != old_last) {
Iterator bkp = old_iterator++;
list.Remove(bkp);
ret = true;
}
while (new_iterator != new_last) {
Iterator bkp = new_iterator++;
list.Insert(bkp.operator->());
ret = true;
}
return ret;
}
// Build one Floating IP entry for a virtual-machine-interface
static void BuildFloatingIpList(Agent *agent, VmInterfaceConfigData *data,
IFMapNode *node) {
ConfigManager *cfg_manager= agent->config_manager();
if (cfg_manager->SkipNode(node)) {
return;
}
// Find VRF for the floating-ip. Following path in graphs leads to VRF
// virtual-machine-port <-> floating-ip <-> floating-ip-pool
// <-> virtual-network <-> routing-instance
IFMapAgentTable *fip_table = static_cast<IFMapAgentTable *>(node->table());
DBGraph *fip_graph = fip_table->GetGraph();
// Iterate thru links for floating-ip looking for floating-ip-pool node
for (DBGraphVertex::adjacency_iterator fip_iter = node->begin(fip_graph);
fip_iter != node->end(fip_graph); ++fip_iter) {
IFMapNode *pool_node = static_cast<IFMapNode *>(fip_iter.operator->());
if (cfg_manager->SkipNode
(pool_node, agent->cfg()->cfg_floatingip_pool_table())) {
continue;
}
// Iterate thru links for floating-ip-pool looking for virtual-network
IFMapAgentTable *pool_table =
static_cast<IFMapAgentTable *> (pool_node->table());
DBGraph *pool_graph = pool_table->GetGraph();
for (DBGraphVertex::adjacency_iterator pool_iter =
pool_node->begin(pool_graph);
pool_iter != pool_node->end(pool_graph); ++pool_iter) {
IFMapNode *vn_node =
static_cast<IFMapNode *>(pool_iter.operator->());
if (cfg_manager->SkipNode
(vn_node, agent->cfg()->cfg_vn_table())) {
continue;
}
VirtualNetwork *cfg = static_cast <VirtualNetwork *>
(vn_node->GetObject());
assert(cfg);
autogen::IdPermsType id_perms = cfg->id_perms();
boost::uuids::uuid vn_uuid;
CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong,
vn_uuid);
IFMapAgentTable *vn_table =
static_cast<IFMapAgentTable *> (vn_node->table());
DBGraph *vn_graph = vn_table->GetGraph();
// Iterate thru links for virtual-network looking for
// routing-instance
for (DBGraphVertex::adjacency_iterator vn_iter =
vn_node->begin(vn_graph);
vn_iter != vn_node->end(vn_graph); ++vn_iter) {
IFMapNode *vrf_node =
static_cast<IFMapNode *>(vn_iter.operator->());
if (cfg_manager->SkipNode
(vrf_node, agent->cfg()->cfg_vrf_table())){
continue;
}
// Checking whether it is default vrf of not
RoutingInstance *ri = static_cast<RoutingInstance *>(vrf_node->GetObject());
if(!(ri->is_default())) {
continue;
}
FloatingIp *fip = static_cast<FloatingIp *>(node->GetObject());
assert(fip != NULL);
LOG(DEBUG, "Add FloatingIP <" << fip->address() << ":" <<
vrf_node->name() << "> to interface " << node->name());
boost::system::error_code ec;
IpAddress addr = IpAddress::from_string(fip->address(), ec);
if (ec.value() != 0) {
LOG(DEBUG, "Error decoding Floating IP address "
<< fip->address());
} else {
IpAddress fixed_ip_addr =
IpAddress::from_string(fip->fixed_ip_address(), ec);
if (ec.value() != 0) {
fixed_ip_addr = Ip4Address(0);
}
data->floating_ip_list_.list_.insert
(VmInterface::FloatingIp(addr, vrf_node->name(),
vn_uuid, fixed_ip_addr));
if (addr.is_v4()) {
data->floating_ip_list_.v4_count_++;
} else {
data->floating_ip_list_.v6_count_++;
}
}
break;
}
break;
}
break;
}
return;
}
// Build list of static-routes on virtual-machine-interface
static void BuildStaticRouteList(VmInterfaceConfigData *data, IFMapNode *node) {
InterfaceRouteTable *entry =
static_cast<InterfaceRouteTable*>(node->GetObject());
assert(entry);
for (std::vector<RouteType>::const_iterator it = entry->routes().begin();
it != entry->routes().end(); it++) {
int plen;
boost::system::error_code ec;
IpAddress ip;
bool add = false;
Ip4Address ip4;
ec = Ip4PrefixParse(it->prefix, &ip4, &plen);
if (ec.value() == 0) {
ip = ip4;
add = true;
} else {
Ip6Address ip6;
ec = Inet6PrefixParse(it->prefix, &ip6, &plen);
if (ec.value() == 0) {
ip = ip6;
add = true;
} else {
LOG(DEBUG, "Error decoding v4/v6 Static Route address " << it->prefix);
}
}
IpAddress gw = IpAddress::from_string(it->next_hop, ec);
if (ec) {
gw = IpAddress::from_string("0.0.0.0", ec);
}
if (add) {
data->static_route_list_.list_.insert
(VmInterface::StaticRoute(data->vrf_name_, ip, plen, gw));
}
}
}
static void BuildResolveRoute(VmInterfaceConfigData *data, IFMapNode *node) {
Subnet *entry =
static_cast<Subnet *>(node->GetObject());
assert(entry);
Ip4Address ip;
boost::system::error_code ec;
ip = Ip4Address::from_string(entry->ip_prefix().ip_prefix, ec);
if (ec.value() == 0) {
data->subnet_ = ip;
data->subnet_plen_ = entry->ip_prefix().ip_prefix_len;
}
}
static void BuildAllowedAddressPairRouteList(VirtualMachineInterface *cfg,
VmInterfaceConfigData *data) {
for (std::vector<AllowedAddressPair>::const_iterator it =
cfg->allowed_address_pairs().begin();
it != cfg->allowed_address_pairs().end(); ++it) {
boost::system::error_code ec;
int plen = it->ip.ip_prefix_len;
Ip4Address ip = Ip4Address::from_string(it->ip.ip_prefix, ec);
if (ec.value() != 0) {
continue;
}
MacAddress mac = MacAddress::FromString(it->mac, &ec);
if (ec.value() != 0) {
mac.Zero();
}
if (ip.is_unspecified() && mac == MacAddress::kZeroMac) {
continue;
}
bool ecmp = false;
if (it->address_mode == "active-active") {
ecmp = true;
}
VmInterface::AllowedAddressPair entry(data->vrf_name_, ip, plen,
ecmp, mac);
data->allowed_address_pair_list_.list_.insert(entry);
}
}
// Build VM Interface VRF or one Service Vlan entry for VM Interface
static void BuildVrfAndServiceVlanInfo(Agent *agent,
VmInterfaceConfigData *data,
IFMapNode *node) {
ConfigManager *cfg_manager= agent->config_manager();
VirtualMachineInterfaceRoutingInstance *entry =
static_cast<VirtualMachineInterfaceRoutingInstance*>(node->GetObject());
assert(entry);
// Ignore node if direction is not yet set. An update will come later
const PolicyBasedForwardingRuleType &rule = entry->data();
if (rule.direction == "") {
return;
}
// Find VRF by looking for link
// virtual-machine-interface-routing-instance <-> routing-instance
IFMapAgentTable *table = static_cast<IFMapAgentTable *>(node->table());
DBGraph *graph = table->GetGraph();
// Iterate thru links looking for routing-instance node
for (DBGraphVertex::adjacency_iterator iter = node->begin(graph);
iter != node->end(graph); ++iter) {
IFMapNode *vrf_node = static_cast<IFMapNode *>(iter.operator->());
if (cfg_manager->SkipNode
(vrf_node, agent->cfg()->cfg_vrf_table())) {
continue;
}
if (rule.vlan_tag == 0 && rule.protocol == ""
&& rule.service_chain_address == "") {
data->vrf_name_ = vrf_node->name();
} else {
boost::system::error_code ec;
Ip4Address addr = Ip4Address::from_string
(rule.service_chain_address, ec);
if (ec.value() != 0) {
LOG(DEBUG, "Error decoding Service VLAN IP address "
<< rule.service_chain_address);
break;
}
if (rule.vlan_tag > 4093) {
LOG(DEBUG, "Invalid VLAN Tag " << rule.vlan_tag);
break;
}
LOG(DEBUG, "Add Service VLAN entry <" << rule.vlan_tag << " : "
<< rule.service_chain_address << " : " << vrf_node->name());
MacAddress smac(agent->vrrp_mac());
MacAddress dmac = MacAddress::FromString(Agent::BcastMac());
if (rule.src_mac != Agent::NullString()) {
smac = MacAddress::FromString(rule.src_mac);
}
if (rule.src_mac != Agent::NullString()) {
dmac = MacAddress::FromString(rule.dst_mac);
}
data->service_vlan_list_.list_.insert
(VmInterface::ServiceVlan(rule.vlan_tag, vrf_node->name(), addr,
32, smac, dmac));
}
break;
}
return;
}
static void BuildInstanceIp(Agent *agent, VmInterfaceConfigData *data,
IFMapNode *node) {
InstanceIp *ip = static_cast<InstanceIp *>(node->GetObject());
boost::system::error_code err;
IpAddress addr = IpAddress::from_string(ip->address(), err);
bool is_primary = false;
if (ip->secondary() != true) {
is_primary = true;
if (addr.is_v4()) {
if (data->addr_ == Ip4Address(0) ||
data->addr_ > addr.to_v4()) {
data->addr_ = addr.to_v4();
if (ip->mode() == "active-active") {
data->ecmp_ = true;
} else {
data->ecmp_ = false;
}
}
} else if (addr.is_v6()) {
if (data->ip6_addr_ == Ip6Address() ||
data->ip6_addr_ > addr.to_v6()) {
data->ip6_addr_ = addr.to_v6();
}
if (ip->mode() == "active-active") {
data->ecmp_ = true;
} else {
data->ecmp_ = false;
}
}
}
bool ecmp = false;
if (ip->mode() == "active-active") {
ecmp = true;
}
if (addr.is_v4()) {
data->instance_ipv4_list_.list_.insert(
VmInterface::InstanceIp(addr, ecmp, is_primary));
} else {
data->instance_ipv6_list_.list_.insert(
VmInterface::InstanceIp(addr, ecmp, is_primary));
}
}
static void BuildSgList(VmInterfaceConfigData *data, IFMapNode *node) {
SecurityGroup *sg_cfg = static_cast<SecurityGroup *>
(node->GetObject());
assert(sg_cfg);
autogen::IdPermsType id_perms = sg_cfg->id_perms();
uint32_t sg_id = SgTable::kInvalidSgId;
stringToInteger(sg_cfg->id(), sg_id);
if (sg_id != SgTable::kInvalidSgId) {
uuid sg_uuid = nil_uuid();
CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong,
sg_uuid);
data->sg_list_.list_.insert
(VmInterface::SecurityGroupEntry(sg_uuid));
}
}
static void BuildVn(VmInterfaceConfigData *data, IFMapNode *node,
const boost::uuids::uuid &u, CfgIntEntry *cfg_entry) {
VirtualNetwork *vn = static_cast<VirtualNetwork *>
(node->GetObject());
assert(vn);
autogen::IdPermsType id_perms = vn->id_perms();
CfgUuidSet(id_perms.uuid.uuid_mslong,
id_perms.uuid.uuid_lslong, data->vn_uuid_);
if (cfg_entry && (cfg_entry->GetVnUuid() != data->vn_uuid_)) {
IFMAP_ERROR(InterfaceConfiguration,
"Virtual-network UUID mismatch for interface:",
UuidToString(u),
"configuration VN uuid",
UuidToString(data->vn_uuid_),
"compute VN uuid",
UuidToString(cfg_entry->GetVnUuid()));
}
}
static void BuildVm(VmInterfaceConfigData *data, IFMapNode *node,
const boost::uuids::uuid &u, CfgIntEntry *cfg_entry) {
VirtualMachine *vm = static_cast<VirtualMachine *>
(node->GetObject());
assert(vm);
autogen::IdPermsType id_perms = vm->id_perms();
CfgUuidSet(id_perms.uuid.uuid_mslong,
id_perms.uuid.uuid_lslong, data->vm_uuid_);
if (cfg_entry && (cfg_entry->GetVmUuid() != data->vm_uuid_)) {
IFMAP_ERROR(InterfaceConfiguration,
"Virtual-machine UUID mismatch for interface:",
UuidToString(u),
"configuration VM UUID is",
UuidToString(data->vm_uuid_),
"compute VM uuid is",
UuidToString(cfg_entry->GetVnUuid()));
}
}
// Get DHCP configuration
static void ReadDhcpOptions(VirtualMachineInterface *cfg,
VmInterfaceConfigData &data) {
data.oper_dhcp_options_.set_options(cfg->dhcp_option_list());
data.oper_dhcp_options_.set_host_routes(cfg->host_routes());
}
// Get interface mirror configuration.
static void ReadAnalyzerNameAndCreate(Agent *agent,
VirtualMachineInterface *cfg,
VmInterfaceConfigData &data) {
if (!cfg) {
return;
}
MirrorActionType mirror_to = cfg->properties().interface_mirror.mirror_to;
if (!mirror_to.analyzer_name.empty()) {
boost::system::error_code ec;
IpAddress dip = IpAddress::from_string(mirror_to.analyzer_ip_address,
ec);
if (ec.value() != 0) {
return;
}
uint16_t dport;
if (mirror_to.udp_port) {
dport = mirror_to.udp_port;
} else {
dport = ContrailPorts::AnalyzerUdpPort();
}
agent->mirror_table()->AddMirrorEntry
(mirror_to.analyzer_name, std::string(), agent->router_id(),
agent->mirror_port(), dip.to_v4(), dport);
data.analyzer_name_ = mirror_to.analyzer_name;
string traffic_direction =
cfg->properties().interface_mirror.traffic_direction;
if (traffic_direction.compare("egress") == 0) {
data.mirror_direction_ = Interface::MIRROR_TX;
} else if (traffic_direction.compare("ingress") == 0) {
data.mirror_direction_ = Interface::MIRROR_RX;
} else {
data.mirror_direction_ = Interface::MIRROR_RX_TX;
}
}
}
static void BuildVrfAssignRule(VirtualMachineInterface *cfg,
VmInterfaceConfigData *data) {
uint32_t id = 1;
for (std::vector<VrfAssignRuleType>::const_iterator iter =
cfg->vrf_assign_table().begin(); iter != cfg->vrf_assign_table().end();
++iter) {
VmInterface::VrfAssignRule entry(id++, iter->match_condition,
iter->routing_instance,
iter->ignore_acl);
data->vrf_assign_rule_list_.list_.insert(entry);
}
}
static IFMapNode *FindTarget(IFMapAgentTable *table, IFMapNode *node,
const std::string &node_type) {
for (DBGraphVertex::adjacency_iterator it = node->begin(table->GetGraph());
it != node->end(table->GetGraph()); ++it) {
IFMapNode *adj_node = static_cast<IFMapNode *>(it.operator->());
if (adj_node->table()->Typename() == node_type)
return adj_node;
}
return NULL;
}
static void ReadDhcpEnable(Agent *agent, VmInterfaceConfigData *data,
IFMapNode *node) {
IFMapAgentTable *table = static_cast<IFMapAgentTable *>(node->table());
for (DBGraphVertex::adjacency_iterator it = node->begin(table->GetGraph());
it != node->end(table->GetGraph()); ++it) {
IFMapNode *adj_node = static_cast<IFMapNode *>(it.operator->());
IFMapNode *ipam_node = NULL;
if (adj_node->table() == agent->cfg()->cfg_vn_network_ipam_table() &&
(ipam_node = FindTarget(table, adj_node, "network-ipam"))) {
VirtualNetworkNetworkIpam *ipam =
static_cast<VirtualNetworkNetworkIpam *>(adj_node->GetObject());
assert(ipam);
const VnSubnetsType &subnets = ipam->data();
boost::system::error_code ec;
for (unsigned int i = 0; i < subnets.ipam_subnets.size(); ++i) {
if (IsIp4SubnetMember(data->addr_,
Ip4Address::from_string(
subnets.ipam_subnets[i].subnet.ip_prefix, ec),
subnets.ipam_subnets[i].subnet.ip_prefix_len)) {
data->dhcp_enable_ = subnets.ipam_subnets[i].enable_dhcp;
return;
}
}
}
}
}
// Check if VMI is a sub-interface. Sub-interface will have
// sub_interface_vlan_tag property set to non-zero
static bool IsVlanSubInterface(VirtualMachineInterface *cfg) {
if (cfg->IsPropertySet(VirtualMachineInterface::PROPERTIES) == false)
return false;
if (cfg->properties().sub_interface_vlan_tag == 0)
return false;
return true;
}
// Builds parent for VMI (not to be confused with parent ifmap-node)
// Possible values are,
// - logical-interface : Incase of baremetals
// - virtual-machine-interface : We support virtual-machine-interface
// sub-interfaces. In this case, another virtual-machine-interface itself
// can be a parent
static PhysicalRouter *BuildParentInfo(Agent *agent,
VmInterfaceConfigData *data,
VirtualMachineInterface *cfg,
IFMapNode *node,
IFMapNode *logical_node,
IFMapNode *parent_vmi_node) {
if (logical_node) {
IFMapNode *physical_node = agent->config_manager()->
FindAdjacentIFMapNode(logical_node, "physical-interface");
agent->interface_table()->
LogicalInterfaceIFNodeToUuid(logical_node, data->logical_interface_);
// Find phyiscal-interface for the VMI
IFMapNode *prouter_node = NULL;
if (physical_node) {
data->physical_interface_ = physical_node->name();
// Find vrouter for the physical interface
prouter_node = agent->config_manager()->
FindAdjacentIFMapNode(physical_node, "physical-router");
}
if (prouter_node == NULL)
return NULL;
return static_cast<PhysicalRouter *>(prouter_node->GetObject());
}
// Check if this is VLAN sub-interface VMI
if (IsVlanSubInterface(cfg) == false) {
return NULL;
}
if (parent_vmi_node == false)
return NULL;
// process Parent VMI for sub-interface
VirtualMachineInterface *parent_cfg =
static_cast <VirtualMachineInterface *> (parent_vmi_node->GetObject());
assert(parent_cfg);
if (IsVlanSubInterface(parent_cfg)) {
return NULL;
}
autogen::IdPermsType id_perms = parent_cfg->id_perms();
CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong,
data->parent_vmi_);
data->rx_vlan_id_ = cfg->properties().sub_interface_vlan_tag;
data->tx_vlan_id_ = cfg->properties().sub_interface_vlan_tag;
return NULL;
}
static void BuildAttributes(Agent *agent, IFMapNode *node,
VirtualMachineInterface *cfg,
VmInterfaceConfigData *data) {
//Extract the local preference
if (cfg->IsPropertySet(VirtualMachineInterface::PROPERTIES)) {
autogen::VirtualMachineInterfacePropertiesType prop = cfg->properties();
//Service instance also would have VirtualMachineInterface
//properties field set, pick up local preference
//value only when it has been initialized to proper
//value, if its 0, ignore the local preference
if (prop.local_preference) {
data->local_preference_ = VmInterface::LOW;
if (prop.local_preference == VmInterface::HIGH) {
data->local_preference_ = VmInterface::HIGH;
}
}
}
ReadAnalyzerNameAndCreate(agent, cfg, *data);
// Fill DHCP option data
ReadDhcpOptions(cfg, *data);
//Fill config data items
data->cfg_name_ = node->name();
data->admin_state_ = cfg->id_perms().enable;
BuildVrfAssignRule(cfg, data);
BuildAllowedAddressPairRouteList(cfg, data);
if (cfg->mac_addresses().size()) {
data->vm_mac_ = cfg->mac_addresses().at(0);
}
}
static void UpdateAttributes(Agent *agent, VmInterfaceConfigData *data) {
// Compute fabric_port_ and need_linklocal_ip_ flags
data->fabric_port_ = false;
data->need_linklocal_ip_ = true;
if (data->vrf_name_ == agent->fabric_vrf_name() ||
data->vrf_name_ == agent->linklocal_vrf_name()) {
data->fabric_port_ = true;
data->need_linklocal_ip_ = false;
}
if (agent->isXenMode()) {
data->need_linklocal_ip_ = false;
}
}
static void ComputeTypeInfo(Agent *agent, VmInterfaceConfigData *data,
CfgIntEntry *cfg_entry, PhysicalRouter *prouter,
IFMapNode *node, IFMapNode *logical_node) {
if (cfg_entry != NULL) {
// Have got InstancePortAdd message. Treat it as VM_ON_TAP by default
// TODO: Need to identify more cases here
data->device_type_ = VmInterface::VM_ON_TAP;
data->vmi_type_ = VmInterface::INSTANCE;
return;
}
data->device_type_ = VmInterface::DEVICE_TYPE_INVALID;
data->vmi_type_ = VmInterface::VMI_TYPE_INVALID;
// Does it have physical-interface
if (data->physical_interface_.empty() == false) {
// no physical-router connected. Should be transient case
if (prouter == NULL) {
// HACK : TSN/ToR agent only supports barements. So, set as
// baremetal anyway
if (agent->tsn_enabled() || agent->tor_agent_enabled()) {
data->device_type_ = VmInterface::TOR;
data->vmi_type_ = VmInterface::BAREMETAL;
}
return;
}
// VMI is either Baremetal or Gateway interface
if (prouter->display_name() == agent->agent_name()) {
// VMI connected to local vrouter. Treat it as GATEWAY
data->device_type_ = VmInterface::LOCAL_DEVICE;
data->vmi_type_ = VmInterface::GATEWAY;
if (logical_node) {
autogen::LogicalInterface *port =
static_cast <autogen::LogicalInterface *>
(logical_node->GetObject());
if (port->vlan_tag()) {
data->rx_vlan_id_ = port->vlan_tag();
data->tx_vlan_id_ = port->vlan_tag();
}
}
return;
} else {
// prouter does not match. Treat as baremetal
data->device_type_ = VmInterface::TOR;
data->vmi_type_ = VmInterface::BAREMETAL;
return;
}
return;
}
// Physical router not specified. Check if this is VMI sub-interface
if (data->parent_vmi_.is_nil() == false) {
data->device_type_ = VmInterface::VM_VLAN_ON_VMI;
data->vmi_type_ = VmInterface::INSTANCE;
return;
}
return;
}
void VmInterface::SetConfigurer(VmInterface::Configurer type) {
configurer_ |= (1 << type);
}
void VmInterface::ResetConfigurer(VmInterface::Configurer type) {
configurer_ &= ~(1 << type);
}
bool VmInterface::IsConfigurerSet(VmInterface::Configurer type) {
return ((configurer_ & (1 << type)) != 0);
}
static bool DeleteVmi(InterfaceTable *table, const uuid &u, DBRequest *req) {
int type = table->GetVmiToVmiType(u);
if (type <= (int)VmInterface::VMI_TYPE_INVALID)
return false;
table->DelVmiToVmiType(u);
// Process delete based on VmiType
if (type == VmInterface::INSTANCE) {
// INSTANCE type are not added by config. We only do RESYNC
req->oper = DBRequest::DB_ENTRY_ADD_CHANGE;
req->key.reset(new VmInterfaceKey(AgentKey::RESYNC, u, ""));
req->data.reset(new VmInterfaceConfigData(NULL, NULL));
return true;
} else {
VmInterface::Delete(table, u, VmInterface::CONFIG);
return false;
}
}
bool InterfaceTable::VmiIFNodeToUuid(IFMapNode *node, boost::uuids::uuid &u) {
VirtualMachineInterface *cfg = static_cast <VirtualMachineInterface *>
(node->GetObject());
autogen::IdPermsType id_perms = cfg->id_perms();
CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong, u);
return true;
}
// Virtual Machine Interface is added or deleted into oper DB from Nova
// messages. The Config notify is used only to change interface.
extern IFMapNode *vn_test_node;
extern IFMapNode *vmi_test_node;
bool InterfaceTable::VmiProcessConfig(IFMapNode *node, DBRequest &req,
const boost::uuids::uuid &u) {
// Get interface UUID
VirtualMachineInterface *cfg = static_cast <VirtualMachineInterface *>
(node->GetObject());
assert(cfg);
// Handle object delete
if (node->IsDeleted()) {
return false;
}
assert(!u.is_nil());
// Get the entry from Interface Config table
CfgIntTable *cfg_table = agent_->interface_config_table();
CfgIntKey cfg_key(u);
CfgIntEntry *cfg_entry =
static_cast <CfgIntEntry *>(cfg_table->Find(&cfg_key));
// Update interface configuration
req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;
VmInterfaceConfigData *data = new VmInterfaceConfigData(agent(), NULL);
data->SetIFMapNode(node);
BuildAttributes(agent_, node, cfg, data);
// Graph walk to get interface configuration
IFMapAgentTable *table = static_cast<IFMapAgentTable *>(node->table());
IFMapNode *vn_node = NULL;
IFMapNode *li_node = NULL;
IFMapNode *parent_vmi_node = NULL;
for (DBGraphVertex::adjacency_iterator iter =
node->begin(table->GetGraph());
iter != node->end(table->GetGraph()); ++iter) {
IFMapNode *adj_node = static_cast<IFMapNode *>(iter.operator->());
if (agent_->config_manager()->SkipNode(adj_node)) {
continue;
}
if (adj_node->table() == agent_->cfg()->cfg_sg_table()) {
BuildSgList(data, adj_node);
}
if (adj_node->table() == agent_->cfg()->cfg_vn_table()) {
vn_node = adj_node;
BuildVn(data, adj_node, u, cfg_entry);
}
if (adj_node->table() == agent_->cfg()->cfg_vm_table()) {
BuildVm(data, adj_node, u, cfg_entry);
}
if (adj_node->table() == agent_->cfg()->cfg_instanceip_table()) {
BuildInstanceIp(agent_, data, adj_node);
}
if (adj_node->table() == agent_->cfg()->cfg_floatingip_table()) {
BuildFloatingIpList(agent_, data, adj_node);
}
if (adj_node->table() == agent_->cfg()->cfg_vm_port_vrf_table()) {
BuildVrfAndServiceVlanInfo(agent_, data, adj_node);
}
if (adj_node->table() == agent_->cfg()->cfg_route_table()) {
BuildStaticRouteList(data, adj_node);
}
if (adj_node->table() == agent_->cfg()->cfg_subnet_table()) {
BuildResolveRoute(data, adj_node);
}
if (adj_node->table() == agent_->cfg()->cfg_logical_port_table()) {
li_node = adj_node;
}
if (adj_node->table() == agent_->cfg()->cfg_vm_interface_table()) {
parent_vmi_node = adj_node;
}
if (adj_node->table() == agent_->cfg()->cfg_logical_port_table()) {
li_node = adj_node;
}
if (adj_node->table() == agent_->cfg()->cfg_vm_interface_table()) {
parent_vmi_node = adj_node;
}
}
UpdateAttributes(agent_, data);
// Get DHCP enable flag from subnet
if (vn_node && data->addr_.to_ulong()) {
ReadDhcpEnable(agent_, data, vn_node);
}
PhysicalRouter *prouter = NULL;
// Build parent for the virtual-machine-interface
prouter = BuildParentInfo(agent_, data, cfg, node, li_node,
parent_vmi_node);
// Compute device-type and vmi-type for the interface
ComputeTypeInfo(agent_, data, cfg_entry, prouter, node, li_node);
InterfaceKey *key = NULL;
if (data->device_type_ == VmInterface::VM_ON_TAP ||
data->device_type_ == VmInterface::DEVICE_TYPE_INVALID) {
key = new VmInterfaceKey(AgentKey::RESYNC, u, "");
} else {
key = new VmInterfaceKey(AgentKey::ADD_DEL_CHANGE, u,
cfg->display_name());
}
if (data->device_type_ != VmInterface::DEVICE_TYPE_INVALID) {
AddVmiToVmiType(u, data->device_type_);
}
req.key.reset(key);
req.data.reset(data);
boost::uuids::uuid dev = nil_uuid();
if (prouter) {
autogen::IdPermsType id_perms = prouter->id_perms();
CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong, dev);
}
UpdatePhysicalDeviceVnEntry(u, dev, data->vn_uuid_, vn_node);
vmi_ifnode_to_req_++;
return true;
}
bool InterfaceTable::VmiIFNodeToReq(IFMapNode *node, DBRequest &req,
const boost::uuids::uuid &u) {
// Handle object delete
if ((req.oper == DBRequest::DB_ENTRY_DELETE) || node->IsDeleted()) {
DelPhysicalDeviceVnEntry(u);
return DeleteVmi(this, u, &req);
}
IFMapDependencyManager *dep = agent()->oper_db()->dependency_manager();
IFMapNodeState *state = dep->IFMapNodeGet(node);
IFMapDependencyManager::IFMapNodePtr vm_node_ref;
if (!state) {
vm_node_ref = dep->SetState(node);
state = dep->IFMapNodeGet(node);
}
if (state->uuid().is_nil())
state->set_uuid(u);
agent()->config_manager()->AddVmiNode(node);
return false;
}
/////////////////////////////////////////////////////////////////////////////
// Routines to manage VmiToPhysicalDeviceVnTree
/////////////////////////////////////////////////////////////////////////////
VmiToPhysicalDeviceVnData::VmiToPhysicalDeviceVnData
(const boost::uuids::uuid &dev, const boost::uuids::uuid &vn) :
dev_(dev), vn_(vn) {
}
VmiToPhysicalDeviceVnData::~VmiToPhysicalDeviceVnData() {
}
void InterfaceTable::UpdatePhysicalDeviceVnEntry(const boost::uuids::uuid &vmi,
boost::uuids::uuid &dev,
boost::uuids::uuid &vn,
IFMapNode *vn_node) {
VmiToPhysicalDeviceVnTree::iterator iter =
vmi_to_physical_device_vn_tree_.find(vmi);
if (iter == vmi_to_physical_device_vn_tree_.end()) {
vmi_to_physical_device_vn_tree_.insert
(make_pair(vmi,VmiToPhysicalDeviceVnData(nil_uuid(), nil_uuid())));
iter = vmi_to_physical_device_vn_tree_.find(vmi);
}
if (iter->second.dev_ != dev || iter->second.vn_ != vn) {
agent()->physical_device_vn_table()->DeleteConfigEntry
(vmi, iter->second.dev_, iter->second.vn_);
}
iter->second.dev_ = dev;
iter->second.vn_ = vn;
agent()->physical_device_vn_table()->AddConfigEntry(vmi, dev, vn);
}
void InterfaceTable::DelPhysicalDeviceVnEntry(const boost::uuids::uuid &vmi) {
VmiToPhysicalDeviceVnTree::iterator iter =
vmi_to_physical_device_vn_tree_.find(vmi);
if (iter == vmi_to_physical_device_vn_tree_.end())
return;
agent()->physical_device_vn_table()->DeleteConfigEntry
(vmi, iter->second.dev_, iter->second.vn_);
vmi_to_physical_device_vn_tree_.erase(iter);
}
/////////////////////////////////////////////////////////////////////////////
// VM Port Key routines
/////////////////////////////////////////////////////////////////////////////
VmInterfaceKey::VmInterfaceKey(AgentKey::DBSubOperation sub_op,
const boost::uuids::uuid &uuid, const std::string &name) :
InterfaceKey(sub_op, Interface::VM_INTERFACE, uuid, name, false) {
}
Interface *VmInterfaceKey::AllocEntry(const InterfaceTable *table) const {
return new VmInterface(uuid_);
}
Interface *VmInterfaceKey::AllocEntry(const InterfaceTable *table,
const InterfaceData *data) const {
const VmInterfaceData *vm_data =
static_cast<const VmInterfaceData *>(data);
VmInterface *vmi = vm_data->OnAdd(table, this);
return vmi;
}
InterfaceKey *VmInterfaceKey::Clone() const {
return new VmInterfaceKey(*this);
}
/////////////////////////////////////////////////////////////////////////////
// VM Port Entry routines
/////////////////////////////////////////////////////////////////////////////
string VmInterface::ToString() const {
return "VM-PORT <" + name() + ">";
}
DBEntryBase::KeyPtr VmInterface::GetDBRequestKey() const {
InterfaceKey *key = new VmInterfaceKey(AgentKey::ADD_DEL_CHANGE, uuid_,
name_);
return DBEntryBase::KeyPtr(key);
}
const Peer *VmInterface::peer() const {
return peer_.get();
}
bool VmInterface::OnChange(VmInterfaceData *data) {
InterfaceTable *table = static_cast<InterfaceTable *>(get_table());
return Resync(table, data);
}
// When VMInterface is added from Config (sub-interface, gateway interface etc.)
// the RESYNC is not called and some of the config like VN and VRF are not
// applied on the interface (See Add() API above). Force change to ensure
// RESYNC is called
void VmInterface::PostAdd() {
InterfaceTable *table = static_cast<InterfaceTable *>(get_table());
DBRequest req;
IFMapNode *node = ifmap_node();
if (node == NULL)
return;
boost::uuids::uuid u;
table->IFNodeToUuid(node, u);
if (table->IFNodeToReq(ifmap_node(), req, u) == true) {
table->Process(req);
}
}
// Handle RESYNC DB Request. Handles multiple sub-types,
// - CONFIG : RESYNC from config message
// - IP_ADDR: RESYNC due to learning IP from DHCP
// - MIRROR : RESYNC due to change in mirror config
bool VmInterface::Resync(const InterfaceTable *table,
const VmInterfaceData *data) {
bool ret = false;
// Copy old values used to update config below
bool old_ipv4_active = ipv4_active_;
bool old_ipv6_active = ipv6_active_;
bool old_l2_active = l2_active_;
bool old_policy = policy_enabled_;
VrfEntryRef old_vrf = vrf_;
Ip4Address old_addr = primary_ip_addr_;
Ip6Address old_v6_addr = primary_ip6_addr_;
bool old_need_linklocal_ip = need_linklocal_ip_;
bool force_update = false;
Ip4Address old_subnet = subnet_;
uint8_t old_subnet_plen = subnet_plen_;
int old_ethernet_tag = ethernet_tag_;
bool old_dhcp_enable = dhcp_enable_;
bool old_layer3_forwarding = layer3_forwarding_;
Ip4Address old_dhcp_addr = dhcp_addr_;
if (data) {
ret = data->OnResync(table, this, &force_update);
}
ipv4_active_ = IsIpv4Active();
ipv6_active_ = IsIpv6Active();
l2_active_ = IsL2Active();
if (ipv4_active_ != old_ipv4_active) {
InterfaceTable *intf_table = static_cast<InterfaceTable *>(get_table());
if (ipv4_active_)
intf_table->incr_active_vmi_count();
else
intf_table->decr_active_vmi_count();
ret = true;
}
if (ipv6_active_ != old_ipv6_active) {
ret = true;
}
if (l2_active_ != old_l2_active) {
ret = true;
}
policy_enabled_ = PolicyEnabled();
if (policy_enabled_ != old_policy) {
ret = true;
}
// Apply config based on old and new values
ApplyConfig(old_ipv4_active, old_l2_active, old_policy, old_vrf.get(),
old_addr, old_ethernet_tag, old_need_linklocal_ip,
old_ipv6_active, old_v6_addr, old_subnet, old_subnet_plen,
old_dhcp_enable, old_layer3_forwarding, force_update,
old_dhcp_addr);
return ret;
}
void VmInterface::Add() {
peer_.reset(new LocalVmPortPeer(LOCAL_VM_PORT_PEER_NAME, id_));
}
bool VmInterface::Delete(const DBRequest *req) {
InterfaceTable *table = static_cast<InterfaceTable *>(get_table());
const VmInterfaceData *vm_data = static_cast<const VmInterfaceData *>
(req->data.get());
vm_data->OnDelete(table, this);
if (configurer_) {
return false;
}
table->DeleteDhcpSnoopEntry(name_);
return true;
}
void VmInterface::UpdateL3(bool old_ipv4_active, VrfEntry *old_vrf,
const Ip4Address &old_addr, int old_ethernet_tag,
bool force_update, bool policy_change,
bool old_ipv6_active,
const Ip6Address &old_v6_addr,
const Ip4Address &old_subnet,
const uint8_t old_subnet_plen,
const Ip4Address &old_dhcp_addr) {
UpdateL3NextHop(old_ipv4_active, old_ipv6_active);
UpdateL3TunnelId(force_update, policy_change);
if (ipv4_active_) {
if (do_dhcp_relay_) {
UpdateIpv4InterfaceRoute(old_ipv4_active, force_update,
policy_change,
old_vrf, old_dhcp_addr);
}
UpdateIpv4InstanceIp(force_update, policy_change, false, old_ethernet_tag);
UpdateMetadataRoute(old_ipv4_active, old_vrf);
UpdateFloatingIp(force_update, policy_change, false);
UpdateServiceVlan(force_update, policy_change);
UpdateAllowedAddressPair(force_update, policy_change, false,
false, false);
UpdateVrfAssignRule();
UpdateResolveRoute(old_ipv4_active, force_update, policy_change,
old_vrf, old_subnet, old_subnet_plen);
}
if (ipv6_active_) {
UpdateIpv6InstanceIp(force_update, policy_change, false, old_ethernet_tag);
}
UpdateStaticRoute(force_update, policy_change);
}
void VmInterface::DeleteL3(bool old_ipv4_active, VrfEntry *old_vrf,
const Ip4Address &old_addr,
bool old_need_linklocal_ip, bool old_ipv6_active,
const Ip6Address &old_v6_addr,
const Ip4Address &old_subnet,
const uint8_t old_subnet_plen,
int old_ethernet_tag,
const Ip4Address &old_dhcp_addr) {
if (old_ipv4_active) {
DeleteIpv4InstanceIp(false, old_ethernet_tag, old_vrf);
DeleteIpv4InstanceIp(true, old_ethernet_tag, old_vrf);
if (old_dhcp_addr != Ip4Address(0)) {
DeleteIpv4InterfaceRoute(old_vrf, old_dhcp_addr);
}
}
if (old_ipv6_active) {
DeleteIpv6InstanceIp(false, old_ethernet_tag, old_vrf);
DeleteIpv6InstanceIp(true, old_ethernet_tag, old_vrf);
}
DeleteMetadataRoute(old_ipv4_active, old_vrf, old_need_linklocal_ip);
DeleteFloatingIp(false, 0);
DeleteServiceVlan();
DeleteStaticRoute();
DeleteAllowedAddressPair(false);
DeleteL3TunnelId();
DeleteVrfAssignRule();
DeleteL3NextHop(old_ipv4_active, old_ipv6_active);
DeleteResolveRoute(old_vrf, old_subnet, old_subnet_plen);
}
void VmInterface::UpdateVxLan() {
int new_vxlan_id = vn_.get() ? vn_->GetVxLanId() : 0;
if (l2_active_ && ((vxlan_id_ == 0) ||
(vxlan_id_ != new_vxlan_id))) {
vxlan_id_ = new_vxlan_id;
}
ethernet_tag_ = IsVxlanMode() ? vxlan_id_ : 0;
}
void VmInterface::AddL2ReceiveRoute(bool old_l2_active) {
if (L2Activated(old_l2_active)) {
InterfaceTable *table = static_cast<InterfaceTable *>(get_table());
Agent *agent = table->agent();
BridgeAgentRouteTable *l2_table = static_cast<BridgeAgentRouteTable *>(
vrf_->GetRouteTable(Agent::BRIDGE));
l2_table->AddBridgeReceiveRoute(peer_.get(), vrf_->GetName(), 0,
GetVifMac(agent), vn_->GetName());
}
}
void VmInterface::UpdateL2(bool old_l2_active, VrfEntry *old_vrf,
int old_ethernet_tag,
bool force_update, bool policy_change,
const Ip4Address &old_v4_addr,
const Ip6Address &old_v6_addr,
bool old_layer3_forwarding) {
if (device_type() == VmInterface::TOR ||
device_type() == VmInterface::DEVICE_TYPE_INVALID)
return;
UpdateVxLan();
UpdateL2NextHop(old_l2_active);
//Update label only if new entry is to be created, so
//no force update on same.
UpdateL2TunnelId(false, policy_change);
UpdateL2InterfaceRoute(old_l2_active, force_update, old_vrf, Ip4Address(),
Ip6Address(), old_ethernet_tag,
old_layer3_forwarding, policy_change,
Ip4Address(), Ip6Address(),
MacAddress::FromString(vm_mac_),
Ip4Address(0));
UpdateIpv4InstanceIp(force_update, policy_change, true, old_ethernet_tag);
UpdateIpv6InstanceIp(force_update, policy_change, true, old_ethernet_tag);
UpdateFloatingIp(force_update, policy_change, true);
UpdateAllowedAddressPair(force_update, policy_change, true, old_l2_active,
old_layer3_forwarding);
//If the interface is Gateway we need to add a receive route,
//such the packet gets routed. Bridging on gateway
//interface is not supported
if (vmi_type() == GATEWAY && L2Activated(old_l2_active)) {
AddL2ReceiveRoute(old_l2_active);
}
}
void VmInterface::UpdateL2(bool force_update) {
UpdateL2(l2_active_, vrf_.get(), ethernet_tag_, force_update, false,
primary_ip_addr_, primary_ip6_addr_, layer3_forwarding_);
}
void VmInterface::DeleteL2(bool old_l2_active, VrfEntry *old_vrf,
int old_ethernet_tag,
const Ip4Address &old_v4_addr,
const Ip6Address &old_v6_addr,
bool old_layer3_forwarding) {
DeleteIpv4InstanceIp(true, old_ethernet_tag, old_vrf);
DeleteIpv6InstanceIp(true, old_ethernet_tag, old_vrf);
DeleteL2InterfaceRoute(old_l2_active, old_vrf, Ip4Address(0),
Ip6Address(), old_ethernet_tag,
MacAddress::FromString(vm_mac_));
DeleteL2TunnelId();
DeleteFloatingIp(true, old_ethernet_tag);
DeleteL2NextHop(old_l2_active);
DeleteL2ReceiveRoute(old_vrf, old_l2_active);
DeleteAllowedAddressPair(true);
}
const MacAddress& VmInterface::GetVifMac(const Agent *agent) const {
if (parent()) {
if (device_type_ == VM_VLAN_ON_VMI) {
const VmInterface *vmi =
static_cast<const VmInterface *>(parent_.get());
return vmi->GetVifMac(agent);
}
return parent()->mac();
} else {
return agent->vrrp_mac();
}
}
void VmInterface::ApplyConfigCommon(const VrfEntry *old_vrf,
bool old_l2_active,
bool old_dhcp_enable) {
//DHCP MAC IP binding
ApplyMacVmBindingConfig(old_vrf, old_l2_active, old_dhcp_enable);
//Security Group update
if (IsActive())
UpdateSecurityGroup();
else
DeleteSecurityGroup();
}
void VmInterface::ApplyMacVmBindingConfig(const VrfEntry *old_vrf,
bool old_l2_active,
bool old_dhcp_enable) {
//Update DHCP and DNS flag in Interface Class.
if (dhcp_enable_) {
dhcp_enabled_ = true;
dns_enabled_ = true;
} else {
dhcp_enabled_ = false;
dns_enabled_ = false;
}
if (L2Deactivated(old_l2_active)) {
DeleteMacVmBinding(old_vrf);
return;
}
//Interface has been activated or
//dhcp toggled for already activated interface
if (L2Activated(old_l2_active) ||
(l2_active_ && (old_dhcp_enable != dhcp_enable_))) {
UpdateMacVmBinding();
}
}
// Apply the latest configuration
void VmInterface::ApplyConfig(bool old_ipv4_active, bool old_l2_active, bool old_policy,
VrfEntry *old_vrf, const Ip4Address &old_addr,
int old_ethernet_tag, bool old_need_linklocal_ip,
bool old_ipv6_active,
const Ip6Address &old_v6_addr,
const Ip4Address &old_subnet,
uint8_t old_subnet_plen,
bool old_dhcp_enable,
bool old_layer3_forwarding,
bool force_update,
const Ip4Address &old_dhcp_addr) {
ApplyConfigCommon(old_vrf, old_l2_active, old_dhcp_enable);
//Need not apply config for TOR VMI as it is more of an inidicative
//interface. No route addition or NH addition happens for this interface.
//Also, when parent is not updated for a non-Nova interface, device type
//remains invalid.
if ((device_type_ == VmInterface::TOR ||
device_type_ == VmInterface::DEVICE_TYPE_INVALID) &&
(old_subnet.is_unspecified() && old_subnet_plen == 0)) {
return;
}
bool policy_change = (policy_enabled_ != old_policy);
if (ipv4_active_ == true || l2_active_ == true) {
UpdateMulticastNextHop(old_ipv4_active, old_l2_active);
} else {
DeleteMulticastNextHop();
}
if (vrf_ && vmi_type() == GATEWAY) {
vrf_->CreateTableLabel();
}
// Add/Del/Update L3
if ((ipv4_active_ || ipv6_active_) && layer3_forwarding_) {
UpdateL3(old_ipv4_active, old_vrf, old_addr, old_ethernet_tag, force_update,
policy_change, old_ipv6_active, old_v6_addr,
old_subnet, old_subnet_plen, old_dhcp_addr);
} else if ((old_ipv4_active || old_ipv6_active)) {
DeleteL3(old_ipv4_active, old_vrf, old_addr, old_need_linklocal_ip,
old_ipv6_active, old_v6_addr,
old_subnet, old_subnet_plen, old_ethernet_tag, old_dhcp_addr);
}
// Add/Del/Update L2
if (l2_active_ && bridging_) {
UpdateL2(old_l2_active, old_vrf, old_ethernet_tag,
force_update, policy_change, old_addr, old_v6_addr,
old_layer3_forwarding);
} else if (old_l2_active) {
DeleteL2(old_l2_active, old_vrf, old_ethernet_tag, old_addr, old_v6_addr,
old_layer3_forwarding);
}
UpdateFlowKeyNextHop();
// Remove floating-ip entries marked for deletion
CleanupFloatingIpList();
if (old_l2_active != l2_active_) {
if (l2_active_) {
SendTrace(ACTIVATED_L2);
} else {
SendTrace(DEACTIVATED_L2);
}
}
if (old_ipv4_active != ipv4_active_) {
if (ipv4_active_) {
SendTrace(ACTIVATED_IPV4);
} else {
SendTrace(DEACTIVATED_IPV4);
}
}
if (old_ipv6_active != ipv6_active_) {
if (ipv6_active_) {
SendTrace(ACTIVATED_IPV6);
} else {
SendTrace(DEACTIVATED_IPV6);
}
}
}
bool VmInterface::CopyIpAddress(Ip4Address &addr) {
bool ret = false;
InterfaceTable *table = static_cast<InterfaceTable *>(get_table());
// Support DHCP relay for fabric-ports if IP address is not configured
do_dhcp_relay_ = (fabric_port_ && addr.to_ulong() == 0 && vrf() &&
vrf()->GetName() == table->agent()->fabric_vrf_name());
if (do_dhcp_relay_) {
// Set config_seen flag on DHCP SNoop entry
table->DhcpSnoopSetConfigSeen(name_);
// IP Address not know. Get DHCP Snoop entry.
// Also sets the config_seen_ flag for DHCP Snoop entry
addr = table->GetDhcpSnoopEntry(name_);
dhcp_addr_ = addr;
}
// Retain the old if new IP could not be got
if (addr.to_ulong() == 0) {
addr = primary_ip_addr_;
}
if (primary_ip_addr_ != addr) {
primary_ip_addr_ = addr;
ret = true;
}
return ret;
}
/////////////////////////////////////////////////////////////////////////////
// VmInterfaceConfigData routines
/////////////////////////////////////////////////////////////////////////////
VmInterfaceConfigData::VmInterfaceConfigData(Agent *agent, IFMapNode *node) :
VmInterfaceData(agent, node, CONFIG, Interface::TRANSPORT_INVALID),
addr_(0), ip6_addr_(), vm_mac_(""),
cfg_name_(""), vm_uuid_(), vm_name_(), vn_uuid_(), vrf_name_(""),
fabric_port_(true), need_linklocal_ip_(false), bridging_(true),
layer3_forwarding_(true), mirror_enable_(false), ecmp_(false),
dhcp_enable_(true), admin_state_(true), analyzer_name_(""),
local_preference_(VmInterface::INVALID), oper_dhcp_options_(),
mirror_direction_(Interface::UNKNOWN), sg_list_(),
floating_ip_list_(), service_vlan_list_(), static_route_list_(),
allowed_address_pair_list_(),
device_type_(VmInterface::DEVICE_TYPE_INVALID),
vmi_type_(VmInterface::VMI_TYPE_INVALID),
physical_interface_(""), parent_vmi_(), subnet_(0), subnet_plen_(0),
rx_vlan_id_(VmInterface::kInvalidVlanId),
tx_vlan_id_(VmInterface::kInvalidVlanId),
logical_interface_(nil_uuid()) {
}
VmInterface *VmInterfaceConfigData::OnAdd(const InterfaceTable *table,
const VmInterfaceKey *key) const {
VmInterface *vmi =
new VmInterface(key->uuid_, key->name_, addr_, vm_mac_, vm_name_,
nil_uuid(), VmInterface::kInvalidVlanId,
VmInterface::kInvalidVlanId, NULL, ip6_addr_,
device_type_, vmi_type_);
vmi->SetConfigurer(VmInterface::CONFIG);
return vmi;
}
bool VmInterfaceConfigData::OnDelete(const InterfaceTable *table,
VmInterface *vmi) const {
if (vmi->IsConfigurerSet(VmInterface::CONFIG) == false)
return true;
vmi->ResetConfigurer(VmInterface::CONFIG);
VmInterfaceConfigData data(NULL, NULL);
vmi->Resync(table, &data);
return true;
}
bool VmInterfaceConfigData::OnResync(const InterfaceTable *table,
VmInterface *vmi,
bool *force_update) const {
bool sg_changed = false;
bool ecmp_changed = false;
bool local_pref_changed = false;
bool ret = false;
ret = vmi->CopyConfig(table, this, &sg_changed, &ecmp_changed,
&local_pref_changed);
if (sg_changed || ecmp_changed || local_pref_changed)
*force_update = true;
return ret;
}
// Copies configuration from DB-Request data. The actual applying of
// configuration, like adding/deleting routes must be done with ApplyConfig()
bool VmInterface::CopyConfig(const InterfaceTable *table,
const VmInterfaceConfigData *data,
bool *sg_changed,
bool *ecmp_changed, bool *local_pref_changed) {
bool ret = false;
if (table) {
VmEntry *vm = table->FindVmRef(data->vm_uuid_);
if (vm_.get() != vm) {
vm_ = vm;
ret = true;
}
VrfEntry *vrf = table->FindVrfRef(data->vrf_name_);
if (vrf_.get() != vrf) {
vrf_ = vrf;
ret = true;
}
MirrorEntry *mirror = table->FindMirrorRef(data->analyzer_name_);
if (mirror_entry_.get() != mirror) {
mirror_entry_ = mirror;
ret = true;
}
}
MirrorDirection mirror_direction = data->mirror_direction_;
if (mirror_direction_ != mirror_direction) {
mirror_direction_ = mirror_direction;
ret = true;
}
string cfg_name = data->cfg_name_;
if (cfg_name_ != cfg_name) {
cfg_name_ = cfg_name;
ret = true;
}
// Read ifindex for the interface
if (table) {
VnEntry *vn = table->FindVnRef(data->vn_uuid_);
if (vn_.get() != vn) {
vn_ = vn;
ret = true;
}
bool val = vn ? vn->layer3_forwarding() : false;
if (layer3_forwarding_ != val) {
layer3_forwarding_ = val;
ret = true;
}
bool bridging_val = vn ? vn->bridging() : false;
if (bridging_ != bridging_val) {
bridging_ = bridging_val;
ret = true;
}
int vxlan_id = vn ? vn->GetVxLanId() : 0;
if (vxlan_id_ != vxlan_id) {
vxlan_id_ = vxlan_id;
ret = true;
}
bool flood_unknown_unicast =
vn ? vn->flood_unknown_unicast(): false;
if (flood_unknown_unicast_ != flood_unknown_unicast) {
flood_unknown_unicast_ = flood_unknown_unicast;
ret = true;
}
}
if (local_preference_ != data->local_preference_) {
local_preference_ = data->local_preference_;
*local_pref_changed = true;
ret = true;
}
if (need_linklocal_ip_ != data->need_linklocal_ip_) {
need_linklocal_ip_ = data->need_linklocal_ip_;
ret = true;
}
// CopyIpAddress uses fabric_port_. So, set it before CopyIpAddresss
if (fabric_port_ != data->fabric_port_) {
fabric_port_ = data->fabric_port_;
ret = true;
}
//If nova gives a instance-ip then retain that
//ip address as primary ip address
//Else choose the ip address to be old
//primary ip address as long as its present in
//new configuration also
Ip4Address ipaddr = data->addr_;
if (nova_ip_addr_ != Ip4Address(0)) {
ipaddr = nova_ip_addr_;
}
if (CopyIpAddress(ipaddr)) {
ret = true;
}
Ip6Address ip6_addr = data->ip6_addr_;
if (nova_ip6_addr_ != Ip6Address()) {
ip6_addr = nova_ip6_addr_;
}
if (CopyIp6Address(ip6_addr)) {
ret = true;
}
if (dhcp_enable_ != data->dhcp_enable_) {
dhcp_enable_ = data->dhcp_enable_;
ret = true;
}
bool mac_set = true;
boost::system::error_code ec;
MacAddress addr(vm_mac_, &ec);
if (ec.value() != 0) {
mac_set = false;
}
if (mac_set_ != mac_set) {
mac_set_ = mac_set;
ret = true;
}
if (admin_state_ != data->admin_state_) {
admin_state_ = data->admin_state_;
ret = true;
}
if (subnet_ != data->subnet_ || subnet_plen_ != data->subnet_plen_) {
subnet_ = data->subnet_;
subnet_plen_ = data->subnet_plen_;
}
// Copy DHCP options; ret is not modified as there is no dependent action
oper_dhcp_options_ = data->oper_dhcp_options_;
// Audit operational and config floating-ip list
FloatingIpSet &old_fip_list = floating_ip_list_.list_;
const FloatingIpSet &new_fip_list = data->floating_ip_list_.list_;
if (AuditList<FloatingIpList, FloatingIpSet::iterator>
(floating_ip_list_, old_fip_list.begin(), old_fip_list.end(),
new_fip_list.begin(), new_fip_list.end())) {
ret = true;
assert(floating_ip_list_.list_.size() ==
(floating_ip_list_.v4_count_ + floating_ip_list_.v6_count_));
}
// Audit operational and config Service VLAN list
ServiceVlanSet &old_service_list = service_vlan_list_.list_;
const ServiceVlanSet &new_service_list = data->service_vlan_list_.list_;
if (AuditList<ServiceVlanList, ServiceVlanSet::iterator>
(service_vlan_list_, old_service_list.begin(), old_service_list.end(),
new_service_list.begin(), new_service_list.end())) {
ret = true;
}
// Audit operational and config Static Route list
StaticRouteSet &old_route_list = static_route_list_.list_;
const StaticRouteSet &new_route_list = data->static_route_list_.list_;
if (AuditList<StaticRouteList, StaticRouteSet::iterator>
(static_route_list_, old_route_list.begin(), old_route_list.end(),
new_route_list.begin(), new_route_list.end())) {
ret = true;
}
// Audit operational and config allowed address pair
AllowedAddressPairSet &old_aap_list = allowed_address_pair_list_.list_;
const AllowedAddressPairSet &new_aap_list = data->
allowed_address_pair_list_.list_;
if (AuditList<AllowedAddressPairList, AllowedAddressPairSet::iterator>
(allowed_address_pair_list_, old_aap_list.begin(), old_aap_list.end(),
new_aap_list.begin(), new_aap_list.end())) {
ret = true;
}
// Audit operational and config Security Group list
SecurityGroupEntrySet &old_sg_list = sg_list_.list_;
const SecurityGroupEntrySet &new_sg_list = data->sg_list_.list_;
*sg_changed =
AuditList<SecurityGroupEntryList, SecurityGroupEntrySet::iterator>
(sg_list_, old_sg_list.begin(), old_sg_list.end(),
new_sg_list.begin(), new_sg_list.end());
if (*sg_changed) {
ret = true;
}
VrfAssignRuleSet &old_vrf_assign_list = vrf_assign_rule_list_.list_;
const VrfAssignRuleSet &new_vrf_assign_list = data->
vrf_assign_rule_list_.list_;
if (AuditList<VrfAssignRuleList, VrfAssignRuleSet::iterator>
(vrf_assign_rule_list_, old_vrf_assign_list.begin(),
old_vrf_assign_list.end(), new_vrf_assign_list.begin(),
new_vrf_assign_list.end())) {
ret = true;
}
InstanceIpSet &old_ipv4_list = instance_ipv4_list_.list_;
InstanceIpSet new_ipv4_list = data->instance_ipv4_list_.list_;
//Native ip of instance should be advertised even if
//config is not present, so manually add that entry
if (nova_ip_addr_ != Ip4Address(0) &&
data->vrf_name_ != Agent::NullString()) {
new_ipv4_list.insert(
VmInterface::InstanceIp(nova_ip_addr_, data->ecmp_, true));
}
if (AuditList<InstanceIpList, InstanceIpSet::iterator>
(instance_ipv4_list_, old_ipv4_list.begin(), old_ipv4_list.end(),
new_ipv4_list.begin(), new_ipv4_list.end())) {
ret = true;
}
InstanceIpSet &old_ipv6_list = instance_ipv6_list_.list_;
InstanceIpSet new_ipv6_list = data->instance_ipv6_list_.list_;
if (nova_ip6_addr_ != Ip6Address() &&
data->vrf_name_ != Agent::NullString()) {
new_ipv6_list.insert(
VmInterface::InstanceIp(nova_ip6_addr_, data->ecmp_, true));
}
if (AuditList<InstanceIpList, InstanceIpSet::iterator>
(instance_ipv6_list_, old_ipv6_list.begin(), old_ipv6_list.end(),
new_ipv6_list.begin(), new_ipv6_list.end())) {
ret = true;
}
if (data->addr_ != Ip4Address(0) && ecmp_ != data->ecmp_) {
ecmp_ = data->ecmp_;
*ecmp_changed = true;
}
if (data->device_type_ != VmInterface::DEVICE_TYPE_INVALID &&
device_type_ != data->device_type_) {
device_type_= data->device_type_;
ret = true;
}
if (device_type_ == LOCAL_DEVICE || device_type_ == VM_VLAN_ON_VMI) {
if (rx_vlan_id_ != data->rx_vlan_id_) {
rx_vlan_id_ = data->rx_vlan_id_;
ret = true;
}
if (tx_vlan_id_ != data->tx_vlan_id_) {
tx_vlan_id_ = data->tx_vlan_id_;
ret = true;
}
}
if (logical_interface_ != data->logical_interface_) {
logical_interface_ = data->logical_interface_;
ret = true;
}
Interface *new_parent = NULL;
if (data->physical_interface_.empty() == false) {
PhysicalInterfaceKey key(data->physical_interface_);
new_parent = static_cast<Interface *>
(table->agent()->interface_table()->FindActiveEntry(&key));
} else if (data->parent_vmi_.is_nil() == false) {
VmInterfaceKey key(AgentKey::RESYNC, data->parent_vmi_, "");
new_parent = static_cast<Interface *>
(table->agent()->interface_table()->FindActiveEntry(&key));
} else {
new_parent = parent_.get();
}
if (parent_ != new_parent) {
parent_ = new_parent;
ret = true;
}
if (table) {
if (os_index_ == kInvalidIndex) {
GetOsParams(table->agent());
if (os_index_ != kInvalidIndex)
ret = true;
}
}
return ret;
}
/////////////////////////////////////////////////////////////////////////////
// VmInterfaceNovaData routines
/////////////////////////////////////////////////////////////////////////////
VmInterfaceNovaData::VmInterfaceNovaData() :
VmInterfaceData(NULL, NULL, INSTANCE_MSG, Interface::TRANSPORT_INVALID),
ipv4_addr_(),
ipv6_addr_(),
mac_addr_(),
vm_name_(),
vm_uuid_(),
vm_project_uuid_(),
physical_interface_(),
tx_vlan_id_(),
rx_vlan_id_() {
}
VmInterfaceNovaData::VmInterfaceNovaData(const Ip4Address &ipv4_addr,
const Ip6Address &ipv6_addr,
const std::string &mac_addr,
const std::string vm_name,
boost::uuids::uuid vm_uuid,
boost::uuids::uuid vm_project_uuid,
const std::string &physical_interface,
uint16_t tx_vlan_id,
uint16_t rx_vlan_id,
VmInterface::DeviceType device_type,
VmInterface::VmiType vmi_type,
Interface::Transport transport) :
VmInterfaceData(NULL, NULL, INSTANCE_MSG, transport),
ipv4_addr_(ipv4_addr),
ipv6_addr_(ipv6_addr),
mac_addr_(mac_addr),
vm_name_(vm_name),
vm_uuid_(vm_uuid),
vm_project_uuid_(vm_project_uuid),
physical_interface_(physical_interface),
tx_vlan_id_(tx_vlan_id),
rx_vlan_id_(rx_vlan_id),
device_type_(device_type),
vmi_type_(vmi_type) {
}
VmInterfaceNovaData::~VmInterfaceNovaData() {
}
VmInterface *VmInterfaceNovaData::OnAdd(const InterfaceTable *table,
const VmInterfaceKey *key) const {
Interface *parent = NULL;
if (tx_vlan_id_ != VmInterface::kInvalidVlanId &&
rx_vlan_id_ != VmInterface::kInvalidVlanId &&
physical_interface_ != Agent::NullString()) {
PhysicalInterfaceKey key_1(physical_interface_);
parent = static_cast<Interface *>
(table->agent()->interface_table()->FindActiveEntry(&key_1));
assert(parent != NULL);
}
VmInterface *vmi =
new VmInterface(key->uuid_, key->name_, ipv4_addr_, mac_addr_, vm_name_,
vm_project_uuid_, tx_vlan_id_, rx_vlan_id_,
parent, ipv6_addr_, device_type_, vmi_type_);
vmi->SetConfigurer(VmInterface::INSTANCE_MSG);
vmi->nova_ip_addr_ = ipv4_addr_;
vmi->nova_ip6_addr_ = ipv6_addr_;
return vmi;
}
bool VmInterfaceNovaData::OnDelete(const InterfaceTable *table,
VmInterface *vmi) const {
if (vmi->IsConfigurerSet(VmInterface::INSTANCE_MSG) == false)
return true;
vmi->ResetConfigurer(VmInterface::CONFIG);
VmInterfaceConfigData data(NULL, NULL);
vmi->Resync(table, &data);
vmi->ResetConfigurer(VmInterface::INSTANCE_MSG);
return true;
}
bool VmInterfaceNovaData::OnResync(const InterfaceTable *table,
VmInterface *vmi,
bool *force_update) const {
bool ret = false;
if (vmi->vm_project_uuid_ != vm_project_uuid_) {
vmi->vm_project_uuid_ = vm_project_uuid_;
ret = true;
}
if (vmi->tx_vlan_id_ != tx_vlan_id_) {
vmi->tx_vlan_id_ = tx_vlan_id_;
ret = true;
}
if (vmi->rx_vlan_id_ != rx_vlan_id_) {
vmi->rx_vlan_id_ = rx_vlan_id_;
ret = true;
}
if (vmi->nova_ip_addr_ != ipv4_addr_) {
vmi->nova_ip_addr_ = ipv4_addr_;
ret = true;
}
if (vmi->nova_ip6_addr_ != ipv6_addr_) {
vmi->nova_ip6_addr_ = ipv6_addr_;
ret = true;
}
vmi->SetConfigurer(VmInterface::INSTANCE_MSG);
return ret;
}
/////////////////////////////////////////////////////////////////////////////
// VmInterfaceMirrorData routines
/////////////////////////////////////////////////////////////////////////////
bool VmInterfaceMirrorData::OnResync(const InterfaceTable *table,
VmInterface *vmi,
bool *force_update) const {
bool ret = false;
MirrorEntry *mirror_entry = NULL;
if (mirror_enable_ == true) {
mirror_entry = table->FindMirrorRef(analyzer_name_);
}
if (vmi->mirror_entry_ != mirror_entry) {
vmi->mirror_entry_ = mirror_entry;
ret = true;
}
return ret;
}
/////////////////////////////////////////////////////////////////////////////
// VmInterfaceIpAddressData routines
/////////////////////////////////////////////////////////////////////////////
// Update for VM IP address only
// For interfaces in IP Fabric VRF, we send DHCP requests to external servers
// if config doesnt provide an address. This address is updated here.
bool VmInterfaceIpAddressData::OnResync(const InterfaceTable *table,
VmInterface *vmi,
bool *force_update) const {
bool ret = false;
if (vmi->os_index_ == VmInterface::kInvalidIndex) {
vmi->GetOsParams(table->agent());
if (vmi->os_index_ != VmInterface::kInvalidIndex)
ret = true;
}
// Ignore IP address change if L3 Forwarding not enabled
if (!vmi->layer3_forwarding_) {
return ret;
}
Ip4Address addr = Ip4Address(0);
if (vmi->CopyIpAddress(addr)) {
ret = true;
}
return ret;
}
/////////////////////////////////////////////////////////////////////////////
// VmInterfaceOsOperStateData routines
/////////////////////////////////////////////////////////////////////////////
// Resync oper-state for the interface
bool VmInterfaceOsOperStateData::OnResync(const InterfaceTable *table,
VmInterface *vmi,
bool *force_update) const {
bool ret = false;
uint32_t old_os_index = vmi->os_index_;
bool old_ipv4_active = vmi->ipv4_active_;
bool old_ipv6_active = vmi->ipv6_active_;
vmi->GetOsParams(table->agent());
if (vmi->os_index_ != old_os_index)
ret = true;
vmi->ipv4_active_ = vmi->IsIpv4Active();
if (vmi->ipv4_active_ != old_ipv4_active)
ret = true;
vmi->ipv6_active_ = vmi->IsIpv6Active();
if (vmi->ipv6_active_ != old_ipv6_active)
ret = true;
return ret;
}
bool VmInterfaceGlobalVrouterData::OnResync(const InterfaceTable *table,
VmInterface *vmi,
bool *force_update) const {
bool ret = false;
if (bridging_ != vmi->bridging_) {
vmi->bridging_ = bridging_;
*force_update = true;
ret = true;
}
if (layer3_forwarding_ != vmi->layer3_forwarding_) {
vmi->layer3_forwarding_ = layer3_forwarding_;
*force_update = true;
ret = true;
}
if (vxlan_id_ != vmi->vxlan_id_)
ret = true;
return ret;
}
/////////////////////////////////////////////////////////////////////////////
// VM Port Entry utility routines
/////////////////////////////////////////////////////////////////////////////
// Does the VMInterface need a physical device to be present
bool VmInterface::NeedDevice() const {
bool ret = true;
if (device_type_ == TOR)
ret = false;
if (device_type_ == VM_VLAN_ON_VMI)
ret = false;
if (subnet_.is_unspecified() == false) {
ret = false;
}
if (transport_ != TRANSPORT_ETHERNET) {
ret = false;
}
if (rx_vlan_id_ != VmInterface::kInvalidVlanId) {
ret = false;
} else {
// Sanity check. rx_vlan_id is set, make sure tx_vlan_id is also set
assert(tx_vlan_id_ == VmInterface::kInvalidVlanId);
}
return ret;
}
void VmInterface::GetOsParams(Agent *agent) {
if (NeedDevice()) {
Interface::GetOsParams(agent);
return;
}
os_index_ = Interface::kInvalidIndex;
mac_ = agent->vrrp_mac();
os_oper_state_ = true;
}
// A VM Interface is L3 active under following conditions,
// - If interface is deleted, it is inactive
// - VN, VRF are set
// - If sub_interface VMIs, parent_ should be set
// (We dont track parent_ and activate sub-interfaces. So, we only check
// parent_ is present and not necessarily active)
// - For non-VMWARE hypervisors,
// The tap interface must be created. This is verified by os_index_
// - MAC address set for the interface
bool VmInterface::IsActive() const {
if (IsDeleted()) {
return false;
}
if (!admin_state_) {
return false;
}
// If sub_interface VMIs, parent_vmi_ should be set
// (We dont track parent_ and activate sub-interfaces. So, we only check
// paremt_vmi is present and not necessarily active)
if (device_type_ == VM_VLAN_ON_VMI) {
if (parent_.get() == NULL)
return false;
}
if ((vn_.get() == NULL) || (vrf_.get() == NULL)) {
return false;
}
if (!vn_.get()->admin_state()) {
return false;
}
if (NeedDevice() == false) {
return true;
}
if (os_index_ == kInvalidIndex)
return false;
if (os_oper_state_ == false)
return false;
return mac_set_;
}
bool VmInterface::IsIpv4Active() const {
if (!layer3_forwarding()) {
return false;
}
if (subnet_.is_unspecified() && primary_ip_addr_.to_ulong() == 0) {
return false;
}
if (subnet_.is_unspecified() == false && parent_ == NULL) {
return false;
}
return IsActive();
}
bool VmInterface::IsIpv6Active() const {
if (!layer3_forwarding() || (primary_ip6_addr_.is_unspecified())) {
return false;
}
return IsActive();
}
bool VmInterface::IsL2Active() const {
if (!bridging()) {
return false;
}
return IsActive();
}
bool VmInterface::WaitForTraffic() const {
if (IsActive() == false) {
return false;
}
//Get the instance ip route and its corresponding traffic seen status
InetUnicastRouteKey rt_key(peer_.get(), vrf_->GetName(),
primary_ip_addr_, 32);
const InetUnicastRouteEntry *rt =
static_cast<const InetUnicastRouteEntry *>(
vrf_->GetInet4UnicastRouteTable()->FindActiveEntry(&rt_key));
if (!rt) {
return false;
}
if (rt->FindPath(peer_.get()) == false) {
return false;
}
return rt->FindPath(peer_.get())->path_preference().wait_for_traffic();
}
// Compute if policy is to be enabled on the interface
bool VmInterface::PolicyEnabled() const {
// Policy not supported for fabric ports
if (fabric_port_) {
return false;
}
if (layer3_forwarding_ == false) {
return false;
}
if (vn_.get() && vn_->IsAclSet()) {
return true;
}
// Floating-IP list and SG List can have entries in del_pending state
// Look for entries in non-del-pending state
FloatingIpSet::iterator fip_it = floating_ip_list_.list_.begin();
while (fip_it != floating_ip_list_.list_.end()) {
if (fip_it->del_pending_ == false) {
return true;
}
fip_it++;
}
SecurityGroupEntrySet::iterator sg_it = sg_list_.list_.begin();
while (sg_it != sg_list_.list_.end()) {
if (sg_it->del_pending_ == false) {
return true;
}
sg_it++;
}
VrfAssignRuleSet::iterator vrf_it = vrf_assign_rule_list_.list_.begin();
while (vrf_it != vrf_assign_rule_list_.list_.end()) {
if (vrf_it->del_pending_ == false) {
return true;
}
vrf_it++;
}
return false;
}
// VN is in VXLAN mode if,
// - Tunnel type computed is VXLAN and
// - vxlan_id_ set in VN is non-zero
bool VmInterface::IsVxlanMode() const {
if (TunnelType::ComputeType(TunnelType::AllType()) != TunnelType::VXLAN)
return false;
return vxlan_id_ != 0;
}
// Allocate MPLS Label for Layer3 routes
void VmInterface::AllocL3MplsLabel(bool force_update, bool policy_change) {
if (fabric_port_)
return;
bool new_entry = false;
Agent *agent = static_cast<InterfaceTable *>(get_table())->agent();
if (label_ == MplsTable::kInvalidLabel) {
label_ = agent->mpls_table()->AllocLabel();
new_entry = true;
}
if (force_update || policy_change || new_entry)
MplsLabel::CreateVPortLabel(agent, label_, GetUuid(), policy_enabled_,
InterfaceNHFlags::INET4);
}
// Delete MPLS Label for Layer3 routes
void VmInterface::DeleteL3MplsLabel() {
if (label_ == MplsTable::kInvalidLabel) {
return;
}
Agent *agent = static_cast<InterfaceTable *>(get_table())->agent();
MplsLabel::Delete(agent, label_);
label_ = MplsTable::kInvalidLabel;
}
// Allocate MPLS Label for Bridge entries
void VmInterface::AllocL2MplsLabel(bool force_update,
bool policy_change) {
bool new_entry = false;
if (l2_label_ == MplsTable::kInvalidLabel) {
Agent *agent = static_cast<InterfaceTable *>(get_table())->agent();
l2_label_ = agent->mpls_table()->AllocLabel();
new_entry = true;
}
Agent *agent = static_cast<InterfaceTable *>(get_table())->agent();
if (force_update || policy_change || new_entry)
MplsLabel::CreateVPortLabel(agent, l2_label_, GetUuid(),
policy_enabled_, InterfaceNHFlags::BRIDGE);
}
// Delete MPLS Label for Bridge Entries
void VmInterface::DeleteL2MplsLabel() {
if (l2_label_ == MplsTable::kInvalidLabel) {
return;
}
Agent *agent = static_cast<InterfaceTable *>(get_table())->agent();
MplsLabel::Delete(agent, l2_label_);
l2_label_ = MplsTable::kInvalidLabel;
}
void VmInterface::UpdateL3TunnelId(bool force_update, bool policy_change) {
//Currently only MPLS encap ind no VXLAN is supported for L3.
//Unconditionally create a label
AllocL3MplsLabel(force_update, policy_change);
}
void VmInterface::DeleteL3TunnelId() {
if (!ipv4_active_ && !ipv6_active_) {
DeleteL3MplsLabel();
}
}
//Check if interface transitioned from inactive to active layer 2 forwarding
bool VmInterface::L2Activated(bool old_l2_active) {
if (old_l2_active == false && l2_active_ == true) {
return true;
}
return false;
}
//Check if interface transitioned from inactive to active IP forwarding
bool VmInterface::Ipv4Activated(bool old_ipv4_active) {
if (old_ipv4_active == false && ipv4_active_ == true) {
return true;
}
return false;
}
bool VmInterface::Ipv6Activated(bool old_ipv6_active) {
if (old_ipv6_active == false && ipv6_active_ == true) {
return true;
}
return false;
}
//Check if interface transitioned from active bridging to inactive state
bool VmInterface::L2Deactivated(bool old_l2_active) {
if (old_l2_active == true && l2_active_ == false) {
return true;
}
return false;
}
//Check if interface transitioned from active IP forwarding to inactive state
bool VmInterface::Ipv4Deactivated(bool old_ipv4_active) {
if (old_ipv4_active == true && ipv4_active_ == false) {
return true;
}
return false;
}
bool VmInterface::Ipv6Deactivated(bool old_ipv6_active) {
if (old_ipv6_active == true && ipv6_active_ == false) {
return true;
}
return false;
}
void VmInterface::UpdateMulticastNextHop(bool old_ipv4_active,
bool old_l2_active) {
if (Ipv4Activated(old_ipv4_active) || L2Activated(old_l2_active)) {
InterfaceNH::CreateMulticastVmInterfaceNH(GetUuid(),
MacAddress::FromString(vm_mac_),
vrf_->GetName());
}
}
void VmInterface::UpdateFlowKeyNextHop() {
InterfaceTable *table = static_cast<InterfaceTable *>(get_table());
Agent *agent = table->agent();
if (ipv4_active_ || ipv6_active_) {
InterfaceNHKey key(new VmInterfaceKey(AgentKey::ADD_DEL_CHANGE,
GetUuid(), ""), true,
InterfaceNHFlags::INET4);
flow_key_nh_ = static_cast<const NextHop *>(
agent->nexthop_table()->FindActiveEntry(&key));
return;
}
InterfaceNHKey key(new VmInterfaceKey(AgentKey::ADD_DEL_CHANGE,
GetUuid(), ""), true,
InterfaceNHFlags::BRIDGE);
flow_key_nh_ = static_cast<const NextHop *>(
agent->nexthop_table()->FindActiveEntry(&key));
}
void VmInterface::UpdateMacVmBinding() {
BridgeAgentRouteTable *table = static_cast<BridgeAgentRouteTable *>
(vrf_->GetBridgeRouteTable());
Agent *agent = table->agent();
table->AddMacVmBindingRoute(agent->mac_vm_binding_peer(),
vrf_->GetName(),
MacAddress::FromString(vm_mac_),
this);
}
void VmInterface::UpdateL2NextHop(bool old_l2_active) {
if (L2Activated(old_l2_active)) {
InterfaceNH::CreateL2VmInterfaceNH(GetUuid(),
MacAddress::FromString(vm_mac_),
vrf_->GetName());
}
}
void VmInterface::UpdateL3NextHop(bool old_ipv4_active, bool old_ipv6_active) {
if (old_ipv4_active || old_ipv6_active) {
return;
}
if (Ipv4Activated(old_ipv4_active) || Ipv6Activated(old_ipv6_active)) {
InterfaceNH::CreateL3VmInterfaceNH(GetUuid(),
MacAddress::FromString(vm_mac_), vrf_->GetName());
}
}
void VmInterface::DeleteMacVmBinding(const VrfEntry *old_vrf) {
if (old_vrf == NULL)
return;
BridgeAgentRouteTable *table = static_cast<BridgeAgentRouteTable *>
(old_vrf->GetBridgeRouteTable());
Agent *agent = table->agent();
table->DeleteMacVmBindingRoute(agent->mac_vm_binding_peer(),
old_vrf->GetName(),
MacAddress::FromString(vm_mac_),
this);
}
void VmInterface::DeleteL2NextHop(bool old_l2_active) {
if (L2Deactivated(old_l2_active)) {
InterfaceNH::DeleteL2InterfaceNH(GetUuid());
}
}
void VmInterface::DeleteL3NextHop(bool old_ipv4_active, bool old_ipv6_active) {
if (Ipv4Deactivated(old_ipv4_active) || Ipv6Deactivated(old_ipv6_active)) {
if (!ipv4_active_ && !ipv6_active_) {
InterfaceNH::DeleteL3InterfaceNH(GetUuid());
}
}
}
void VmInterface::DeleteMulticastNextHop() {
InterfaceNH::DeleteMulticastVmInterfaceNH(GetUuid());
}
void VmInterface::DeleteL2ReceiveRoute(const VrfEntry *old_vrf,
bool old_l2_active) {
if (L2Deactivated(old_l2_active) && old_vrf) {
InterfaceTable *table = static_cast<InterfaceTable *>(get_table());
Agent *agent = table->agent();
BridgeAgentRouteTable::Delete(peer_.get(), old_vrf->GetName(),
GetVifMac(agent), 0);
}
}
Ip4Address VmInterface::GetGateway(const IpAddress &vm_ip) const {
Ip4Address ip(0);
if (vn_.get() == NULL) {
return ip;
}
const VnIpam *ipam = NULL;
if (subnet_.is_unspecified()) {
ipam = vn_->GetIpam(vm_ip);
} else {
ipam = vn_->GetIpam(subnet_);
}
if (ipam && ipam->default_gw.is_v4()) {
ip = ipam->default_gw.to_v4();
}
return ip;
}
// Add/Update route. Delete old route if VRF or address changed
void VmInterface::UpdateIpv4InterfaceRoute(bool old_ipv4_active, bool force_update,
bool policy_change,
VrfEntry * old_vrf,
const Ip4Address &old_addr) {
Ip4Address ip = GetGateway(primary_ip_addr_);
// If interface was already active earlier and there is no force_update or
// policy_change, return
if (old_ipv4_active == true && force_update == false
&& policy_change == false && old_addr == primary_ip_addr_ &&
vm_ip_gw_addr_ == ip) {
return;
}
// We need to have valid IP and VRF to add route
if (primary_ip_addr_.to_ulong() != 0 && vrf_.get() != NULL) {
// Add route if old was inactive or force_update is set
if (old_ipv4_active == false || force_update == true ||
old_addr != primary_ip_addr_ || vm_ip_gw_addr_ != ip) {
vm_ip_gw_addr_ = ip;
AddRoute(vrf_->GetName(), primary_ip_addr_, 32, vn_->GetName(),
policy_enabled_, ecmp_, vm_ip_gw_addr_, Ip4Address(0));
} else if (policy_change == true) {
// If old-l3-active and there is change in policy, invoke RESYNC of
// route to account for change in NH policy
InetUnicastAgentRouteTable::ReEvaluatePaths(agent(),
vrf_->GetName(),
primary_ip_addr_, 32);
}
}
// If there is change in VRF or IP address, delete old route
if (old_vrf != vrf_.get() || primary_ip_addr_ != old_addr) {
DeleteIpv4InterfaceRoute(old_vrf, old_addr);
}
}
// Add/Update route. Delete old route if VRF or address changed
void VmInterface::UpdateIpv6InterfaceRoute(bool old_ipv6_active, bool force_update,
bool policy_change,
VrfEntry * old_vrf,
const Ip6Address &old_addr) {
const VnIpam *ipam = vn_->GetIpam(primary_ip6_addr_);
Ip6Address ip6;
if (ipam) {
ip6 = ipam->default_gw.to_v6();
}
// If interface was already active earlier and there is no force_update or
// policy_change, return
if (old_ipv6_active == true && force_update == false
&& policy_change == false && vm_ip6_gw_addr_ == ip6) {
return;
}
// We need to have valid IP and VRF to add route
if (!primary_ip6_addr_.is_unspecified() && vrf_.get() != NULL) {
// Add route if old was inactive or force_update is set
if (old_ipv6_active == false || force_update == true ||
old_addr != primary_ip6_addr_ || vm_ip6_gw_addr_ != ip6) {
vm_ip6_gw_addr_ = ip6;
SecurityGroupList sg_id_list;
CopySgIdList(&sg_id_list);
PathPreference path_preference;
SetPathPreference(&path_preference, false, Ip4Address(0));
//TODO: change subnet_gw_ip to Ip6Address
InetUnicastAgentRouteTable::AddLocalVmRoute
(peer_.get(), vrf_->GetName(), primary_ip6_addr_, 128, GetUuid(),
vn_->GetName(), label_, sg_id_list, false, path_preference,
vm_ip6_gw_addr_);
} else if (policy_change == true) {
// If old-l3-active and there is change in policy, invoke RESYNC of
// route to account for change in NH policy
InetUnicastAgentRouteTable::ReEvaluatePaths(agent(),
vrf_->GetName(),
primary_ip6_addr_, 128);
}
}
// If there is change in VRF or IP address, delete old route
if (old_vrf != vrf_.get() || primary_ip6_addr_ != old_addr) {
DeleteIpv6InterfaceRoute(old_vrf, old_addr);
}
}
void VmInterface::UpdateResolveRoute(bool old_ipv4_active, bool force_update,
bool policy_change, VrfEntry * old_vrf,
const Ip4Address &old_addr,
uint8_t old_plen) {
if (old_ipv4_active == true && force_update == false
&& policy_change == false && old_addr == subnet_ &&
subnet_plen_ == old_plen) {
return;
}
if (old_vrf && (old_vrf != vrf_.get() ||
old_addr != subnet_ ||
subnet_plen_ != old_plen)) {
DeleteResolveRoute(old_vrf, old_addr, old_plen);
}
if (subnet_.to_ulong() != 0 && vrf_.get() != NULL && vn_.get() != NULL) {
SecurityGroupList sg_id_list;
CopySgIdList(&sg_id_list);
VmInterfaceKey vm_intf_key(AgentKey::ADD_DEL_CHANGE, GetUuid(), "");
InetUnicastAgentRouteTable::AddResolveRoute(peer_.get(), vrf_->GetName(),
Address::GetIp4SubnetAddress(subnet_, subnet_plen_),
subnet_plen_, vm_intf_key, vrf_->table_label(),
policy_enabled_, vn_->GetName(), sg_id_list);
}
}
void VmInterface::DeleteResolveRoute(VrfEntry *old_vrf,
const Ip4Address &old_addr,
const uint8_t plen) {
DeleteRoute(old_vrf->GetName(), old_addr, plen);
}
void VmInterface::DeleteIpv4InterfaceRoute(VrfEntry *old_vrf,
const Ip4Address &old_addr) {
if ((old_vrf == NULL) || (old_addr.to_ulong() == 0))
return;
DeleteRoute(old_vrf->GetName(), old_addr, 32);
}
void VmInterface::DeleteIpv6InterfaceRoute(VrfEntry *old_vrf,
const Ip6Address &old_addr) {
if ((old_vrf == NULL) || (old_addr.is_unspecified()))
return;
InetUnicastAgentRouteTable::Delete(peer_.get(), old_vrf->GetName(),
old_addr, 128);
}
// Add meta-data route if linklocal_ip is needed
void VmInterface::UpdateMetadataRoute(bool old_ipv4_active, VrfEntry *old_vrf) {
if (ipv4_active_ == false || old_ipv4_active == true)
return;
if (!need_linklocal_ip_) {
return;
}
InterfaceTable *table = static_cast<InterfaceTable *>(get_table());
Agent *agent = table->agent();
table->VmPortToMetaDataIp(id(), vrf_->vrf_id(), &mdata_addr_);
PathPreference path_preference;
SetPathPreference(&path_preference, false, Ip4Address(0));
InetUnicastAgentRouteTable::AddLocalVmRoute
(agent->link_local_peer(), agent->fabric_vrf_name(), mdata_addr_,
32, GetUuid(), vn_->GetName(), label_, SecurityGroupList(), true,
path_preference, Ip4Address(0));
}
// Delete meta-data route
void VmInterface::DeleteMetadataRoute(bool old_active, VrfEntry *old_vrf,
bool old_need_linklocal_ip) {
if (!old_need_linklocal_ip) {
return;
}
InterfaceTable *table = static_cast<InterfaceTable *>(get_table());
Agent *agent = table->agent();
InetUnicastAgentRouteTable::Delete(agent->link_local_peer(),
agent->fabric_vrf_name(),
mdata_addr_, 32);
}
void VmInterface::CleanupFloatingIpList() {
FloatingIpSet::iterator it = floating_ip_list_.list_.begin();
while (it != floating_ip_list_.list_.end()) {
FloatingIpSet::iterator prev = it++;
if (prev->del_pending_ == false)
continue;
if (prev->floating_ip_.is_v4()) {
floating_ip_list_.v4_count_--;
assert(floating_ip_list_.v4_count_ >= 0);
} else {
floating_ip_list_.v6_count_--;
assert(floating_ip_list_.v6_count_ >= 0);
}
floating_ip_list_.list_.erase(prev);
}
}
void VmInterface::UpdateFloatingIp(bool force_update, bool policy_change,
bool l2) {
FloatingIpSet::iterator it = floating_ip_list_.list_.begin();
while (it != floating_ip_list_.list_.end()) {
FloatingIpSet::iterator prev = it++;
if (prev->del_pending_) {
prev->DeActivate(this, l2);
} else {
prev->Activate(this, force_update||policy_change, l2);
}
}
}
void VmInterface::DeleteFloatingIp(bool l2, uint32_t old_ethernet_tag) {
FloatingIpSet::iterator it = floating_ip_list_.list_.begin();
while (it != floating_ip_list_.list_.end()) {
FloatingIpSet::iterator prev = it++;
prev->DeActivate(this, l2);
}
}
void VmInterface::UpdateServiceVlan(bool force_update, bool policy_change) {
ServiceVlanSet::iterator it = service_vlan_list_.list_.begin();
while (it != service_vlan_list_.list_.end()) {
ServiceVlanSet::iterator prev = it++;
if (prev->del_pending_) {
prev->DeActivate(this);
service_vlan_list_.list_.erase(prev);
} else {
prev->Activate(this, force_update);
}
}
}
void VmInterface::DeleteServiceVlan() {
ServiceVlanSet::iterator it = service_vlan_list_.list_.begin();
while (it != service_vlan_list_.list_.end()) {
ServiceVlanSet::iterator prev = it++;
prev->DeActivate(this);
if (prev->del_pending_) {
service_vlan_list_.list_.erase(prev);
}
}
}
void VmInterface::UpdateStaticRoute(bool force_update, bool policy_change) {
StaticRouteSet::iterator it = static_route_list_.list_.begin();
while (it != static_route_list_.list_.end()) {
StaticRouteSet::iterator prev = it++;
/* V4 static routes should be enabled only if ipv4_active_ is true
* V6 static routes should be enabled only if ipv6_active_ is true
*/
if ((!ipv4_active_ && prev->addr_.is_v4()) ||
(!ipv6_active_ && prev->addr_.is_v6())) {
continue;
}
if (prev->del_pending_) {
prev->DeActivate(this);
static_route_list_.list_.erase(prev);
} else {
prev->Activate(this, force_update, policy_change);
}
}
}
void VmInterface::DeleteStaticRoute() {
StaticRouteSet::iterator it = static_route_list_.list_.begin();
while (it != static_route_list_.list_.end()) {
StaticRouteSet::iterator prev = it++;
prev->DeActivate(this);
if (prev->del_pending_) {
static_route_list_.list_.erase(prev);
}
}
}
void VmInterface::UpdateAllowedAddressPair(bool force_update, bool policy_change,
bool l2, bool old_layer2_forwarding,
bool old_layer3_forwarding) {
AllowedAddressPairSet::iterator it =
allowed_address_pair_list_.list_.begin();
while (it != allowed_address_pair_list_.list_.end()) {
AllowedAddressPairSet::iterator prev = it++;
if (prev->del_pending_) {
prev->L2DeActivate(this);
prev->DeActivate(this);
allowed_address_pair_list_.list_.erase(prev);
} else {
if (l2) {
prev->L2Activate(this, force_update, policy_change,
old_layer2_forwarding, old_layer3_forwarding);
} else {
prev->Activate(this, force_update, policy_change);
}
}
}
}
void VmInterface::DeleteAllowedAddressPair(bool l2) {
AllowedAddressPairSet::iterator it =
allowed_address_pair_list_.list_.begin();
while (it != allowed_address_pair_list_.list_.end()) {
AllowedAddressPairSet::iterator prev = it++;
if (l2) {
prev->L2DeActivate(this);
} else {
prev->DeActivate(this);
}
if (prev->del_pending_) {
prev->L2DeActivate(this);
prev->DeActivate(this);
allowed_address_pair_list_.list_.erase(prev);
}
}
}
static bool CompareAddressType(const AddressType &lhs,
const AddressType &rhs) {
if (lhs.subnet.ip_prefix != rhs.subnet.ip_prefix) {
return false;
}
if (lhs.subnet.ip_prefix_len != rhs.subnet.ip_prefix_len) {
return false;
}
if (lhs.virtual_network != rhs.virtual_network) {
return false;
}
if (lhs.security_group != rhs.security_group) {
return false;
}
return true;
}
static bool ComparePortType(const PortType &lhs,
const PortType &rhs) {
if (lhs.start_port != rhs.start_port) {
return false;
}
if (lhs.end_port != rhs.end_port) {
return false;
}
return true;
}
static bool CompareMatchConditionType(const MatchConditionType &lhs,
const MatchConditionType &rhs) {
if (lhs.protocol != rhs.protocol) {
return lhs.protocol < rhs.protocol;
}
if (!CompareAddressType(lhs.src_address, rhs.src_address)) {
return false;
}
if (!ComparePortType(lhs.src_port, rhs.src_port)) {
return false;
}
if (!CompareAddressType(lhs.dst_address, rhs.dst_address)) {
return false;
}
if (!ComparePortType(lhs.dst_port, rhs.dst_port)) {
return false;
}
return true;
}
void VmInterface::UpdateVrfAssignRule() {
Agent *agent = static_cast<InterfaceTable *>(get_table())->agent();
//Erase all delete marked entry
VrfAssignRuleSet::iterator it = vrf_assign_rule_list_.list_.begin();
while (it != vrf_assign_rule_list_.list_.end()) {
VrfAssignRuleSet::iterator prev = it++;
if (prev->del_pending_) {
vrf_assign_rule_list_.list_.erase(prev);
}
}
if (vrf_assign_rule_list_.list_.size() == 0 &&
vrf_assign_acl_.get() != NULL) {
DeleteVrfAssignRule();
return;
}
if (vrf_assign_rule_list_.list_.size() == 0) {
return;
}
AclSpec acl_spec;
acl_spec.acl_id = uuid_;
//Create the ACL
it = vrf_assign_rule_list_.list_.begin();
uint32_t id = 0;
for (;it != vrf_assign_rule_list_.list_.end();it++) {
//Go thru all match condition and create ACL entry
AclEntrySpec ace_spec;
ace_spec.id = id++;
if (ace_spec.Populate(&(it->match_condition_)) == false) {
continue;
}
ActionSpec vrf_translate_spec;
vrf_translate_spec.ta_type = TrafficAction::VRF_TRANSLATE_ACTION;
vrf_translate_spec.simple_action = TrafficAction::VRF_TRANSLATE;
vrf_translate_spec.vrf_translate.set_vrf_name(it->vrf_name_);
vrf_translate_spec.vrf_translate.set_ignore_acl(it->ignore_acl_);
ace_spec.action_l.push_back(vrf_translate_spec);
acl_spec.acl_entry_specs_.push_back(ace_spec);
}
DBRequest req;
AclKey *key = new AclKey(acl_spec.acl_id);
AclData *data = new AclData(agent, NULL, acl_spec);
req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;
req.key.reset(key);
req.data.reset(data);
agent->acl_table()->Process(req);
AclKey entry_key(uuid_);
AclDBEntry *acl = static_cast<AclDBEntry *>(
agent->acl_table()->FindActiveEntry(&entry_key));
assert(acl);
vrf_assign_acl_ = acl;
}
void VmInterface::DeleteVrfAssignRule() {
Agent *agent = static_cast<InterfaceTable *>(get_table())->agent();
VrfAssignRuleSet::iterator it = vrf_assign_rule_list_.list_.begin();
while (it != vrf_assign_rule_list_.list_.end()) {
VrfAssignRuleSet::iterator prev = it++;
if (prev->del_pending_) {
vrf_assign_rule_list_.list_.erase(prev);
}
}
if (vrf_assign_acl_ != NULL) {
vrf_assign_acl_ = NULL;
DBRequest req;
AclKey *key = new AclKey(uuid_);
req.oper = DBRequest::DB_ENTRY_DELETE;
req.key.reset(key);
req.data.reset(NULL);
agent->acl_table()->Process(req);
}
}
void VmInterface::UpdateSecurityGroup() {
SecurityGroupEntrySet::iterator it = sg_list_.list_.begin();
while (it != sg_list_.list_.end()) {
SecurityGroupEntrySet::iterator prev = it++;
if (prev->del_pending_) {
sg_list_.list_.erase(prev);
} else {
prev->Activate(this);
}
}
}
void VmInterface::DeleteSecurityGroup() {
SecurityGroupEntrySet::iterator it = sg_list_.list_.begin();
while (it != sg_list_.list_.end()) {
SecurityGroupEntrySet::iterator prev = it++;
if (prev->del_pending_) {
sg_list_.list_.erase(prev);
}
}
}
void VmInterface::UpdateL2TunnelId(bool force_update, bool policy_change) {
AllocL2MplsLabel(force_update, policy_change);
}
void VmInterface::DeleteL2TunnelId() {
DeleteL2MplsLabel();
}
void VmInterface::UpdateL2InterfaceRoute(bool old_l2_active, bool force_update,
VrfEntry *old_vrf,
const Ip4Address &old_v4_addr,
const Ip6Address &old_v6_addr,
int old_ethernet_tag,
bool old_layer3_forwarding,
bool policy_changed,
const Ip4Address &new_ip_addr,
const Ip6Address &new_ip6_addr,
const MacAddress &mac,
const IpAddress &dependent_ip) const {
if (l2_active_ == false)
return;
if (ethernet_tag_ != old_ethernet_tag) {
force_update = true;
}
if (old_layer3_forwarding != layer3_forwarding_) {
force_update = true;
}
//Encap change will result in force update of l2 routes.
if (force_update) {
DeleteL2InterfaceRoute(true, old_vrf, old_v4_addr,
old_v6_addr, old_ethernet_tag, mac);
} else {
if (new_ip_addr != old_v4_addr) {
force_update = true;
DeleteL2InterfaceRoute(true, old_vrf, old_v4_addr, Ip6Address(),
old_ethernet_tag, mac);
}
if (new_ip6_addr != old_v6_addr) {
force_update = true;
DeleteL2InterfaceRoute(true, old_vrf, Ip4Address(), old_v6_addr,
old_ethernet_tag, mac);
}
}
assert(peer_.get());
EvpnAgentRouteTable *table = static_cast<EvpnAgentRouteTable *>
(vrf_->GetEvpnRouteTable());
SecurityGroupList sg_id_list;
CopySgIdList(&sg_id_list);
PathPreference path_preference;
SetPathPreference(&path_preference, false, dependent_ip);
if (policy_changed == true) {
//Resync the nexthop
table->ResyncVmRoute(peer_.get(), vrf_->GetName(),
mac, new_ip_addr,
ethernet_tag_, NULL);
table->ResyncVmRoute(peer_.get(), vrf_->GetName(),
mac, new_ip6_addr,
ethernet_tag_, NULL);
}
if (old_l2_active && force_update == false)
return;
if (new_ip_addr.is_unspecified() || layer3_forwarding_ == true) {
table->AddLocalVmRoute(peer_.get(), vrf_->GetName(),
mac, this, new_ip_addr,
l2_label_, vn_->GetName(), sg_id_list,
path_preference, ethernet_tag_);
}
if (new_ip6_addr.is_unspecified() == false && layer3_forwarding_ == true) {
table->AddLocalVmRoute(peer_.get(), vrf_->GetName(),
mac, this, new_ip6_addr,
l2_label_, vn_->GetName(), sg_id_list,
path_preference, ethernet_tag_);
}
}
void VmInterface::DeleteL2InterfaceRoute(bool old_l2_active, VrfEntry *old_vrf,
const Ip4Address &old_v4_addr,
const Ip6Address &old_v6_addr,
int old_ethernet_tag,
const MacAddress &mac) const {
if (old_l2_active == false)
return;
if (old_vrf == NULL)
return;
EvpnAgentRouteTable *table = static_cast<EvpnAgentRouteTable *>
(old_vrf->GetEvpnRouteTable());
table->DelLocalVmRoute(peer_.get(), old_vrf->GetName(), mac,
this, old_v4_addr,
old_ethernet_tag);
table->DelLocalVmRoute(peer_.get(), old_vrf->GetName(), mac,
this, old_v6_addr,
old_ethernet_tag);
}
// Copy the SG List for VM Interface. Used to add route for interface
void VmInterface::CopySgIdList(SecurityGroupList *sg_id_list) const {
SecurityGroupEntrySet::const_iterator it;
for (it = sg_list_.list_.begin(); it != sg_list_.list_.end(); ++it) {
if (it->del_pending_)
continue;
if (it->sg_.get() == NULL)
continue;
sg_id_list->push_back(it->sg_->GetSgId());
}
}
// Set path-preference information for the route
void VmInterface::SetPathPreference(PathPreference *pref, bool ecmp,
const IpAddress &dependent_ip) const {
pref->set_ecmp(ecmp);
if (local_preference_ != INVALID) {
pref->set_static_preference(true);
}
if (local_preference_ == HIGH) {
pref->set_preference(PathPreference::HIGH);
}
pref->set_dependent_ip(dependent_ip);
pref->set_vrf(vrf()->GetName());
}
//Add a route for VM port
//If ECMP route, add new composite NH and mpls label for same
void VmInterface::AddRoute(const std::string &vrf_name, const IpAddress &addr,
uint32_t plen, const std::string &dest_vn,
bool policy, bool ecmp, const IpAddress &gw_ip,
const IpAddress &dependent_rt) {
SecurityGroupList sg_id_list;
CopySgIdList(&sg_id_list);
PathPreference path_preference;
SetPathPreference(&path_preference, ecmp, dependent_rt);
InetUnicastAgentRouteTable::AddLocalVmRoute(peer_.get(), vrf_name, addr,
plen, GetUuid(),
dest_vn, label_,
sg_id_list, false,
path_preference, gw_ip);
return;
}
void VmInterface::ResolveRoute(const std::string &vrf_name, const Ip4Address &addr,
uint32_t plen, const std::string &dest_vn, bool policy) {
SecurityGroupList sg_id_list;
CopySgIdList(&sg_id_list);
VmInterfaceKey vm_intf_key(AgentKey::ADD_DEL_CHANGE, GetUuid(), "");
InetUnicastAgentRouteTable::AddResolveRoute(peer_.get(), vrf_name,
Address::GetIp4SubnetAddress(addr, plen),
plen, vm_intf_key, vrf_->table_label(),
policy, dest_vn, sg_id_list);
}
void VmInterface::DeleteRoute(const std::string &vrf_name,
const IpAddress &addr, uint32_t plen) {
InetUnicastAgentRouteTable::Delete(peer_.get(), vrf_name, addr, plen);
return;
}
// DHCP options applicable to the Interface
bool VmInterface::GetInterfaceDhcpOptions(
std::vector<autogen::DhcpOptionType> *options) const {
if (oper_dhcp_options().are_dhcp_options_set()) {
*options = oper_dhcp_options().dhcp_options();
return true;
}
return false;
}
// DHCP options applicable to the Subnet to which the interface belongs
bool VmInterface::GetSubnetDhcpOptions(
std::vector<autogen::DhcpOptionType> *options,
bool ipv6) const {
if (vn()) {
const std::vector<VnIpam> &vn_ipam = vn()->GetVnIpam();
uint32_t index;
for (index = 0; index < vn_ipam.size(); ++index) {
if (!ipv6 && vn_ipam[index].IsSubnetMember(primary_ip_addr())) {
break;
}
if (ipv6 && vn_ipam[index].IsSubnetMember(primary_ip6_addr())) {
break;
}
}
if (index < vn_ipam.size() &&
vn_ipam[index].oper_dhcp_options.are_dhcp_options_set()) {
*options = vn_ipam[index].oper_dhcp_options.dhcp_options();
return true;
}
}
return false;
}
// DHCP options applicable to the Ipam to which the interface belongs
bool VmInterface::GetIpamDhcpOptions(
std::vector<autogen::DhcpOptionType> *options,
bool ipv6) const {
if (vn()) {
std::string ipam_name;
autogen::IpamType ipam_type;
if (!ipv6 &&
vn()->GetIpamData(primary_ip_addr(), &ipam_name, &ipam_type)) {
*options = ipam_type.dhcp_option_list.dhcp_option;
return true;
}
if (ipv6 &&
vn()->GetIpamData(primary_ip6_addr(), &ipam_name, &ipam_type)) {
*options = ipam_type.dhcp_option_list.dhcp_option;
return true;
}
}
return false;
}
/////////////////////////////////////////////////////////////////////////////
// InstanceIp routines
/////////////////////////////////////////////////////////////////////////////
VmInterface::InstanceIp::InstanceIp() :
ListEntry(), ip_(), ecmp_(false), l2_installed_(false), old_ecmp_(false),
is_primary_(false) {
}
VmInterface::InstanceIp::InstanceIp(const InstanceIp &rhs) :
ListEntry(rhs.installed_, rhs.del_pending_),
ip_(rhs.ip_), ecmp_(rhs.ecmp_),
l2_installed_(rhs.l2_installed_), old_ecmp_(rhs.old_ecmp_),
is_primary_(rhs.is_primary_) {
}
VmInterface::InstanceIp::InstanceIp(const IpAddress &addr,
bool ecmp, bool is_primary) :
ListEntry(), ip_(addr), ecmp_(ecmp),
l2_installed_(false), old_ecmp_(false), is_primary_(is_primary) {
}
VmInterface::InstanceIp::~InstanceIp() {
}
bool VmInterface::InstanceIp::operator() (const InstanceIp &lhs,
const InstanceIp &rhs) const {
return lhs.IsLess(&rhs);
}
bool VmInterface::InstanceIp::IsLess(const InstanceIp *rhs) const {
return ip_ < rhs->ip_;
}
void VmInterface::InstanceIp::L3Activate(VmInterface *interface,
bool force_update) const {
if (gw_ip_ != interface->GetGateway(ip_)) {
force_update = true;
}
if (old_ecmp_ != ecmp_) {
force_update = true;
old_ecmp_ = ecmp_;
}
// Add route if not installed or if force requested
if (installed_ && force_update == false) {
return;
}
if (ip_.is_v4()) {
interface->AddRoute(interface->vrf()->GetName(), ip_.to_v4(), 32,
interface->vn()->GetName(), true, ecmp_,
interface->GetGateway(ip_), Ip4Address(0));
} else if (ip_.is_v6()) {
interface->AddRoute(interface->vrf()->GetName(), ip_.to_v6(), 128,
interface->vn()->GetName(), true, false,
Ip6Address(), Ip6Address());
}
installed_ = true;
}
void VmInterface::InstanceIp::L3DeActivate(VmInterface *interface,
VrfEntry *old_vrf) const {
if (installed_ == false) {
return;
}
if (ip_.is_v4()) {
interface->DeleteRoute(old_vrf->GetName(), ip_, 32);
} else if (ip_.is_v6()) {
interface->DeleteRoute(old_vrf->GetName(), ip_, 128);
}
installed_ = false;
}
void VmInterface::InstanceIp::L2Activate(VmInterface *interface,
bool force_update,
uint32_t old_ethernet_tag) const {
Ip4Address ipv4(0);
Ip6Address ipv6;
if (ip_.is_v4()) {
if (interface->IsIpv4Active() == false) {
return;
}
ipv4 = ip_.to_v4();
} else {
if (interface->IsIpv6Active() == false) {
return;
}
ipv6 = ip_.to_v6();
}
if (l2_installed_ == false || force_update) {
interface->UpdateL2InterfaceRoute(false, force_update,
interface->vrf(), ipv4, ipv6,
old_ethernet_tag, false,
false, ipv4, ipv6,
MacAddress::FromString(interface->vm_mac()),
Ip4Address(0));
l2_installed_ = true;
}
}
void VmInterface::InstanceIp::L2DeActivate(VmInterface *interface,
VrfEntry *old_vrf,
uint32_t old_ethernet_tag) const {
if (l2_installed_ == false) {
return;
}
Ip4Address ipv4(0);
Ip6Address ipv6;
if (ip_.is_v4()) {
ipv4 = ip_.to_v4();
} else {
ipv6 = ip_.to_v6();
}
interface->DeleteL2InterfaceRoute(true, old_vrf, ipv4, ipv6,
old_ethernet_tag,
MacAddress::FromString(interface->vm_mac()));
l2_installed_ = false;
}
void VmInterface::InstanceIp::Activate(VmInterface *interface,
bool force_update, bool l2,
int old_ethernet_tag) const {
if (l2) {
L2Activate(interface, force_update, old_ethernet_tag);
} else {
L3Activate(interface, force_update);
}
}
void VmInterface::InstanceIp::DeActivate(VmInterface *interface, bool l2,
VrfEntry *old_vrf,
uint32_t old_ethernet_tag) const {
if (l2) {
L2DeActivate(interface, old_vrf, old_ethernet_tag);
} else {
L3DeActivate(interface, old_vrf);
}
}
void VmInterface::InstanceIpList::Insert(const InstanceIp *rhs) {
list_.insert(*rhs);
}
void VmInterface::InstanceIpList::Update(const InstanceIp *lhs,
const InstanceIp *rhs) {
}
void VmInterface::InstanceIpList::Remove(InstanceIpSet::iterator &it) {
it->set_del_pending(true);
}
/////////////////////////////////////////////////////////////////////////////
// FloatingIp routines
/////////////////////////////////////////////////////////////////////////////
VmInterface::FloatingIp::FloatingIp() :
ListEntry(), floating_ip_(), vn_(NULL),
vrf_(NULL, this), vrf_name_(""), vn_uuid_(), l2_installed_(false),
ethernet_tag_(0), fixed_ip_(), force_l3_update_(false),
force_l2_update_(false) {
}
VmInterface::FloatingIp::FloatingIp(const FloatingIp &rhs) :
ListEntry(rhs.installed_, rhs.del_pending_),
floating_ip_(rhs.floating_ip_), vn_(rhs.vn_), vrf_(rhs.vrf_, this),
vrf_name_(rhs.vrf_name_), vn_uuid_(rhs.vn_uuid_),
l2_installed_(rhs.l2_installed_), ethernet_tag_(rhs.ethernet_tag_),
fixed_ip_(rhs.fixed_ip_), force_l3_update_(rhs.force_l3_update_),
force_l2_update_(rhs.force_l2_update_) {
}
VmInterface::FloatingIp::FloatingIp(const IpAddress &addr,
const std::string &vrf,
const boost::uuids::uuid &vn_uuid,
const IpAddress &fixed_ip) :
ListEntry(), floating_ip_(addr), vn_(NULL), vrf_(NULL, this), vrf_name_(vrf),
vn_uuid_(vn_uuid), l2_installed_(false), ethernet_tag_(0),
fixed_ip_(fixed_ip), force_l3_update_(false), force_l2_update_(false){
}
VmInterface::FloatingIp::~FloatingIp() {
}
bool VmInterface::FloatingIp::operator() (const FloatingIp &lhs,
const FloatingIp &rhs) const {
return lhs.IsLess(&rhs);
}
// Compare key for FloatingIp. Key is <floating_ip_ and vrf_name_> for both
// Config and Operational processing
bool VmInterface::FloatingIp::IsLess(const FloatingIp *rhs) const {
if (floating_ip_ != rhs->floating_ip_)
return floating_ip_ < rhs->floating_ip_;
return (vrf_name_ < rhs->vrf_name_);
}
void VmInterface::FloatingIp::L3Activate(VmInterface *interface,
bool force_update) const {
// Add route if not installed or if force requested
if (installed_ && force_update == false && force_l3_update_ == false) {
return;
}
if (fixed_ip_.is_v4() && fixed_ip_ == Ip4Address(0)) {
fixed_ip_ = GetFixedIp(interface);
}
InterfaceTable *table =
static_cast<InterfaceTable *>(interface->get_table());
if (floating_ip_.is_v4()) {
interface->AddRoute(vrf_.get()->GetName(), floating_ip_.to_v4(), 32,
vn_->GetName(), true, interface->ecmp(), Ip4Address(0),
GetFixedIp(interface));
if (table->update_floatingip_cb().empty() == false) {
table->update_floatingip_cb()(interface, vn_.get(),
floating_ip_.to_v4(), false);
}
} else if (floating_ip_.is_v6()) {
interface->AddRoute(vrf_.get()->GetName(), floating_ip_.to_v6(), 128,
vn_->GetName(), true, false, Ip6Address(),
GetFixedIp(interface));
//TODO:: callback for DNS handling
}
installed_ = true;
force_l3_update_ = false;
}
void VmInterface::FloatingIp::L3DeActivate(VmInterface *interface) const {
if (installed_ == false)
return;
if (floating_ip_.is_v4()) {
interface->DeleteRoute(vrf_.get()->GetName(), floating_ip_, 32);
InterfaceTable *table =
static_cast<InterfaceTable *>(interface->get_table());
if (table->update_floatingip_cb().empty() == false) {
table->update_floatingip_cb()(interface, vn_.get(),
floating_ip_.to_v4(), true);
}
} else if (floating_ip_.is_v6()) {
interface->DeleteRoute(vrf_.get()->GetName(), floating_ip_, 128);
//TODO:: callback for DNS handling
}
installed_ = false;
}
void VmInterface::FloatingIp::L2Activate(VmInterface *interface,
bool force_update) const {
// Add route if not installed or if force requested
if (l2_installed_ && force_update == false &&
force_l2_update_ == false) {
return;
}
SecurityGroupList sg_id_list;
interface->CopySgIdList(&sg_id_list);
PathPreference path_preference;
interface->SetPathPreference(&path_preference, false, GetFixedIp(interface));
EvpnAgentRouteTable *evpn_table = static_cast<EvpnAgentRouteTable *>
(vrf_->GetEvpnRouteTable());
//Agent *agent = evpn_table->agent();
ethernet_tag_ = vn_->ComputeEthernetTag();
evpn_table->AddReceiveRoute(interface->peer_.get(), vrf_->GetName(),
interface->l2_label(),
MacAddress::FromString(interface->vm_mac()),
floating_ip_, ethernet_tag_, vn_->GetName(),
path_preference);
l2_installed_ = true;
force_l2_update_ = false;
}
void VmInterface::FloatingIp::L2DeActivate(VmInterface *interface) const {
if (l2_installed_ == false)
return;
EvpnAgentRouteTable *evpn_table = static_cast<EvpnAgentRouteTable *>
(vrf_->GetEvpnRouteTable());
evpn_table->DelLocalVmRoute(interface->peer_.get(), vrf_->GetName(),
MacAddress::FromString(interface->vm_mac()),
interface, floating_ip_, ethernet_tag_);
ethernet_tag_ = 0;
l2_installed_ = false;
}
void VmInterface::FloatingIp::Activate(VmInterface *interface,
bool force_update, bool l2) const {
InterfaceTable *table =
static_cast<InterfaceTable *>(interface->get_table());
if (vn_.get() == NULL) {
vn_ = table->FindVnRef(vn_uuid_);
assert(vn_.get());
}
if (vrf_.get() == NULL) {
vrf_ = table->FindVrfRef(vrf_name_);
assert(vrf_.get());
}
if (l2)
L2Activate(interface, force_update);
else
L3Activate(interface, force_update);
}
void VmInterface::FloatingIp::DeActivate(VmInterface *interface, bool l2) const{
if (l2)
L2DeActivate(interface);
else
L3DeActivate(interface);
if (installed_ == false && l2_installed_ == false)
vrf_ = NULL;
}
const IpAddress
VmInterface::FloatingIp::GetFixedIp(const VmInterface *interface) const {
if (fixed_ip_.to_v4() == Ip4Address(0)) {
if (floating_ip_.is_v4() == true) {
return interface->primary_ip_addr();
} else {
return interface->primary_ip6_addr();
}
}
return fixed_ip_;
}
void VmInterface::FloatingIpList::Insert(const FloatingIp *rhs) {
std::pair<FloatingIpSet::iterator, bool> ret = list_.insert(*rhs);
if (ret.second) {
if (rhs->floating_ip_.is_v4()) {
v4_count_++;
} else {
v6_count_++;
}
}
}
void VmInterface::FloatingIpList::Update(const FloatingIp *lhs,
const FloatingIp *rhs) {
if (lhs->fixed_ip_ != rhs->fixed_ip_) {
lhs->fixed_ip_ = rhs->fixed_ip_;
lhs->force_l3_update_ = true;
lhs->force_l2_update_ = true;
}
}
void VmInterface::FloatingIpList::Remove(FloatingIpSet::iterator &it) {
it->set_del_pending(true);
}
/////////////////////////////////////////////////////////////////////////////
// StaticRoute routines
/////////////////////////////////////////////////////////////////////////////
VmInterface::StaticRoute::StaticRoute() :
ListEntry(), vrf_(""), addr_(), plen_(0), gw_() {
}
VmInterface::StaticRoute::StaticRoute(const StaticRoute &rhs) :
ListEntry(rhs.installed_, rhs.del_pending_), vrf_(rhs.vrf_),
addr_(rhs.addr_), plen_(rhs.plen_), gw_(rhs.gw_) {
}
VmInterface::StaticRoute::StaticRoute(const std::string &vrf,
const IpAddress &addr,
uint32_t plen, const IpAddress &gw) :
ListEntry(), vrf_(vrf), addr_(addr), plen_(plen), gw_(gw) {
}
VmInterface::StaticRoute::~StaticRoute() {
}
bool VmInterface::StaticRoute::operator() (const StaticRoute &lhs,
const StaticRoute &rhs) const {
return lhs.IsLess(&rhs);
}
bool VmInterface::StaticRoute::IsLess(const StaticRoute *rhs) const {
#if 0
//Enable once we can add static routes across vrf
if (vrf_name_ != rhs->vrf_name_)
return vrf_name_ < rhs->vrf_name_;
#endif
if (addr_ != rhs->addr_)
return addr_ < rhs->addr_;
if (plen_ < rhs->plen_) {
return plen_ < rhs->plen_;
}
return gw_ < rhs->gw_;
}
void VmInterface::StaticRoute::Activate(VmInterface *interface,
bool force_update,
bool policy_change) const {
bool ecmp = false;
if (installed_ && force_update == false && policy_change == false)
return;
if (vrf_ != interface->vrf()->GetName()) {
vrf_ = interface->vrf()->GetName();
}
if (installed_ == true && policy_change) {
InetUnicastAgentRouteTable::ReEvaluatePaths(interface->agent(),
vrf_, addr_, plen_);
} else if (installed_ == false || force_update) {
if (addr_.is_v4()) {
ecmp = interface->ecmp();
}
Ip4Address gw_ip(0);
if (gw_.is_v4() && addr_.is_v4() && gw_.to_v4() != gw_ip) {
SecurityGroupList sg_id_list;
interface->CopySgIdList(&sg_id_list);
InetUnicastAgentRouteTable::AddGatewayRoute(interface->peer_.get(),
vrf_, addr_.to_v4(),
plen_, gw_.to_v4(), interface->vn_->GetName(),
interface->vrf_->table_label(),
sg_id_list);
} else {
interface->AddRoute(vrf_, addr_, plen_,
interface->vn_->GetName(),
interface->policy_enabled(),
ecmp, IpAddress(), interface->primary_ip_addr());
}
}
installed_ = true;
}
void VmInterface::StaticRoute::DeActivate(VmInterface *interface) const {
if (installed_ == false)
return;
interface->DeleteRoute(vrf_, addr_, plen_);
installed_ = false;
}
void VmInterface::StaticRouteList::Insert(const StaticRoute *rhs) {
list_.insert(*rhs);
}
void VmInterface::StaticRouteList::Update(const StaticRoute *lhs,
const StaticRoute *rhs) {
}
void VmInterface::StaticRouteList::Remove(StaticRouteSet::iterator &it) {
it->set_del_pending(true);
}
///////////////////////////////////////////////////////////////////////////////
//Allowed addresss pair route
///////////////////////////////////////////////////////////////////////////////
VmInterface::AllowedAddressPair::AllowedAddressPair() :
ListEntry(), vrf_(""), addr_(0), plen_(0), ecmp_(false), mac_(),
l2_entry_installed_(false), ethernet_tag_(0), vrf_ref_(NULL, this), gw_ip_(0) {
}
VmInterface::AllowedAddressPair::AllowedAddressPair(
const AllowedAddressPair &rhs) : ListEntry(rhs.installed_,
rhs.del_pending_), vrf_(rhs.vrf_), addr_(rhs.addr_), plen_(rhs.plen_),
ecmp_(rhs.ecmp_), mac_(rhs.mac_),
l2_entry_installed_(rhs.l2_entry_installed_), ethernet_tag_(rhs.ethernet_tag_),
vrf_ref_(rhs.vrf_ref_, this), gw_ip_(rhs.gw_ip_) {
}
VmInterface::AllowedAddressPair::AllowedAddressPair(const std::string &vrf,
const Ip4Address &addr,
uint32_t plen, bool ecmp,
const MacAddress &mac) :
ListEntry(), vrf_(vrf), addr_(addr), plen_(plen), ecmp_(ecmp), mac_(mac),
l2_entry_installed_(false), ethernet_tag_(0), vrf_ref_(NULL, this) {
}
VmInterface::AllowedAddressPair::~AllowedAddressPair() {
}
bool VmInterface::AllowedAddressPair::operator() (const AllowedAddressPair &lhs,
const AllowedAddressPair &rhs)
const {
return lhs.IsLess(&rhs);
}
bool VmInterface::AllowedAddressPair::IsLess(const AllowedAddressPair *rhs) const {
#if 0
//Enable once we can add static routes across vrf
if (vrf_name_ != rhs->vrf_name_)
return vrf_name_ < rhs->vrf_name_;
#endif
if (addr_ != rhs->addr_)
return addr_ < rhs->addr_;
if (plen_ < rhs->plen_) {
return plen_ < rhs->plen_;
}
return mac_ < rhs->mac_;
}
void VmInterface::AllowedAddressPair::L2Activate(VmInterface *interface,
bool force_update,
bool policy_change,
bool old_layer2_forwarding,
bool old_layer3_forwarding) const {
if (mac_ == MacAddress::kZeroMac) {
return;
}
if (l2_entry_installed_ && force_update == false &&
policy_change == false && ethernet_tag_ == interface->ethernet_tag() &&
old_layer3_forwarding == interface->layer3_forwarding()) {
return;
}
if (vrf_ != interface->vrf()->GetName()) {
vrf_ = interface->vrf()->GetName();
}
vrf_ref_ = interface->vrf();
if (old_layer3_forwarding != interface->layer3_forwarding() ||
l2_entry_installed_ == false) {
force_update = true;
}
if (ethernet_tag_ != interface->ethernet_tag()) {
force_update = true;
}
if (l2_entry_installed_ == false || force_update || policy_change) {
Ip4Address dependent_rt = Ip4Address(0);
if (ecmp_ == true) {
dependent_rt = interface->primary_ip_addr();
}
interface->UpdateL2InterfaceRoute(old_layer2_forwarding, force_update,
interface->vrf(), addr_, Ip6Address(),
ethernet_tag_, old_layer3_forwarding,
policy_change, addr_, Ip6Address(), mac_,
dependent_rt);
ethernet_tag_ = interface->ethernet_tag();
//If layer3 forwarding is disabled
// * IP + mac allowed address pair should not be published
// * Only mac allowed address pair should be published
//Logic for same is present in UpdateL2InterfaceRoute
if (interface->layer3_forwarding() || addr_.is_unspecified() == true) {
l2_entry_installed_ = true;
} else {
l2_entry_installed_ = false;
}
}
}
void VmInterface::AllowedAddressPair::L2DeActivate(VmInterface *interface) const{
if (mac_ == MacAddress::kZeroMac) {
return;
}
if (l2_entry_installed_ == false) {
return;
}
interface->DeleteL2InterfaceRoute(true, vrf_ref_.get(), addr_,
Ip6Address(), ethernet_tag_, mac_);
l2_entry_installed_ = false;
vrf_ref_ = NULL;
}
void VmInterface::AllowedAddressPair::Activate(VmInterface *interface,
bool force_update,
bool policy_change) const {
const VnIpam *ipam = interface->vn_->GetIpam(addr_);
Ip4Address ip(0);
if (ipam) {
ip = ipam->default_gw.to_v4();
}
if (installed_ && force_update == false && policy_change == false &&
gw_ip_ == ip) {
return;
}
if (vrf_ != interface->vrf()->GetName()) {
vrf_ = interface->vrf()->GetName();
}
if (installed_ == true && policy_change) {
InetUnicastAgentRouteTable::ReEvaluatePaths(interface->agent(),
vrf_, addr_, plen_);
} else if (installed_ == false || force_update || gw_ip_ != ip) {
gw_ip_ = ip;
Ip4Address dependent_rt = Ip4Address(0);
if (ecmp_ == true) {
dependent_rt = interface->primary_ip_addr();
}
interface->AddRoute(vrf_, addr_, plen_, interface->vn_->GetName(),
interface->policy_enabled(),
ecmp_, gw_ip_, dependent_rt);
}
installed_ = true;
}
void VmInterface::AllowedAddressPair::DeActivate(VmInterface *interface) const {
if (installed_ == false)
return;
interface->DeleteRoute(vrf_, addr_, plen_);
installed_ = false;
}
void VmInterface::AllowedAddressPairList::Insert(const AllowedAddressPair *rhs) {
list_.insert(*rhs);
}
void VmInterface::AllowedAddressPairList::Update(const AllowedAddressPair *lhs,
const AllowedAddressPair *rhs) {
}
void VmInterface::AllowedAddressPairList::Remove(AllowedAddressPairSet::iterator &it) {
it->set_del_pending(true);
}
/////////////////////////////////////////////////////////////////////////////
// SecurityGroup routines
/////////////////////////////////////////////////////////////////////////////
VmInterface::SecurityGroupEntry::SecurityGroupEntry() :
ListEntry(), uuid_(nil_uuid()) {
}
VmInterface::SecurityGroupEntry::SecurityGroupEntry
(const SecurityGroupEntry &rhs) :
ListEntry(rhs.installed_, rhs.del_pending_), uuid_(rhs.uuid_) {
}
VmInterface::SecurityGroupEntry::SecurityGroupEntry(const uuid &u) :
ListEntry(), uuid_(u) {
}
VmInterface::SecurityGroupEntry::~SecurityGroupEntry() {
}
bool VmInterface::SecurityGroupEntry::operator ==
(const SecurityGroupEntry &rhs) const {
return uuid_ == rhs.uuid_;
}
bool VmInterface::SecurityGroupEntry::operator()
(const SecurityGroupEntry &lhs, const SecurityGroupEntry &rhs) const {
return lhs.IsLess(&rhs);
}
bool VmInterface::SecurityGroupEntry::IsLess
(const SecurityGroupEntry *rhs) const {
return uuid_ < rhs->uuid_;
}
void VmInterface::SecurityGroupEntry::Activate(VmInterface *interface) const {
if (sg_.get() != NULL)
return;
Agent *agent = static_cast<InterfaceTable *>
(interface->get_table())->agent();
SgKey sg_key(uuid_);
sg_ = static_cast<SgEntry *>
(agent->sg_table()->FindActiveEntry(&sg_key));
}
void VmInterface::SecurityGroupEntry::DeActivate(VmInterface *interface) const {
}
void VmInterface::SecurityGroupEntryList::Insert
(const SecurityGroupEntry *rhs) {
list_.insert(*rhs);
}
void VmInterface::SecurityGroupEntryList::Update
(const SecurityGroupEntry *lhs, const SecurityGroupEntry *rhs) {
}
void VmInterface::SecurityGroupEntryList::Remove
(SecurityGroupEntrySet::iterator &it) {
it->set_del_pending(true);
}
/////////////////////////////////////////////////////////////////////////////
// ServiceVlan routines
/////////////////////////////////////////////////////////////////////////////
VmInterface::ServiceVlan::ServiceVlan() :
ListEntry(), tag_(0), vrf_name_(""), addr_(0), plen_(32), smac_(), dmac_(),
vrf_(NULL, this), label_(MplsTable::kInvalidLabel) {
}
VmInterface::ServiceVlan::ServiceVlan(const ServiceVlan &rhs) :
ListEntry(rhs.installed_, rhs.del_pending_), tag_(rhs.tag_),
vrf_name_(rhs.vrf_name_), addr_(rhs.addr_), plen_(rhs.plen_),
smac_(rhs.smac_), dmac_(rhs.dmac_), vrf_(rhs.vrf_, this), label_(rhs.label_) {
}
VmInterface::ServiceVlan::ServiceVlan(uint16_t tag, const std::string &vrf_name,
const Ip4Address &addr, uint8_t plen,
const MacAddress &smac,
const MacAddress &dmac) :
ListEntry(), tag_(tag), vrf_name_(vrf_name), addr_(addr), plen_(plen),
smac_(smac), dmac_(dmac), vrf_(NULL, this), label_(MplsTable::kInvalidLabel)
{
}
VmInterface::ServiceVlan::~ServiceVlan() {
}
bool VmInterface::ServiceVlan::operator() (const ServiceVlan &lhs,
const ServiceVlan &rhs) const {
return lhs.IsLess(&rhs);
}
bool VmInterface::ServiceVlan::IsLess(const ServiceVlan *rhs) const {
return tag_ < rhs->tag_;
}
void VmInterface::ServiceVlan::Activate(VmInterface *interface,
bool force_update) const {
InterfaceTable *table =
static_cast<InterfaceTable *>(interface->get_table());
VrfEntry *vrf = table->FindVrfRef(vrf_name_);
assert(vrf);
if (label_ == MplsTable::kInvalidLabel) {
VlanNH::Create(interface->GetUuid(), tag_, vrf_name_, smac_, dmac_);
label_ = table->agent()->mpls_table()->AllocLabel();
MplsLabel::CreateVlanNh(table->agent(), label_,
interface->GetUuid(), tag_);
VrfAssignTable::CreateVlan(interface->GetUuid(), vrf_name_, tag_);
}
if (vrf_.get() != vrf) {
interface->ServiceVlanRouteDel(*this);
vrf_ = vrf;
installed_ = false;
}
if (installed_ && force_update == false)
return;
interface->ServiceVlanRouteAdd(*this);
installed_ = true;
}
void VmInterface::ServiceVlan::DeActivate(VmInterface *interface) const {
if (label_ != MplsTable::kInvalidLabel) {
VrfAssignTable::DeleteVlan(interface->GetUuid(), tag_);
interface->ServiceVlanRouteDel(*this);
Agent *agent =
static_cast<InterfaceTable *>(interface->get_table())->agent();
MplsLabel::Delete(agent, label_);
label_ = MplsTable::kInvalidLabel;
VlanNH::Delete(interface->GetUuid(), tag_);
vrf_ = NULL;
}
installed_ = false;
return;
}
void VmInterface::ServiceVlanList::Insert(const ServiceVlan *rhs) {
list_.insert(*rhs);
}
void VmInterface::ServiceVlanList::Update(const ServiceVlan *lhs,
const ServiceVlan *rhs) {
}
void VmInterface::ServiceVlanList::Remove(ServiceVlanSet::iterator &it) {
it->set_del_pending(true);
}
uint32_t VmInterface::GetServiceVlanLabel(const VrfEntry *vrf) const {
ServiceVlanSet::const_iterator it = service_vlan_list_.list_.begin();
while (it != service_vlan_list_.list_.end()) {
if (it->vrf_.get() == vrf) {
return it->label_;
}
it++;
}
return 0;
}
uint32_t VmInterface::GetServiceVlanTag(const VrfEntry *vrf) const {
ServiceVlanSet::const_iterator it = service_vlan_list_.list_.begin();
while (it != service_vlan_list_.list_.end()) {
if (it->vrf_.get() == vrf) {
return it->tag_;
}
it++;
}
return 0;
}
const VrfEntry* VmInterface::GetServiceVlanVrf(uint16_t vlan_tag) const {
ServiceVlanSet::const_iterator it = service_vlan_list_.list_.begin();
while (it != service_vlan_list_.list_.end()) {
if (it->tag_ == vlan_tag) {
return it->vrf_.get();
}
it++;
}
return NULL;
}
void VmInterface::ServiceVlanRouteAdd(const ServiceVlan &entry) {
if (vrf_.get() == NULL ||
vn_.get() == NULL) {
return;
}
SecurityGroupList sg_id_list;
CopySgIdList(&sg_id_list);
PathPreference path_preference;
SetPathPreference(&path_preference, ecmp(), primary_ip_addr());
// With IRB model, add L2 Receive route for SMAC and DMAC to ensure
// packets from service vm go thru routing
BridgeAgentRouteTable *table = static_cast<BridgeAgentRouteTable *>
(vrf_->GetBridgeRouteTable());
table->AddBridgeReceiveRoute(peer_.get(), entry.vrf_->GetName(),
0, entry.dmac_, vn()->GetName());
table->AddBridgeReceiveRoute(peer_.get(), entry.vrf_->GetName(),
0, entry.smac_, vn()->GetName());
InetUnicastAgentRouteTable::AddVlanNHRoute
(peer_.get(), entry.vrf_->GetName(), entry.addr_, 32,
GetUuid(), entry.tag_, entry.label_, vn()->GetName(), sg_id_list,
path_preference);
entry.installed_ = true;
return;
}
void VmInterface::ServiceVlanRouteDel(const ServiceVlan &entry) {
if (entry.installed_ == false) {
return;
}
InetUnicastAgentRouteTable::Delete
(peer_.get(), entry.vrf_->GetName(), entry.addr_, 32);
// Delete the L2 Recive routes added for smac_ and dmac_
BridgeAgentRouteTable *table = static_cast<BridgeAgentRouteTable *>
(entry.vrf_->GetBridgeRouteTable());
table->Delete(peer_.get(), entry.vrf_->GetName(), entry.dmac_,
0);
table->Delete(peer_.get(), entry.vrf_->GetName(), entry.smac_,
0);
entry.installed_ = false;
return;
}
bool VmInterface::HasFloatingIp(Address::Family family) const {
if (family == Address::INET) {
return floating_ip_list_.v4_count_ > 0;
} else {
return floating_ip_list_.v6_count_ > 0;
}
}
bool VmInterface::HasFloatingIp() const {
return floating_ip_list_.list_.size() != 0;
}
bool VmInterface::IsFloatingIp(const IpAddress &ip) const {
VmInterface::FloatingIpSet::const_iterator it =
floating_ip_list_.list_.begin();
while(it != floating_ip_list_.list_.end()) {
if ((*it).floating_ip_ == ip) {
return true;
}
it++;
}
return false;
}
////////////////////////////////////////////////////////////////////////////
// VRF assign rule routines
////////////////////////////////////////////////////////////////////////////
VmInterface::VrfAssignRule::VrfAssignRule():
ListEntry(), id_(0), vrf_name_(" "), vrf_(NULL, this), ignore_acl_(false) {
}
VmInterface::VrfAssignRule::VrfAssignRule(const VrfAssignRule &rhs):
ListEntry(rhs.installed_, rhs.del_pending_), id_(rhs.id_),
vrf_name_(rhs.vrf_name_), vrf_(rhs.vrf_, this), ignore_acl_(rhs.ignore_acl_),
match_condition_(rhs.match_condition_) {
}
VmInterface::VrfAssignRule::VrfAssignRule(uint32_t id,
const autogen::MatchConditionType &match_condition,
const std::string &vrf_name,
bool ignore_acl):
ListEntry(), id_(id), vrf_name_(vrf_name), vrf_(NULL, this),
ignore_acl_(ignore_acl), match_condition_(match_condition) {
}
VmInterface::VrfAssignRule::~VrfAssignRule() {
}
bool VmInterface::VrfAssignRule::operator() (const VrfAssignRule &lhs,
const VrfAssignRule &rhs) const {
return lhs.IsLess(&rhs);
}
bool VmInterface::VrfAssignRule::IsLess(const VrfAssignRule *rhs) const {
if (id_ != rhs->id_) {
return id_ < rhs->id_;
}
if (vrf_name_ != rhs->vrf_name_) {
return vrf_name_ < rhs->vrf_name_;
}
if (ignore_acl_ != rhs->ignore_acl_) {
return ignore_acl_ < rhs->ignore_acl_;
}
return CompareMatchConditionType(match_condition_, rhs->match_condition_);
}
void VmInterface::VrfAssignRuleList::Insert(const VrfAssignRule *rhs) {
list_.insert(*rhs);
}
void VmInterface::VrfAssignRuleList::Update(const VrfAssignRule *lhs,
const VrfAssignRule *rhs) {
}
void VmInterface::VrfAssignRuleList::Remove(VrfAssignRuleSet::iterator &it) {
it->set_del_pending(true);
}
const string VmInterface::GetAnalyzer() const {
if (mirror_entry()) {
return mirror_entry()->GetAnalyzerName();
} else {
return std::string();
}
}
void VmInterface::SendTrace(Trace event) {
InterfaceInfo intf_info;
intf_info.set_name(name_);
intf_info.set_index(id_);
switch(event) {
case ACTIVATED_IPV4:
intf_info.set_op("IPV4 Activated");
break;
case DEACTIVATED_IPV4:
intf_info.set_op("IPV4 Deactivated");
break;
case ACTIVATED_IPV6:
intf_info.set_op("IPV6 Activated");
break;
case DEACTIVATED_IPV6:
intf_info.set_op("IPV6 Deactivated");
break;
case ACTIVATED_L2:
intf_info.set_op("L2 Activated");
break;
case DEACTIVATED_L2:
intf_info.set_op("L2 Deactivated");
break;
case ADD:
intf_info.set_op("Add");
break;
case DELETE:
intf_info.set_op("Delete");
break;
case FLOATING_IP_CHANGE: {
intf_info.set_op("Floating IP change");
std::vector<FloatingIPInfo> fip_list;
FloatingIpSet::iterator it = floating_ip_list_.list_.begin();
while (it != floating_ip_list_.list_.end()) {
const FloatingIp &ip = *it;
FloatingIPInfo fip;
fip.set_ip_address(ip.floating_ip_.to_string());
fip.set_vrf_name(ip.vrf_->GetName());
fip_list.push_back(fip);
it++;
}
intf_info.set_fip(fip_list);
break;
}
case SERVICE_CHANGE:
break;
}
intf_info.set_ip_address(primary_ip_addr_.to_string());
if (vm_) {
intf_info.set_vm(UuidToString(vm_->GetUuid()));
}
if (vn_) {
intf_info.set_vn(vn_->GetName());
}
if (vrf_) {
intf_info.set_vrf(vrf_->GetName());
}
intf_info.set_vm_project(UuidToString(vm_project_uuid_));
OPER_TRACE(Interface, intf_info);
}
/////////////////////////////////////////////////////////////////////////////
// VM Interface DB Table utility functions
/////////////////////////////////////////////////////////////////////////////
// Add a VM-Interface
void VmInterface::NovaAdd(InterfaceTable *table, const uuid &intf_uuid,
const string &os_name, const Ip4Address &addr,
const string &mac, const string &vm_name,
const uuid &vm_project_uuid, uint16_t tx_vlan_id,
uint16_t rx_vlan_id, const std::string &parent,
const Ip6Address &ip6,
Interface::Transport transport) {
DBRequest req(DBRequest::DB_ENTRY_ADD_CHANGE);
req.key.reset(new VmInterfaceKey(AgentKey::ADD_DEL_CHANGE, intf_uuid,
os_name));
req.data.reset(new VmInterfaceNovaData(addr, ip6, mac, vm_name,
nil_uuid(), vm_project_uuid, parent,
tx_vlan_id, rx_vlan_id,
VmInterface::VM_ON_TAP,
VmInterface::INSTANCE,
transport));
table->Enqueue(&req);
}
// Delete a VM-Interface
void VmInterface::Delete(InterfaceTable *table, const uuid &intf_uuid,
VmInterface::Configurer configurer) {
DBRequest req(DBRequest::DB_ENTRY_DELETE);
req.key.reset(new VmInterfaceKey(AgentKey::ADD_DEL_CHANGE, intf_uuid, ""));
if (configurer == VmInterface::CONFIG) {
req.data.reset(new VmInterfaceConfigData(NULL, NULL));
} else if (configurer == VmInterface::INSTANCE_MSG) {
req.data.reset(new VmInterfaceNovaData());
} else {
assert(0);
}
table->Enqueue(&req);
}
bool VmInterface::CopyIp6Address(const Ip6Address &addr) {
bool ret = false;
// Retain the old if new IP could not be got
if (addr.is_unspecified()) {
return false;
}
if (primary_ip6_addr_ != addr) {
primary_ip6_addr_ = addr;
ret = true;
}
return ret;
}
void VmInterface::UpdateIpv4InstanceIp(bool force_update, bool policy_change,
bool l2,
uint32_t old_ethernet_tag) {
if (l2 && old_ethernet_tag != ethernet_tag()) {
force_update = true;
}
InstanceIpSet::iterator it = instance_ipv4_list_.list_.begin();
while (it != instance_ipv4_list_.list_.end()) {
InstanceIpSet::iterator prev = it++;
if (prev->del_pending_) {
prev->DeActivate(this, l2, vrf(), old_ethernet_tag);
if (prev->installed() == false) {
instance_ipv4_list_.list_.erase(prev);
}
} else {
prev->Activate(this, force_update||policy_change, l2,
old_ethernet_tag);
}
}
}
void VmInterface::DeleteIpv4InstanceIp(bool l2, uint32_t old_ethernet_tag,
VrfEntry *old_vrf_entry) {
InstanceIpSet::iterator it = instance_ipv4_list_.list_.begin();
while (it != instance_ipv4_list_.list_.end()) {
InstanceIpSet::iterator prev = it++;
prev->DeActivate(this, l2, old_vrf_entry, old_ethernet_tag);
if (prev->del_pending_ && prev->installed() == false) {
instance_ipv4_list_.list_.erase(prev);
}
}
}
void VmInterface::UpdateIpv6InstanceIp(bool force_update, bool policy_change,
bool l2,
uint32_t old_ethernet_tag) {
if (l2 && old_ethernet_tag != ethernet_tag()) {
force_update = true;
}
InstanceIpSet::iterator it = instance_ipv6_list_.list_.begin();
while (it != instance_ipv6_list_.list_.end()) {
InstanceIpSet::iterator prev = it++;
if (prev->del_pending_) {
prev->DeActivate(this, l2, vrf(), old_ethernet_tag);
if (prev->installed() == false) {
instance_ipv6_list_.list_.erase(prev);
}
} else {
prev->Activate(this, force_update||policy_change, l2,
old_ethernet_tag);
}
}
}
void VmInterface::DeleteIpv6InstanceIp(bool l2, uint32_t old_ethernet_tag,
VrfEntry *old_vrf_entry) {
InstanceIpSet::iterator it = instance_ipv6_list_.list_.begin();
while (it != instance_ipv6_list_.list_.end()) {
InstanceIpSet::iterator prev = it++;
prev->DeActivate(this, l2, old_vrf_entry, old_ethernet_tag);
if (prev->del_pending_ && prev->installed() == false) {
instance_ipv6_list_.list_.erase(prev);
}
}
}
Add check for VRF delete
In case VRF is deleted, do not continue in WaitForTraffic.
Change-Id: I4db6613eeeead0c9bf74df23f776368c9afb1372
closes-bug: 1495644
(cherry picked from commit 2a33e127c4fc86912f0c9b0b000aa50ec3e0d374)
/*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include <sys/types.h>
#include <net/ethernet.h>
#include <boost/uuid/uuid_io.hpp>
#include "base/logging.h"
#include "db/db.h"
#include "db/db_entry.h"
#include "db/db_table.h"
#include "ifmap/ifmap_node.h"
#include "net/address_util.h"
#include <cfg/cfg_init.h>
#include <cfg/cfg_interface.h>
#include <cmn/agent.h>
#include <init/agent_param.h>
#include <oper/operdb_init.h>
#include <oper/ifmap_dependency_manager.h>
#include <oper/config_manager.h>
#include <oper/route_common.h>
#include <oper/vm.h>
#include <oper/vn.h>
#include <oper/vrf.h>
#include <oper/nexthop.h>
#include <oper/mpls.h>
#include <oper/mirror_table.h>
#include <oper/interface_common.h>
#include <oper/vrf_assign.h>
#include <oper/vxlan.h>
#include <oper/oper_dhcp_options.h>
#include <oper/inet_unicast_route.h>
#include <oper/physical_device_vn.h>
#include <oper/ifmap_dependency_manager.h>
#include <bgp_schema_types.h>
#include <vnc_cfg_types.h>
#include <oper/agent_sandesh.h>
#include <oper/sg.h>
#include "sandesh/sandesh_trace.h"
#include "sandesh/common/vns_types.h"
#include "sandesh/common/vns_constants.h"
#include <filter/acl.h>
using namespace std;
using namespace boost::uuids;
using namespace autogen;
VmInterface::VmInterface(const boost::uuids::uuid &uuid) :
Interface(Interface::VM_INTERFACE, uuid, "", NULL), vm_(NULL),
vn_(NULL), primary_ip_addr_(0), mdata_addr_(0), subnet_bcast_addr_(0),
primary_ip6_addr_(), vm_mac_(""), policy_enabled_(false),
mirror_entry_(NULL), mirror_direction_(MIRROR_RX_TX), cfg_name_(""),
fabric_port_(true), need_linklocal_ip_(false), dhcp_enable_(true),
do_dhcp_relay_(false), vm_name_(),
vm_project_uuid_(nil_uuid()), vxlan_id_(0), bridging_(true),
layer3_forwarding_(true), flood_unknown_unicast_(false),
mac_set_(false), ecmp_(false),
tx_vlan_id_(kInvalidVlanId), rx_vlan_id_(kInvalidVlanId), parent_(NULL),
local_preference_(VmInterface::INVALID), oper_dhcp_options_(),
sg_list_(), floating_ip_list_(), service_vlan_list_(), static_route_list_(),
allowed_address_pair_list_(), vrf_assign_rule_list_(),
vrf_assign_acl_(NULL), vm_ip_gw_addr_(0), vm_ip6_gw_addr_(),
device_type_(VmInterface::DEVICE_TYPE_INVALID),
vmi_type_(VmInterface::VMI_TYPE_INVALID),
configurer_(0), subnet_(0), subnet_plen_(0), ethernet_tag_(0),
logical_interface_(nil_uuid()), nova_ip_addr_(0), nova_ip6_addr_(),
dhcp_addr_(0) {
ipv4_active_ = false;
ipv6_active_ = false;
l2_active_ = false;
}
VmInterface::VmInterface(const boost::uuids::uuid &uuid,
const std::string &name,
const Ip4Address &addr, const std::string &mac,
const std::string &vm_name,
const boost::uuids::uuid &vm_project_uuid,
uint16_t tx_vlan_id, uint16_t rx_vlan_id,
Interface *parent, const Ip6Address &a6,
DeviceType device_type, VmiType vmi_type) :
Interface(Interface::VM_INTERFACE, uuid, name, NULL), vm_(NULL),
vn_(NULL), primary_ip_addr_(addr), mdata_addr_(0), subnet_bcast_addr_(0),
primary_ip6_addr_(a6), vm_mac_(mac), policy_enabled_(false),
mirror_entry_(NULL), mirror_direction_(MIRROR_RX_TX), cfg_name_(""),
fabric_port_(true), need_linklocal_ip_(false), dhcp_enable_(true),
do_dhcp_relay_(false), vm_name_(vm_name),
vm_project_uuid_(vm_project_uuid), vxlan_id_(0),
bridging_(true), layer3_forwarding_(true),
flood_unknown_unicast_(false), mac_set_(false),
ecmp_(false), tx_vlan_id_(tx_vlan_id), rx_vlan_id_(rx_vlan_id),
parent_(parent), local_preference_(VmInterface::INVALID), oper_dhcp_options_(),
sg_list_(), floating_ip_list_(), service_vlan_list_(), static_route_list_(),
allowed_address_pair_list_(), vrf_assign_rule_list_(),
vrf_assign_acl_(NULL), device_type_(device_type),
vmi_type_(vmi_type), configurer_(0), subnet_(0),
subnet_plen_(0), ethernet_tag_(0), logical_interface_(nil_uuid()),
nova_ip_addr_(0), nova_ip6_addr_(), dhcp_addr_(0) {
ipv4_active_ = false;
ipv6_active_ = false;
l2_active_ = false;
}
VmInterface::~VmInterface() {
}
bool VmInterface::CmpInterface(const DBEntry &rhs) const {
const VmInterface &intf=static_cast<const VmInterface &>(rhs);
return uuid_ < intf.uuid_;
}
/////////////////////////////////////////////////////////////////////////////
// Template function to audit two lists. This is used to synchronize the
// operational and config list for Floating-IP, Service-Vlans, Static Routes
// and SG List
/////////////////////////////////////////////////////////////////////////////
template<class List, class Iterator>
bool AuditList(List &list, Iterator old_first, Iterator old_last,
Iterator new_first, Iterator new_last) {
bool ret = false;
Iterator old_iterator = old_first;
Iterator new_iterator = new_first;
while (old_iterator != old_last && new_iterator != new_last) {
if (old_iterator->IsLess(new_iterator.operator->())) {
Iterator bkp = old_iterator++;
list.Remove(bkp);
ret = true;
} else if (new_iterator->IsLess(old_iterator.operator->())) {
Iterator bkp = new_iterator++;
list.Insert(bkp.operator->());
ret = true;
} else {
Iterator old_bkp = old_iterator++;
Iterator new_bkp = new_iterator++;
list.Update(old_bkp.operator->(), new_bkp.operator->());
ret = true;
}
}
while (old_iterator != old_last) {
Iterator bkp = old_iterator++;
list.Remove(bkp);
ret = true;
}
while (new_iterator != new_last) {
Iterator bkp = new_iterator++;
list.Insert(bkp.operator->());
ret = true;
}
return ret;
}
// Build one Floating IP entry for a virtual-machine-interface
static void BuildFloatingIpList(Agent *agent, VmInterfaceConfigData *data,
IFMapNode *node) {
ConfigManager *cfg_manager= agent->config_manager();
if (cfg_manager->SkipNode(node)) {
return;
}
// Find VRF for the floating-ip. Following path in graphs leads to VRF
// virtual-machine-port <-> floating-ip <-> floating-ip-pool
// <-> virtual-network <-> routing-instance
IFMapAgentTable *fip_table = static_cast<IFMapAgentTable *>(node->table());
DBGraph *fip_graph = fip_table->GetGraph();
// Iterate thru links for floating-ip looking for floating-ip-pool node
for (DBGraphVertex::adjacency_iterator fip_iter = node->begin(fip_graph);
fip_iter != node->end(fip_graph); ++fip_iter) {
IFMapNode *pool_node = static_cast<IFMapNode *>(fip_iter.operator->());
if (cfg_manager->SkipNode
(pool_node, agent->cfg()->cfg_floatingip_pool_table())) {
continue;
}
// Iterate thru links for floating-ip-pool looking for virtual-network
IFMapAgentTable *pool_table =
static_cast<IFMapAgentTable *> (pool_node->table());
DBGraph *pool_graph = pool_table->GetGraph();
for (DBGraphVertex::adjacency_iterator pool_iter =
pool_node->begin(pool_graph);
pool_iter != pool_node->end(pool_graph); ++pool_iter) {
IFMapNode *vn_node =
static_cast<IFMapNode *>(pool_iter.operator->());
if (cfg_manager->SkipNode
(vn_node, agent->cfg()->cfg_vn_table())) {
continue;
}
VirtualNetwork *cfg = static_cast <VirtualNetwork *>
(vn_node->GetObject());
assert(cfg);
autogen::IdPermsType id_perms = cfg->id_perms();
boost::uuids::uuid vn_uuid;
CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong,
vn_uuid);
IFMapAgentTable *vn_table =
static_cast<IFMapAgentTable *> (vn_node->table());
DBGraph *vn_graph = vn_table->GetGraph();
// Iterate thru links for virtual-network looking for
// routing-instance
for (DBGraphVertex::adjacency_iterator vn_iter =
vn_node->begin(vn_graph);
vn_iter != vn_node->end(vn_graph); ++vn_iter) {
IFMapNode *vrf_node =
static_cast<IFMapNode *>(vn_iter.operator->());
if (cfg_manager->SkipNode
(vrf_node, agent->cfg()->cfg_vrf_table())){
continue;
}
// Checking whether it is default vrf of not
RoutingInstance *ri = static_cast<RoutingInstance *>(vrf_node->GetObject());
if(!(ri->is_default())) {
continue;
}
FloatingIp *fip = static_cast<FloatingIp *>(node->GetObject());
assert(fip != NULL);
LOG(DEBUG, "Add FloatingIP <" << fip->address() << ":" <<
vrf_node->name() << "> to interface " << node->name());
boost::system::error_code ec;
IpAddress addr = IpAddress::from_string(fip->address(), ec);
if (ec.value() != 0) {
LOG(DEBUG, "Error decoding Floating IP address "
<< fip->address());
} else {
IpAddress fixed_ip_addr =
IpAddress::from_string(fip->fixed_ip_address(), ec);
if (ec.value() != 0) {
fixed_ip_addr = Ip4Address(0);
}
data->floating_ip_list_.list_.insert
(VmInterface::FloatingIp(addr, vrf_node->name(),
vn_uuid, fixed_ip_addr));
if (addr.is_v4()) {
data->floating_ip_list_.v4_count_++;
} else {
data->floating_ip_list_.v6_count_++;
}
}
break;
}
break;
}
break;
}
return;
}
// Build list of static-routes on virtual-machine-interface
static void BuildStaticRouteList(VmInterfaceConfigData *data, IFMapNode *node) {
InterfaceRouteTable *entry =
static_cast<InterfaceRouteTable*>(node->GetObject());
assert(entry);
for (std::vector<RouteType>::const_iterator it = entry->routes().begin();
it != entry->routes().end(); it++) {
int plen;
boost::system::error_code ec;
IpAddress ip;
bool add = false;
Ip4Address ip4;
ec = Ip4PrefixParse(it->prefix, &ip4, &plen);
if (ec.value() == 0) {
ip = ip4;
add = true;
} else {
Ip6Address ip6;
ec = Inet6PrefixParse(it->prefix, &ip6, &plen);
if (ec.value() == 0) {
ip = ip6;
add = true;
} else {
LOG(DEBUG, "Error decoding v4/v6 Static Route address " << it->prefix);
}
}
IpAddress gw = IpAddress::from_string(it->next_hop, ec);
if (ec) {
gw = IpAddress::from_string("0.0.0.0", ec);
}
if (add) {
data->static_route_list_.list_.insert
(VmInterface::StaticRoute(data->vrf_name_, ip, plen, gw));
}
}
}
static void BuildResolveRoute(VmInterfaceConfigData *data, IFMapNode *node) {
Subnet *entry =
static_cast<Subnet *>(node->GetObject());
assert(entry);
Ip4Address ip;
boost::system::error_code ec;
ip = Ip4Address::from_string(entry->ip_prefix().ip_prefix, ec);
if (ec.value() == 0) {
data->subnet_ = ip;
data->subnet_plen_ = entry->ip_prefix().ip_prefix_len;
}
}
static void BuildAllowedAddressPairRouteList(VirtualMachineInterface *cfg,
VmInterfaceConfigData *data) {
for (std::vector<AllowedAddressPair>::const_iterator it =
cfg->allowed_address_pairs().begin();
it != cfg->allowed_address_pairs().end(); ++it) {
boost::system::error_code ec;
int plen = it->ip.ip_prefix_len;
Ip4Address ip = Ip4Address::from_string(it->ip.ip_prefix, ec);
if (ec.value() != 0) {
continue;
}
MacAddress mac = MacAddress::FromString(it->mac, &ec);
if (ec.value() != 0) {
mac.Zero();
}
if (ip.is_unspecified() && mac == MacAddress::kZeroMac) {
continue;
}
bool ecmp = false;
if (it->address_mode == "active-active") {
ecmp = true;
}
VmInterface::AllowedAddressPair entry(data->vrf_name_, ip, plen,
ecmp, mac);
data->allowed_address_pair_list_.list_.insert(entry);
}
}
// Build VM Interface VRF or one Service Vlan entry for VM Interface
static void BuildVrfAndServiceVlanInfo(Agent *agent,
VmInterfaceConfigData *data,
IFMapNode *node) {
ConfigManager *cfg_manager= agent->config_manager();
VirtualMachineInterfaceRoutingInstance *entry =
static_cast<VirtualMachineInterfaceRoutingInstance*>(node->GetObject());
assert(entry);
// Ignore node if direction is not yet set. An update will come later
const PolicyBasedForwardingRuleType &rule = entry->data();
if (rule.direction == "") {
return;
}
// Find VRF by looking for link
// virtual-machine-interface-routing-instance <-> routing-instance
IFMapAgentTable *table = static_cast<IFMapAgentTable *>(node->table());
DBGraph *graph = table->GetGraph();
// Iterate thru links looking for routing-instance node
for (DBGraphVertex::adjacency_iterator iter = node->begin(graph);
iter != node->end(graph); ++iter) {
IFMapNode *vrf_node = static_cast<IFMapNode *>(iter.operator->());
if (cfg_manager->SkipNode
(vrf_node, agent->cfg()->cfg_vrf_table())) {
continue;
}
if (rule.vlan_tag == 0 && rule.protocol == ""
&& rule.service_chain_address == "") {
data->vrf_name_ = vrf_node->name();
} else {
boost::system::error_code ec;
Ip4Address addr = Ip4Address::from_string
(rule.service_chain_address, ec);
if (ec.value() != 0) {
LOG(DEBUG, "Error decoding Service VLAN IP address "
<< rule.service_chain_address);
break;
}
if (rule.vlan_tag > 4093) {
LOG(DEBUG, "Invalid VLAN Tag " << rule.vlan_tag);
break;
}
LOG(DEBUG, "Add Service VLAN entry <" << rule.vlan_tag << " : "
<< rule.service_chain_address << " : " << vrf_node->name());
MacAddress smac(agent->vrrp_mac());
MacAddress dmac = MacAddress::FromString(Agent::BcastMac());
if (rule.src_mac != Agent::NullString()) {
smac = MacAddress::FromString(rule.src_mac);
}
if (rule.src_mac != Agent::NullString()) {
dmac = MacAddress::FromString(rule.dst_mac);
}
data->service_vlan_list_.list_.insert
(VmInterface::ServiceVlan(rule.vlan_tag, vrf_node->name(), addr,
32, smac, dmac));
}
break;
}
return;
}
static void BuildInstanceIp(Agent *agent, VmInterfaceConfigData *data,
IFMapNode *node) {
InstanceIp *ip = static_cast<InstanceIp *>(node->GetObject());
boost::system::error_code err;
IpAddress addr = IpAddress::from_string(ip->address(), err);
bool is_primary = false;
if (ip->secondary() != true) {
is_primary = true;
if (addr.is_v4()) {
if (data->addr_ == Ip4Address(0) ||
data->addr_ > addr.to_v4()) {
data->addr_ = addr.to_v4();
if (ip->mode() == "active-active") {
data->ecmp_ = true;
} else {
data->ecmp_ = false;
}
}
} else if (addr.is_v6()) {
if (data->ip6_addr_ == Ip6Address() ||
data->ip6_addr_ > addr.to_v6()) {
data->ip6_addr_ = addr.to_v6();
}
if (ip->mode() == "active-active") {
data->ecmp_ = true;
} else {
data->ecmp_ = false;
}
}
}
bool ecmp = false;
if (ip->mode() == "active-active") {
ecmp = true;
}
if (addr.is_v4()) {
data->instance_ipv4_list_.list_.insert(
VmInterface::InstanceIp(addr, ecmp, is_primary));
} else {
data->instance_ipv6_list_.list_.insert(
VmInterface::InstanceIp(addr, ecmp, is_primary));
}
}
static void BuildSgList(VmInterfaceConfigData *data, IFMapNode *node) {
SecurityGroup *sg_cfg = static_cast<SecurityGroup *>
(node->GetObject());
assert(sg_cfg);
autogen::IdPermsType id_perms = sg_cfg->id_perms();
uint32_t sg_id = SgTable::kInvalidSgId;
stringToInteger(sg_cfg->id(), sg_id);
if (sg_id != SgTable::kInvalidSgId) {
uuid sg_uuid = nil_uuid();
CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong,
sg_uuid);
data->sg_list_.list_.insert
(VmInterface::SecurityGroupEntry(sg_uuid));
}
}
static void BuildVn(VmInterfaceConfigData *data, IFMapNode *node,
const boost::uuids::uuid &u, CfgIntEntry *cfg_entry) {
VirtualNetwork *vn = static_cast<VirtualNetwork *>
(node->GetObject());
assert(vn);
autogen::IdPermsType id_perms = vn->id_perms();
CfgUuidSet(id_perms.uuid.uuid_mslong,
id_perms.uuid.uuid_lslong, data->vn_uuid_);
if (cfg_entry && (cfg_entry->GetVnUuid() != data->vn_uuid_)) {
IFMAP_ERROR(InterfaceConfiguration,
"Virtual-network UUID mismatch for interface:",
UuidToString(u),
"configuration VN uuid",
UuidToString(data->vn_uuid_),
"compute VN uuid",
UuidToString(cfg_entry->GetVnUuid()));
}
}
static void BuildVm(VmInterfaceConfigData *data, IFMapNode *node,
const boost::uuids::uuid &u, CfgIntEntry *cfg_entry) {
VirtualMachine *vm = static_cast<VirtualMachine *>
(node->GetObject());
assert(vm);
autogen::IdPermsType id_perms = vm->id_perms();
CfgUuidSet(id_perms.uuid.uuid_mslong,
id_perms.uuid.uuid_lslong, data->vm_uuid_);
if (cfg_entry && (cfg_entry->GetVmUuid() != data->vm_uuid_)) {
IFMAP_ERROR(InterfaceConfiguration,
"Virtual-machine UUID mismatch for interface:",
UuidToString(u),
"configuration VM UUID is",
UuidToString(data->vm_uuid_),
"compute VM uuid is",
UuidToString(cfg_entry->GetVnUuid()));
}
}
// Get DHCP configuration
static void ReadDhcpOptions(VirtualMachineInterface *cfg,
VmInterfaceConfigData &data) {
data.oper_dhcp_options_.set_options(cfg->dhcp_option_list());
data.oper_dhcp_options_.set_host_routes(cfg->host_routes());
}
// Get interface mirror configuration.
static void ReadAnalyzerNameAndCreate(Agent *agent,
VirtualMachineInterface *cfg,
VmInterfaceConfigData &data) {
if (!cfg) {
return;
}
MirrorActionType mirror_to = cfg->properties().interface_mirror.mirror_to;
if (!mirror_to.analyzer_name.empty()) {
boost::system::error_code ec;
IpAddress dip = IpAddress::from_string(mirror_to.analyzer_ip_address,
ec);
if (ec.value() != 0) {
return;
}
uint16_t dport;
if (mirror_to.udp_port) {
dport = mirror_to.udp_port;
} else {
dport = ContrailPorts::AnalyzerUdpPort();
}
agent->mirror_table()->AddMirrorEntry
(mirror_to.analyzer_name, std::string(), agent->router_id(),
agent->mirror_port(), dip.to_v4(), dport);
data.analyzer_name_ = mirror_to.analyzer_name;
string traffic_direction =
cfg->properties().interface_mirror.traffic_direction;
if (traffic_direction.compare("egress") == 0) {
data.mirror_direction_ = Interface::MIRROR_TX;
} else if (traffic_direction.compare("ingress") == 0) {
data.mirror_direction_ = Interface::MIRROR_RX;
} else {
data.mirror_direction_ = Interface::MIRROR_RX_TX;
}
}
}
static void BuildVrfAssignRule(VirtualMachineInterface *cfg,
VmInterfaceConfigData *data) {
uint32_t id = 1;
for (std::vector<VrfAssignRuleType>::const_iterator iter =
cfg->vrf_assign_table().begin(); iter != cfg->vrf_assign_table().end();
++iter) {
VmInterface::VrfAssignRule entry(id++, iter->match_condition,
iter->routing_instance,
iter->ignore_acl);
data->vrf_assign_rule_list_.list_.insert(entry);
}
}
static IFMapNode *FindTarget(IFMapAgentTable *table, IFMapNode *node,
const std::string &node_type) {
for (DBGraphVertex::adjacency_iterator it = node->begin(table->GetGraph());
it != node->end(table->GetGraph()); ++it) {
IFMapNode *adj_node = static_cast<IFMapNode *>(it.operator->());
if (adj_node->table()->Typename() == node_type)
return adj_node;
}
return NULL;
}
static void ReadDhcpEnable(Agent *agent, VmInterfaceConfigData *data,
IFMapNode *node) {
IFMapAgentTable *table = static_cast<IFMapAgentTable *>(node->table());
for (DBGraphVertex::adjacency_iterator it = node->begin(table->GetGraph());
it != node->end(table->GetGraph()); ++it) {
IFMapNode *adj_node = static_cast<IFMapNode *>(it.operator->());
IFMapNode *ipam_node = NULL;
if (adj_node->table() == agent->cfg()->cfg_vn_network_ipam_table() &&
(ipam_node = FindTarget(table, adj_node, "network-ipam"))) {
VirtualNetworkNetworkIpam *ipam =
static_cast<VirtualNetworkNetworkIpam *>(adj_node->GetObject());
assert(ipam);
const VnSubnetsType &subnets = ipam->data();
boost::system::error_code ec;
for (unsigned int i = 0; i < subnets.ipam_subnets.size(); ++i) {
if (IsIp4SubnetMember(data->addr_,
Ip4Address::from_string(
subnets.ipam_subnets[i].subnet.ip_prefix, ec),
subnets.ipam_subnets[i].subnet.ip_prefix_len)) {
data->dhcp_enable_ = subnets.ipam_subnets[i].enable_dhcp;
return;
}
}
}
}
}
// Check if VMI is a sub-interface. Sub-interface will have
// sub_interface_vlan_tag property set to non-zero
static bool IsVlanSubInterface(VirtualMachineInterface *cfg) {
if (cfg->IsPropertySet(VirtualMachineInterface::PROPERTIES) == false)
return false;
if (cfg->properties().sub_interface_vlan_tag == 0)
return false;
return true;
}
// Builds parent for VMI (not to be confused with parent ifmap-node)
// Possible values are,
// - logical-interface : Incase of baremetals
// - virtual-machine-interface : We support virtual-machine-interface
// sub-interfaces. In this case, another virtual-machine-interface itself
// can be a parent
static PhysicalRouter *BuildParentInfo(Agent *agent,
VmInterfaceConfigData *data,
VirtualMachineInterface *cfg,
IFMapNode *node,
IFMapNode *logical_node,
IFMapNode *parent_vmi_node) {
if (logical_node) {
IFMapNode *physical_node = agent->config_manager()->
FindAdjacentIFMapNode(logical_node, "physical-interface");
agent->interface_table()->
LogicalInterfaceIFNodeToUuid(logical_node, data->logical_interface_);
// Find phyiscal-interface for the VMI
IFMapNode *prouter_node = NULL;
if (physical_node) {
data->physical_interface_ = physical_node->name();
// Find vrouter for the physical interface
prouter_node = agent->config_manager()->
FindAdjacentIFMapNode(physical_node, "physical-router");
}
if (prouter_node == NULL)
return NULL;
return static_cast<PhysicalRouter *>(prouter_node->GetObject());
}
// Check if this is VLAN sub-interface VMI
if (IsVlanSubInterface(cfg) == false) {
return NULL;
}
if (parent_vmi_node == false)
return NULL;
// process Parent VMI for sub-interface
VirtualMachineInterface *parent_cfg =
static_cast <VirtualMachineInterface *> (parent_vmi_node->GetObject());
assert(parent_cfg);
if (IsVlanSubInterface(parent_cfg)) {
return NULL;
}
autogen::IdPermsType id_perms = parent_cfg->id_perms();
CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong,
data->parent_vmi_);
data->rx_vlan_id_ = cfg->properties().sub_interface_vlan_tag;
data->tx_vlan_id_ = cfg->properties().sub_interface_vlan_tag;
return NULL;
}
static void BuildAttributes(Agent *agent, IFMapNode *node,
VirtualMachineInterface *cfg,
VmInterfaceConfigData *data) {
//Extract the local preference
if (cfg->IsPropertySet(VirtualMachineInterface::PROPERTIES)) {
autogen::VirtualMachineInterfacePropertiesType prop = cfg->properties();
//Service instance also would have VirtualMachineInterface
//properties field set, pick up local preference
//value only when it has been initialized to proper
//value, if its 0, ignore the local preference
if (prop.local_preference) {
data->local_preference_ = VmInterface::LOW;
if (prop.local_preference == VmInterface::HIGH) {
data->local_preference_ = VmInterface::HIGH;
}
}
}
ReadAnalyzerNameAndCreate(agent, cfg, *data);
// Fill DHCP option data
ReadDhcpOptions(cfg, *data);
//Fill config data items
data->cfg_name_ = node->name();
data->admin_state_ = cfg->id_perms().enable;
BuildVrfAssignRule(cfg, data);
BuildAllowedAddressPairRouteList(cfg, data);
if (cfg->mac_addresses().size()) {
data->vm_mac_ = cfg->mac_addresses().at(0);
}
}
static void UpdateAttributes(Agent *agent, VmInterfaceConfigData *data) {
// Compute fabric_port_ and need_linklocal_ip_ flags
data->fabric_port_ = false;
data->need_linklocal_ip_ = true;
if (data->vrf_name_ == agent->fabric_vrf_name() ||
data->vrf_name_ == agent->linklocal_vrf_name()) {
data->fabric_port_ = true;
data->need_linklocal_ip_ = false;
}
if (agent->isXenMode()) {
data->need_linklocal_ip_ = false;
}
}
static void ComputeTypeInfo(Agent *agent, VmInterfaceConfigData *data,
CfgIntEntry *cfg_entry, PhysicalRouter *prouter,
IFMapNode *node, IFMapNode *logical_node) {
if (cfg_entry != NULL) {
// Have got InstancePortAdd message. Treat it as VM_ON_TAP by default
// TODO: Need to identify more cases here
data->device_type_ = VmInterface::VM_ON_TAP;
data->vmi_type_ = VmInterface::INSTANCE;
return;
}
data->device_type_ = VmInterface::DEVICE_TYPE_INVALID;
data->vmi_type_ = VmInterface::VMI_TYPE_INVALID;
// Does it have physical-interface
if (data->physical_interface_.empty() == false) {
// no physical-router connected. Should be transient case
if (prouter == NULL) {
// HACK : TSN/ToR agent only supports barements. So, set as
// baremetal anyway
if (agent->tsn_enabled() || agent->tor_agent_enabled()) {
data->device_type_ = VmInterface::TOR;
data->vmi_type_ = VmInterface::BAREMETAL;
}
return;
}
// VMI is either Baremetal or Gateway interface
if (prouter->display_name() == agent->agent_name()) {
// VMI connected to local vrouter. Treat it as GATEWAY
data->device_type_ = VmInterface::LOCAL_DEVICE;
data->vmi_type_ = VmInterface::GATEWAY;
if (logical_node) {
autogen::LogicalInterface *port =
static_cast <autogen::LogicalInterface *>
(logical_node->GetObject());
if (port->vlan_tag()) {
data->rx_vlan_id_ = port->vlan_tag();
data->tx_vlan_id_ = port->vlan_tag();
}
}
return;
} else {
// prouter does not match. Treat as baremetal
data->device_type_ = VmInterface::TOR;
data->vmi_type_ = VmInterface::BAREMETAL;
return;
}
return;
}
// Physical router not specified. Check if this is VMI sub-interface
if (data->parent_vmi_.is_nil() == false) {
data->device_type_ = VmInterface::VM_VLAN_ON_VMI;
data->vmi_type_ = VmInterface::INSTANCE;
return;
}
return;
}
void VmInterface::SetConfigurer(VmInterface::Configurer type) {
configurer_ |= (1 << type);
}
void VmInterface::ResetConfigurer(VmInterface::Configurer type) {
configurer_ &= ~(1 << type);
}
bool VmInterface::IsConfigurerSet(VmInterface::Configurer type) {
return ((configurer_ & (1 << type)) != 0);
}
static bool DeleteVmi(InterfaceTable *table, const uuid &u, DBRequest *req) {
int type = table->GetVmiToVmiType(u);
if (type <= (int)VmInterface::VMI_TYPE_INVALID)
return false;
table->DelVmiToVmiType(u);
// Process delete based on VmiType
if (type == VmInterface::INSTANCE) {
// INSTANCE type are not added by config. We only do RESYNC
req->oper = DBRequest::DB_ENTRY_ADD_CHANGE;
req->key.reset(new VmInterfaceKey(AgentKey::RESYNC, u, ""));
req->data.reset(new VmInterfaceConfigData(NULL, NULL));
return true;
} else {
VmInterface::Delete(table, u, VmInterface::CONFIG);
return false;
}
}
bool InterfaceTable::VmiIFNodeToUuid(IFMapNode *node, boost::uuids::uuid &u) {
VirtualMachineInterface *cfg = static_cast <VirtualMachineInterface *>
(node->GetObject());
autogen::IdPermsType id_perms = cfg->id_perms();
CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong, u);
return true;
}
// Virtual Machine Interface is added or deleted into oper DB from Nova
// messages. The Config notify is used only to change interface.
extern IFMapNode *vn_test_node;
extern IFMapNode *vmi_test_node;
bool InterfaceTable::VmiProcessConfig(IFMapNode *node, DBRequest &req,
const boost::uuids::uuid &u) {
// Get interface UUID
VirtualMachineInterface *cfg = static_cast <VirtualMachineInterface *>
(node->GetObject());
assert(cfg);
// Handle object delete
if (node->IsDeleted()) {
return false;
}
assert(!u.is_nil());
// Get the entry from Interface Config table
CfgIntTable *cfg_table = agent_->interface_config_table();
CfgIntKey cfg_key(u);
CfgIntEntry *cfg_entry =
static_cast <CfgIntEntry *>(cfg_table->Find(&cfg_key));
// Update interface configuration
req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;
VmInterfaceConfigData *data = new VmInterfaceConfigData(agent(), NULL);
data->SetIFMapNode(node);
BuildAttributes(agent_, node, cfg, data);
// Graph walk to get interface configuration
IFMapAgentTable *table = static_cast<IFMapAgentTable *>(node->table());
IFMapNode *vn_node = NULL;
IFMapNode *li_node = NULL;
IFMapNode *parent_vmi_node = NULL;
for (DBGraphVertex::adjacency_iterator iter =
node->begin(table->GetGraph());
iter != node->end(table->GetGraph()); ++iter) {
IFMapNode *adj_node = static_cast<IFMapNode *>(iter.operator->());
if (agent_->config_manager()->SkipNode(adj_node)) {
continue;
}
if (adj_node->table() == agent_->cfg()->cfg_sg_table()) {
BuildSgList(data, adj_node);
}
if (adj_node->table() == agent_->cfg()->cfg_vn_table()) {
vn_node = adj_node;
BuildVn(data, adj_node, u, cfg_entry);
}
if (adj_node->table() == agent_->cfg()->cfg_vm_table()) {
BuildVm(data, adj_node, u, cfg_entry);
}
if (adj_node->table() == agent_->cfg()->cfg_instanceip_table()) {
BuildInstanceIp(agent_, data, adj_node);
}
if (adj_node->table() == agent_->cfg()->cfg_floatingip_table()) {
BuildFloatingIpList(agent_, data, adj_node);
}
if (adj_node->table() == agent_->cfg()->cfg_vm_port_vrf_table()) {
BuildVrfAndServiceVlanInfo(agent_, data, adj_node);
}
if (adj_node->table() == agent_->cfg()->cfg_route_table()) {
BuildStaticRouteList(data, adj_node);
}
if (adj_node->table() == agent_->cfg()->cfg_subnet_table()) {
BuildResolveRoute(data, adj_node);
}
if (adj_node->table() == agent_->cfg()->cfg_logical_port_table()) {
li_node = adj_node;
}
if (adj_node->table() == agent_->cfg()->cfg_vm_interface_table()) {
parent_vmi_node = adj_node;
}
if (adj_node->table() == agent_->cfg()->cfg_logical_port_table()) {
li_node = adj_node;
}
if (adj_node->table() == agent_->cfg()->cfg_vm_interface_table()) {
parent_vmi_node = adj_node;
}
}
UpdateAttributes(agent_, data);
// Get DHCP enable flag from subnet
if (vn_node && data->addr_.to_ulong()) {
ReadDhcpEnable(agent_, data, vn_node);
}
PhysicalRouter *prouter = NULL;
// Build parent for the virtual-machine-interface
prouter = BuildParentInfo(agent_, data, cfg, node, li_node,
parent_vmi_node);
// Compute device-type and vmi-type for the interface
ComputeTypeInfo(agent_, data, cfg_entry, prouter, node, li_node);
InterfaceKey *key = NULL;
if (data->device_type_ == VmInterface::VM_ON_TAP ||
data->device_type_ == VmInterface::DEVICE_TYPE_INVALID) {
key = new VmInterfaceKey(AgentKey::RESYNC, u, "");
} else {
key = new VmInterfaceKey(AgentKey::ADD_DEL_CHANGE, u,
cfg->display_name());
}
if (data->device_type_ != VmInterface::DEVICE_TYPE_INVALID) {
AddVmiToVmiType(u, data->device_type_);
}
req.key.reset(key);
req.data.reset(data);
boost::uuids::uuid dev = nil_uuid();
if (prouter) {
autogen::IdPermsType id_perms = prouter->id_perms();
CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong, dev);
}
UpdatePhysicalDeviceVnEntry(u, dev, data->vn_uuid_, vn_node);
vmi_ifnode_to_req_++;
return true;
}
bool InterfaceTable::VmiIFNodeToReq(IFMapNode *node, DBRequest &req,
const boost::uuids::uuid &u) {
// Handle object delete
if ((req.oper == DBRequest::DB_ENTRY_DELETE) || node->IsDeleted()) {
DelPhysicalDeviceVnEntry(u);
return DeleteVmi(this, u, &req);
}
IFMapDependencyManager *dep = agent()->oper_db()->dependency_manager();
IFMapNodeState *state = dep->IFMapNodeGet(node);
IFMapDependencyManager::IFMapNodePtr vm_node_ref;
if (!state) {
vm_node_ref = dep->SetState(node);
state = dep->IFMapNodeGet(node);
}
if (state->uuid().is_nil())
state->set_uuid(u);
agent()->config_manager()->AddVmiNode(node);
return false;
}
/////////////////////////////////////////////////////////////////////////////
// Routines to manage VmiToPhysicalDeviceVnTree
/////////////////////////////////////////////////////////////////////////////
VmiToPhysicalDeviceVnData::VmiToPhysicalDeviceVnData
(const boost::uuids::uuid &dev, const boost::uuids::uuid &vn) :
dev_(dev), vn_(vn) {
}
VmiToPhysicalDeviceVnData::~VmiToPhysicalDeviceVnData() {
}
void InterfaceTable::UpdatePhysicalDeviceVnEntry(const boost::uuids::uuid &vmi,
boost::uuids::uuid &dev,
boost::uuids::uuid &vn,
IFMapNode *vn_node) {
VmiToPhysicalDeviceVnTree::iterator iter =
vmi_to_physical_device_vn_tree_.find(vmi);
if (iter == vmi_to_physical_device_vn_tree_.end()) {
vmi_to_physical_device_vn_tree_.insert
(make_pair(vmi,VmiToPhysicalDeviceVnData(nil_uuid(), nil_uuid())));
iter = vmi_to_physical_device_vn_tree_.find(vmi);
}
if (iter->second.dev_ != dev || iter->second.vn_ != vn) {
agent()->physical_device_vn_table()->DeleteConfigEntry
(vmi, iter->second.dev_, iter->second.vn_);
}
iter->second.dev_ = dev;
iter->second.vn_ = vn;
agent()->physical_device_vn_table()->AddConfigEntry(vmi, dev, vn);
}
void InterfaceTable::DelPhysicalDeviceVnEntry(const boost::uuids::uuid &vmi) {
VmiToPhysicalDeviceVnTree::iterator iter =
vmi_to_physical_device_vn_tree_.find(vmi);
if (iter == vmi_to_physical_device_vn_tree_.end())
return;
agent()->physical_device_vn_table()->DeleteConfigEntry
(vmi, iter->second.dev_, iter->second.vn_);
vmi_to_physical_device_vn_tree_.erase(iter);
}
/////////////////////////////////////////////////////////////////////////////
// VM Port Key routines
/////////////////////////////////////////////////////////////////////////////
VmInterfaceKey::VmInterfaceKey(AgentKey::DBSubOperation sub_op,
const boost::uuids::uuid &uuid, const std::string &name) :
InterfaceKey(sub_op, Interface::VM_INTERFACE, uuid, name, false) {
}
Interface *VmInterfaceKey::AllocEntry(const InterfaceTable *table) const {
return new VmInterface(uuid_);
}
Interface *VmInterfaceKey::AllocEntry(const InterfaceTable *table,
const InterfaceData *data) const {
const VmInterfaceData *vm_data =
static_cast<const VmInterfaceData *>(data);
VmInterface *vmi = vm_data->OnAdd(table, this);
return vmi;
}
InterfaceKey *VmInterfaceKey::Clone() const {
return new VmInterfaceKey(*this);
}
/////////////////////////////////////////////////////////////////////////////
// VM Port Entry routines
/////////////////////////////////////////////////////////////////////////////
string VmInterface::ToString() const {
return "VM-PORT <" + name() + ">";
}
DBEntryBase::KeyPtr VmInterface::GetDBRequestKey() const {
InterfaceKey *key = new VmInterfaceKey(AgentKey::ADD_DEL_CHANGE, uuid_,
name_);
return DBEntryBase::KeyPtr(key);
}
const Peer *VmInterface::peer() const {
return peer_.get();
}
bool VmInterface::OnChange(VmInterfaceData *data) {
InterfaceTable *table = static_cast<InterfaceTable *>(get_table());
return Resync(table, data);
}
// When VMInterface is added from Config (sub-interface, gateway interface etc.)
// the RESYNC is not called and some of the config like VN and VRF are not
// applied on the interface (See Add() API above). Force change to ensure
// RESYNC is called
void VmInterface::PostAdd() {
InterfaceTable *table = static_cast<InterfaceTable *>(get_table());
DBRequest req;
IFMapNode *node = ifmap_node();
if (node == NULL)
return;
boost::uuids::uuid u;
table->IFNodeToUuid(node, u);
if (table->IFNodeToReq(ifmap_node(), req, u) == true) {
table->Process(req);
}
}
// Handle RESYNC DB Request. Handles multiple sub-types,
// - CONFIG : RESYNC from config message
// - IP_ADDR: RESYNC due to learning IP from DHCP
// - MIRROR : RESYNC due to change in mirror config
bool VmInterface::Resync(const InterfaceTable *table,
const VmInterfaceData *data) {
bool ret = false;
// Copy old values used to update config below
bool old_ipv4_active = ipv4_active_;
bool old_ipv6_active = ipv6_active_;
bool old_l2_active = l2_active_;
bool old_policy = policy_enabled_;
VrfEntryRef old_vrf = vrf_;
Ip4Address old_addr = primary_ip_addr_;
Ip6Address old_v6_addr = primary_ip6_addr_;
bool old_need_linklocal_ip = need_linklocal_ip_;
bool force_update = false;
Ip4Address old_subnet = subnet_;
uint8_t old_subnet_plen = subnet_plen_;
int old_ethernet_tag = ethernet_tag_;
bool old_dhcp_enable = dhcp_enable_;
bool old_layer3_forwarding = layer3_forwarding_;
Ip4Address old_dhcp_addr = dhcp_addr_;
if (data) {
ret = data->OnResync(table, this, &force_update);
}
ipv4_active_ = IsIpv4Active();
ipv6_active_ = IsIpv6Active();
l2_active_ = IsL2Active();
if (ipv4_active_ != old_ipv4_active) {
InterfaceTable *intf_table = static_cast<InterfaceTable *>(get_table());
if (ipv4_active_)
intf_table->incr_active_vmi_count();
else
intf_table->decr_active_vmi_count();
ret = true;
}
if (ipv6_active_ != old_ipv6_active) {
ret = true;
}
if (l2_active_ != old_l2_active) {
ret = true;
}
policy_enabled_ = PolicyEnabled();
if (policy_enabled_ != old_policy) {
ret = true;
}
// Apply config based on old and new values
ApplyConfig(old_ipv4_active, old_l2_active, old_policy, old_vrf.get(),
old_addr, old_ethernet_tag, old_need_linklocal_ip,
old_ipv6_active, old_v6_addr, old_subnet, old_subnet_plen,
old_dhcp_enable, old_layer3_forwarding, force_update,
old_dhcp_addr);
return ret;
}
void VmInterface::Add() {
peer_.reset(new LocalVmPortPeer(LOCAL_VM_PORT_PEER_NAME, id_));
}
bool VmInterface::Delete(const DBRequest *req) {
InterfaceTable *table = static_cast<InterfaceTable *>(get_table());
const VmInterfaceData *vm_data = static_cast<const VmInterfaceData *>
(req->data.get());
vm_data->OnDelete(table, this);
if (configurer_) {
return false;
}
table->DeleteDhcpSnoopEntry(name_);
return true;
}
void VmInterface::UpdateL3(bool old_ipv4_active, VrfEntry *old_vrf,
const Ip4Address &old_addr, int old_ethernet_tag,
bool force_update, bool policy_change,
bool old_ipv6_active,
const Ip6Address &old_v6_addr,
const Ip4Address &old_subnet,
const uint8_t old_subnet_plen,
const Ip4Address &old_dhcp_addr) {
UpdateL3NextHop(old_ipv4_active, old_ipv6_active);
UpdateL3TunnelId(force_update, policy_change);
if (ipv4_active_) {
if (do_dhcp_relay_) {
UpdateIpv4InterfaceRoute(old_ipv4_active, force_update,
policy_change,
old_vrf, old_dhcp_addr);
}
UpdateIpv4InstanceIp(force_update, policy_change, false, old_ethernet_tag);
UpdateMetadataRoute(old_ipv4_active, old_vrf);
UpdateFloatingIp(force_update, policy_change, false);
UpdateServiceVlan(force_update, policy_change);
UpdateAllowedAddressPair(force_update, policy_change, false,
false, false);
UpdateVrfAssignRule();
UpdateResolveRoute(old_ipv4_active, force_update, policy_change,
old_vrf, old_subnet, old_subnet_plen);
}
if (ipv6_active_) {
UpdateIpv6InstanceIp(force_update, policy_change, false, old_ethernet_tag);
}
UpdateStaticRoute(force_update, policy_change);
}
void VmInterface::DeleteL3(bool old_ipv4_active, VrfEntry *old_vrf,
const Ip4Address &old_addr,
bool old_need_linklocal_ip, bool old_ipv6_active,
const Ip6Address &old_v6_addr,
const Ip4Address &old_subnet,
const uint8_t old_subnet_plen,
int old_ethernet_tag,
const Ip4Address &old_dhcp_addr) {
if (old_ipv4_active) {
DeleteIpv4InstanceIp(false, old_ethernet_tag, old_vrf);
DeleteIpv4InstanceIp(true, old_ethernet_tag, old_vrf);
if (old_dhcp_addr != Ip4Address(0)) {
DeleteIpv4InterfaceRoute(old_vrf, old_dhcp_addr);
}
}
if (old_ipv6_active) {
DeleteIpv6InstanceIp(false, old_ethernet_tag, old_vrf);
DeleteIpv6InstanceIp(true, old_ethernet_tag, old_vrf);
}
DeleteMetadataRoute(old_ipv4_active, old_vrf, old_need_linklocal_ip);
DeleteFloatingIp(false, 0);
DeleteServiceVlan();
DeleteStaticRoute();
DeleteAllowedAddressPair(false);
DeleteL3TunnelId();
DeleteVrfAssignRule();
DeleteL3NextHop(old_ipv4_active, old_ipv6_active);
DeleteResolveRoute(old_vrf, old_subnet, old_subnet_plen);
}
void VmInterface::UpdateVxLan() {
int new_vxlan_id = vn_.get() ? vn_->GetVxLanId() : 0;
if (l2_active_ && ((vxlan_id_ == 0) ||
(vxlan_id_ != new_vxlan_id))) {
vxlan_id_ = new_vxlan_id;
}
ethernet_tag_ = IsVxlanMode() ? vxlan_id_ : 0;
}
void VmInterface::AddL2ReceiveRoute(bool old_l2_active) {
if (L2Activated(old_l2_active)) {
InterfaceTable *table = static_cast<InterfaceTable *>(get_table());
Agent *agent = table->agent();
BridgeAgentRouteTable *l2_table = static_cast<BridgeAgentRouteTable *>(
vrf_->GetRouteTable(Agent::BRIDGE));
l2_table->AddBridgeReceiveRoute(peer_.get(), vrf_->GetName(), 0,
GetVifMac(agent), vn_->GetName());
}
}
void VmInterface::UpdateL2(bool old_l2_active, VrfEntry *old_vrf,
int old_ethernet_tag,
bool force_update, bool policy_change,
const Ip4Address &old_v4_addr,
const Ip6Address &old_v6_addr,
bool old_layer3_forwarding) {
if (device_type() == VmInterface::TOR ||
device_type() == VmInterface::DEVICE_TYPE_INVALID)
return;
UpdateVxLan();
UpdateL2NextHop(old_l2_active);
//Update label only if new entry is to be created, so
//no force update on same.
UpdateL2TunnelId(false, policy_change);
UpdateL2InterfaceRoute(old_l2_active, force_update, old_vrf, Ip4Address(),
Ip6Address(), old_ethernet_tag,
old_layer3_forwarding, policy_change,
Ip4Address(), Ip6Address(),
MacAddress::FromString(vm_mac_),
Ip4Address(0));
UpdateIpv4InstanceIp(force_update, policy_change, true, old_ethernet_tag);
UpdateIpv6InstanceIp(force_update, policy_change, true, old_ethernet_tag);
UpdateFloatingIp(force_update, policy_change, true);
UpdateAllowedAddressPair(force_update, policy_change, true, old_l2_active,
old_layer3_forwarding);
//If the interface is Gateway we need to add a receive route,
//such the packet gets routed. Bridging on gateway
//interface is not supported
if (vmi_type() == GATEWAY && L2Activated(old_l2_active)) {
AddL2ReceiveRoute(old_l2_active);
}
}
void VmInterface::UpdateL2(bool force_update) {
UpdateL2(l2_active_, vrf_.get(), ethernet_tag_, force_update, false,
primary_ip_addr_, primary_ip6_addr_, layer3_forwarding_);
}
void VmInterface::DeleteL2(bool old_l2_active, VrfEntry *old_vrf,
int old_ethernet_tag,
const Ip4Address &old_v4_addr,
const Ip6Address &old_v6_addr,
bool old_layer3_forwarding) {
DeleteIpv4InstanceIp(true, old_ethernet_tag, old_vrf);
DeleteIpv6InstanceIp(true, old_ethernet_tag, old_vrf);
DeleteL2InterfaceRoute(old_l2_active, old_vrf, Ip4Address(0),
Ip6Address(), old_ethernet_tag,
MacAddress::FromString(vm_mac_));
DeleteL2TunnelId();
DeleteFloatingIp(true, old_ethernet_tag);
DeleteL2NextHop(old_l2_active);
DeleteL2ReceiveRoute(old_vrf, old_l2_active);
DeleteAllowedAddressPair(true);
}
const MacAddress& VmInterface::GetVifMac(const Agent *agent) const {
if (parent()) {
if (device_type_ == VM_VLAN_ON_VMI) {
const VmInterface *vmi =
static_cast<const VmInterface *>(parent_.get());
return vmi->GetVifMac(agent);
}
return parent()->mac();
} else {
return agent->vrrp_mac();
}
}
void VmInterface::ApplyConfigCommon(const VrfEntry *old_vrf,
bool old_l2_active,
bool old_dhcp_enable) {
//DHCP MAC IP binding
ApplyMacVmBindingConfig(old_vrf, old_l2_active, old_dhcp_enable);
//Security Group update
if (IsActive())
UpdateSecurityGroup();
else
DeleteSecurityGroup();
}
void VmInterface::ApplyMacVmBindingConfig(const VrfEntry *old_vrf,
bool old_l2_active,
bool old_dhcp_enable) {
//Update DHCP and DNS flag in Interface Class.
if (dhcp_enable_) {
dhcp_enabled_ = true;
dns_enabled_ = true;
} else {
dhcp_enabled_ = false;
dns_enabled_ = false;
}
if (L2Deactivated(old_l2_active)) {
DeleteMacVmBinding(old_vrf);
return;
}
//Interface has been activated or
//dhcp toggled for already activated interface
if (L2Activated(old_l2_active) ||
(l2_active_ && (old_dhcp_enable != dhcp_enable_))) {
UpdateMacVmBinding();
}
}
// Apply the latest configuration
void VmInterface::ApplyConfig(bool old_ipv4_active, bool old_l2_active, bool old_policy,
VrfEntry *old_vrf, const Ip4Address &old_addr,
int old_ethernet_tag, bool old_need_linklocal_ip,
bool old_ipv6_active,
const Ip6Address &old_v6_addr,
const Ip4Address &old_subnet,
uint8_t old_subnet_plen,
bool old_dhcp_enable,
bool old_layer3_forwarding,
bool force_update,
const Ip4Address &old_dhcp_addr) {
ApplyConfigCommon(old_vrf, old_l2_active, old_dhcp_enable);
//Need not apply config for TOR VMI as it is more of an inidicative
//interface. No route addition or NH addition happens for this interface.
//Also, when parent is not updated for a non-Nova interface, device type
//remains invalid.
if ((device_type_ == VmInterface::TOR ||
device_type_ == VmInterface::DEVICE_TYPE_INVALID) &&
(old_subnet.is_unspecified() && old_subnet_plen == 0)) {
return;
}
bool policy_change = (policy_enabled_ != old_policy);
if (ipv4_active_ == true || l2_active_ == true) {
UpdateMulticastNextHop(old_ipv4_active, old_l2_active);
} else {
DeleteMulticastNextHop();
}
if (vrf_ && vmi_type() == GATEWAY) {
vrf_->CreateTableLabel();
}
// Add/Del/Update L3
if ((ipv4_active_ || ipv6_active_) && layer3_forwarding_) {
UpdateL3(old_ipv4_active, old_vrf, old_addr, old_ethernet_tag, force_update,
policy_change, old_ipv6_active, old_v6_addr,
old_subnet, old_subnet_plen, old_dhcp_addr);
} else if ((old_ipv4_active || old_ipv6_active)) {
DeleteL3(old_ipv4_active, old_vrf, old_addr, old_need_linklocal_ip,
old_ipv6_active, old_v6_addr,
old_subnet, old_subnet_plen, old_ethernet_tag, old_dhcp_addr);
}
// Add/Del/Update L2
if (l2_active_ && bridging_) {
UpdateL2(old_l2_active, old_vrf, old_ethernet_tag,
force_update, policy_change, old_addr, old_v6_addr,
old_layer3_forwarding);
} else if (old_l2_active) {
DeleteL2(old_l2_active, old_vrf, old_ethernet_tag, old_addr, old_v6_addr,
old_layer3_forwarding);
}
UpdateFlowKeyNextHop();
// Remove floating-ip entries marked for deletion
CleanupFloatingIpList();
if (old_l2_active != l2_active_) {
if (l2_active_) {
SendTrace(ACTIVATED_L2);
} else {
SendTrace(DEACTIVATED_L2);
}
}
if (old_ipv4_active != ipv4_active_) {
if (ipv4_active_) {
SendTrace(ACTIVATED_IPV4);
} else {
SendTrace(DEACTIVATED_IPV4);
}
}
if (old_ipv6_active != ipv6_active_) {
if (ipv6_active_) {
SendTrace(ACTIVATED_IPV6);
} else {
SendTrace(DEACTIVATED_IPV6);
}
}
}
bool VmInterface::CopyIpAddress(Ip4Address &addr) {
bool ret = false;
InterfaceTable *table = static_cast<InterfaceTable *>(get_table());
// Support DHCP relay for fabric-ports if IP address is not configured
do_dhcp_relay_ = (fabric_port_ && addr.to_ulong() == 0 && vrf() &&
vrf()->GetName() == table->agent()->fabric_vrf_name());
if (do_dhcp_relay_) {
// Set config_seen flag on DHCP SNoop entry
table->DhcpSnoopSetConfigSeen(name_);
// IP Address not know. Get DHCP Snoop entry.
// Also sets the config_seen_ flag for DHCP Snoop entry
addr = table->GetDhcpSnoopEntry(name_);
dhcp_addr_ = addr;
}
// Retain the old if new IP could not be got
if (addr.to_ulong() == 0) {
addr = primary_ip_addr_;
}
if (primary_ip_addr_ != addr) {
primary_ip_addr_ = addr;
ret = true;
}
return ret;
}
/////////////////////////////////////////////////////////////////////////////
// VmInterfaceConfigData routines
/////////////////////////////////////////////////////////////////////////////
VmInterfaceConfigData::VmInterfaceConfigData(Agent *agent, IFMapNode *node) :
VmInterfaceData(agent, node, CONFIG, Interface::TRANSPORT_INVALID),
addr_(0), ip6_addr_(), vm_mac_(""),
cfg_name_(""), vm_uuid_(), vm_name_(), vn_uuid_(), vrf_name_(""),
fabric_port_(true), need_linklocal_ip_(false), bridging_(true),
layer3_forwarding_(true), mirror_enable_(false), ecmp_(false),
dhcp_enable_(true), admin_state_(true), analyzer_name_(""),
local_preference_(VmInterface::INVALID), oper_dhcp_options_(),
mirror_direction_(Interface::UNKNOWN), sg_list_(),
floating_ip_list_(), service_vlan_list_(), static_route_list_(),
allowed_address_pair_list_(),
device_type_(VmInterface::DEVICE_TYPE_INVALID),
vmi_type_(VmInterface::VMI_TYPE_INVALID),
physical_interface_(""), parent_vmi_(), subnet_(0), subnet_plen_(0),
rx_vlan_id_(VmInterface::kInvalidVlanId),
tx_vlan_id_(VmInterface::kInvalidVlanId),
logical_interface_(nil_uuid()) {
}
VmInterface *VmInterfaceConfigData::OnAdd(const InterfaceTable *table,
const VmInterfaceKey *key) const {
VmInterface *vmi =
new VmInterface(key->uuid_, key->name_, addr_, vm_mac_, vm_name_,
nil_uuid(), VmInterface::kInvalidVlanId,
VmInterface::kInvalidVlanId, NULL, ip6_addr_,
device_type_, vmi_type_);
vmi->SetConfigurer(VmInterface::CONFIG);
return vmi;
}
bool VmInterfaceConfigData::OnDelete(const InterfaceTable *table,
VmInterface *vmi) const {
if (vmi->IsConfigurerSet(VmInterface::CONFIG) == false)
return true;
vmi->ResetConfigurer(VmInterface::CONFIG);
VmInterfaceConfigData data(NULL, NULL);
vmi->Resync(table, &data);
return true;
}
bool VmInterfaceConfigData::OnResync(const InterfaceTable *table,
VmInterface *vmi,
bool *force_update) const {
bool sg_changed = false;
bool ecmp_changed = false;
bool local_pref_changed = false;
bool ret = false;
ret = vmi->CopyConfig(table, this, &sg_changed, &ecmp_changed,
&local_pref_changed);
if (sg_changed || ecmp_changed || local_pref_changed)
*force_update = true;
return ret;
}
// Copies configuration from DB-Request data. The actual applying of
// configuration, like adding/deleting routes must be done with ApplyConfig()
bool VmInterface::CopyConfig(const InterfaceTable *table,
const VmInterfaceConfigData *data,
bool *sg_changed,
bool *ecmp_changed, bool *local_pref_changed) {
bool ret = false;
if (table) {
VmEntry *vm = table->FindVmRef(data->vm_uuid_);
if (vm_.get() != vm) {
vm_ = vm;
ret = true;
}
VrfEntry *vrf = table->FindVrfRef(data->vrf_name_);
if (vrf_.get() != vrf) {
vrf_ = vrf;
ret = true;
}
MirrorEntry *mirror = table->FindMirrorRef(data->analyzer_name_);
if (mirror_entry_.get() != mirror) {
mirror_entry_ = mirror;
ret = true;
}
}
MirrorDirection mirror_direction = data->mirror_direction_;
if (mirror_direction_ != mirror_direction) {
mirror_direction_ = mirror_direction;
ret = true;
}
string cfg_name = data->cfg_name_;
if (cfg_name_ != cfg_name) {
cfg_name_ = cfg_name;
ret = true;
}
// Read ifindex for the interface
if (table) {
VnEntry *vn = table->FindVnRef(data->vn_uuid_);
if (vn_.get() != vn) {
vn_ = vn;
ret = true;
}
bool val = vn ? vn->layer3_forwarding() : false;
if (layer3_forwarding_ != val) {
layer3_forwarding_ = val;
ret = true;
}
bool bridging_val = vn ? vn->bridging() : false;
if (bridging_ != bridging_val) {
bridging_ = bridging_val;
ret = true;
}
int vxlan_id = vn ? vn->GetVxLanId() : 0;
if (vxlan_id_ != vxlan_id) {
vxlan_id_ = vxlan_id;
ret = true;
}
bool flood_unknown_unicast =
vn ? vn->flood_unknown_unicast(): false;
if (flood_unknown_unicast_ != flood_unknown_unicast) {
flood_unknown_unicast_ = flood_unknown_unicast;
ret = true;
}
}
if (local_preference_ != data->local_preference_) {
local_preference_ = data->local_preference_;
*local_pref_changed = true;
ret = true;
}
if (need_linklocal_ip_ != data->need_linklocal_ip_) {
need_linklocal_ip_ = data->need_linklocal_ip_;
ret = true;
}
// CopyIpAddress uses fabric_port_. So, set it before CopyIpAddresss
if (fabric_port_ != data->fabric_port_) {
fabric_port_ = data->fabric_port_;
ret = true;
}
//If nova gives a instance-ip then retain that
//ip address as primary ip address
//Else choose the ip address to be old
//primary ip address as long as its present in
//new configuration also
Ip4Address ipaddr = data->addr_;
if (nova_ip_addr_ != Ip4Address(0)) {
ipaddr = nova_ip_addr_;
}
if (CopyIpAddress(ipaddr)) {
ret = true;
}
Ip6Address ip6_addr = data->ip6_addr_;
if (nova_ip6_addr_ != Ip6Address()) {
ip6_addr = nova_ip6_addr_;
}
if (CopyIp6Address(ip6_addr)) {
ret = true;
}
if (dhcp_enable_ != data->dhcp_enable_) {
dhcp_enable_ = data->dhcp_enable_;
ret = true;
}
bool mac_set = true;
boost::system::error_code ec;
MacAddress addr(vm_mac_, &ec);
if (ec.value() != 0) {
mac_set = false;
}
if (mac_set_ != mac_set) {
mac_set_ = mac_set;
ret = true;
}
if (admin_state_ != data->admin_state_) {
admin_state_ = data->admin_state_;
ret = true;
}
if (subnet_ != data->subnet_ || subnet_plen_ != data->subnet_plen_) {
subnet_ = data->subnet_;
subnet_plen_ = data->subnet_plen_;
}
// Copy DHCP options; ret is not modified as there is no dependent action
oper_dhcp_options_ = data->oper_dhcp_options_;
// Audit operational and config floating-ip list
FloatingIpSet &old_fip_list = floating_ip_list_.list_;
const FloatingIpSet &new_fip_list = data->floating_ip_list_.list_;
if (AuditList<FloatingIpList, FloatingIpSet::iterator>
(floating_ip_list_, old_fip_list.begin(), old_fip_list.end(),
new_fip_list.begin(), new_fip_list.end())) {
ret = true;
assert(floating_ip_list_.list_.size() ==
(floating_ip_list_.v4_count_ + floating_ip_list_.v6_count_));
}
// Audit operational and config Service VLAN list
ServiceVlanSet &old_service_list = service_vlan_list_.list_;
const ServiceVlanSet &new_service_list = data->service_vlan_list_.list_;
if (AuditList<ServiceVlanList, ServiceVlanSet::iterator>
(service_vlan_list_, old_service_list.begin(), old_service_list.end(),
new_service_list.begin(), new_service_list.end())) {
ret = true;
}
// Audit operational and config Static Route list
StaticRouteSet &old_route_list = static_route_list_.list_;
const StaticRouteSet &new_route_list = data->static_route_list_.list_;
if (AuditList<StaticRouteList, StaticRouteSet::iterator>
(static_route_list_, old_route_list.begin(), old_route_list.end(),
new_route_list.begin(), new_route_list.end())) {
ret = true;
}
// Audit operational and config allowed address pair
AllowedAddressPairSet &old_aap_list = allowed_address_pair_list_.list_;
const AllowedAddressPairSet &new_aap_list = data->
allowed_address_pair_list_.list_;
if (AuditList<AllowedAddressPairList, AllowedAddressPairSet::iterator>
(allowed_address_pair_list_, old_aap_list.begin(), old_aap_list.end(),
new_aap_list.begin(), new_aap_list.end())) {
ret = true;
}
// Audit operational and config Security Group list
SecurityGroupEntrySet &old_sg_list = sg_list_.list_;
const SecurityGroupEntrySet &new_sg_list = data->sg_list_.list_;
*sg_changed =
AuditList<SecurityGroupEntryList, SecurityGroupEntrySet::iterator>
(sg_list_, old_sg_list.begin(), old_sg_list.end(),
new_sg_list.begin(), new_sg_list.end());
if (*sg_changed) {
ret = true;
}
VrfAssignRuleSet &old_vrf_assign_list = vrf_assign_rule_list_.list_;
const VrfAssignRuleSet &new_vrf_assign_list = data->
vrf_assign_rule_list_.list_;
if (AuditList<VrfAssignRuleList, VrfAssignRuleSet::iterator>
(vrf_assign_rule_list_, old_vrf_assign_list.begin(),
old_vrf_assign_list.end(), new_vrf_assign_list.begin(),
new_vrf_assign_list.end())) {
ret = true;
}
InstanceIpSet &old_ipv4_list = instance_ipv4_list_.list_;
InstanceIpSet new_ipv4_list = data->instance_ipv4_list_.list_;
//Native ip of instance should be advertised even if
//config is not present, so manually add that entry
if (nova_ip_addr_ != Ip4Address(0) &&
data->vrf_name_ != Agent::NullString()) {
new_ipv4_list.insert(
VmInterface::InstanceIp(nova_ip_addr_, data->ecmp_, true));
}
if (AuditList<InstanceIpList, InstanceIpSet::iterator>
(instance_ipv4_list_, old_ipv4_list.begin(), old_ipv4_list.end(),
new_ipv4_list.begin(), new_ipv4_list.end())) {
ret = true;
}
InstanceIpSet &old_ipv6_list = instance_ipv6_list_.list_;
InstanceIpSet new_ipv6_list = data->instance_ipv6_list_.list_;
if (nova_ip6_addr_ != Ip6Address() &&
data->vrf_name_ != Agent::NullString()) {
new_ipv6_list.insert(
VmInterface::InstanceIp(nova_ip6_addr_, data->ecmp_, true));
}
if (AuditList<InstanceIpList, InstanceIpSet::iterator>
(instance_ipv6_list_, old_ipv6_list.begin(), old_ipv6_list.end(),
new_ipv6_list.begin(), new_ipv6_list.end())) {
ret = true;
}
if (data->addr_ != Ip4Address(0) && ecmp_ != data->ecmp_) {
ecmp_ = data->ecmp_;
*ecmp_changed = true;
}
if (data->device_type_ != VmInterface::DEVICE_TYPE_INVALID &&
device_type_ != data->device_type_) {
device_type_= data->device_type_;
ret = true;
}
if (device_type_ == LOCAL_DEVICE || device_type_ == VM_VLAN_ON_VMI) {
if (rx_vlan_id_ != data->rx_vlan_id_) {
rx_vlan_id_ = data->rx_vlan_id_;
ret = true;
}
if (tx_vlan_id_ != data->tx_vlan_id_) {
tx_vlan_id_ = data->tx_vlan_id_;
ret = true;
}
}
if (logical_interface_ != data->logical_interface_) {
logical_interface_ = data->logical_interface_;
ret = true;
}
Interface *new_parent = NULL;
if (data->physical_interface_.empty() == false) {
PhysicalInterfaceKey key(data->physical_interface_);
new_parent = static_cast<Interface *>
(table->agent()->interface_table()->FindActiveEntry(&key));
} else if (data->parent_vmi_.is_nil() == false) {
VmInterfaceKey key(AgentKey::RESYNC, data->parent_vmi_, "");
new_parent = static_cast<Interface *>
(table->agent()->interface_table()->FindActiveEntry(&key));
} else {
new_parent = parent_.get();
}
if (parent_ != new_parent) {
parent_ = new_parent;
ret = true;
}
if (table) {
if (os_index_ == kInvalidIndex) {
GetOsParams(table->agent());
if (os_index_ != kInvalidIndex)
ret = true;
}
}
return ret;
}
/////////////////////////////////////////////////////////////////////////////
// VmInterfaceNovaData routines
/////////////////////////////////////////////////////////////////////////////
VmInterfaceNovaData::VmInterfaceNovaData() :
VmInterfaceData(NULL, NULL, INSTANCE_MSG, Interface::TRANSPORT_INVALID),
ipv4_addr_(),
ipv6_addr_(),
mac_addr_(),
vm_name_(),
vm_uuid_(),
vm_project_uuid_(),
physical_interface_(),
tx_vlan_id_(),
rx_vlan_id_() {
}
VmInterfaceNovaData::VmInterfaceNovaData(const Ip4Address &ipv4_addr,
const Ip6Address &ipv6_addr,
const std::string &mac_addr,
const std::string vm_name,
boost::uuids::uuid vm_uuid,
boost::uuids::uuid vm_project_uuid,
const std::string &physical_interface,
uint16_t tx_vlan_id,
uint16_t rx_vlan_id,
VmInterface::DeviceType device_type,
VmInterface::VmiType vmi_type,
Interface::Transport transport) :
VmInterfaceData(NULL, NULL, INSTANCE_MSG, transport),
ipv4_addr_(ipv4_addr),
ipv6_addr_(ipv6_addr),
mac_addr_(mac_addr),
vm_name_(vm_name),
vm_uuid_(vm_uuid),
vm_project_uuid_(vm_project_uuid),
physical_interface_(physical_interface),
tx_vlan_id_(tx_vlan_id),
rx_vlan_id_(rx_vlan_id),
device_type_(device_type),
vmi_type_(vmi_type) {
}
VmInterfaceNovaData::~VmInterfaceNovaData() {
}
VmInterface *VmInterfaceNovaData::OnAdd(const InterfaceTable *table,
const VmInterfaceKey *key) const {
Interface *parent = NULL;
if (tx_vlan_id_ != VmInterface::kInvalidVlanId &&
rx_vlan_id_ != VmInterface::kInvalidVlanId &&
physical_interface_ != Agent::NullString()) {
PhysicalInterfaceKey key_1(physical_interface_);
parent = static_cast<Interface *>
(table->agent()->interface_table()->FindActiveEntry(&key_1));
assert(parent != NULL);
}
VmInterface *vmi =
new VmInterface(key->uuid_, key->name_, ipv4_addr_, mac_addr_, vm_name_,
vm_project_uuid_, tx_vlan_id_, rx_vlan_id_,
parent, ipv6_addr_, device_type_, vmi_type_);
vmi->SetConfigurer(VmInterface::INSTANCE_MSG);
vmi->nova_ip_addr_ = ipv4_addr_;
vmi->nova_ip6_addr_ = ipv6_addr_;
return vmi;
}
bool VmInterfaceNovaData::OnDelete(const InterfaceTable *table,
VmInterface *vmi) const {
if (vmi->IsConfigurerSet(VmInterface::INSTANCE_MSG) == false)
return true;
vmi->ResetConfigurer(VmInterface::CONFIG);
VmInterfaceConfigData data(NULL, NULL);
vmi->Resync(table, &data);
vmi->ResetConfigurer(VmInterface::INSTANCE_MSG);
return true;
}
bool VmInterfaceNovaData::OnResync(const InterfaceTable *table,
VmInterface *vmi,
bool *force_update) const {
bool ret = false;
if (vmi->vm_project_uuid_ != vm_project_uuid_) {
vmi->vm_project_uuid_ = vm_project_uuid_;
ret = true;
}
if (vmi->tx_vlan_id_ != tx_vlan_id_) {
vmi->tx_vlan_id_ = tx_vlan_id_;
ret = true;
}
if (vmi->rx_vlan_id_ != rx_vlan_id_) {
vmi->rx_vlan_id_ = rx_vlan_id_;
ret = true;
}
if (vmi->nova_ip_addr_ != ipv4_addr_) {
vmi->nova_ip_addr_ = ipv4_addr_;
ret = true;
}
if (vmi->nova_ip6_addr_ != ipv6_addr_) {
vmi->nova_ip6_addr_ = ipv6_addr_;
ret = true;
}
vmi->SetConfigurer(VmInterface::INSTANCE_MSG);
return ret;
}
/////////////////////////////////////////////////////////////////////////////
// VmInterfaceMirrorData routines
/////////////////////////////////////////////////////////////////////////////
bool VmInterfaceMirrorData::OnResync(const InterfaceTable *table,
VmInterface *vmi,
bool *force_update) const {
bool ret = false;
MirrorEntry *mirror_entry = NULL;
if (mirror_enable_ == true) {
mirror_entry = table->FindMirrorRef(analyzer_name_);
}
if (vmi->mirror_entry_ != mirror_entry) {
vmi->mirror_entry_ = mirror_entry;
ret = true;
}
return ret;
}
/////////////////////////////////////////////////////////////////////////////
// VmInterfaceIpAddressData routines
/////////////////////////////////////////////////////////////////////////////
// Update for VM IP address only
// For interfaces in IP Fabric VRF, we send DHCP requests to external servers
// if config doesnt provide an address. This address is updated here.
bool VmInterfaceIpAddressData::OnResync(const InterfaceTable *table,
VmInterface *vmi,
bool *force_update) const {
bool ret = false;
if (vmi->os_index_ == VmInterface::kInvalidIndex) {
vmi->GetOsParams(table->agent());
if (vmi->os_index_ != VmInterface::kInvalidIndex)
ret = true;
}
// Ignore IP address change if L3 Forwarding not enabled
if (!vmi->layer3_forwarding_) {
return ret;
}
Ip4Address addr = Ip4Address(0);
if (vmi->CopyIpAddress(addr)) {
ret = true;
}
return ret;
}
/////////////////////////////////////////////////////////////////////////////
// VmInterfaceOsOperStateData routines
/////////////////////////////////////////////////////////////////////////////
// Resync oper-state for the interface
bool VmInterfaceOsOperStateData::OnResync(const InterfaceTable *table,
VmInterface *vmi,
bool *force_update) const {
bool ret = false;
uint32_t old_os_index = vmi->os_index_;
bool old_ipv4_active = vmi->ipv4_active_;
bool old_ipv6_active = vmi->ipv6_active_;
vmi->GetOsParams(table->agent());
if (vmi->os_index_ != old_os_index)
ret = true;
vmi->ipv4_active_ = vmi->IsIpv4Active();
if (vmi->ipv4_active_ != old_ipv4_active)
ret = true;
vmi->ipv6_active_ = vmi->IsIpv6Active();
if (vmi->ipv6_active_ != old_ipv6_active)
ret = true;
return ret;
}
bool VmInterfaceGlobalVrouterData::OnResync(const InterfaceTable *table,
VmInterface *vmi,
bool *force_update) const {
bool ret = false;
if (bridging_ != vmi->bridging_) {
vmi->bridging_ = bridging_;
*force_update = true;
ret = true;
}
if (layer3_forwarding_ != vmi->layer3_forwarding_) {
vmi->layer3_forwarding_ = layer3_forwarding_;
*force_update = true;
ret = true;
}
if (vxlan_id_ != vmi->vxlan_id_)
ret = true;
return ret;
}
/////////////////////////////////////////////////////////////////////////////
// VM Port Entry utility routines
/////////////////////////////////////////////////////////////////////////////
// Does the VMInterface need a physical device to be present
bool VmInterface::NeedDevice() const {
bool ret = true;
if (device_type_ == TOR)
ret = false;
if (device_type_ == VM_VLAN_ON_VMI)
ret = false;
if (subnet_.is_unspecified() == false) {
ret = false;
}
if (transport_ != TRANSPORT_ETHERNET) {
ret = false;
}
if (rx_vlan_id_ != VmInterface::kInvalidVlanId) {
ret = false;
} else {
// Sanity check. rx_vlan_id is set, make sure tx_vlan_id is also set
assert(tx_vlan_id_ == VmInterface::kInvalidVlanId);
}
return ret;
}
void VmInterface::GetOsParams(Agent *agent) {
if (NeedDevice()) {
Interface::GetOsParams(agent);
return;
}
os_index_ = Interface::kInvalidIndex;
mac_ = agent->vrrp_mac();
os_oper_state_ = true;
}
// A VM Interface is L3 active under following conditions,
// - If interface is deleted, it is inactive
// - VN, VRF are set
// - If sub_interface VMIs, parent_ should be set
// (We dont track parent_ and activate sub-interfaces. So, we only check
// parent_ is present and not necessarily active)
// - For non-VMWARE hypervisors,
// The tap interface must be created. This is verified by os_index_
// - MAC address set for the interface
bool VmInterface::IsActive() const {
if (IsDeleted()) {
return false;
}
if (!admin_state_) {
return false;
}
// If sub_interface VMIs, parent_vmi_ should be set
// (We dont track parent_ and activate sub-interfaces. So, we only check
// paremt_vmi is present and not necessarily active)
if (device_type_ == VM_VLAN_ON_VMI) {
if (parent_.get() == NULL)
return false;
}
if ((vn_.get() == NULL) || (vrf_.get() == NULL)) {
return false;
}
if (!vn_.get()->admin_state()) {
return false;
}
if (NeedDevice() == false) {
return true;
}
if (os_index_ == kInvalidIndex)
return false;
if (os_oper_state_ == false)
return false;
return mac_set_;
}
bool VmInterface::IsIpv4Active() const {
if (!layer3_forwarding()) {
return false;
}
if (subnet_.is_unspecified() && primary_ip_addr_.to_ulong() == 0) {
return false;
}
if (subnet_.is_unspecified() == false && parent_ == NULL) {
return false;
}
return IsActive();
}
bool VmInterface::IsIpv6Active() const {
if (!layer3_forwarding() || (primary_ip6_addr_.is_unspecified())) {
return false;
}
return IsActive();
}
bool VmInterface::IsL2Active() const {
if (!bridging()) {
return false;
}
return IsActive();
}
bool VmInterface::WaitForTraffic() const {
// do not continue if the interface is inactive or if the VRF is deleted
if (IsActive() == false || vrf_->IsDeleted()) {
return false;
}
//Get the instance ip route and its corresponding traffic seen status
InetUnicastRouteKey rt_key(peer_.get(), vrf_->GetName(),
primary_ip_addr_, 32);
const InetUnicastRouteEntry *rt =
static_cast<const InetUnicastRouteEntry *>(
vrf_->GetInet4UnicastRouteTable()->FindActiveEntry(&rt_key));
if (!rt) {
return false;
}
if (rt->FindPath(peer_.get()) == false) {
return false;
}
return rt->FindPath(peer_.get())->path_preference().wait_for_traffic();
}
// Compute if policy is to be enabled on the interface
bool VmInterface::PolicyEnabled() const {
// Policy not supported for fabric ports
if (fabric_port_) {
return false;
}
if (layer3_forwarding_ == false) {
return false;
}
if (vn_.get() && vn_->IsAclSet()) {
return true;
}
// Floating-IP list and SG List can have entries in del_pending state
// Look for entries in non-del-pending state
FloatingIpSet::iterator fip_it = floating_ip_list_.list_.begin();
while (fip_it != floating_ip_list_.list_.end()) {
if (fip_it->del_pending_ == false) {
return true;
}
fip_it++;
}
SecurityGroupEntrySet::iterator sg_it = sg_list_.list_.begin();
while (sg_it != sg_list_.list_.end()) {
if (sg_it->del_pending_ == false) {
return true;
}
sg_it++;
}
VrfAssignRuleSet::iterator vrf_it = vrf_assign_rule_list_.list_.begin();
while (vrf_it != vrf_assign_rule_list_.list_.end()) {
if (vrf_it->del_pending_ == false) {
return true;
}
vrf_it++;
}
return false;
}
// VN is in VXLAN mode if,
// - Tunnel type computed is VXLAN and
// - vxlan_id_ set in VN is non-zero
bool VmInterface::IsVxlanMode() const {
if (TunnelType::ComputeType(TunnelType::AllType()) != TunnelType::VXLAN)
return false;
return vxlan_id_ != 0;
}
// Allocate MPLS Label for Layer3 routes
void VmInterface::AllocL3MplsLabel(bool force_update, bool policy_change) {
if (fabric_port_)
return;
bool new_entry = false;
Agent *agent = static_cast<InterfaceTable *>(get_table())->agent();
if (label_ == MplsTable::kInvalidLabel) {
label_ = agent->mpls_table()->AllocLabel();
new_entry = true;
}
if (force_update || policy_change || new_entry)
MplsLabel::CreateVPortLabel(agent, label_, GetUuid(), policy_enabled_,
InterfaceNHFlags::INET4);
}
// Delete MPLS Label for Layer3 routes
void VmInterface::DeleteL3MplsLabel() {
if (label_ == MplsTable::kInvalidLabel) {
return;
}
Agent *agent = static_cast<InterfaceTable *>(get_table())->agent();
MplsLabel::Delete(agent, label_);
label_ = MplsTable::kInvalidLabel;
}
// Allocate MPLS Label for Bridge entries
void VmInterface::AllocL2MplsLabel(bool force_update,
bool policy_change) {
bool new_entry = false;
if (l2_label_ == MplsTable::kInvalidLabel) {
Agent *agent = static_cast<InterfaceTable *>(get_table())->agent();
l2_label_ = agent->mpls_table()->AllocLabel();
new_entry = true;
}
Agent *agent = static_cast<InterfaceTable *>(get_table())->agent();
if (force_update || policy_change || new_entry)
MplsLabel::CreateVPortLabel(agent, l2_label_, GetUuid(),
policy_enabled_, InterfaceNHFlags::BRIDGE);
}
// Delete MPLS Label for Bridge Entries
void VmInterface::DeleteL2MplsLabel() {
if (l2_label_ == MplsTable::kInvalidLabel) {
return;
}
Agent *agent = static_cast<InterfaceTable *>(get_table())->agent();
MplsLabel::Delete(agent, l2_label_);
l2_label_ = MplsTable::kInvalidLabel;
}
void VmInterface::UpdateL3TunnelId(bool force_update, bool policy_change) {
//Currently only MPLS encap ind no VXLAN is supported for L3.
//Unconditionally create a label
AllocL3MplsLabel(force_update, policy_change);
}
void VmInterface::DeleteL3TunnelId() {
if (!ipv4_active_ && !ipv6_active_) {
DeleteL3MplsLabel();
}
}
//Check if interface transitioned from inactive to active layer 2 forwarding
bool VmInterface::L2Activated(bool old_l2_active) {
if (old_l2_active == false && l2_active_ == true) {
return true;
}
return false;
}
//Check if interface transitioned from inactive to active IP forwarding
bool VmInterface::Ipv4Activated(bool old_ipv4_active) {
if (old_ipv4_active == false && ipv4_active_ == true) {
return true;
}
return false;
}
bool VmInterface::Ipv6Activated(bool old_ipv6_active) {
if (old_ipv6_active == false && ipv6_active_ == true) {
return true;
}
return false;
}
//Check if interface transitioned from active bridging to inactive state
bool VmInterface::L2Deactivated(bool old_l2_active) {
if (old_l2_active == true && l2_active_ == false) {
return true;
}
return false;
}
//Check if interface transitioned from active IP forwarding to inactive state
bool VmInterface::Ipv4Deactivated(bool old_ipv4_active) {
if (old_ipv4_active == true && ipv4_active_ == false) {
return true;
}
return false;
}
bool VmInterface::Ipv6Deactivated(bool old_ipv6_active) {
if (old_ipv6_active == true && ipv6_active_ == false) {
return true;
}
return false;
}
void VmInterface::UpdateMulticastNextHop(bool old_ipv4_active,
bool old_l2_active) {
if (Ipv4Activated(old_ipv4_active) || L2Activated(old_l2_active)) {
InterfaceNH::CreateMulticastVmInterfaceNH(GetUuid(),
MacAddress::FromString(vm_mac_),
vrf_->GetName());
}
}
void VmInterface::UpdateFlowKeyNextHop() {
InterfaceTable *table = static_cast<InterfaceTable *>(get_table());
Agent *agent = table->agent();
if (ipv4_active_ || ipv6_active_) {
InterfaceNHKey key(new VmInterfaceKey(AgentKey::ADD_DEL_CHANGE,
GetUuid(), ""), true,
InterfaceNHFlags::INET4);
flow_key_nh_ = static_cast<const NextHop *>(
agent->nexthop_table()->FindActiveEntry(&key));
return;
}
InterfaceNHKey key(new VmInterfaceKey(AgentKey::ADD_DEL_CHANGE,
GetUuid(), ""), true,
InterfaceNHFlags::BRIDGE);
flow_key_nh_ = static_cast<const NextHop *>(
agent->nexthop_table()->FindActiveEntry(&key));
}
void VmInterface::UpdateMacVmBinding() {
BridgeAgentRouteTable *table = static_cast<BridgeAgentRouteTable *>
(vrf_->GetBridgeRouteTable());
Agent *agent = table->agent();
table->AddMacVmBindingRoute(agent->mac_vm_binding_peer(),
vrf_->GetName(),
MacAddress::FromString(vm_mac_),
this);
}
void VmInterface::UpdateL2NextHop(bool old_l2_active) {
if (L2Activated(old_l2_active)) {
InterfaceNH::CreateL2VmInterfaceNH(GetUuid(),
MacAddress::FromString(vm_mac_),
vrf_->GetName());
}
}
void VmInterface::UpdateL3NextHop(bool old_ipv4_active, bool old_ipv6_active) {
if (old_ipv4_active || old_ipv6_active) {
return;
}
if (Ipv4Activated(old_ipv4_active) || Ipv6Activated(old_ipv6_active)) {
InterfaceNH::CreateL3VmInterfaceNH(GetUuid(),
MacAddress::FromString(vm_mac_), vrf_->GetName());
}
}
void VmInterface::DeleteMacVmBinding(const VrfEntry *old_vrf) {
if (old_vrf == NULL)
return;
BridgeAgentRouteTable *table = static_cast<BridgeAgentRouteTable *>
(old_vrf->GetBridgeRouteTable());
Agent *agent = table->agent();
table->DeleteMacVmBindingRoute(agent->mac_vm_binding_peer(),
old_vrf->GetName(),
MacAddress::FromString(vm_mac_),
this);
}
void VmInterface::DeleteL2NextHop(bool old_l2_active) {
if (L2Deactivated(old_l2_active)) {
InterfaceNH::DeleteL2InterfaceNH(GetUuid());
}
}
void VmInterface::DeleteL3NextHop(bool old_ipv4_active, bool old_ipv6_active) {
if (Ipv4Deactivated(old_ipv4_active) || Ipv6Deactivated(old_ipv6_active)) {
if (!ipv4_active_ && !ipv6_active_) {
InterfaceNH::DeleteL3InterfaceNH(GetUuid());
}
}
}
void VmInterface::DeleteMulticastNextHop() {
InterfaceNH::DeleteMulticastVmInterfaceNH(GetUuid());
}
void VmInterface::DeleteL2ReceiveRoute(const VrfEntry *old_vrf,
bool old_l2_active) {
if (L2Deactivated(old_l2_active) && old_vrf) {
InterfaceTable *table = static_cast<InterfaceTable *>(get_table());
Agent *agent = table->agent();
BridgeAgentRouteTable::Delete(peer_.get(), old_vrf->GetName(),
GetVifMac(agent), 0);
}
}
Ip4Address VmInterface::GetGateway(const IpAddress &vm_ip) const {
Ip4Address ip(0);
if (vn_.get() == NULL) {
return ip;
}
const VnIpam *ipam = NULL;
if (subnet_.is_unspecified()) {
ipam = vn_->GetIpam(vm_ip);
} else {
ipam = vn_->GetIpam(subnet_);
}
if (ipam && ipam->default_gw.is_v4()) {
ip = ipam->default_gw.to_v4();
}
return ip;
}
// Add/Update route. Delete old route if VRF or address changed
void VmInterface::UpdateIpv4InterfaceRoute(bool old_ipv4_active, bool force_update,
bool policy_change,
VrfEntry * old_vrf,
const Ip4Address &old_addr) {
Ip4Address ip = GetGateway(primary_ip_addr_);
// If interface was already active earlier and there is no force_update or
// policy_change, return
if (old_ipv4_active == true && force_update == false
&& policy_change == false && old_addr == primary_ip_addr_ &&
vm_ip_gw_addr_ == ip) {
return;
}
// We need to have valid IP and VRF to add route
if (primary_ip_addr_.to_ulong() != 0 && vrf_.get() != NULL) {
// Add route if old was inactive or force_update is set
if (old_ipv4_active == false || force_update == true ||
old_addr != primary_ip_addr_ || vm_ip_gw_addr_ != ip) {
vm_ip_gw_addr_ = ip;
AddRoute(vrf_->GetName(), primary_ip_addr_, 32, vn_->GetName(),
policy_enabled_, ecmp_, vm_ip_gw_addr_, Ip4Address(0));
} else if (policy_change == true) {
// If old-l3-active and there is change in policy, invoke RESYNC of
// route to account for change in NH policy
InetUnicastAgentRouteTable::ReEvaluatePaths(agent(),
vrf_->GetName(),
primary_ip_addr_, 32);
}
}
// If there is change in VRF or IP address, delete old route
if (old_vrf != vrf_.get() || primary_ip_addr_ != old_addr) {
DeleteIpv4InterfaceRoute(old_vrf, old_addr);
}
}
// Add/Update route. Delete old route if VRF or address changed
void VmInterface::UpdateIpv6InterfaceRoute(bool old_ipv6_active, bool force_update,
bool policy_change,
VrfEntry * old_vrf,
const Ip6Address &old_addr) {
const VnIpam *ipam = vn_->GetIpam(primary_ip6_addr_);
Ip6Address ip6;
if (ipam) {
ip6 = ipam->default_gw.to_v6();
}
// If interface was already active earlier and there is no force_update or
// policy_change, return
if (old_ipv6_active == true && force_update == false
&& policy_change == false && vm_ip6_gw_addr_ == ip6) {
return;
}
// We need to have valid IP and VRF to add route
if (!primary_ip6_addr_.is_unspecified() && vrf_.get() != NULL) {
// Add route if old was inactive or force_update is set
if (old_ipv6_active == false || force_update == true ||
old_addr != primary_ip6_addr_ || vm_ip6_gw_addr_ != ip6) {
vm_ip6_gw_addr_ = ip6;
SecurityGroupList sg_id_list;
CopySgIdList(&sg_id_list);
PathPreference path_preference;
SetPathPreference(&path_preference, false, Ip4Address(0));
//TODO: change subnet_gw_ip to Ip6Address
InetUnicastAgentRouteTable::AddLocalVmRoute
(peer_.get(), vrf_->GetName(), primary_ip6_addr_, 128, GetUuid(),
vn_->GetName(), label_, sg_id_list, false, path_preference,
vm_ip6_gw_addr_);
} else if (policy_change == true) {
// If old-l3-active and there is change in policy, invoke RESYNC of
// route to account for change in NH policy
InetUnicastAgentRouteTable::ReEvaluatePaths(agent(),
vrf_->GetName(),
primary_ip6_addr_, 128);
}
}
// If there is change in VRF or IP address, delete old route
if (old_vrf != vrf_.get() || primary_ip6_addr_ != old_addr) {
DeleteIpv6InterfaceRoute(old_vrf, old_addr);
}
}
void VmInterface::UpdateResolveRoute(bool old_ipv4_active, bool force_update,
bool policy_change, VrfEntry * old_vrf,
const Ip4Address &old_addr,
uint8_t old_plen) {
if (old_ipv4_active == true && force_update == false
&& policy_change == false && old_addr == subnet_ &&
subnet_plen_ == old_plen) {
return;
}
if (old_vrf && (old_vrf != vrf_.get() ||
old_addr != subnet_ ||
subnet_plen_ != old_plen)) {
DeleteResolveRoute(old_vrf, old_addr, old_plen);
}
if (subnet_.to_ulong() != 0 && vrf_.get() != NULL && vn_.get() != NULL) {
SecurityGroupList sg_id_list;
CopySgIdList(&sg_id_list);
VmInterfaceKey vm_intf_key(AgentKey::ADD_DEL_CHANGE, GetUuid(), "");
InetUnicastAgentRouteTable::AddResolveRoute(peer_.get(), vrf_->GetName(),
Address::GetIp4SubnetAddress(subnet_, subnet_plen_),
subnet_plen_, vm_intf_key, vrf_->table_label(),
policy_enabled_, vn_->GetName(), sg_id_list);
}
}
void VmInterface::DeleteResolveRoute(VrfEntry *old_vrf,
const Ip4Address &old_addr,
const uint8_t plen) {
DeleteRoute(old_vrf->GetName(), old_addr, plen);
}
void VmInterface::DeleteIpv4InterfaceRoute(VrfEntry *old_vrf,
const Ip4Address &old_addr) {
if ((old_vrf == NULL) || (old_addr.to_ulong() == 0))
return;
DeleteRoute(old_vrf->GetName(), old_addr, 32);
}
void VmInterface::DeleteIpv6InterfaceRoute(VrfEntry *old_vrf,
const Ip6Address &old_addr) {
if ((old_vrf == NULL) || (old_addr.is_unspecified()))
return;
InetUnicastAgentRouteTable::Delete(peer_.get(), old_vrf->GetName(),
old_addr, 128);
}
// Add meta-data route if linklocal_ip is needed
void VmInterface::UpdateMetadataRoute(bool old_ipv4_active, VrfEntry *old_vrf) {
if (ipv4_active_ == false || old_ipv4_active == true)
return;
if (!need_linklocal_ip_) {
return;
}
InterfaceTable *table = static_cast<InterfaceTable *>(get_table());
Agent *agent = table->agent();
table->VmPortToMetaDataIp(id(), vrf_->vrf_id(), &mdata_addr_);
PathPreference path_preference;
SetPathPreference(&path_preference, false, Ip4Address(0));
InetUnicastAgentRouteTable::AddLocalVmRoute
(agent->link_local_peer(), agent->fabric_vrf_name(), mdata_addr_,
32, GetUuid(), vn_->GetName(), label_, SecurityGroupList(), true,
path_preference, Ip4Address(0));
}
// Delete meta-data route
void VmInterface::DeleteMetadataRoute(bool old_active, VrfEntry *old_vrf,
bool old_need_linklocal_ip) {
if (!old_need_linklocal_ip) {
return;
}
InterfaceTable *table = static_cast<InterfaceTable *>(get_table());
Agent *agent = table->agent();
InetUnicastAgentRouteTable::Delete(agent->link_local_peer(),
agent->fabric_vrf_name(),
mdata_addr_, 32);
}
void VmInterface::CleanupFloatingIpList() {
FloatingIpSet::iterator it = floating_ip_list_.list_.begin();
while (it != floating_ip_list_.list_.end()) {
FloatingIpSet::iterator prev = it++;
if (prev->del_pending_ == false)
continue;
if (prev->floating_ip_.is_v4()) {
floating_ip_list_.v4_count_--;
assert(floating_ip_list_.v4_count_ >= 0);
} else {
floating_ip_list_.v6_count_--;
assert(floating_ip_list_.v6_count_ >= 0);
}
floating_ip_list_.list_.erase(prev);
}
}
void VmInterface::UpdateFloatingIp(bool force_update, bool policy_change,
bool l2) {
FloatingIpSet::iterator it = floating_ip_list_.list_.begin();
while (it != floating_ip_list_.list_.end()) {
FloatingIpSet::iterator prev = it++;
if (prev->del_pending_) {
prev->DeActivate(this, l2);
} else {
prev->Activate(this, force_update||policy_change, l2);
}
}
}
void VmInterface::DeleteFloatingIp(bool l2, uint32_t old_ethernet_tag) {
FloatingIpSet::iterator it = floating_ip_list_.list_.begin();
while (it != floating_ip_list_.list_.end()) {
FloatingIpSet::iterator prev = it++;
prev->DeActivate(this, l2);
}
}
void VmInterface::UpdateServiceVlan(bool force_update, bool policy_change) {
ServiceVlanSet::iterator it = service_vlan_list_.list_.begin();
while (it != service_vlan_list_.list_.end()) {
ServiceVlanSet::iterator prev = it++;
if (prev->del_pending_) {
prev->DeActivate(this);
service_vlan_list_.list_.erase(prev);
} else {
prev->Activate(this, force_update);
}
}
}
void VmInterface::DeleteServiceVlan() {
ServiceVlanSet::iterator it = service_vlan_list_.list_.begin();
while (it != service_vlan_list_.list_.end()) {
ServiceVlanSet::iterator prev = it++;
prev->DeActivate(this);
if (prev->del_pending_) {
service_vlan_list_.list_.erase(prev);
}
}
}
void VmInterface::UpdateStaticRoute(bool force_update, bool policy_change) {
StaticRouteSet::iterator it = static_route_list_.list_.begin();
while (it != static_route_list_.list_.end()) {
StaticRouteSet::iterator prev = it++;
/* V4 static routes should be enabled only if ipv4_active_ is true
* V6 static routes should be enabled only if ipv6_active_ is true
*/
if ((!ipv4_active_ && prev->addr_.is_v4()) ||
(!ipv6_active_ && prev->addr_.is_v6())) {
continue;
}
if (prev->del_pending_) {
prev->DeActivate(this);
static_route_list_.list_.erase(prev);
} else {
prev->Activate(this, force_update, policy_change);
}
}
}
void VmInterface::DeleteStaticRoute() {
StaticRouteSet::iterator it = static_route_list_.list_.begin();
while (it != static_route_list_.list_.end()) {
StaticRouteSet::iterator prev = it++;
prev->DeActivate(this);
if (prev->del_pending_) {
static_route_list_.list_.erase(prev);
}
}
}
void VmInterface::UpdateAllowedAddressPair(bool force_update, bool policy_change,
bool l2, bool old_layer2_forwarding,
bool old_layer3_forwarding) {
AllowedAddressPairSet::iterator it =
allowed_address_pair_list_.list_.begin();
while (it != allowed_address_pair_list_.list_.end()) {
AllowedAddressPairSet::iterator prev = it++;
if (prev->del_pending_) {
prev->L2DeActivate(this);
prev->DeActivate(this);
allowed_address_pair_list_.list_.erase(prev);
} else {
if (l2) {
prev->L2Activate(this, force_update, policy_change,
old_layer2_forwarding, old_layer3_forwarding);
} else {
prev->Activate(this, force_update, policy_change);
}
}
}
}
void VmInterface::DeleteAllowedAddressPair(bool l2) {
AllowedAddressPairSet::iterator it =
allowed_address_pair_list_.list_.begin();
while (it != allowed_address_pair_list_.list_.end()) {
AllowedAddressPairSet::iterator prev = it++;
if (l2) {
prev->L2DeActivate(this);
} else {
prev->DeActivate(this);
}
if (prev->del_pending_) {
prev->L2DeActivate(this);
prev->DeActivate(this);
allowed_address_pair_list_.list_.erase(prev);
}
}
}
static bool CompareAddressType(const AddressType &lhs,
const AddressType &rhs) {
if (lhs.subnet.ip_prefix != rhs.subnet.ip_prefix) {
return false;
}
if (lhs.subnet.ip_prefix_len != rhs.subnet.ip_prefix_len) {
return false;
}
if (lhs.virtual_network != rhs.virtual_network) {
return false;
}
if (lhs.security_group != rhs.security_group) {
return false;
}
return true;
}
static bool ComparePortType(const PortType &lhs,
const PortType &rhs) {
if (lhs.start_port != rhs.start_port) {
return false;
}
if (lhs.end_port != rhs.end_port) {
return false;
}
return true;
}
static bool CompareMatchConditionType(const MatchConditionType &lhs,
const MatchConditionType &rhs) {
if (lhs.protocol != rhs.protocol) {
return lhs.protocol < rhs.protocol;
}
if (!CompareAddressType(lhs.src_address, rhs.src_address)) {
return false;
}
if (!ComparePortType(lhs.src_port, rhs.src_port)) {
return false;
}
if (!CompareAddressType(lhs.dst_address, rhs.dst_address)) {
return false;
}
if (!ComparePortType(lhs.dst_port, rhs.dst_port)) {
return false;
}
return true;
}
void VmInterface::UpdateVrfAssignRule() {
Agent *agent = static_cast<InterfaceTable *>(get_table())->agent();
//Erase all delete marked entry
VrfAssignRuleSet::iterator it = vrf_assign_rule_list_.list_.begin();
while (it != vrf_assign_rule_list_.list_.end()) {
VrfAssignRuleSet::iterator prev = it++;
if (prev->del_pending_) {
vrf_assign_rule_list_.list_.erase(prev);
}
}
if (vrf_assign_rule_list_.list_.size() == 0 &&
vrf_assign_acl_.get() != NULL) {
DeleteVrfAssignRule();
return;
}
if (vrf_assign_rule_list_.list_.size() == 0) {
return;
}
AclSpec acl_spec;
acl_spec.acl_id = uuid_;
//Create the ACL
it = vrf_assign_rule_list_.list_.begin();
uint32_t id = 0;
for (;it != vrf_assign_rule_list_.list_.end();it++) {
//Go thru all match condition and create ACL entry
AclEntrySpec ace_spec;
ace_spec.id = id++;
if (ace_spec.Populate(&(it->match_condition_)) == false) {
continue;
}
ActionSpec vrf_translate_spec;
vrf_translate_spec.ta_type = TrafficAction::VRF_TRANSLATE_ACTION;
vrf_translate_spec.simple_action = TrafficAction::VRF_TRANSLATE;
vrf_translate_spec.vrf_translate.set_vrf_name(it->vrf_name_);
vrf_translate_spec.vrf_translate.set_ignore_acl(it->ignore_acl_);
ace_spec.action_l.push_back(vrf_translate_spec);
acl_spec.acl_entry_specs_.push_back(ace_spec);
}
DBRequest req;
AclKey *key = new AclKey(acl_spec.acl_id);
AclData *data = new AclData(agent, NULL, acl_spec);
req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;
req.key.reset(key);
req.data.reset(data);
agent->acl_table()->Process(req);
AclKey entry_key(uuid_);
AclDBEntry *acl = static_cast<AclDBEntry *>(
agent->acl_table()->FindActiveEntry(&entry_key));
assert(acl);
vrf_assign_acl_ = acl;
}
void VmInterface::DeleteVrfAssignRule() {
Agent *agent = static_cast<InterfaceTable *>(get_table())->agent();
VrfAssignRuleSet::iterator it = vrf_assign_rule_list_.list_.begin();
while (it != vrf_assign_rule_list_.list_.end()) {
VrfAssignRuleSet::iterator prev = it++;
if (prev->del_pending_) {
vrf_assign_rule_list_.list_.erase(prev);
}
}
if (vrf_assign_acl_ != NULL) {
vrf_assign_acl_ = NULL;
DBRequest req;
AclKey *key = new AclKey(uuid_);
req.oper = DBRequest::DB_ENTRY_DELETE;
req.key.reset(key);
req.data.reset(NULL);
agent->acl_table()->Process(req);
}
}
void VmInterface::UpdateSecurityGroup() {
SecurityGroupEntrySet::iterator it = sg_list_.list_.begin();
while (it != sg_list_.list_.end()) {
SecurityGroupEntrySet::iterator prev = it++;
if (prev->del_pending_) {
sg_list_.list_.erase(prev);
} else {
prev->Activate(this);
}
}
}
void VmInterface::DeleteSecurityGroup() {
SecurityGroupEntrySet::iterator it = sg_list_.list_.begin();
while (it != sg_list_.list_.end()) {
SecurityGroupEntrySet::iterator prev = it++;
if (prev->del_pending_) {
sg_list_.list_.erase(prev);
}
}
}
void VmInterface::UpdateL2TunnelId(bool force_update, bool policy_change) {
AllocL2MplsLabel(force_update, policy_change);
}
void VmInterface::DeleteL2TunnelId() {
DeleteL2MplsLabel();
}
void VmInterface::UpdateL2InterfaceRoute(bool old_l2_active, bool force_update,
VrfEntry *old_vrf,
const Ip4Address &old_v4_addr,
const Ip6Address &old_v6_addr,
int old_ethernet_tag,
bool old_layer3_forwarding,
bool policy_changed,
const Ip4Address &new_ip_addr,
const Ip6Address &new_ip6_addr,
const MacAddress &mac,
const IpAddress &dependent_ip) const {
if (l2_active_ == false)
return;
if (ethernet_tag_ != old_ethernet_tag) {
force_update = true;
}
if (old_layer3_forwarding != layer3_forwarding_) {
force_update = true;
}
//Encap change will result in force update of l2 routes.
if (force_update) {
DeleteL2InterfaceRoute(true, old_vrf, old_v4_addr,
old_v6_addr, old_ethernet_tag, mac);
} else {
if (new_ip_addr != old_v4_addr) {
force_update = true;
DeleteL2InterfaceRoute(true, old_vrf, old_v4_addr, Ip6Address(),
old_ethernet_tag, mac);
}
if (new_ip6_addr != old_v6_addr) {
force_update = true;
DeleteL2InterfaceRoute(true, old_vrf, Ip4Address(), old_v6_addr,
old_ethernet_tag, mac);
}
}
assert(peer_.get());
EvpnAgentRouteTable *table = static_cast<EvpnAgentRouteTable *>
(vrf_->GetEvpnRouteTable());
SecurityGroupList sg_id_list;
CopySgIdList(&sg_id_list);
PathPreference path_preference;
SetPathPreference(&path_preference, false, dependent_ip);
if (policy_changed == true) {
//Resync the nexthop
table->ResyncVmRoute(peer_.get(), vrf_->GetName(),
mac, new_ip_addr,
ethernet_tag_, NULL);
table->ResyncVmRoute(peer_.get(), vrf_->GetName(),
mac, new_ip6_addr,
ethernet_tag_, NULL);
}
if (old_l2_active && force_update == false)
return;
if (new_ip_addr.is_unspecified() || layer3_forwarding_ == true) {
table->AddLocalVmRoute(peer_.get(), vrf_->GetName(),
mac, this, new_ip_addr,
l2_label_, vn_->GetName(), sg_id_list,
path_preference, ethernet_tag_);
}
if (new_ip6_addr.is_unspecified() == false && layer3_forwarding_ == true) {
table->AddLocalVmRoute(peer_.get(), vrf_->GetName(),
mac, this, new_ip6_addr,
l2_label_, vn_->GetName(), sg_id_list,
path_preference, ethernet_tag_);
}
}
void VmInterface::DeleteL2InterfaceRoute(bool old_l2_active, VrfEntry *old_vrf,
const Ip4Address &old_v4_addr,
const Ip6Address &old_v6_addr,
int old_ethernet_tag,
const MacAddress &mac) const {
if (old_l2_active == false)
return;
if (old_vrf == NULL)
return;
EvpnAgentRouteTable *table = static_cast<EvpnAgentRouteTable *>
(old_vrf->GetEvpnRouteTable());
table->DelLocalVmRoute(peer_.get(), old_vrf->GetName(), mac,
this, old_v4_addr,
old_ethernet_tag);
table->DelLocalVmRoute(peer_.get(), old_vrf->GetName(), mac,
this, old_v6_addr,
old_ethernet_tag);
}
// Copy the SG List for VM Interface. Used to add route for interface
void VmInterface::CopySgIdList(SecurityGroupList *sg_id_list) const {
SecurityGroupEntrySet::const_iterator it;
for (it = sg_list_.list_.begin(); it != sg_list_.list_.end(); ++it) {
if (it->del_pending_)
continue;
if (it->sg_.get() == NULL)
continue;
sg_id_list->push_back(it->sg_->GetSgId());
}
}
// Set path-preference information for the route
void VmInterface::SetPathPreference(PathPreference *pref, bool ecmp,
const IpAddress &dependent_ip) const {
pref->set_ecmp(ecmp);
if (local_preference_ != INVALID) {
pref->set_static_preference(true);
}
if (local_preference_ == HIGH) {
pref->set_preference(PathPreference::HIGH);
}
pref->set_dependent_ip(dependent_ip);
pref->set_vrf(vrf()->GetName());
}
//Add a route for VM port
//If ECMP route, add new composite NH and mpls label for same
void VmInterface::AddRoute(const std::string &vrf_name, const IpAddress &addr,
uint32_t plen, const std::string &dest_vn,
bool policy, bool ecmp, const IpAddress &gw_ip,
const IpAddress &dependent_rt) {
SecurityGroupList sg_id_list;
CopySgIdList(&sg_id_list);
PathPreference path_preference;
SetPathPreference(&path_preference, ecmp, dependent_rt);
InetUnicastAgentRouteTable::AddLocalVmRoute(peer_.get(), vrf_name, addr,
plen, GetUuid(),
dest_vn, label_,
sg_id_list, false,
path_preference, gw_ip);
return;
}
void VmInterface::ResolveRoute(const std::string &vrf_name, const Ip4Address &addr,
uint32_t plen, const std::string &dest_vn, bool policy) {
SecurityGroupList sg_id_list;
CopySgIdList(&sg_id_list);
VmInterfaceKey vm_intf_key(AgentKey::ADD_DEL_CHANGE, GetUuid(), "");
InetUnicastAgentRouteTable::AddResolveRoute(peer_.get(), vrf_name,
Address::GetIp4SubnetAddress(addr, plen),
plen, vm_intf_key, vrf_->table_label(),
policy, dest_vn, sg_id_list);
}
void VmInterface::DeleteRoute(const std::string &vrf_name,
const IpAddress &addr, uint32_t plen) {
InetUnicastAgentRouteTable::Delete(peer_.get(), vrf_name, addr, plen);
return;
}
// DHCP options applicable to the Interface
bool VmInterface::GetInterfaceDhcpOptions(
std::vector<autogen::DhcpOptionType> *options) const {
if (oper_dhcp_options().are_dhcp_options_set()) {
*options = oper_dhcp_options().dhcp_options();
return true;
}
return false;
}
// DHCP options applicable to the Subnet to which the interface belongs
bool VmInterface::GetSubnetDhcpOptions(
std::vector<autogen::DhcpOptionType> *options,
bool ipv6) const {
if (vn()) {
const std::vector<VnIpam> &vn_ipam = vn()->GetVnIpam();
uint32_t index;
for (index = 0; index < vn_ipam.size(); ++index) {
if (!ipv6 && vn_ipam[index].IsSubnetMember(primary_ip_addr())) {
break;
}
if (ipv6 && vn_ipam[index].IsSubnetMember(primary_ip6_addr())) {
break;
}
}
if (index < vn_ipam.size() &&
vn_ipam[index].oper_dhcp_options.are_dhcp_options_set()) {
*options = vn_ipam[index].oper_dhcp_options.dhcp_options();
return true;
}
}
return false;
}
// DHCP options applicable to the Ipam to which the interface belongs
bool VmInterface::GetIpamDhcpOptions(
std::vector<autogen::DhcpOptionType> *options,
bool ipv6) const {
if (vn()) {
std::string ipam_name;
autogen::IpamType ipam_type;
if (!ipv6 &&
vn()->GetIpamData(primary_ip_addr(), &ipam_name, &ipam_type)) {
*options = ipam_type.dhcp_option_list.dhcp_option;
return true;
}
if (ipv6 &&
vn()->GetIpamData(primary_ip6_addr(), &ipam_name, &ipam_type)) {
*options = ipam_type.dhcp_option_list.dhcp_option;
return true;
}
}
return false;
}
/////////////////////////////////////////////////////////////////////////////
// InstanceIp routines
/////////////////////////////////////////////////////////////////////////////
VmInterface::InstanceIp::InstanceIp() :
ListEntry(), ip_(), ecmp_(false), l2_installed_(false), old_ecmp_(false),
is_primary_(false) {
}
VmInterface::InstanceIp::InstanceIp(const InstanceIp &rhs) :
ListEntry(rhs.installed_, rhs.del_pending_),
ip_(rhs.ip_), ecmp_(rhs.ecmp_),
l2_installed_(rhs.l2_installed_), old_ecmp_(rhs.old_ecmp_),
is_primary_(rhs.is_primary_) {
}
VmInterface::InstanceIp::InstanceIp(const IpAddress &addr,
bool ecmp, bool is_primary) :
ListEntry(), ip_(addr), ecmp_(ecmp),
l2_installed_(false), old_ecmp_(false), is_primary_(is_primary) {
}
VmInterface::InstanceIp::~InstanceIp() {
}
bool VmInterface::InstanceIp::operator() (const InstanceIp &lhs,
const InstanceIp &rhs) const {
return lhs.IsLess(&rhs);
}
bool VmInterface::InstanceIp::IsLess(const InstanceIp *rhs) const {
return ip_ < rhs->ip_;
}
void VmInterface::InstanceIp::L3Activate(VmInterface *interface,
bool force_update) const {
if (gw_ip_ != interface->GetGateway(ip_)) {
force_update = true;
}
if (old_ecmp_ != ecmp_) {
force_update = true;
old_ecmp_ = ecmp_;
}
// Add route if not installed or if force requested
if (installed_ && force_update == false) {
return;
}
if (ip_.is_v4()) {
interface->AddRoute(interface->vrf()->GetName(), ip_.to_v4(), 32,
interface->vn()->GetName(), true, ecmp_,
interface->GetGateway(ip_), Ip4Address(0));
} else if (ip_.is_v6()) {
interface->AddRoute(interface->vrf()->GetName(), ip_.to_v6(), 128,
interface->vn()->GetName(), true, false,
Ip6Address(), Ip6Address());
}
installed_ = true;
}
void VmInterface::InstanceIp::L3DeActivate(VmInterface *interface,
VrfEntry *old_vrf) const {
if (installed_ == false) {
return;
}
if (ip_.is_v4()) {
interface->DeleteRoute(old_vrf->GetName(), ip_, 32);
} else if (ip_.is_v6()) {
interface->DeleteRoute(old_vrf->GetName(), ip_, 128);
}
installed_ = false;
}
void VmInterface::InstanceIp::L2Activate(VmInterface *interface,
bool force_update,
uint32_t old_ethernet_tag) const {
Ip4Address ipv4(0);
Ip6Address ipv6;
if (ip_.is_v4()) {
if (interface->IsIpv4Active() == false) {
return;
}
ipv4 = ip_.to_v4();
} else {
if (interface->IsIpv6Active() == false) {
return;
}
ipv6 = ip_.to_v6();
}
if (l2_installed_ == false || force_update) {
interface->UpdateL2InterfaceRoute(false, force_update,
interface->vrf(), ipv4, ipv6,
old_ethernet_tag, false,
false, ipv4, ipv6,
MacAddress::FromString(interface->vm_mac()),
Ip4Address(0));
l2_installed_ = true;
}
}
void VmInterface::InstanceIp::L2DeActivate(VmInterface *interface,
VrfEntry *old_vrf,
uint32_t old_ethernet_tag) const {
if (l2_installed_ == false) {
return;
}
Ip4Address ipv4(0);
Ip6Address ipv6;
if (ip_.is_v4()) {
ipv4 = ip_.to_v4();
} else {
ipv6 = ip_.to_v6();
}
interface->DeleteL2InterfaceRoute(true, old_vrf, ipv4, ipv6,
old_ethernet_tag,
MacAddress::FromString(interface->vm_mac()));
l2_installed_ = false;
}
void VmInterface::InstanceIp::Activate(VmInterface *interface,
bool force_update, bool l2,
int old_ethernet_tag) const {
if (l2) {
L2Activate(interface, force_update, old_ethernet_tag);
} else {
L3Activate(interface, force_update);
}
}
void VmInterface::InstanceIp::DeActivate(VmInterface *interface, bool l2,
VrfEntry *old_vrf,
uint32_t old_ethernet_tag) const {
if (l2) {
L2DeActivate(interface, old_vrf, old_ethernet_tag);
} else {
L3DeActivate(interface, old_vrf);
}
}
void VmInterface::InstanceIpList::Insert(const InstanceIp *rhs) {
list_.insert(*rhs);
}
void VmInterface::InstanceIpList::Update(const InstanceIp *lhs,
const InstanceIp *rhs) {
}
void VmInterface::InstanceIpList::Remove(InstanceIpSet::iterator &it) {
it->set_del_pending(true);
}
/////////////////////////////////////////////////////////////////////////////
// FloatingIp routines
/////////////////////////////////////////////////////////////////////////////
VmInterface::FloatingIp::FloatingIp() :
ListEntry(), floating_ip_(), vn_(NULL),
vrf_(NULL, this), vrf_name_(""), vn_uuid_(), l2_installed_(false),
ethernet_tag_(0), fixed_ip_(), force_l3_update_(false),
force_l2_update_(false) {
}
VmInterface::FloatingIp::FloatingIp(const FloatingIp &rhs) :
ListEntry(rhs.installed_, rhs.del_pending_),
floating_ip_(rhs.floating_ip_), vn_(rhs.vn_), vrf_(rhs.vrf_, this),
vrf_name_(rhs.vrf_name_), vn_uuid_(rhs.vn_uuid_),
l2_installed_(rhs.l2_installed_), ethernet_tag_(rhs.ethernet_tag_),
fixed_ip_(rhs.fixed_ip_), force_l3_update_(rhs.force_l3_update_),
force_l2_update_(rhs.force_l2_update_) {
}
VmInterface::FloatingIp::FloatingIp(const IpAddress &addr,
const std::string &vrf,
const boost::uuids::uuid &vn_uuid,
const IpAddress &fixed_ip) :
ListEntry(), floating_ip_(addr), vn_(NULL), vrf_(NULL, this), vrf_name_(vrf),
vn_uuid_(vn_uuid), l2_installed_(false), ethernet_tag_(0),
fixed_ip_(fixed_ip), force_l3_update_(false), force_l2_update_(false){
}
VmInterface::FloatingIp::~FloatingIp() {
}
bool VmInterface::FloatingIp::operator() (const FloatingIp &lhs,
const FloatingIp &rhs) const {
return lhs.IsLess(&rhs);
}
// Compare key for FloatingIp. Key is <floating_ip_ and vrf_name_> for both
// Config and Operational processing
bool VmInterface::FloatingIp::IsLess(const FloatingIp *rhs) const {
if (floating_ip_ != rhs->floating_ip_)
return floating_ip_ < rhs->floating_ip_;
return (vrf_name_ < rhs->vrf_name_);
}
void VmInterface::FloatingIp::L3Activate(VmInterface *interface,
bool force_update) const {
// Add route if not installed or if force requested
if (installed_ && force_update == false && force_l3_update_ == false) {
return;
}
if (fixed_ip_.is_v4() && fixed_ip_ == Ip4Address(0)) {
fixed_ip_ = GetFixedIp(interface);
}
InterfaceTable *table =
static_cast<InterfaceTable *>(interface->get_table());
if (floating_ip_.is_v4()) {
interface->AddRoute(vrf_.get()->GetName(), floating_ip_.to_v4(), 32,
vn_->GetName(), true, interface->ecmp(), Ip4Address(0),
GetFixedIp(interface));
if (table->update_floatingip_cb().empty() == false) {
table->update_floatingip_cb()(interface, vn_.get(),
floating_ip_.to_v4(), false);
}
} else if (floating_ip_.is_v6()) {
interface->AddRoute(vrf_.get()->GetName(), floating_ip_.to_v6(), 128,
vn_->GetName(), true, false, Ip6Address(),
GetFixedIp(interface));
//TODO:: callback for DNS handling
}
installed_ = true;
force_l3_update_ = false;
}
void VmInterface::FloatingIp::L3DeActivate(VmInterface *interface) const {
if (installed_ == false)
return;
if (floating_ip_.is_v4()) {
interface->DeleteRoute(vrf_.get()->GetName(), floating_ip_, 32);
InterfaceTable *table =
static_cast<InterfaceTable *>(interface->get_table());
if (table->update_floatingip_cb().empty() == false) {
table->update_floatingip_cb()(interface, vn_.get(),
floating_ip_.to_v4(), true);
}
} else if (floating_ip_.is_v6()) {
interface->DeleteRoute(vrf_.get()->GetName(), floating_ip_, 128);
//TODO:: callback for DNS handling
}
installed_ = false;
}
void VmInterface::FloatingIp::L2Activate(VmInterface *interface,
bool force_update) const {
// Add route if not installed or if force requested
if (l2_installed_ && force_update == false &&
force_l2_update_ == false) {
return;
}
SecurityGroupList sg_id_list;
interface->CopySgIdList(&sg_id_list);
PathPreference path_preference;
interface->SetPathPreference(&path_preference, false, GetFixedIp(interface));
EvpnAgentRouteTable *evpn_table = static_cast<EvpnAgentRouteTable *>
(vrf_->GetEvpnRouteTable());
//Agent *agent = evpn_table->agent();
ethernet_tag_ = vn_->ComputeEthernetTag();
evpn_table->AddReceiveRoute(interface->peer_.get(), vrf_->GetName(),
interface->l2_label(),
MacAddress::FromString(interface->vm_mac()),
floating_ip_, ethernet_tag_, vn_->GetName(),
path_preference);
l2_installed_ = true;
force_l2_update_ = false;
}
void VmInterface::FloatingIp::L2DeActivate(VmInterface *interface) const {
if (l2_installed_ == false)
return;
EvpnAgentRouteTable *evpn_table = static_cast<EvpnAgentRouteTable *>
(vrf_->GetEvpnRouteTable());
evpn_table->DelLocalVmRoute(interface->peer_.get(), vrf_->GetName(),
MacAddress::FromString(interface->vm_mac()),
interface, floating_ip_, ethernet_tag_);
ethernet_tag_ = 0;
l2_installed_ = false;
}
void VmInterface::FloatingIp::Activate(VmInterface *interface,
bool force_update, bool l2) const {
InterfaceTable *table =
static_cast<InterfaceTable *>(interface->get_table());
if (vn_.get() == NULL) {
vn_ = table->FindVnRef(vn_uuid_);
assert(vn_.get());
}
if (vrf_.get() == NULL) {
vrf_ = table->FindVrfRef(vrf_name_);
assert(vrf_.get());
}
if (l2)
L2Activate(interface, force_update);
else
L3Activate(interface, force_update);
}
void VmInterface::FloatingIp::DeActivate(VmInterface *interface, bool l2) const{
if (l2)
L2DeActivate(interface);
else
L3DeActivate(interface);
if (installed_ == false && l2_installed_ == false)
vrf_ = NULL;
}
const IpAddress
VmInterface::FloatingIp::GetFixedIp(const VmInterface *interface) const {
if (fixed_ip_.to_v4() == Ip4Address(0)) {
if (floating_ip_.is_v4() == true) {
return interface->primary_ip_addr();
} else {
return interface->primary_ip6_addr();
}
}
return fixed_ip_;
}
void VmInterface::FloatingIpList::Insert(const FloatingIp *rhs) {
std::pair<FloatingIpSet::iterator, bool> ret = list_.insert(*rhs);
if (ret.second) {
if (rhs->floating_ip_.is_v4()) {
v4_count_++;
} else {
v6_count_++;
}
}
}
void VmInterface::FloatingIpList::Update(const FloatingIp *lhs,
const FloatingIp *rhs) {
if (lhs->fixed_ip_ != rhs->fixed_ip_) {
lhs->fixed_ip_ = rhs->fixed_ip_;
lhs->force_l3_update_ = true;
lhs->force_l2_update_ = true;
}
}
void VmInterface::FloatingIpList::Remove(FloatingIpSet::iterator &it) {
it->set_del_pending(true);
}
/////////////////////////////////////////////////////////////////////////////
// StaticRoute routines
/////////////////////////////////////////////////////////////////////////////
VmInterface::StaticRoute::StaticRoute() :
ListEntry(), vrf_(""), addr_(), plen_(0), gw_() {
}
VmInterface::StaticRoute::StaticRoute(const StaticRoute &rhs) :
ListEntry(rhs.installed_, rhs.del_pending_), vrf_(rhs.vrf_),
addr_(rhs.addr_), plen_(rhs.plen_), gw_(rhs.gw_) {
}
VmInterface::StaticRoute::StaticRoute(const std::string &vrf,
const IpAddress &addr,
uint32_t plen, const IpAddress &gw) :
ListEntry(), vrf_(vrf), addr_(addr), plen_(plen), gw_(gw) {
}
VmInterface::StaticRoute::~StaticRoute() {
}
bool VmInterface::StaticRoute::operator() (const StaticRoute &lhs,
const StaticRoute &rhs) const {
return lhs.IsLess(&rhs);
}
bool VmInterface::StaticRoute::IsLess(const StaticRoute *rhs) const {
#if 0
//Enable once we can add static routes across vrf
if (vrf_name_ != rhs->vrf_name_)
return vrf_name_ < rhs->vrf_name_;
#endif
if (addr_ != rhs->addr_)
return addr_ < rhs->addr_;
if (plen_ < rhs->plen_) {
return plen_ < rhs->plen_;
}
return gw_ < rhs->gw_;
}
void VmInterface::StaticRoute::Activate(VmInterface *interface,
bool force_update,
bool policy_change) const {
bool ecmp = false;
if (installed_ && force_update == false && policy_change == false)
return;
if (vrf_ != interface->vrf()->GetName()) {
vrf_ = interface->vrf()->GetName();
}
if (installed_ == true && policy_change) {
InetUnicastAgentRouteTable::ReEvaluatePaths(interface->agent(),
vrf_, addr_, plen_);
} else if (installed_ == false || force_update) {
if (addr_.is_v4()) {
ecmp = interface->ecmp();
}
Ip4Address gw_ip(0);
if (gw_.is_v4() && addr_.is_v4() && gw_.to_v4() != gw_ip) {
SecurityGroupList sg_id_list;
interface->CopySgIdList(&sg_id_list);
InetUnicastAgentRouteTable::AddGatewayRoute(interface->peer_.get(),
vrf_, addr_.to_v4(),
plen_, gw_.to_v4(), interface->vn_->GetName(),
interface->vrf_->table_label(),
sg_id_list);
} else {
interface->AddRoute(vrf_, addr_, plen_,
interface->vn_->GetName(),
interface->policy_enabled(),
ecmp, IpAddress(), interface->primary_ip_addr());
}
}
installed_ = true;
}
void VmInterface::StaticRoute::DeActivate(VmInterface *interface) const {
if (installed_ == false)
return;
interface->DeleteRoute(vrf_, addr_, plen_);
installed_ = false;
}
void VmInterface::StaticRouteList::Insert(const StaticRoute *rhs) {
list_.insert(*rhs);
}
void VmInterface::StaticRouteList::Update(const StaticRoute *lhs,
const StaticRoute *rhs) {
}
void VmInterface::StaticRouteList::Remove(StaticRouteSet::iterator &it) {
it->set_del_pending(true);
}
///////////////////////////////////////////////////////////////////////////////
//Allowed addresss pair route
///////////////////////////////////////////////////////////////////////////////
VmInterface::AllowedAddressPair::AllowedAddressPair() :
ListEntry(), vrf_(""), addr_(0), plen_(0), ecmp_(false), mac_(),
l2_entry_installed_(false), ethernet_tag_(0), vrf_ref_(NULL, this), gw_ip_(0) {
}
VmInterface::AllowedAddressPair::AllowedAddressPair(
const AllowedAddressPair &rhs) : ListEntry(rhs.installed_,
rhs.del_pending_), vrf_(rhs.vrf_), addr_(rhs.addr_), plen_(rhs.plen_),
ecmp_(rhs.ecmp_), mac_(rhs.mac_),
l2_entry_installed_(rhs.l2_entry_installed_), ethernet_tag_(rhs.ethernet_tag_),
vrf_ref_(rhs.vrf_ref_, this), gw_ip_(rhs.gw_ip_) {
}
VmInterface::AllowedAddressPair::AllowedAddressPair(const std::string &vrf,
const Ip4Address &addr,
uint32_t plen, bool ecmp,
const MacAddress &mac) :
ListEntry(), vrf_(vrf), addr_(addr), plen_(plen), ecmp_(ecmp), mac_(mac),
l2_entry_installed_(false), ethernet_tag_(0), vrf_ref_(NULL, this) {
}
VmInterface::AllowedAddressPair::~AllowedAddressPair() {
}
bool VmInterface::AllowedAddressPair::operator() (const AllowedAddressPair &lhs,
const AllowedAddressPair &rhs)
const {
return lhs.IsLess(&rhs);
}
bool VmInterface::AllowedAddressPair::IsLess(const AllowedAddressPair *rhs) const {
#if 0
//Enable once we can add static routes across vrf
if (vrf_name_ != rhs->vrf_name_)
return vrf_name_ < rhs->vrf_name_;
#endif
if (addr_ != rhs->addr_)
return addr_ < rhs->addr_;
if (plen_ < rhs->plen_) {
return plen_ < rhs->plen_;
}
return mac_ < rhs->mac_;
}
void VmInterface::AllowedAddressPair::L2Activate(VmInterface *interface,
bool force_update,
bool policy_change,
bool old_layer2_forwarding,
bool old_layer3_forwarding) const {
if (mac_ == MacAddress::kZeroMac) {
return;
}
if (l2_entry_installed_ && force_update == false &&
policy_change == false && ethernet_tag_ == interface->ethernet_tag() &&
old_layer3_forwarding == interface->layer3_forwarding()) {
return;
}
if (vrf_ != interface->vrf()->GetName()) {
vrf_ = interface->vrf()->GetName();
}
vrf_ref_ = interface->vrf();
if (old_layer3_forwarding != interface->layer3_forwarding() ||
l2_entry_installed_ == false) {
force_update = true;
}
if (ethernet_tag_ != interface->ethernet_tag()) {
force_update = true;
}
if (l2_entry_installed_ == false || force_update || policy_change) {
Ip4Address dependent_rt = Ip4Address(0);
if (ecmp_ == true) {
dependent_rt = interface->primary_ip_addr();
}
interface->UpdateL2InterfaceRoute(old_layer2_forwarding, force_update,
interface->vrf(), addr_, Ip6Address(),
ethernet_tag_, old_layer3_forwarding,
policy_change, addr_, Ip6Address(), mac_,
dependent_rt);
ethernet_tag_ = interface->ethernet_tag();
//If layer3 forwarding is disabled
// * IP + mac allowed address pair should not be published
// * Only mac allowed address pair should be published
//Logic for same is present in UpdateL2InterfaceRoute
if (interface->layer3_forwarding() || addr_.is_unspecified() == true) {
l2_entry_installed_ = true;
} else {
l2_entry_installed_ = false;
}
}
}
void VmInterface::AllowedAddressPair::L2DeActivate(VmInterface *interface) const{
if (mac_ == MacAddress::kZeroMac) {
return;
}
if (l2_entry_installed_ == false) {
return;
}
interface->DeleteL2InterfaceRoute(true, vrf_ref_.get(), addr_,
Ip6Address(), ethernet_tag_, mac_);
l2_entry_installed_ = false;
vrf_ref_ = NULL;
}
void VmInterface::AllowedAddressPair::Activate(VmInterface *interface,
bool force_update,
bool policy_change) const {
const VnIpam *ipam = interface->vn_->GetIpam(addr_);
Ip4Address ip(0);
if (ipam) {
ip = ipam->default_gw.to_v4();
}
if (installed_ && force_update == false && policy_change == false &&
gw_ip_ == ip) {
return;
}
if (vrf_ != interface->vrf()->GetName()) {
vrf_ = interface->vrf()->GetName();
}
if (installed_ == true && policy_change) {
InetUnicastAgentRouteTable::ReEvaluatePaths(interface->agent(),
vrf_, addr_, plen_);
} else if (installed_ == false || force_update || gw_ip_ != ip) {
gw_ip_ = ip;
Ip4Address dependent_rt = Ip4Address(0);
if (ecmp_ == true) {
dependent_rt = interface->primary_ip_addr();
}
interface->AddRoute(vrf_, addr_, plen_, interface->vn_->GetName(),
interface->policy_enabled(),
ecmp_, gw_ip_, dependent_rt);
}
installed_ = true;
}
void VmInterface::AllowedAddressPair::DeActivate(VmInterface *interface) const {
if (installed_ == false)
return;
interface->DeleteRoute(vrf_, addr_, plen_);
installed_ = false;
}
void VmInterface::AllowedAddressPairList::Insert(const AllowedAddressPair *rhs) {
list_.insert(*rhs);
}
void VmInterface::AllowedAddressPairList::Update(const AllowedAddressPair *lhs,
const AllowedAddressPair *rhs) {
}
void VmInterface::AllowedAddressPairList::Remove(AllowedAddressPairSet::iterator &it) {
it->set_del_pending(true);
}
/////////////////////////////////////////////////////////////////////////////
// SecurityGroup routines
/////////////////////////////////////////////////////////////////////////////
VmInterface::SecurityGroupEntry::SecurityGroupEntry() :
ListEntry(), uuid_(nil_uuid()) {
}
VmInterface::SecurityGroupEntry::SecurityGroupEntry
(const SecurityGroupEntry &rhs) :
ListEntry(rhs.installed_, rhs.del_pending_), uuid_(rhs.uuid_) {
}
VmInterface::SecurityGroupEntry::SecurityGroupEntry(const uuid &u) :
ListEntry(), uuid_(u) {
}
VmInterface::SecurityGroupEntry::~SecurityGroupEntry() {
}
bool VmInterface::SecurityGroupEntry::operator ==
(const SecurityGroupEntry &rhs) const {
return uuid_ == rhs.uuid_;
}
bool VmInterface::SecurityGroupEntry::operator()
(const SecurityGroupEntry &lhs, const SecurityGroupEntry &rhs) const {
return lhs.IsLess(&rhs);
}
bool VmInterface::SecurityGroupEntry::IsLess
(const SecurityGroupEntry *rhs) const {
return uuid_ < rhs->uuid_;
}
void VmInterface::SecurityGroupEntry::Activate(VmInterface *interface) const {
if (sg_.get() != NULL)
return;
Agent *agent = static_cast<InterfaceTable *>
(interface->get_table())->agent();
SgKey sg_key(uuid_);
sg_ = static_cast<SgEntry *>
(agent->sg_table()->FindActiveEntry(&sg_key));
}
void VmInterface::SecurityGroupEntry::DeActivate(VmInterface *interface) const {
}
void VmInterface::SecurityGroupEntryList::Insert
(const SecurityGroupEntry *rhs) {
list_.insert(*rhs);
}
void VmInterface::SecurityGroupEntryList::Update
(const SecurityGroupEntry *lhs, const SecurityGroupEntry *rhs) {
}
void VmInterface::SecurityGroupEntryList::Remove
(SecurityGroupEntrySet::iterator &it) {
it->set_del_pending(true);
}
/////////////////////////////////////////////////////////////////////////////
// ServiceVlan routines
/////////////////////////////////////////////////////////////////////////////
VmInterface::ServiceVlan::ServiceVlan() :
ListEntry(), tag_(0), vrf_name_(""), addr_(0), plen_(32), smac_(), dmac_(),
vrf_(NULL, this), label_(MplsTable::kInvalidLabel) {
}
VmInterface::ServiceVlan::ServiceVlan(const ServiceVlan &rhs) :
ListEntry(rhs.installed_, rhs.del_pending_), tag_(rhs.tag_),
vrf_name_(rhs.vrf_name_), addr_(rhs.addr_), plen_(rhs.plen_),
smac_(rhs.smac_), dmac_(rhs.dmac_), vrf_(rhs.vrf_, this), label_(rhs.label_) {
}
VmInterface::ServiceVlan::ServiceVlan(uint16_t tag, const std::string &vrf_name,
const Ip4Address &addr, uint8_t plen,
const MacAddress &smac,
const MacAddress &dmac) :
ListEntry(), tag_(tag), vrf_name_(vrf_name), addr_(addr), plen_(plen),
smac_(smac), dmac_(dmac), vrf_(NULL, this), label_(MplsTable::kInvalidLabel)
{
}
VmInterface::ServiceVlan::~ServiceVlan() {
}
bool VmInterface::ServiceVlan::operator() (const ServiceVlan &lhs,
const ServiceVlan &rhs) const {
return lhs.IsLess(&rhs);
}
bool VmInterface::ServiceVlan::IsLess(const ServiceVlan *rhs) const {
return tag_ < rhs->tag_;
}
void VmInterface::ServiceVlan::Activate(VmInterface *interface,
bool force_update) const {
InterfaceTable *table =
static_cast<InterfaceTable *>(interface->get_table());
VrfEntry *vrf = table->FindVrfRef(vrf_name_);
assert(vrf);
if (label_ == MplsTable::kInvalidLabel) {
VlanNH::Create(interface->GetUuid(), tag_, vrf_name_, smac_, dmac_);
label_ = table->agent()->mpls_table()->AllocLabel();
MplsLabel::CreateVlanNh(table->agent(), label_,
interface->GetUuid(), tag_);
VrfAssignTable::CreateVlan(interface->GetUuid(), vrf_name_, tag_);
}
if (vrf_.get() != vrf) {
interface->ServiceVlanRouteDel(*this);
vrf_ = vrf;
installed_ = false;
}
if (installed_ && force_update == false)
return;
interface->ServiceVlanRouteAdd(*this);
installed_ = true;
}
void VmInterface::ServiceVlan::DeActivate(VmInterface *interface) const {
if (label_ != MplsTable::kInvalidLabel) {
VrfAssignTable::DeleteVlan(interface->GetUuid(), tag_);
interface->ServiceVlanRouteDel(*this);
Agent *agent =
static_cast<InterfaceTable *>(interface->get_table())->agent();
MplsLabel::Delete(agent, label_);
label_ = MplsTable::kInvalidLabel;
VlanNH::Delete(interface->GetUuid(), tag_);
vrf_ = NULL;
}
installed_ = false;
return;
}
void VmInterface::ServiceVlanList::Insert(const ServiceVlan *rhs) {
list_.insert(*rhs);
}
void VmInterface::ServiceVlanList::Update(const ServiceVlan *lhs,
const ServiceVlan *rhs) {
}
void VmInterface::ServiceVlanList::Remove(ServiceVlanSet::iterator &it) {
it->set_del_pending(true);
}
uint32_t VmInterface::GetServiceVlanLabel(const VrfEntry *vrf) const {
ServiceVlanSet::const_iterator it = service_vlan_list_.list_.begin();
while (it != service_vlan_list_.list_.end()) {
if (it->vrf_.get() == vrf) {
return it->label_;
}
it++;
}
return 0;
}
uint32_t VmInterface::GetServiceVlanTag(const VrfEntry *vrf) const {
ServiceVlanSet::const_iterator it = service_vlan_list_.list_.begin();
while (it != service_vlan_list_.list_.end()) {
if (it->vrf_.get() == vrf) {
return it->tag_;
}
it++;
}
return 0;
}
const VrfEntry* VmInterface::GetServiceVlanVrf(uint16_t vlan_tag) const {
ServiceVlanSet::const_iterator it = service_vlan_list_.list_.begin();
while (it != service_vlan_list_.list_.end()) {
if (it->tag_ == vlan_tag) {
return it->vrf_.get();
}
it++;
}
return NULL;
}
void VmInterface::ServiceVlanRouteAdd(const ServiceVlan &entry) {
if (vrf_.get() == NULL ||
vn_.get() == NULL) {
return;
}
SecurityGroupList sg_id_list;
CopySgIdList(&sg_id_list);
PathPreference path_preference;
SetPathPreference(&path_preference, ecmp(), primary_ip_addr());
// With IRB model, add L2 Receive route for SMAC and DMAC to ensure
// packets from service vm go thru routing
BridgeAgentRouteTable *table = static_cast<BridgeAgentRouteTable *>
(vrf_->GetBridgeRouteTable());
table->AddBridgeReceiveRoute(peer_.get(), entry.vrf_->GetName(),
0, entry.dmac_, vn()->GetName());
table->AddBridgeReceiveRoute(peer_.get(), entry.vrf_->GetName(),
0, entry.smac_, vn()->GetName());
InetUnicastAgentRouteTable::AddVlanNHRoute
(peer_.get(), entry.vrf_->GetName(), entry.addr_, 32,
GetUuid(), entry.tag_, entry.label_, vn()->GetName(), sg_id_list,
path_preference);
entry.installed_ = true;
return;
}
void VmInterface::ServiceVlanRouteDel(const ServiceVlan &entry) {
if (entry.installed_ == false) {
return;
}
InetUnicastAgentRouteTable::Delete
(peer_.get(), entry.vrf_->GetName(), entry.addr_, 32);
// Delete the L2 Recive routes added for smac_ and dmac_
BridgeAgentRouteTable *table = static_cast<BridgeAgentRouteTable *>
(entry.vrf_->GetBridgeRouteTable());
table->Delete(peer_.get(), entry.vrf_->GetName(), entry.dmac_,
0);
table->Delete(peer_.get(), entry.vrf_->GetName(), entry.smac_,
0);
entry.installed_ = false;
return;
}
bool VmInterface::HasFloatingIp(Address::Family family) const {
if (family == Address::INET) {
return floating_ip_list_.v4_count_ > 0;
} else {
return floating_ip_list_.v6_count_ > 0;
}
}
bool VmInterface::HasFloatingIp() const {
return floating_ip_list_.list_.size() != 0;
}
bool VmInterface::IsFloatingIp(const IpAddress &ip) const {
VmInterface::FloatingIpSet::const_iterator it =
floating_ip_list_.list_.begin();
while(it != floating_ip_list_.list_.end()) {
if ((*it).floating_ip_ == ip) {
return true;
}
it++;
}
return false;
}
////////////////////////////////////////////////////////////////////////////
// VRF assign rule routines
////////////////////////////////////////////////////////////////////////////
VmInterface::VrfAssignRule::VrfAssignRule():
ListEntry(), id_(0), vrf_name_(" "), vrf_(NULL, this), ignore_acl_(false) {
}
VmInterface::VrfAssignRule::VrfAssignRule(const VrfAssignRule &rhs):
ListEntry(rhs.installed_, rhs.del_pending_), id_(rhs.id_),
vrf_name_(rhs.vrf_name_), vrf_(rhs.vrf_, this), ignore_acl_(rhs.ignore_acl_),
match_condition_(rhs.match_condition_) {
}
VmInterface::VrfAssignRule::VrfAssignRule(uint32_t id,
const autogen::MatchConditionType &match_condition,
const std::string &vrf_name,
bool ignore_acl):
ListEntry(), id_(id), vrf_name_(vrf_name), vrf_(NULL, this),
ignore_acl_(ignore_acl), match_condition_(match_condition) {
}
VmInterface::VrfAssignRule::~VrfAssignRule() {
}
bool VmInterface::VrfAssignRule::operator() (const VrfAssignRule &lhs,
const VrfAssignRule &rhs) const {
return lhs.IsLess(&rhs);
}
bool VmInterface::VrfAssignRule::IsLess(const VrfAssignRule *rhs) const {
if (id_ != rhs->id_) {
return id_ < rhs->id_;
}
if (vrf_name_ != rhs->vrf_name_) {
return vrf_name_ < rhs->vrf_name_;
}
if (ignore_acl_ != rhs->ignore_acl_) {
return ignore_acl_ < rhs->ignore_acl_;
}
return CompareMatchConditionType(match_condition_, rhs->match_condition_);
}
void VmInterface::VrfAssignRuleList::Insert(const VrfAssignRule *rhs) {
list_.insert(*rhs);
}
void VmInterface::VrfAssignRuleList::Update(const VrfAssignRule *lhs,
const VrfAssignRule *rhs) {
}
void VmInterface::VrfAssignRuleList::Remove(VrfAssignRuleSet::iterator &it) {
it->set_del_pending(true);
}
const string VmInterface::GetAnalyzer() const {
if (mirror_entry()) {
return mirror_entry()->GetAnalyzerName();
} else {
return std::string();
}
}
void VmInterface::SendTrace(Trace event) {
InterfaceInfo intf_info;
intf_info.set_name(name_);
intf_info.set_index(id_);
switch(event) {
case ACTIVATED_IPV4:
intf_info.set_op("IPV4 Activated");
break;
case DEACTIVATED_IPV4:
intf_info.set_op("IPV4 Deactivated");
break;
case ACTIVATED_IPV6:
intf_info.set_op("IPV6 Activated");
break;
case DEACTIVATED_IPV6:
intf_info.set_op("IPV6 Deactivated");
break;
case ACTIVATED_L2:
intf_info.set_op("L2 Activated");
break;
case DEACTIVATED_L2:
intf_info.set_op("L2 Deactivated");
break;
case ADD:
intf_info.set_op("Add");
break;
case DELETE:
intf_info.set_op("Delete");
break;
case FLOATING_IP_CHANGE: {
intf_info.set_op("Floating IP change");
std::vector<FloatingIPInfo> fip_list;
FloatingIpSet::iterator it = floating_ip_list_.list_.begin();
while (it != floating_ip_list_.list_.end()) {
const FloatingIp &ip = *it;
FloatingIPInfo fip;
fip.set_ip_address(ip.floating_ip_.to_string());
fip.set_vrf_name(ip.vrf_->GetName());
fip_list.push_back(fip);
it++;
}
intf_info.set_fip(fip_list);
break;
}
case SERVICE_CHANGE:
break;
}
intf_info.set_ip_address(primary_ip_addr_.to_string());
if (vm_) {
intf_info.set_vm(UuidToString(vm_->GetUuid()));
}
if (vn_) {
intf_info.set_vn(vn_->GetName());
}
if (vrf_) {
intf_info.set_vrf(vrf_->GetName());
}
intf_info.set_vm_project(UuidToString(vm_project_uuid_));
OPER_TRACE(Interface, intf_info);
}
/////////////////////////////////////////////////////////////////////////////
// VM Interface DB Table utility functions
/////////////////////////////////////////////////////////////////////////////
// Add a VM-Interface
void VmInterface::NovaAdd(InterfaceTable *table, const uuid &intf_uuid,
const string &os_name, const Ip4Address &addr,
const string &mac, const string &vm_name,
const uuid &vm_project_uuid, uint16_t tx_vlan_id,
uint16_t rx_vlan_id, const std::string &parent,
const Ip6Address &ip6,
Interface::Transport transport) {
DBRequest req(DBRequest::DB_ENTRY_ADD_CHANGE);
req.key.reset(new VmInterfaceKey(AgentKey::ADD_DEL_CHANGE, intf_uuid,
os_name));
req.data.reset(new VmInterfaceNovaData(addr, ip6, mac, vm_name,
nil_uuid(), vm_project_uuid, parent,
tx_vlan_id, rx_vlan_id,
VmInterface::VM_ON_TAP,
VmInterface::INSTANCE,
transport));
table->Enqueue(&req);
}
// Delete a VM-Interface
void VmInterface::Delete(InterfaceTable *table, const uuid &intf_uuid,
VmInterface::Configurer configurer) {
DBRequest req(DBRequest::DB_ENTRY_DELETE);
req.key.reset(new VmInterfaceKey(AgentKey::ADD_DEL_CHANGE, intf_uuid, ""));
if (configurer == VmInterface::CONFIG) {
req.data.reset(new VmInterfaceConfigData(NULL, NULL));
} else if (configurer == VmInterface::INSTANCE_MSG) {
req.data.reset(new VmInterfaceNovaData());
} else {
assert(0);
}
table->Enqueue(&req);
}
bool VmInterface::CopyIp6Address(const Ip6Address &addr) {
bool ret = false;
// Retain the old if new IP could not be got
if (addr.is_unspecified()) {
return false;
}
if (primary_ip6_addr_ != addr) {
primary_ip6_addr_ = addr;
ret = true;
}
return ret;
}
void VmInterface::UpdateIpv4InstanceIp(bool force_update, bool policy_change,
bool l2,
uint32_t old_ethernet_tag) {
if (l2 && old_ethernet_tag != ethernet_tag()) {
force_update = true;
}
InstanceIpSet::iterator it = instance_ipv4_list_.list_.begin();
while (it != instance_ipv4_list_.list_.end()) {
InstanceIpSet::iterator prev = it++;
if (prev->del_pending_) {
prev->DeActivate(this, l2, vrf(), old_ethernet_tag);
if (prev->installed() == false) {
instance_ipv4_list_.list_.erase(prev);
}
} else {
prev->Activate(this, force_update||policy_change, l2,
old_ethernet_tag);
}
}
}
void VmInterface::DeleteIpv4InstanceIp(bool l2, uint32_t old_ethernet_tag,
VrfEntry *old_vrf_entry) {
InstanceIpSet::iterator it = instance_ipv4_list_.list_.begin();
while (it != instance_ipv4_list_.list_.end()) {
InstanceIpSet::iterator prev = it++;
prev->DeActivate(this, l2, old_vrf_entry, old_ethernet_tag);
if (prev->del_pending_ && prev->installed() == false) {
instance_ipv4_list_.list_.erase(prev);
}
}
}
void VmInterface::UpdateIpv6InstanceIp(bool force_update, bool policy_change,
bool l2,
uint32_t old_ethernet_tag) {
if (l2 && old_ethernet_tag != ethernet_tag()) {
force_update = true;
}
InstanceIpSet::iterator it = instance_ipv6_list_.list_.begin();
while (it != instance_ipv6_list_.list_.end()) {
InstanceIpSet::iterator prev = it++;
if (prev->del_pending_) {
prev->DeActivate(this, l2, vrf(), old_ethernet_tag);
if (prev->installed() == false) {
instance_ipv6_list_.list_.erase(prev);
}
} else {
prev->Activate(this, force_update||policy_change, l2,
old_ethernet_tag);
}
}
}
void VmInterface::DeleteIpv6InstanceIp(bool l2, uint32_t old_ethernet_tag,
VrfEntry *old_vrf_entry) {
InstanceIpSet::iterator it = instance_ipv6_list_.list_.begin();
while (it != instance_ipv6_list_.list_.end()) {
InstanceIpSet::iterator prev = it++;
prev->DeActivate(this, l2, old_vrf_entry, old_ethernet_tag);
if (prev->del_pending_ && prev->installed() == false) {
instance_ipv6_list_.list_.erase(prev);
}
}
}
|
#include "Log.h"
#include "Socket.h"
#include "Buffer.h"
#include <string.h>
#include <atomic>
#define SOCKET_MAX_CONNECTIONS 5
/* ------------------------------------- */
#if (defined __CYGWIN__ || defined __GNUC__)
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define SOCKET_HANDLE int
#define INVALID_SOCKET 0
#define SOCKET_ERROR -1
namespace {
std::string ErrorMessage (const std::string& inMethod) {
return "[Socket] CygWin::" + inMethod + " failed";
}
}
/* ------------------------------------- */
#elif _MSC_VER >= 1800
#undef UNICODE
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#define SOCKET_HANDLE SOCKET
namespace {
std::string ErrorMessage (const std::string& inMethod) {
return "[Socket] WinSock2::" + inMethod + " failed with code " + std::to_string (WSAGetLastError ());
}
}
/* ------------------------------------- */
#else
static_assert (true, "Incompatible compiler");
#endif
/* ------------------------------------- */
class OS::Socket::Implementation {
public:
Implementation () :
mSocketHandle (INVALID_SOCKET),
mLatestAddrInfo (NULL),
mIsConnected (false),
mIsListening (false)
{
}
~Implementation () {
LOGMESSAGE (OS::Log::kTrace, std::string ("[Socket](") + std::to_string (GetId ()) + std::string (") is being destructed"));
}
public:
bool IsConnected () const {
return mIsConnected;
}
bool IsListening () const {
return mIsListening;
}
bool Initialize (SOCKET_HANDLE inSocketHandle) {
mIsListening = false;
mIsConnected = true;
mSocketHandle = inSocketHandle;
LOGMESSAGE (OS::Log::kDebug, std::string ("[Socket](") + std::to_string (GetId ()) + std::string (") initialized"));
return true;
}
bool Initialize (const std::string& inAddress, const std::string& inPort) {
mIsListening = false;
mIsConnected = false;
struct addrinfo hints;
#if (defined __CYGWIN__ || defined __GNUC__)
::memset (&hints, 0, sizeof (hints));
#else
ZeroMemory (&hints, sizeof (hints));
#endif
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the server address and port
int res = getaddrinfo (inAddress.c_str (), inPort.c_str (), &hints, &mLatestAddrInfo);
if (res != 0) {
LOGMESSAGE (OS::Log::kDebug, ErrorMessage ("getaddrinfo"));
return false;
}
// Create a SOCKET for connecting to server
mSocketHandle = socket (mLatestAddrInfo->ai_family, mLatestAddrInfo->ai_socktype, mLatestAddrInfo->ai_protocol);
if (mSocketHandle == INVALID_SOCKET) {
LOGMESSAGE (OS::Log::kDebug, ErrorMessage ("socket"));
return false;
}
LOGMESSAGE (OS::Log::kDebug, "[Socket](" + std::to_string (GetId ()) + ") initialized at " + inAddress + ":" + inPort);
return true;
}
void Close () {
if (mIsConnected || mIsListening) {
freeaddrinfo (mLatestAddrInfo);
shutdown (mSocketHandle, 2);
#if (defined __CYGWIN__ || defined __GNUC__)
close (mSocketHandle);
#else
closesocket (mSocketHandle);
#endif
LOGMESSAGE (OS::Log::kDebug, std::string ("[Socket](") + std::to_string (GetId ()) + std::string (") closed"));
}
mIsConnected = false;
mIsListening = false;
}
bool Listen () {
if (!mIsListening) {
int result = bind (mSocketHandle, mLatestAddrInfo->ai_addr, (int) mLatestAddrInfo->ai_addrlen);
if (result == SOCKET_ERROR) {
LOGMESSAGE (OS::Log::kDebug, ErrorMessage ("bind"));
return false;
}
result = listen (mSocketHandle, SOCKET_MAX_CONNECTIONS);
if (result == SOCKET_ERROR) {
LOGMESSAGE (OS::Log::kDebug, ErrorMessage ("listen"));
return false;
}
}
mIsListening = true;
LOGMESSAGE (OS::Log::kDebug, std::string ("[Socket](") + std::to_string (GetId ()) + std::string (") listening..."));
return true;
}
bool Accept (OS::Socket& outSocket) {
if (!mIsListening) {
return false;
}
SOCKET_HANDLE clientSocket = accept (mSocketHandle, NULL, NULL);
if (clientSocket == INVALID_SOCKET) {
LOGMESSAGE (OS::Log::kDebug, ErrorMessage ("accept"));
return false;
}
outSocket.Initialize (clientSocket);
LOGMESSAGE (OS::Log::kDebug, std::string ("[Socket](") + std::to_string (GetId ()) + std::string (") connected to socket " + std::to_string (outSocket.GetId ())));
return true;
}
bool Connect () {
if (mIsConnected) {
return true;
}
// Connect to server.
int res = connect (mSocketHandle, mLatestAddrInfo->ai_addr, (int) mLatestAddrInfo->ai_addrlen);
if (res == SOCKET_ERROR) {
LOGMESSAGE (OS::Log::kDebug, ErrorMessage ("connect"));
return false;
}
LOGMESSAGE (OS::Log::kDebug, std::string ("[Socket](") + std::to_string (GetId ()) + std::string (") connected to server"));
mIsConnected = true;
return true;
}
unsigned GetId () const {
return static_cast<unsigned> (mSocketHandle);
}
bool Send (const OS::Buffer& inBuffer) {
if (!mIsConnected) {
return false;
}
int result = send (mSocketHandle, inBuffer.GetDataPointer (), inBuffer.GetSize (), 0);
if (result == SOCKET_ERROR) {
LOGMESSAGE (OS::Log::kDebug, ErrorMessage ("send"));
Close ();
return false;
}
LOGMESSAGE (OS::Log::kTrace, std::string ("[Socket] Send ") + std::to_string (inBuffer.GetSize ()) + std::string (" bytes to client id ") + std::to_string (mSocketHandle));
return true;
}
bool Receive (OS::Buffer& outBuffer) {
if (!mIsConnected) {
return false;
}
int result = recv (mSocketHandle, outBuffer.GetDataPointer (), outBuffer.GetMaxSize (), 0);
if (result == 0) {
LOGMESSAGE (OS::Log::kDebug, std::string ("[Socket] Received termination signal from client with id ") + std::to_string (mSocketHandle));
Close ();
return false;
}
if (result < 0) {
LOGMESSAGE (OS::Log::kDebug, ErrorMessage ("recv"));
Close ();
return false;
}
outBuffer.Resize (result);
LOGMESSAGE (OS::Log::kTrace, std::string ("[Socket] Received ") + std::to_string (result) + std::string (" bytes from client with id ") + std::to_string (mSocketHandle));
return true;
}
private:
SOCKET_HANDLE mSocketHandle;
struct addrinfo *mLatestAddrInfo;
std::atomic<bool> mIsConnected;
std::atomic<bool> mIsListening;
};
/* ------------------------------------- */
OS::Socket::Socket (const std::string& inAddress, const std::string& inPortNumber) :
mAddress (inAddress),
mPortNumber (inPortNumber),
mImpl (std::make_unique <Implementation> ())
{
}
OS::Socket::~Socket () {
}
bool OS::Socket::Initialize () {
return mImpl->Initialize (mAddress, mPortNumber);
}
bool OS::Socket::Initialize (unsigned inHandle) {
return mImpl->Initialize (inHandle);
}
void OS::Socket::Close () {
mImpl->Close ();
}
unsigned OS::Socket::GetId () {
return mImpl->GetId ();
}
bool OS::Socket::Listen () {
return mImpl->Listen ();
}
bool OS::Socket::Accept (OS::Socket& outSocket) {
return mImpl->Accept (outSocket);
}
bool OS::Socket::Connect () {
return mImpl->Connect ();
}
bool OS::Socket::Send (const Buffer& inBuffer) {
return mImpl->Send (inBuffer);
}
bool OS::Socket::Receive (Buffer& outBuffer) {
return mImpl->Receive (outBuffer);
}
bool OS::Socket::IsConnected () const {
return mImpl->IsConnected ();
}
bool OS::Socket::IsListening () const {
return mImpl->IsListening ();
}
reuse address
#include "Log.h"
#include "Socket.h"
#include "Buffer.h"
#include <string.h>
#include <atomic>
#define SOCKET_MAX_CONNECTIONS 5
/* ------------------------------------- */
#if (defined __CYGWIN__ || defined __GNUC__)
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define SOCKET_HANDLE int
#define INVALID_SOCKET 0
#define SOCKET_ERROR -1
namespace {
std::string ErrorMessage (const std::string& inMethod) {
return "[Socket] CygWin::" + inMethod + " failed";
}
}
/* ------------------------------------- */
#elif _MSC_VER >= 1800
#undef UNICODE
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#define SOCKET_HANDLE SOCKET
namespace {
std::string ErrorMessage (const std::string& inMethod) {
return "[Socket] WinSock2::" + inMethod + " failed with code " + std::to_string (WSAGetLastError ());
}
}
/* ------------------------------------- */
#else
static_assert (true, "Incompatible compiler");
#endif
/* ------------------------------------- */
class OS::Socket::Implementation {
public:
Implementation () :
mSocketHandle (INVALID_SOCKET),
mLatestAddrInfo (NULL),
mIsConnected (false),
mIsListening (false)
{
}
~Implementation () {
LOGMESSAGE (OS::Log::kTrace, std::string ("[Socket](") + std::to_string (GetId ()) + std::string (") is being destructed"));
}
public:
bool IsConnected () const {
return mIsConnected;
}
bool IsListening () const {
return mIsListening;
}
bool Initialize (SOCKET_HANDLE inSocketHandle) {
mIsListening = false;
mIsConnected = true;
mSocketHandle = inSocketHandle;
LOGMESSAGE (OS::Log::kDebug, std::string ("[Socket](") + std::to_string (GetId ()) + std::string (") initialized"));
return true;
}
bool Initialize (const std::string& inAddress, const std::string& inPort) {
mIsListening = false;
mIsConnected = false;
struct addrinfo hints;
#if (defined __CYGWIN__ || defined __GNUC__)
::memset (&hints, 0, sizeof (hints));
#else
ZeroMemory (&hints, sizeof (hints));
#endif
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the server address and port
int res = getaddrinfo (inAddress.c_str (), inPort.c_str (), &hints, &mLatestAddrInfo);
if (res != 0) {
LOGMESSAGE (OS::Log::kDebug, ErrorMessage ("getaddrinfo"));
return false;
}
// Create a SOCKET for connecting to server
mSocketHandle = socket (mLatestAddrInfo->ai_family, mLatestAddrInfo->ai_socktype, mLatestAddrInfo->ai_protocol);
if (mSocketHandle == INVALID_SOCKET) {
LOGMESSAGE (OS::Log::kDebug, ErrorMessage ("socket"));
return false;
}
int flag (1);
#if (defined __CYGWIN__ || defined __GNUC__)
if (setsockopt (mSocketHandle, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char*>(&flag), sizeof(flag)) < 0) {
#else
if (setsockopt (mSocketHandle, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, reinterpret_cast<char*>(&flag), sizeof(flag)) < 0) {
#endif
LOGMESSAGE (OS::Log::kDebug, ErrorMessage ("setsocketopt"));
return false;
}
LOGMESSAGE (OS::Log::kDebug, "[Socket](" + std::to_string (GetId ()) + ") initialized at " + inAddress + ":" + inPort);
return true;
}
void Close () {
if (mIsConnected || mIsListening) {
freeaddrinfo (mLatestAddrInfo);
shutdown (mSocketHandle, 2);
#if (defined __CYGWIN__ || defined __GNUC__)
close (mSocketHandle);
#else
closesocket (mSocketHandle);
#endif
LOGMESSAGE (OS::Log::kDebug, std::string ("[Socket](") + std::to_string (GetId ()) + std::string (") closed"));
}
mIsConnected = false;
mIsListening = false;
}
bool Listen () {
if (!mIsListening) {
int result = bind (mSocketHandle, mLatestAddrInfo->ai_addr, (int) mLatestAddrInfo->ai_addrlen);
if (result == SOCKET_ERROR) {
LOGMESSAGE (OS::Log::kDebug, ErrorMessage ("bind"));
return false;
}
result = listen (mSocketHandle, SOCKET_MAX_CONNECTIONS);
if (result == SOCKET_ERROR) {
LOGMESSAGE (OS::Log::kDebug, ErrorMessage ("listen"));
return false;
}
}
mIsListening = true;
LOGMESSAGE (OS::Log::kDebug, std::string ("[Socket](") + std::to_string (GetId ()) + std::string (") listening..."));
return true;
}
bool Accept (OS::Socket& outSocket) {
if (!mIsListening) {
return false;
}
SOCKET_HANDLE clientSocket = accept (mSocketHandle, NULL, NULL);
if (clientSocket == INVALID_SOCKET) {
LOGMESSAGE (OS::Log::kDebug, ErrorMessage ("accept"));
return false;
}
outSocket.Initialize (clientSocket);
LOGMESSAGE (OS::Log::kDebug, std::string ("[Socket](") + std::to_string (GetId ()) + std::string (") connected to socket " + std::to_string (outSocket.GetId ())));
return true;
}
bool Connect () {
if (mIsConnected) {
return true;
}
// Connect to server.
int res = connect (mSocketHandle, mLatestAddrInfo->ai_addr, (int) mLatestAddrInfo->ai_addrlen);
if (res == SOCKET_ERROR) {
LOGMESSAGE (OS::Log::kDebug, ErrorMessage ("connect"));
return false;
}
LOGMESSAGE (OS::Log::kDebug, std::string ("[Socket](") + std::to_string (GetId ()) + std::string (") connected to server"));
mIsConnected = true;
return true;
}
unsigned GetId () const {
return static_cast<unsigned> (mSocketHandle);
}
bool Send (const OS::Buffer& inBuffer) {
if (!mIsConnected) {
return false;
}
int result = send (mSocketHandle, inBuffer.GetDataPointer (), inBuffer.GetSize (), 0);
if (result == SOCKET_ERROR) {
LOGMESSAGE (OS::Log::kDebug, ErrorMessage ("send"));
Close ();
return false;
}
LOGMESSAGE (OS::Log::kTrace, std::string ("[Socket] Send ") + std::to_string (inBuffer.GetSize ()) + std::string (" bytes to client id ") + std::to_string (mSocketHandle));
return true;
}
bool Receive (OS::Buffer& outBuffer) {
if (!mIsConnected) {
return false;
}
int result = recv (mSocketHandle, outBuffer.GetDataPointer (), outBuffer.GetMaxSize (), 0);
if (result == 0) {
LOGMESSAGE (OS::Log::kDebug, std::string ("[Socket] Received termination signal from client with id ") + std::to_string (mSocketHandle));
Close ();
return false;
}
if (result < 0) {
LOGMESSAGE (OS::Log::kDebug, ErrorMessage ("recv"));
Close ();
return false;
}
outBuffer.Resize (result);
LOGMESSAGE (OS::Log::kTrace, std::string ("[Socket] Received ") + std::to_string (result) + std::string (" bytes from client with id ") + std::to_string (mSocketHandle));
return true;
}
private:
SOCKET_HANDLE mSocketHandle;
struct addrinfo *mLatestAddrInfo;
std::atomic<bool> mIsConnected;
std::atomic<bool> mIsListening;
};
/* ------------------------------------- */
OS::Socket::Socket (const std::string& inAddress, const std::string& inPortNumber) :
mAddress (inAddress),
mPortNumber (inPortNumber),
mImpl (std::make_unique <Implementation> ())
{
}
OS::Socket::~Socket () {
}
bool OS::Socket::Initialize () {
return mImpl->Initialize (mAddress, mPortNumber);
}
bool OS::Socket::Initialize (unsigned inHandle) {
return mImpl->Initialize (inHandle);
}
void OS::Socket::Close () {
mImpl->Close ();
}
unsigned OS::Socket::GetId () {
return mImpl->GetId ();
}
bool OS::Socket::Listen () {
return mImpl->Listen ();
}
bool OS::Socket::Accept (OS::Socket& outSocket) {
return mImpl->Accept (outSocket);
}
bool OS::Socket::Connect () {
return mImpl->Connect ();
}
bool OS::Socket::Send (const Buffer& inBuffer) {
return mImpl->Send (inBuffer);
}
bool OS::Socket::Receive (Buffer& outBuffer) {
return mImpl->Receive (outBuffer);
}
bool OS::Socket::IsConnected () const {
return mImpl->IsConnected ();
}
bool OS::Socket::IsListening () const {
return mImpl->IsListening ();
}
|
#include "stdafx.h"
#include "SyntaxTree.h"
#include "CodeInfo.h"
using CodeInfo::nodeList;
using CodeInfo::cmdList;
using CodeInfo::cmdInfoList;
NodeZeroOP* TakeLastNode()
{
NodeZeroOP* last = nodeList.back();
nodeList.pop_back();
return last;
}
static char* binCommandToText[] = { "+", "-", "*", "/", "**", "%", "<", ">", "<=", ">=", "==", "!=", "<<", ">>", "&", "|", "^", "&&", "||", "^^"};
static char* unaryCommandToText[] = { "-", "-", "-", "~", "~", "!", "!" };
//////////////////////////////////////////////////////////////////////////
unsigned int indentDepth = 1;
void OutputIdent(FILE *fOut)
{
for(unsigned int i = 0; i < indentDepth; i++)
fprintf(fOut, "\t");
}
void OutputCFunctionName(FILE *fOut, FunctionInfo *funcInfo)
{
const char *namePrefix = *funcInfo->name == '$' ? "__" : "";
unsigned int nameShift = *funcInfo->name == '$' ? 1 : 0;
char fName[NULLC_MAX_VARIABLE_NAME_LENGTH];
sprintf(fName, (funcInfo->type == FunctionInfo::LOCAL || !funcInfo->visible) ? "%s%s_%d" : "%s%s", namePrefix, funcInfo->name + nameShift, CodeInfo::FindFunctionByPtr(funcInfo));
if(const char *opName = funcInfo->GetOperatorName())
{
strcpy(fName, opName);
}else{
for(unsigned int k = 0; k < funcInfo->nameLength; k++)
{
if(fName[k] == ':' || fName[k] == '$' || fName[k] == '[' || fName[k] == ']')
fName[k] = '_';
}
for(unsigned int k = 0; k < CodeInfo::classCount; k++)
{
if(CodeInfo::typeInfo[k]->nameHash == funcInfo->nameHash)
{
strcat(fName, "__");
break;
}
}
}
unsigned int length = (unsigned int)strlen(fName);
if(fName[length-1] == '$')
fName[length-1] = '_';
fprintf(fOut, "%s", fName);
}
int level = 0;
char linePrefix[256];
unsigned int prefixSize = 2;
bool preNeedChange = false;
void GoDown()
{
level++;
prefixSize -= 2;
linePrefix[prefixSize] = 0;
sprintf(linePrefix + prefixSize, " |__");
prefixSize += 5;
}
void GoDownB()
{
GoDown();
preNeedChange = true;
}
void GoUp()
{
level--;
prefixSize -= 5;
linePrefix[prefixSize] = 0;
sprintf(linePrefix + prefixSize, "__");
prefixSize += 2;
}
void DrawLine(FILE *fGraph)
{
fprintf(fGraph, "%s", linePrefix);
if(preNeedChange)
{
preNeedChange = false;
GoUp();
level++;
prefixSize -= 2;
linePrefix[prefixSize] = 0;
sprintf(linePrefix + prefixSize, " __");
prefixSize += 5;
}
}
//Functions for work with types
//This function converts a type according to result type of binary operation between types 'first' and 'second'
//For example, int * double = double, so first operand will be transformed to double
// double * int = double, no transformations
asmStackType ConvertFirstForSecond(asmStackType first, asmStackType second)
{
if(first == STYPE_INT && second == STYPE_DOUBLE)
{
cmdList.push_back(VMCmd(cmdItoD));
return second;
}
if(first == STYPE_LONG && second == STYPE_DOUBLE)
{
cmdList.push_back(VMCmd(cmdLtoD));
return second;
}
if(first == STYPE_INT && second == STYPE_LONG)
{
cmdList.push_back(VMCmd(cmdItoL));
return second;
}
return first;
}
//This functions transforms first type to second one
void ConvertFirstToSecond(asmStackType first, asmStackType second)
{
if(second == STYPE_DOUBLE)
{
if(first == STYPE_INT)
cmdList.push_back(VMCmd(cmdItoD));
else if(first == STYPE_LONG)
cmdList.push_back(VMCmd(cmdLtoD));
}else if(second == STYPE_LONG){
if(first == STYPE_INT)
cmdList.push_back(VMCmd(cmdItoL));
else if(first == STYPE_DOUBLE)
cmdList.push_back(VMCmd(cmdDtoL));
}else if(second == STYPE_INT){
if(first == STYPE_DOUBLE)
cmdList.push_back(VMCmd(cmdDtoI));
else if(first == STYPE_LONG)
cmdList.push_back(VMCmd(cmdLtoI));
}
}
TypeInfo* ChooseBinaryOpResultType(TypeInfo* a, TypeInfo* b)
{
if(a->type == TypeInfo::TYPE_DOUBLE)
return a;
if(b->type == TypeInfo::TYPE_DOUBLE)
return b;
if(a->type == TypeInfo::TYPE_FLOAT)
return a;
if(b->type == TypeInfo::TYPE_FLOAT)
return b;
if(a->type == TypeInfo::TYPE_LONG)
return a;
if(b->type == TypeInfo::TYPE_LONG)
return b;
if(a->type == TypeInfo::TYPE_INT)
return a;
if(b->type == TypeInfo::TYPE_INT)
return b;
if(a->type == TypeInfo::TYPE_SHORT)
return a;
if(b->type == TypeInfo::TYPE_SHORT)
return b;
if(a->type == TypeInfo::TYPE_CHAR)
return a;
if(b->type == TypeInfo::TYPE_CHAR)
return b;
assert(false);
return NULL;
}
// class implementation
//////////////////////////////////////////////////////////////////////////
// Node that doesn't have any child nodes
ChunkedStackPool<4092> NodeZeroOP::nodePool;
NodeZeroOP::NodeZeroOP()
{
typeInfo = typeVoid;
sourcePos = NULL;
prev = next = head = NULL;
nodeType = typeNodeZeroOp;
}
NodeZeroOP::NodeZeroOP(TypeInfo* tinfo)
{
typeInfo = tinfo;
sourcePos = NULL;
prev = next = head = NULL;
nodeType = typeNodeZeroOp;
}
NodeZeroOP::~NodeZeroOP()
{
}
void NodeZeroOP::Compile()
{
}
void NodeZeroOP::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s ZeroOp\r\n", typeInfo->GetFullTypeName());
}
void NodeZeroOP::TranslateToC(FILE *fOut)
{
OutputIdent(fOut);
fprintf(fOut, "/* node translation unknown */\r\n");
}
void NodeZeroOP::SetCodeInfo(const char* newSourcePos)
{
sourcePos = newSourcePos;
}
void NodeZeroOP::AddExtraNode()
{
assert(nodeList.size() > 0);
nodeList.back()->next = head;
if(head)
head->prev = nodeList.back();
head = TakeLastNode();
}
void NodeZeroOP::CompileExtra()
{
NodeZeroOP *curr = head;
while(curr)
{
curr->Compile();
curr = curr->next;
}
}
void NodeZeroOP::LogToStreamExtra(FILE *fGraph)
{
NodeZeroOP *curr = head;
while(curr)
{
curr->LogToStream(fGraph);
curr = curr->next;
}
}
void NodeZeroOP::TranslateToCExtra(FILE *fOut)
{
NodeZeroOP *curr = head;
while(curr)
{
curr->TranslateToC(fOut);
curr = curr->next;
}
}
//////////////////////////////////////////////////////////////////////////
// Node that have one child node
NodeOneOP::NodeOneOP()
{
first = NULL;
nodeType = typeNodeOneOp;
}
NodeOneOP::~NodeOneOP()
{
}
void NodeOneOP::Compile()
{
CompileExtra();
first->Compile();
}
void NodeOneOP::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s OneOP :\r\n", typeInfo->GetFullTypeName());
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
}
void NodeOneOP::TranslateToC(FILE *fOut)
{
first->TranslateToC(fOut);
}
//////////////////////////////////////////////////////////////////////////
// Node that have two child nodes
NodeTwoOP::NodeTwoOP()
{
second = NULL;
nodeType = typeNodeTwoOp;
}
NodeTwoOP::~NodeTwoOP()
{
}
void NodeTwoOP::Compile()
{
CompileExtra();
NodeOneOP::Compile();
second->Compile();
}
void NodeTwoOP::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s TwoOp :\r\n", typeInfo->GetFullTypeName());
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
second->LogToStream(fGraph);
GoUp();
}
//////////////////////////////////////////////////////////////////////////
// Node that have three child nodes
NodeThreeOP::NodeThreeOP()
{
third = NULL;
nodeType = typeNodeThreeOp;
}
NodeThreeOP::~NodeThreeOP()
{
}
void NodeThreeOP::Compile()
{
CompileExtra();
NodeTwoOP::Compile();
third->Compile();
}
void NodeThreeOP::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s ThreeOp :\r\n", typeInfo->GetFullTypeName());
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
second->LogToStream(fGraph);
third->LogToStream(fGraph);
GoUp();
}
//////////////////////////////////////////////////////////////////////////
// Node that puts a number on top of the stack
void NodeNumber::Compile()
{
assert(typeInfo->size <= 8);
if(typeInfo->stackType != STYPE_INT)
cmdList.push_back(VMCmd(cmdPushImmt, num.quad.high));
cmdList.push_back(VMCmd(cmdPushImmt, num.quad.low));
}
void NodeNumber::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s Number\r\n", typeInfo->GetFullTypeName());
}
void NodeNumber::TranslateToC(FILE *fOut)
{
if(typeInfo->refLevel)
fprintf(fOut, "(void*)(%d)", num.integer);
else if(typeInfo == typeChar || typeInfo == typeShort || typeInfo == typeInt)
fprintf(fOut, "%d", num.integer);
else if(typeInfo == typeDouble)
fprintf(fOut, "%f", num.real);
else if(typeInfo == typeFloat)
fprintf(fOut, "%ff", num.real);
else if(typeInfo == typeLong)
fprintf(fOut, "%I64dLL", num.integer64);
else
fprintf(fOut, "%%unknown_number%%");
}
bool NodeNumber::ConvertTo(TypeInfo *target)
{
if(target == typeInt)
{
num.integer = GetInteger();
}else if(target == typeDouble || target == typeFloat){
num.real = GetDouble();
}else if(target == typeLong){
num.integer64 = GetLong();
}else{
return false;
}
typeInfo = target;
return true;
}
//////////////////////////////////////////////////////////////////////////
// Node that removes value left on top of the stack by child node
NodePopOp::NodePopOp()
{
first = TakeLastNode();
nodeType = typeNodePopOp;
}
NodePopOp::~NodePopOp()
{
}
void NodePopOp::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
// Child node computes value
first->Compile();
if(first->typeInfo != typeVoid && first->typeInfo->size)
{
// Removing it from top of the stack
cmdList.push_back(VMCmd(cmdPop, first->typeInfo->type == TypeInfo::TYPE_COMPLEX ? first->typeInfo->size : stackTypeSize[first->typeInfo->stackType]));
}
}
void NodePopOp::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s PopOp :\r\n", typeInfo->GetFullTypeName());
GoDownB();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
}
void NodePopOp::TranslateToC(FILE *fOut)
{
OutputIdent(fOut);
first->TranslateToC(fOut);
fprintf(fOut, ";\r\n");
}
//////////////////////////////////////////////////////////////////////////
// Node that applies selected operation on value on top of the stack
NodeUnaryOp::NodeUnaryOp(CmdID cmd)
{
// Unary operation
cmdID = cmd;
first = TakeLastNode();
// Resulting type is the same as source type with exception for logical NOT
bool logicalOp = cmd == cmdLogNot;
typeInfo = logicalOp ? typeInt : first->typeInfo;
if((first->typeInfo->refLevel != 0 && !logicalOp) || (first->typeInfo->type == TypeInfo::TYPE_COMPLEX && first->typeInfo != typeObject))
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: unary operation '%s' is not supported on '%s'", unaryCommandToText[cmdID - cmdNeg], first->typeInfo->GetFullTypeName());
nodeType = typeNodeUnaryOp;
}
NodeUnaryOp::~NodeUnaryOp()
{
}
void NodeUnaryOp::Compile()
{
CompileExtra();
asmOperType aOT = operTypeForStackType[first->typeInfo->stackType];
// Child node computes value
first->Compile();
if(first->typeInfo == typeObject)
cmdList.push_back(VMCmd(cmdPop, 4));
// Execute command
if(aOT == OTYPE_INT || first->typeInfo == typeObject)
cmdList.push_back(VMCmd((InstructionCode)cmdID));
else if(aOT == OTYPE_LONG)
cmdList.push_back(VMCmd((InstructionCode)(cmdID + 1)));
else
cmdList.push_back(VMCmd((InstructionCode)(cmdID + 2)));
}
void NodeUnaryOp::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s UnaryOp :\r\n", typeInfo->GetFullTypeName());
GoDownB();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
}
void NodeUnaryOp::TranslateToC(FILE *fOut)
{
switch(cmdID)
{
case cmdNeg:
fprintf(fOut, "-");
break;
case cmdBitNot:
fprintf(fOut, "~");
break;
case cmdLogNot:
fprintf(fOut, "!");
break;
default:
fprintf(fOut, "%%unknown_unary_command%%");
}
first->TranslateToC(fOut);
}
//////////////////////////////////////////////////////////////////////////
// Node that returns from function or program
NodeReturnOp::NodeReturnOp(bool localRet, TypeInfo* tinfo, FunctionInfo* parentFunc)
{
localReturn = localRet;
parentFunction = parentFunc;
// Result type is set from outside
typeInfo = tinfo;
first = TakeLastNode();
if(first->nodeType == typeNodeNumber && first->typeInfo != typeInfo)
((NodeNumber*)first)->ConvertTo(typeInfo);
nodeType = typeNodeReturnOp;
}
NodeReturnOp::~NodeReturnOp()
{
}
void NodeReturnOp::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
// Compute value that we're going to return
first->Compile();
// Convert it to the return type of the function
if(typeInfo)
ConvertFirstToSecond(first->typeInfo->stackType, typeInfo->stackType);
// Return from function or program
TypeInfo *retType = typeInfo ? typeInfo : first->typeInfo;
asmOperType operType = operTypeForStackType[retType->stackType];
unsigned int retSize = retType == typeFloat ? 8 : retType->size;
if(retSize != 0 && retSize < 4)
retSize = 4;
if(parentFunction && parentFunction->closeUpvals)
cmdList.push_back(VMCmd(cmdCloseUpvals, (unsigned short)CodeInfo::FindFunctionByPtr(parentFunction), 0));
cmdList.push_back(VMCmd(cmdReturn, (unsigned char)operType, (unsigned short)localReturn, retSize));
}
void NodeReturnOp::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
if(typeInfo)
fprintf(fGraph, "%s ReturnOp :\r\n", typeInfo->GetFullTypeName());
else
fprintf(fGraph, "%s ReturnOp :\r\n", first->typeInfo->GetFullTypeName());
GoDownB();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
}
void NodeReturnOp::TranslateToC(FILE *fOut)
{
static unsigned int retVarID = 0;
TranslateToCExtra(fOut);
if(parentFunction && parentFunction->closeUpvals)
{
OutputIdent(fOut);
typeInfo->OutputCType(fOut, "");
fprintf(fOut, "__nullcRetVar%d = ", retVarID);
if(typeInfo != first->typeInfo)
{
fprintf(fOut, "(");
typeInfo->OutputCType(fOut, "");
fprintf(fOut, ")(");
}
first->TranslateToC(fOut);
if(typeInfo != first->typeInfo)
fprintf(fOut, ")");
fprintf(fOut, ";\r\n");
char name[NULLC_MAX_VARIABLE_NAME_LENGTH];
// Glue together parameter list, extra parameter and local list. Every list could be empty.
VariableInfo *curr = parentFunction->firstParam ? parentFunction->firstParam : (parentFunction->firstLocal ? parentFunction->firstLocal : parentFunction->extraParam);
if(parentFunction->firstParam)
parentFunction->lastParam->next = (parentFunction->firstLocal ? parentFunction->firstLocal : parentFunction->extraParam);
if(parentFunction->firstLocal)
parentFunction->lastLocal->next = parentFunction->extraParam;
unsigned int hashThis = GetStringHash("this");
for(; curr; curr = curr->next)
{
if(curr->usedAsExternal)
{
const char *namePrefix = *curr->name.begin == '$' ? "__" : "";
unsigned int nameShift = *curr->name.begin == '$' ? 1 : 0;
sprintf(name, "%s%.*s_%d", namePrefix, curr->name.end - curr->name.begin-nameShift, curr->name.begin+nameShift, curr->pos);
OutputIdent(fOut);
if(curr->nameHash == hashThis)
fprintf(fOut, "__nullcCloseUpvalue(__upvalue_%d___context, &__context);\r\n", CodeInfo::FindFunctionByPtr(curr->parentFunction));
else
fprintf(fOut, "__nullcCloseUpvalue(__upvalue_%d_%s, &%s);\r\n", CodeInfo::FindFunctionByPtr(curr->parentFunction), name, name);
}
}
if(parentFunction->firstParam)
parentFunction->lastParam->next = NULL;
if(parentFunction->firstLocal)
parentFunction->lastLocal->next = NULL;
OutputIdent(fOut);
fprintf(fOut, "return __nullcRetVar%d;\r\n", retVarID++);
return;
}
OutputIdent(fOut);
if(typeInfo == typeVoid || first->typeInfo == typeVoid)
{
fprintf(fOut, "return;\r\n");
}else{
fprintf(fOut, "return ");
if(typeInfo != first->typeInfo)
{
fprintf(fOut, "(");
typeInfo->OutputCType(fOut, "");
fprintf(fOut, ")(");
}
first->TranslateToC(fOut);
if(typeInfo != first->typeInfo)
fprintf(fOut, ")");
fprintf(fOut, ";\r\n");
}
}
//////////////////////////////////////////////////////////////////////////
NodeBlock::NodeBlock(FunctionInfo* parentFunc, unsigned int shift)
{
parentFunction = parentFunc;
stackFrameShift = shift;
first = TakeLastNode();
nodeType = typeNodeBlockOp;
}
NodeBlock::~NodeBlock()
{
}
void NodeBlock::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
// Compute value that we're going to return
first->Compile();
if(parentFunction->closeUpvals)
cmdList.push_back(VMCmd(cmdCloseUpvals, (unsigned short)CodeInfo::FindFunctionByPtr(parentFunction), stackFrameShift));
}
void NodeBlock::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s BlockOp (close upvalues from offset %d of function %s) %s:\r\n", first->typeInfo->GetFullTypeName(), stackFrameShift, parentFunction->name, parentFunction->closeUpvals ? "yes" : "no");
GoDownB();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
}
void NodeBlock::TranslateToC(FILE *fOut)
{
first->TranslateToC(fOut);
char name[NULLC_MAX_VARIABLE_NAME_LENGTH];
// Glue together parameter list, extra parameter and local list. Every list could be empty.
VariableInfo *curr = parentFunction->firstParam ? parentFunction->firstParam : (parentFunction->firstLocal ? parentFunction->firstLocal : parentFunction->extraParam);
if(parentFunction->firstParam)
parentFunction->lastParam->next = (parentFunction->firstLocal ? parentFunction->firstLocal : parentFunction->extraParam);
if(parentFunction->firstLocal)
parentFunction->lastLocal->next = parentFunction->extraParam;
unsigned int hashThis = GetStringHash("this");
for(; curr; curr = curr->next)
{
if(curr->usedAsExternal)
{
const char *namePrefix = *curr->name.begin == '$' ? "__" : "";
unsigned int nameShift = *curr->name.begin == '$' ? 1 : 0;
sprintf(name, "%s%.*s_%d", namePrefix, curr->name.end - curr->name.begin-nameShift, curr->name.begin+nameShift, curr->pos);
OutputIdent(fOut);
if(curr->nameHash == hashThis)
fprintf(fOut, "__nullcCloseUpvalue(__upvalue_%d___context, &__context);\r\n", CodeInfo::FindFunctionByPtr(curr->parentFunction));
else
fprintf(fOut, "__nullcCloseUpvalue(__upvalue_%d_%s, &%s);\r\n", CodeInfo::FindFunctionByPtr(curr->parentFunction), name, name);
}
}
if(parentFunction->firstParam)
parentFunction->lastParam->next = NULL;
if(parentFunction->firstLocal)
parentFunction->lastLocal->next = NULL;
}
//////////////////////////////////////////////////////////////////////////
// Nodes that compiles function
NodeFuncDef::NodeFuncDef(FunctionInfo *info, unsigned int varShift)
{
// Function description
funcInfo = info;
// Size of all local variables
shift = varShift;
disabled = false;
first = TakeLastNode();
nodeType = typeNodeFuncDef;
}
NodeFuncDef::~NodeFuncDef()
{
}
void NodeFuncDef::Enable()
{
disabled = false;
}
void NodeFuncDef::Disable()
{
disabled = true;
}
void NodeFuncDef::Compile()
{
if(disabled)
{
CompileExtra();
return;
}
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
funcInfo->address = cmdList.size();
assert(funcInfo->allParamSize + 4 < 65536);
// Save previous stack frame, and expand current by shift bytes
cmdList.push_back(VMCmd(cmdPushVTop, (unsigned short)(funcInfo->allParamSize + 4), shift));
// Generate function code
first->Compile();
if(funcInfo->retType == typeVoid)
{
// If function returns void, this is implicit return
cmdList.push_back(VMCmd(cmdReturn, 0, 1, 0));
}else{
// Stop program execution if user forgot the return statement
cmdList.push_back(VMCmd(cmdReturn, bitRetError, 1, 0));
}
funcInfo->codeSize = cmdList.size() - funcInfo->address;
}
void NodeFuncDef::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s FuncDef %s %s\r\n", typeInfo->GetFullTypeName(), funcInfo->name, (disabled ? " disabled" : ""));
if(!disabled)
{
GoDownB();
first->LogToStream(fGraph);
GoUp();
}else{
GoDownB();
LogToStreamExtra(fGraph);
GoUp();
}
}
void NodeFuncDef::TranslateToC(FILE *fOut)
{
unsigned int oldIndent = indentDepth;
indentDepth = 0;
if(!disabled)
{
funcInfo->retType->OutputCType(fOut, " ");
OutputCFunctionName(fOut, funcInfo);
fprintf(fOut, "(");
char name[NULLC_MAX_VARIABLE_NAME_LENGTH];
VariableInfo *param = funcInfo->firstParam;
for(; param; param = param->next)
{
sprintf(name, "%.*s_%d", param->name.end - param->name.begin, param->name.begin, param->pos);
param->varType->OutputCType(fOut, name);
fprintf(fOut, ", ");
}
if(funcInfo->type == FunctionInfo::THISCALL)
{
funcInfo->parentClass->OutputCType(fOut, "* __context");
}else if(funcInfo->type == FunctionInfo::LOCAL){
fprintf(fOut, "void* __");
OutputCFunctionName(fOut, funcInfo);
fprintf(fOut, "_ext_%d", funcInfo->allParamSize);
}else{
fprintf(fOut, "void* unused");
}
fprintf(fOut, ")\r\n{\r\n");
indentDepth++;
VariableInfo *local = funcInfo->firstLocal;
for(; local; local = local->next)
{
OutputIdent(fOut);
const char *namePrefix = *local->name.begin == '$' ? "__" : "";
unsigned int nameShift = *local->name.begin == '$' ? 1 : 0;
unsigned int length = sprintf(name, "%s%.*s_%d", namePrefix, local->name.end - local->name.begin-nameShift, local->name.begin+nameShift, local->pos);
for(unsigned int k = 0; k < length; k++)
{
if(name[k] == ':' || name[k] == '$')
name[k] = '_';
}
local->varType->OutputCType(fOut, name);
fprintf(fOut, ";\r\n");
}
first->TranslateToC(fOut);
indentDepth--;
fprintf(fOut, "}\r\n");
}else{
indentDepth++;
TranslateToCExtra(fOut);
indentDepth--;
}
indentDepth = oldIndent;
}
//////////////////////////////////////////////////////////////////////////
// Node that calls function
NodeFuncCall::NodeFuncCall(FunctionInfo *info, FunctionType *type)
{
// Function description
funcInfo = info;
// Function type description
funcType = type;
// Result type is fetched from function type
typeInfo = funcType->retType;
if(funcInfo && funcInfo->type == FunctionInfo::LOCAL)
first = TakeLastNode();
if(!funcInfo)
first = TakeLastNode();
if(funcType->paramCount > 0)
{
paramHead = paramTail = TakeLastNode();
if(paramHead->nodeType == typeNodeNumber && funcType->paramType[0] != paramHead->typeInfo)
((NodeNumber*)paramHead)->ConvertTo(funcType->paramType[0]);
}else{
paramHead = paramTail = NULL;
}
// Take nodes for all parameters
for(unsigned int i = 1; i < funcType->paramCount; i++)
{
paramTail->next = TakeLastNode();
TypeInfo *paramType = funcType->paramType[i];
if(paramTail->next->nodeType == typeNodeNumber && paramType != paramTail->next->typeInfo)
((NodeNumber*)paramTail->next)->ConvertTo(paramType);
paramTail->next->prev = paramTail;
paramTail = paramTail->next;
}
if(funcInfo && funcInfo->type == FunctionInfo::THISCALL)
first = TakeLastNode();
nodeType = typeNodeFuncCall;
}
NodeFuncCall::~NodeFuncCall()
{
}
void NodeFuncCall::Compile()
{
CompileExtra();
// Find parameter values
if(first)
first->Compile();
else if(funcInfo)
cmdList.push_back(VMCmd(cmdPushImmt, 0));
if(funcType->paramCount > 0)
{
NodeZeroOP *curr = paramHead;
TypeInfo **paramType = funcType->paramType + funcType->paramCount - 1;
do
{
if(*paramType == typeFloat && curr->nodeType == typeNodeNumber)
{
float num = (float)((NodeNumber*)curr)->GetDouble();
cmdList.push_back(VMCmd(cmdPushImmt, *(int*)&num));
}else{
// Compute parameter value
curr->Compile();
// Convert it to type that function expects
ConvertFirstToSecond(curr->typeInfo->stackType, (*paramType)->stackType);
if(*paramType == typeFloat)
cmdList.push_back(VMCmd(cmdDtoF));
}
curr = curr->next;
paramType--;
}while(curr);
}
unsigned int ID = CodeInfo::FindFunctionByPtr(funcInfo);
unsigned short helper = (unsigned short)((typeInfo->type == TypeInfo::TYPE_COMPLEX || typeInfo->type == TypeInfo::TYPE_VOID) ? typeInfo->size : (bitRetSimple | operTypeForStackType[typeInfo->stackType]));
if(funcInfo)
cmdList.push_back(VMCmd(cmdCall, helper, ID));
else
cmdList.push_back(VMCmd(cmdCallPtr, helper, funcType->paramSize));
}
void NodeFuncCall::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s FuncCall '%s' %d\r\n", typeInfo->GetFullTypeName(), (funcInfo ? funcInfo->name : "$ptr"), funcType->paramCount);
GoDown();
LogToStreamExtra(fGraph);
if(first)
first->LogToStream(fGraph);
NodeZeroOP *curr = paramTail;
while(curr)
{
if(curr == paramHead)
{
GoUp();
GoDownB();
}
curr->LogToStream(fGraph);
curr = curr->prev;
}
GoUp();
}
void NodeFuncCall::TranslateToC(FILE *fOut)
{
TranslateToCExtra(fOut);
if(funcInfo)
OutputCFunctionName(fOut, funcInfo);
if(!funcInfo)
{
fprintf(fOut, "((");
funcType->retType->OutputCType(fOut, "");
fprintf(fOut, "(*)(");
NodeZeroOP *curr = paramTail;
TypeInfo **paramType = funcType->paramType;
while(curr)
{
(*paramType)->OutputCType(fOut, "");
fprintf(fOut, ", ");
curr = curr->prev;
paramType++;
}
fprintf(fOut, "void*))");
fprintf(fOut, "(");
first->TranslateToC(fOut);
fprintf(fOut, ").ptr)");
}
fprintf(fOut, "(");
NodeZeroOP *curr = paramTail;
TypeInfo **paramType = funcType->paramType;
while(curr)
{
if(*paramType != curr->typeInfo)
{
fprintf(fOut, "(");
(*paramType)->OutputCType(fOut, "");
fprintf(fOut, ")(");
}
curr->TranslateToC(fOut);
if(*paramType != curr->typeInfo)
fprintf(fOut, ")");
fprintf(fOut, ", ");
curr = curr->prev;
paramType++;
}
if(!funcInfo)
fprintf(fOut, "(");
if(first)
first->TranslateToC(fOut);
else if(funcInfo)
fprintf(fOut, "(void*)0");
if(!funcInfo)
fprintf(fOut, ").context");
fprintf(fOut, ")");
}
//////////////////////////////////////////////////////////////////////////
// Node that fetches variable value
NodeGetAddress::NodeGetAddress(VariableInfo* vInfo, int vAddress, bool absAddr, TypeInfo *retInfo)
{
assert(retInfo);
varInfo = vInfo;
addressOriginal = varAddress = vAddress;
absAddress = absAddr;
typeOrig = retInfo;
typeInfo = CodeInfo::GetReferenceType(typeOrig);
nodeType = typeNodeGetAddress;
}
NodeGetAddress::~NodeGetAddress()
{
}
bool NodeGetAddress::IsAbsoluteAddress()
{
return absAddress;
}
void NodeGetAddress::IndexArray(int shift)
{
assert(typeOrig->arrLevel != 0);
varAddress += typeOrig->subType->size * shift;
typeOrig = typeOrig->subType;
typeInfo = CodeInfo::GetReferenceType(typeOrig);
}
void NodeGetAddress::ShiftToMember(TypeInfo::MemberVariable *member)
{
assert(member);
varAddress += member->offset;
typeOrig = member->type;
typeInfo = CodeInfo::GetReferenceType(typeOrig);
}
void NodeGetAddress::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
cmdList.push_back(VMCmd(cmdGetAddr, absAddress ? 0 : 1, varAddress));
}
void NodeGetAddress::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s GetAddress ", typeInfo->GetFullTypeName());
if(varInfo)
fprintf(fGraph, "%s '%.*s'", varInfo->varType->GetFullTypeName(), varInfo->name.end-varInfo->name.begin, varInfo->name.begin);
else
fprintf(fGraph, "$$$");
fprintf(fGraph, " (%d %s)\r\n", (int)varAddress, (absAddress ? " absolute" : " relative"));
LogToStreamExtra(fGraph);
}
void NodeGetAddress::TranslateToC(FILE *fOut)
{
if(head)
fprintf(fOut, "(");
NodeZeroOP *curr = head;
while(curr)
{
assert(curr->nodeType == typeNodePopOp);
((NodePopOp*)curr)->GetFirstNode()->TranslateToC(fOut);
fprintf(fOut, ", ");
curr = curr->next;
}
TranslateToCEx(fOut, true);
if(head)
fprintf(fOut, ")");
}
void NodeGetAddress::TranslateToCEx(FILE *fOut, bool takeAddress)
{
if(takeAddress)
fprintf(fOut, "&");
if(varInfo && varInfo->nameHash != GetStringHash("this"))
{
const char *namePrefix = *varInfo->name.begin == '$' ? "__" : "";
unsigned int nameShift = *varInfo->name.begin == '$' ? 1 : 0;
fprintf(fOut, varAddress - addressOriginal ? "%s%.*s%+d" : "%s%.*s", namePrefix, varInfo->name.end-varInfo->name.begin-nameShift, varInfo->name.begin+nameShift, (varAddress - addressOriginal) / (typeOrig->size ? typeOrig->size : 1));
if(varInfo->blockDepth > 1)
fprintf(fOut, "_%d", varInfo->pos);
}else{
fprintf(fOut, "__context");
}
}
//////////////////////////////////////////////////////////////////////////
NodeGetUpvalue::NodeGetUpvalue(FunctionInfo* functionInfo, int closureOffset, int closureElement, TypeInfo *retInfo)
{
closurePos = closureOffset;
closureElem = closureElement;
typeInfo = retInfo;
parentFunc = functionInfo;
nodeType = typeNodeGetUpvalue;
}
NodeGetUpvalue::~NodeGetUpvalue()
{
}
void NodeGetUpvalue::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
cmdList.push_back(VMCmd(cmdPushInt, ADDRESS_RELATIVE, (unsigned short)typeInfo->size, closurePos));
cmdList.push_back(VMCmd(cmdPushIntStk, 0, (unsigned short)typeInfo->size, closureElem));
}
void NodeGetUpvalue::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s GetUpvalue (base + %d)[%d]\r\n", typeInfo->GetFullTypeName(), closurePos, closureElem);
LogToStreamExtra(fGraph);
}
void NodeGetUpvalue::TranslateToC(FILE *fOut)
{
fprintf(fOut, "(");
typeInfo->OutputCType(fOut, "");
fprintf(fOut, ")");
fprintf(fOut, "((__nullcUpvalue*)((char*)__");
OutputCFunctionName(fOut, parentFunc);
fprintf(fOut, "_ext_%d + %d))->ptr", closurePos, closureElem);
}
//////////////////////////////////////////////////////////////////////////
NodeConvertPtr::NodeConvertPtr(TypeInfo *dstType)
{
assert(dstType);
typeInfo = dstType;
first = TakeLastNode();
nodeType = typeNodeConvertPtr;
}
NodeConvertPtr::~NodeConvertPtr()
{
}
void NodeConvertPtr::Compile()
{
CompileExtra();
first->Compile();
if(typeInfo == typeObject || typeInfo == typeTypeid)
{
cmdList.push_back(VMCmd(cmdPushTypeID, first->typeInfo->subType->typeIndex));
}else{
cmdList.push_back(VMCmd(cmdConvertPtr, typeInfo->subType->typeIndex));
}
}
void NodeConvertPtr::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s ConvertPtr :\r\n", typeInfo->GetFullTypeName());
GoDownB();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
}
void NodeConvertPtr::TranslateToC(FILE *fOut)
{
TranslateToCExtra(fOut);
if(typeInfo == typeObject || typeInfo == typeTypeid)
{
fprintf(fOut, "__nullcMakeAutoRef((void*)");
first->TranslateToC(fOut);
fprintf(fOut, ", %d)", first->typeInfo->subType->typeIndex);
}else{
fprintf(fOut, "(");
typeInfo->OutputCType(fOut, "");
fprintf(fOut, ")");
fprintf(fOut, "__nullcGetAutoRef(");
first->TranslateToC(fOut);
fprintf(fOut, ", %d)", typeInfo->subType->typeIndex);
}
}
//////////////////////////////////////////////////////////////////////////
// Node that sets value to the variable
NodeVariableSet::NodeVariableSet(TypeInfo* targetType, bool firstDefinition, bool swapNodes)
{
assert(targetType);
typeInfo = targetType->subType;
if(swapNodes)
second = TakeLastNode();
// Address of the target variable
first = TakeLastNode();
assert(first->typeInfo->refLevel != 0);
if(!swapNodes)
second = TakeLastNode();
if(typeInfo->arrLevel < 2 && typeInfo->refLevel == 0 && second->nodeType == typeNodeNumber)
static_cast<NodeNumber*>(second)->ConvertTo(typeInfo);
// If this is the first array definition and value is array sub-type, we set it to all array elements
arrSetAll = (firstDefinition && typeInfo->arrLevel == 1 && typeInfo->arrSize != -1 && second->typeInfo->arrLevel == 0 && second->typeInfo->refLevel == 0 && typeInfo->subType->type != TypeInfo::TYPE_COMPLEX && second->typeInfo->type != TypeInfo::TYPE_COMPLEX);
if(second->typeInfo == typeVoid)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: cannot convert from void to %s", typeInfo->GetFullTypeName());
if(typeInfo == typeVoid)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: cannot convert from %s to void", second->typeInfo->GetFullTypeName());
// If types don't match
if(second->typeInfo != typeInfo)
{
// If it is not build-in basic types or if pointers point to different types
if(typeInfo->type == TypeInfo::TYPE_COMPLEX || second->typeInfo->type == TypeInfo::TYPE_COMPLEX || typeInfo->subType != second->typeInfo->subType)
{
if(!(typeInfo->arrLevel != 0 && second->typeInfo->arrLevel == 0 && arrSetAll))
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: cannot convert '%s' to '%s'", second->typeInfo->GetFullTypeName(), typeInfo->GetFullTypeName());
}
}
absAddress = true;
knownAddress = false;
addrShift = 0;
if(first->nodeType == typeNodeGetAddress)
{
absAddress = static_cast<NodeGetAddress*>(first)->IsAbsoluteAddress();
addrShift = static_cast<NodeGetAddress*>(first)->varAddress;
knownAddress = true;
}
#ifndef NULLC_ENABLE_C_TRANSLATION
if(first->nodeType == typeNodeShiftAddress)
{
addrShift = static_cast<NodeShiftAddress*>(first)->memberShift;
NodeZeroOP *oldFirst = first;
first = static_cast<NodeShiftAddress*>(first)->first;
static_cast<NodeShiftAddress*>(oldFirst)->first = NULL;
}
if(first->nodeType == typeNodeArrayIndex && static_cast<NodeArrayIndex*>(first)->knownShift)
{
addrShift = static_cast<NodeArrayIndex*>(first)->shiftValue;
NodeZeroOP *oldFirst = first;
first = static_cast<NodeArrayIndex*>(first)->first;
static_cast<NodeArrayIndex*>(oldFirst)->first = NULL;
}
#endif
if(arrSetAll)
{
elemCount = typeInfo->size / typeInfo->subType->size;
typeInfo = typeInfo->subType;
}
nodeType = typeNodeVariableSet;
}
NodeVariableSet::~NodeVariableSet()
{
}
void NodeVariableSet::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
asmStackType asmST = typeInfo->stackType;
asmDataType asmDT = typeInfo->dataType;
second->Compile();
ConvertFirstToSecond(second->typeInfo->stackType, asmST);
if(!knownAddress)
first->Compile();
if(arrSetAll)
{
assert(knownAddress);
cmdList.push_back(VMCmd(cmdPushImmt, elemCount));
cmdList.push_back(VMCmd(cmdSetRange, absAddress ? ADDRESS_ABOLUTE : ADDRESS_RELATIVE, (unsigned short)(asmDT), addrShift));
}else{
if(knownAddress)
{
cmdList.push_back(VMCmd(cmdMovType[asmDT>>2], absAddress ? ADDRESS_ABOLUTE : ADDRESS_RELATIVE, (unsigned short)typeInfo->size, addrShift));
}else{
cmdList.push_back(VMCmd(cmdMovTypeStk[asmDT>>2], asmST == STYPE_DOUBLE ? 1 : 0, (unsigned short)typeInfo->size, addrShift));
}
}
}
void NodeVariableSet::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s VariableSet %s\r\n", typeInfo->GetFullTypeName(), (arrSetAll ? "set all elements" : ""));
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
GoDownB();
second->LogToStream(fGraph);
GoUp();
}
void NodeVariableSet::TranslateToC(FILE *fOut)
{
TranslateToCExtra(fOut);
if(arrSetAll)
{
if(typeInfo == typeChar)
fprintf(fOut, "memset(*(");
else
fprintf(fOut, "__nullcSetArray(*(");
first->TranslateToC(fOut);
fprintf(fOut, ".ptr), ");
second->TranslateToC(fOut);
fprintf(fOut, ", %d)", elemCount);
}else{
if(second->nodeType == typeNodeExpressionList && second->typeInfo->subType == typeChar && second->typeInfo->arrSize != TypeInfo::UNSIZED_ARRAY)
{
fprintf(fOut, "memcpy((");
first->TranslateToC(fOut);
fprintf(fOut, ")->ptr, ");
second->TranslateToC(fOut);
fprintf(fOut, ", %d)", first->typeInfo->subType->size);
}else{
fprintf(fOut, "*(");
first->TranslateToC(fOut);
fprintf(fOut, ") = ");
if(first->typeInfo->subType != second->typeInfo || (first->typeInfo->subType->refLevel && second->nodeType == typeNodeFuncCall))
{
fprintf(fOut, "(");
first->typeInfo->subType->OutputCType(fOut, "");
fprintf(fOut, ")");
}
second->TranslateToC(fOut);
}
}
}
//////////////////////////////////////////////////////////////////////////
// Node to change variable value with following operations: += -= *= /= **=
NodeVariableModify::NodeVariableModify(TypeInfo* targetType, CmdID cmd)
{
assert(targetType);
typeInfo = targetType->subType;
cmdID = cmd;
second = TakeLastNode();
// Address of the target variable
first = TakeLastNode();
assert(first->typeInfo->refLevel != 0);
if(second->typeInfo == typeVoid)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: cannot convert from void to %s", typeInfo->GetFullTypeName());
if(typeInfo == typeVoid)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: cannot convert from %s to void", second->typeInfo->GetFullTypeName());
if(first->typeInfo->subType->refLevel != 0 || second->typeInfo->refLevel != 0 || typeInfo->type == TypeInfo::TYPE_COMPLEX || second->typeInfo->type == TypeInfo::TYPE_COMPLEX)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: there is no build-in operator for types '%s' and '%s'", typeInfo->GetFullTypeName(), second->typeInfo->GetFullTypeName());
// If types don't match
if(second->typeInfo != typeInfo)
{
// If it is not build-in basic types or if pointers point to different types
if(typeInfo->type == TypeInfo::TYPE_COMPLEX || second->typeInfo->type == TypeInfo::TYPE_COMPLEX || typeInfo->subType != second->typeInfo->subType)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: cannot convert '%s' to '%s'", second->typeInfo->GetFullTypeName(), typeInfo->GetFullTypeName());
}
absAddress = true;
knownAddress = false;
addrShift = 0;
#ifndef NULLC_ENABLE_C_TRANSLATION
if(first->nodeType == typeNodeGetAddress)
{
absAddress = static_cast<NodeGetAddress*>(first)->IsAbsoluteAddress();
addrShift = static_cast<NodeGetAddress*>(first)->varAddress;
knownAddress = true;
}
if(first->nodeType == typeNodeShiftAddress)
{
addrShift = static_cast<NodeShiftAddress*>(first)->memberShift;
NodeZeroOP *oldFirst = first;
first = static_cast<NodeShiftAddress*>(first)->first;
static_cast<NodeShiftAddress*>(oldFirst)->first = NULL;
}
if(first->nodeType == typeNodeArrayIndex && static_cast<NodeArrayIndex*>(first)->knownShift)
{
addrShift = static_cast<NodeArrayIndex*>(first)->shiftValue;
NodeZeroOP *oldFirst = first;
first = static_cast<NodeArrayIndex*>(first)->first;
static_cast<NodeArrayIndex*>(oldFirst)->first = NULL;
}
#endif
nodeType = typeNodeVariableModify;
}
NodeVariableModify::~NodeVariableModify()
{
}
void NodeVariableModify::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
asmStackType asmSTfirst = typeInfo->stackType;
asmDataType asmDT = typeInfo->dataType;
asmStackType asmSTsecond = second->typeInfo->stackType;
// Calculate address of the first operand, if it isn't known
if(!knownAddress)
first->Compile();
// Put first operand on top of the stack
if(knownAddress)
cmdList.push_back(VMCmd(cmdPushType[asmDT>>2], absAddress ? ADDRESS_ABOLUTE : ADDRESS_RELATIVE, (unsigned short)typeInfo->size, addrShift));
else
cmdList.push_back(VMCmd(cmdPushTypeStk[asmDT>>2], asmDT == DTYPE_DOUBLE ? 1 : 0, (unsigned short)typeInfo->size, addrShift));
// Convert it to the type that results from operation made between two operands.
asmStackType asmSTresult = ConvertFirstForSecond(asmSTfirst, asmSTsecond);
// Calculate second operand value
second->Compile();
// Convert it to the type that results from operation made between two operands.
ConvertFirstForSecond(asmSTsecond, asmSTresult);
// Make a binary operation of corresponding type
if(asmSTresult == STYPE_INT)
cmdList.push_back(VMCmd((InstructionCode)(cmdID)));
else if(asmSTresult == STYPE_LONG)
cmdList.push_back(VMCmd((InstructionCode)(cmdID - cmdAdd + cmdAddL)));
else if(asmSTresult == STYPE_DOUBLE)
cmdList.push_back(VMCmd((InstructionCode)(cmdID - cmdAdd + cmdAddD)));
else
assert(!"unknown operator type in NodeVariableModify");
// Convert to the type of first operand
ConvertFirstToSecond(asmSTresult, asmSTfirst);
// Calculate address of the first operand, if it isn't known
if(!knownAddress)
first->Compile();
// Put first operand on top of the stack
if(knownAddress)
{
cmdList.push_back(VMCmd(cmdMovType[asmDT>>2], absAddress ? ADDRESS_ABOLUTE : ADDRESS_RELATIVE, (unsigned short)typeInfo->size, addrShift));
}else{
cmdList.push_back(VMCmd(cmdMovTypeStk[asmDT>>2], asmDT == DTYPE_DOUBLE ? 1 : 0, (unsigned short)typeInfo->size, addrShift));
}
}
void NodeVariableModify::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s VariableModify\r\n", typeInfo->GetFullTypeName());
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
GoDownB();
second->LogToStream(fGraph);
GoUp();
}
void NodeVariableModify::TranslateToC(FILE *fOut)
{
TranslateToCExtra(fOut);
if(cmdID == cmdPow)
{
fprintf(fOut, "__nullcPowSet(");
first->TranslateToC(fOut);
fprintf(fOut, ", ");
second->TranslateToC(fOut);
fprintf(fOut, ")");
}else{
const char *operation = "???";
switch(cmdID)
{
case cmdAdd:
operation = "+=";
break;
case cmdSub:
operation = "-=";
break;
case cmdMul:
operation = "*=";
break;
case cmdDiv:
operation = "/=";
break;
}
fprintf(fOut, "*(");
first->TranslateToC(fOut);
fprintf(fOut, ") %s ", operation);
second->TranslateToC(fOut);
}
}
//////////////////////////////////////////////////////////////////////////
// Node that calculates address of the array element
NodeArrayIndex::NodeArrayIndex(TypeInfo* parentType)
{
assert(parentType);
typeParent = parentType;
typeInfo = CodeInfo::GetReferenceType(parentType->subType);
// Node that calculates array index
second = TakeLastNode();
if(second->typeInfo->type == TypeInfo::TYPE_COMPLEX || second->typeInfo->type == TypeInfo::TYPE_VOID)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: cannot index array with type '%s'", second->typeInfo->GetFullTypeName());
// Node that calculates address of the first array element
first = TakeLastNode();
shiftValue = 0;
knownShift = false;
if(second->nodeType == typeNodeNumber && typeParent->arrSize != TypeInfo::UNSIZED_ARRAY)
{
shiftValue = typeParent->subType->size * static_cast<NodeNumber*>(second)->GetInteger();
knownShift = true;
}
if(!knownShift && typeParent->subType->size > 65535)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: cannot index array when sizeof(%s) exceeds 65535 bytes", typeParent->subType->GetFullTypeName());
nodeType = typeNodeArrayIndex;
}
NodeArrayIndex::~NodeArrayIndex()
{
}
void NodeArrayIndex::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
// Get address of the first array element
first->Compile();
if(knownShift)
{
cmdList.push_back(VMCmd(cmdPushImmt, shiftValue));
// Add it to the address of the first element
cmdList.push_back(VMCmd(cmdAdd));
}else{
// Compute index value
second->Compile();
// Convert it to integer and multiply by the size of the element
if(second->typeInfo->stackType != STYPE_INT)
cmdList.push_back(VMCmd(second->typeInfo->stackType == STYPE_DOUBLE ? cmdDtoI : cmdLtoI));
cmdList.push_back(VMCmd(typeParent->arrSize == TypeInfo::UNSIZED_ARRAY ? cmdIndexStk : cmdIndex, (unsigned short)typeParent->subType->size, typeParent->arrSize));
}
}
void NodeArrayIndex::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s ArrayIndex %s known: %d shiftval: %d\r\n", typeInfo->GetFullTypeName(), typeParent->GetFullTypeName(), knownShift, shiftValue);
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
GoDownB();
second->LogToStream(fGraph);
GoUp();
}
void NodeArrayIndex::TranslateToC(FILE *fOut)
{
if(first->typeInfo->arrSize == TypeInfo::UNSIZED_ARRAY)
{
fprintf(fOut, "(");
fprintf(fOut, "(");
typeInfo->OutputCType(fOut, "");
fprintf(fOut, ")(");
first->TranslateToC(fOut);
fprintf(fOut, ").ptr + ");
if(second->typeInfo != typeInt)
fprintf(fOut, "(unsigned)(");
second->TranslateToC(fOut);
if(second->typeInfo != typeInt)
fprintf(fOut, ")");
fprintf(fOut, ")");
}else{
fprintf(fOut, "&(");
first->TranslateToC(fOut);
fprintf(fOut, ")");
fprintf(fOut, "->ptr");
fprintf(fOut, "[");
if(second->typeInfo != typeInt)
fprintf(fOut, "(unsigned)(");
second->TranslateToC(fOut);
if(second->typeInfo != typeInt)
fprintf(fOut, ")");
fprintf(fOut, "]");
}
}
//////////////////////////////////////////////////////////////////////////
// Node to get value by address (dereference pointer)
NodeDereference::NodeDereference(FunctionInfo* setClosure, unsigned int offsetToPrevClosure)
{
originalNode = first = TakeLastNode();
assert(first->typeInfo);
assert(first->typeInfo->subType);
typeInfo = first->typeInfo->subType;
absAddress = true;
knownAddress = false;
addrShift = 0;
closureFunc = setClosure;
offsetToPreviousClosure = offsetToPrevClosure;
neutralized = false;
#ifndef NULLC_ENABLE_C_TRANSLATION
if(first->nodeType == typeNodeGetAddress)
{
absAddress = static_cast<NodeGetAddress*>(first)->IsAbsoluteAddress();
addrShift = static_cast<NodeGetAddress*>(first)->varAddress;
knownAddress = true;
}
if(first->nodeType == typeNodeShiftAddress)
{
addrShift = static_cast<NodeShiftAddress*>(first)->memberShift;
NodeZeroOP *oldFirst = first;
first = static_cast<NodeShiftAddress*>(first)->first;
static_cast<NodeShiftAddress*>(oldFirst)->first = NULL;
}
if(first->nodeType == typeNodeArrayIndex && static_cast<NodeArrayIndex*>(first)->knownShift)
{
addrShift = static_cast<NodeArrayIndex*>(first)->shiftValue;
NodeZeroOP *oldFirst = first;
first = static_cast<NodeArrayIndex*>(first)->first;
static_cast<NodeArrayIndex*>(oldFirst)->first = NULL;
}
#endif
nodeType = typeNodeDereference;
}
NodeDereference::~NodeDereference()
{
}
void NodeDereference::Neutralize()
{
neutralized = true;
typeInfo = originalNode->typeInfo;
}
void NodeDereference::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
if(typeInfo->size == 0)
return;
asmDataType asmDT = typeInfo->dataType;
if(neutralized)
{
originalNode->Compile();
}else{
if(closureFunc)
{
first->Compile();
cmdList.push_back(VMCmd(cmdCreateClosure, (unsigned short)offsetToPreviousClosure, CodeInfo::FindFunctionByPtr(closureFunc)));
}else{
if(!knownAddress)
first->Compile();
if(knownAddress)
cmdList.push_back(VMCmd(cmdPushType[asmDT>>2], absAddress ? ADDRESS_ABOLUTE : ADDRESS_RELATIVE, (unsigned short)typeInfo->size, addrShift));
else
cmdList.push_back(VMCmd(cmdPushTypeStk[asmDT>>2], asmDT == DTYPE_DOUBLE ? 1 : 0, (unsigned short)typeInfo->size, addrShift));
}
}
}
void NodeDereference::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s Dereference%s", typeInfo->GetFullTypeName(), closureFunc ? " and create closure" : "");
if(knownAddress)
fprintf(fGraph, " at known address [%s%d]\r\n", absAddress ? "" : "base+", addrShift);
else
fprintf(fGraph, " at [ptr+%d]\r\n", addrShift);
GoDownB();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
}
bool nodeDereferenceEndInComma = false;
void NodeDereference::TranslateToC(FILE *fOut)
{
TranslateToCExtra(fOut);
if(closureFunc)
{
OutputIdent(fOut);
assert(first->nodeType == typeNodeVariableSet);
assert(((NodeOneOP*)first)->GetFirstNode()->nodeType == typeNodeGetAddress);
VariableInfo *closure = ((NodeGetAddress*)((NodeOneOP*)first)->GetFirstNode())->varInfo;
char closureName[NULLC_MAX_VARIABLE_NAME_LENGTH];
const char *namePrefix = *closure->name.begin == '$' ? "__" : "";
unsigned int nameShift = *closure->name.begin == '$' ? 1 : 0;
unsigned int length = sprintf(closureName, "%s%.*s_%d", namePrefix, closure->name.end - closure->name.begin-nameShift, closure->name.begin+nameShift, closure->pos);
for(unsigned int k = 0; k < length; k++)
{
if(closureName[k] == ':' || closureName[k] == '$')
closureName[k] = '_';
}
fprintf(fOut, "(%s = (", closureName);
closure->varType->OutputCType(fOut, "");
fprintf(fOut, ")__newS(%d, (void*)0)),\r\n", closure->varType->subType->size);
unsigned int pos = 0;
for(FunctionInfo::ExternalInfo *curr = closureFunc->firstExternal; curr; curr = curr->next)
{
OutputIdent(fOut);
fprintf(fOut, "(%s->ptr[%d] = ", closureName, pos);
VariableInfo *varInfo = curr->variable;
char variableName[NULLC_MAX_VARIABLE_NAME_LENGTH];
if(varInfo->nameHash == GetStringHash("this"))
{
strcpy(variableName, "__context");
}else{
namePrefix = *varInfo->name.begin == '$' ? "__" : "";
nameShift = *varInfo->name.begin == '$' ? 1 : 0;
sprintf(variableName, "%s%.*s_%d", namePrefix, varInfo->name.end-varInfo->name.begin-nameShift, varInfo->name.begin+nameShift, varInfo->pos);
}
if(curr->targetLocal)
{
fprintf(fOut, "(int*)&%s", variableName);
}else{
assert(closureFunc->parentFunc);
fprintf(fOut, "((int**)__%s_%d_ext_%d)[%d]", closureFunc->parentFunc->name, CodeInfo::FindFunctionByPtr(closureFunc->parentFunc), closureFunc->parentFunc->allParamSize, curr->targetPos >> 2);
}
fprintf(fOut, "),\r\n");
OutputIdent(fOut);
fprintf(fOut, "(%s->ptr[%d] = (int*)__upvalue_%d_%s),\r\n", closureName, pos+1, CodeInfo::FindFunctionByPtr(varInfo->parentFunction), variableName);
OutputIdent(fOut);
fprintf(fOut, "(%s->ptr[%d] = (int*)%d),\r\n", closureName, pos+2, curr->variable->varType->size);
OutputIdent(fOut);
fprintf(fOut, "(__upvalue_%d_%s = (__nullcUpvalue*)&%s->ptr[%d])", CodeInfo::FindFunctionByPtr(varInfo->parentFunction), variableName, closureName, pos);
if(curr->next)
fprintf(fOut, ",\r\n");
pos += ((varInfo->varType->size >> 2) < 3 ? 3 : 1 + (varInfo->varType->size >> 2));
}
if(nodeDereferenceEndInComma)
fprintf(fOut, ",\r\n");
else
fprintf(fOut, ";\r\n");
}else{
if(!neutralized)
fprintf(fOut, "*(");
first->TranslateToC(fOut);
if(!neutralized)
fprintf(fOut, ")");
}
}
//////////////////////////////////////////////////////////////////////////
// Node that shifts address to the class member
NodeShiftAddress::NodeShiftAddress(TypeInfo::MemberVariable *classMember)
{
member = classMember;
memberShift = member->offset;
typeInfo = CodeInfo::GetReferenceType(member->type);
first = TakeLastNode();
#ifndef NULLC_ENABLE_C_TRANSLATION
if(first->nodeType == typeNodeShiftAddress)
{
memberShift += static_cast<NodeShiftAddress*>(first)->memberShift;
NodeZeroOP *oldFirst = first;
first = static_cast<NodeShiftAddress*>(first)->first;
static_cast<NodeShiftAddress*>(oldFirst)->first = NULL;
}
#endif
nodeType = typeNodeShiftAddress;
}
NodeShiftAddress::~NodeShiftAddress()
{
}
void NodeShiftAddress::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
// Get variable address
first->Compile();
if(memberShift)
{
cmdList.push_back(VMCmd(cmdPushImmt, memberShift));
// Add the shift to the address
cmdList.push_back(VMCmd(cmdAdd));
}
}
void NodeShiftAddress::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s ShiftAddress [+%d]\r\n", typeInfo->GetFullTypeName(), memberShift);
GoDownB();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
}
void NodeShiftAddress::TranslateToC(FILE *fOut)
{
fprintf(fOut, "&(", member->name);
first->TranslateToC(fOut);
fprintf(fOut, ")->%s", member->name);
}
//////////////////////////////////////////////////////////////////////////
// Node for increment and decrement operations
NodePreOrPostOp::NodePreOrPostOp(bool isInc, bool preOp)
{
first = TakeLastNode();
assert(first->typeInfo->refLevel != 0);
typeInfo = first->typeInfo->subType;
incOp = isInc;
if(typeInfo->type == TypeInfo::TYPE_COMPLEX || typeInfo->refLevel != 0)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: %s is not supported on '%s'", (isInc ? "increment" : "decrement"), typeInfo->GetFullTypeName());
prefixOp = preOp;
optimised = false;
absAddress = true;
knownAddress = false;
addrShift = 0;
#ifndef NULLC_ENABLE_C_TRANSLATION
if(first->nodeType == typeNodeGetAddress)
{
absAddress = static_cast<NodeGetAddress*>(first)->IsAbsoluteAddress();
addrShift = static_cast<NodeGetAddress*>(first)->varAddress;
knownAddress = true;
}
if(first->nodeType == typeNodeShiftAddress)
{
addrShift = static_cast<NodeShiftAddress*>(first)->memberShift;
NodeZeroOP *oldFirst = first;
first = static_cast<NodeShiftAddress*>(first)->first;
static_cast<NodeShiftAddress*>(oldFirst)->first = NULL;
}
if(first->nodeType == typeNodeArrayIndex && static_cast<NodeArrayIndex*>(first)->knownShift)
{
addrShift = static_cast<NodeArrayIndex*>(first)->shiftValue;
NodeZeroOP *oldFirst = first;
first = static_cast<NodeArrayIndex*>(first)->first;
static_cast<NodeArrayIndex*>(oldFirst)->first = NULL;
}
#endif
nodeType = typeNodePreOrPostOp;
}
NodePreOrPostOp::~NodePreOrPostOp()
{
}
void NodePreOrPostOp::SetOptimised(bool doOptimisation)
{
optimised = doOptimisation;
}
void NodePreOrPostOp::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
asmStackType asmST = typeInfo->stackType;
asmDataType asmDT = typeInfo->dataType;
asmOperType aOT = operTypeForStackType[typeInfo->stackType];
InstructionCode pushCmd = knownAddress ? cmdPushType[asmDT>>2] : cmdPushTypeStk[asmDT>>2];
InstructionCode movCmd = knownAddress ? cmdMovType[asmDT>>2] : cmdMovTypeStk[asmDT>>2];
if(!knownAddress)
first->Compile();
cmdList.push_back(VMCmd(pushCmd, absAddress ? ADDRESS_ABOLUTE : ADDRESS_RELATIVE, (unsigned short)typeInfo->size, addrShift));
cmdList.push_back(VMCmd(incOp ? cmdIncType[aOT] : cmdDecType[aOT]));
if(!knownAddress)
first->Compile();
cmdList.push_back(VMCmd(movCmd, absAddress ? ADDRESS_ABOLUTE : ADDRESS_RELATIVE, (unsigned short)typeInfo->size, addrShift));
if(!prefixOp && !optimised)
cmdList.push_back(VMCmd(!incOp ? cmdIncType[aOT] : cmdDecType[aOT]));
if(optimised)
cmdList.push_back(VMCmd(cmdPop, stackTypeSize[asmST]));
}
void NodePreOrPostOp::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s PreOrPostOp %s\r\n", typeInfo->GetFullTypeName(), (prefixOp ? "prefix" : "postfix"));
GoDownB();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
}
void NodePreOrPostOp::TranslateToC(FILE *fOut)
{
if(head)
fprintf(fOut, "(");
NodeZeroOP *curr = head;
while(curr)
{
assert(curr->nodeType == typeNodePopOp);
((NodePopOp*)curr)->GetFirstNode()->TranslateToC(fOut);
fprintf(fOut, ", ");
curr = curr->next;
}
if(typeInfo == typeDouble || typeInfo == typeFloat)
{
if(optimised)
{
OutputIdent(fOut);
fprintf(fOut, "*(");
first->TranslateToC(fOut);
fprintf(fOut, incOp ? ") += 1.0" : ") -= 1.0");
}else{
if(prefixOp)
{
fprintf(fOut, "(*(");
first->TranslateToC(fOut);
fprintf(fOut, incOp ? ") += 1.0)" : ") -= 1.0)");
}else{
fprintf(fOut, "((*(");
first->TranslateToC(fOut);
fprintf(fOut, incOp ? ") += 1.0) - 1.0)" : ") -= 1.0) + 1.0)");
}
}
}else{
if(optimised)
OutputIdent(fOut);
if(prefixOp)
fprintf(fOut, incOp ? "++" : "--");
fprintf(fOut, "(*(");
first->TranslateToC(fOut);
fprintf(fOut, "))");
if(!prefixOp)
fprintf(fOut, incOp ? "++" : "--");
}
if(head)
fprintf(fOut, ")");
if(optimised)
fprintf(fOut, ";\r\n");
}
//////////////////////////////////////////////////////////////////////////
// Node that gets function address
NodeFunctionAddress::NodeFunctionAddress(FunctionInfo* functionInfo)
{
funcInfo = functionInfo;
typeInfo = funcInfo->funcType;
if(funcInfo->type == FunctionInfo::LOCAL || funcInfo->type == FunctionInfo::THISCALL)
first = TakeLastNode();
nodeType = typeNodeFunctionAddress;
}
NodeFunctionAddress::~NodeFunctionAddress()
{
}
void NodeFunctionAddress::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
unsigned int ID = CodeInfo::FindFunctionByPtr(funcInfo);
cmdList.push_back(VMCmd(cmdFuncAddr, ID));
if(funcInfo->type == FunctionInfo::NORMAL)
{
cmdList.push_back(VMCmd(cmdPushImmt, funcInfo->funcPtr ? ~0ul : 0));
}else if(funcInfo->type == FunctionInfo::LOCAL || funcInfo->type == FunctionInfo::THISCALL){
first->Compile();
}
}
void NodeFunctionAddress::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s FunctionAddress %s %s\r\n", typeInfo->GetFullTypeName(), funcInfo->name, (funcInfo->funcPtr ? " external" : ""));
LogToStreamExtra(fGraph);
if(first)
{
GoDownB();
first->LogToStream(fGraph);
GoUp();
}
}
void NodeFunctionAddress::TranslateToC(FILE *fOut)
{
fprintf(fOut, "(");
nodeDereferenceEndInComma = true;
TranslateToCExtra(fOut);
nodeDereferenceEndInComma = false;
OutputIdent(fOut);
fprintf(fOut, "__nullcMakeFunction((void*)");
OutputCFunctionName(fOut, funcInfo);
fprintf(fOut, ", ");
if(funcInfo->type == FunctionInfo::NORMAL)
{
fprintf(fOut, "(void*)%uu", funcInfo->funcPtr ? ~0ul : 0);
}else if(funcInfo->type == FunctionInfo::LOCAL || funcInfo->type == FunctionInfo::THISCALL){
if(first->nodeType == typeNodeDereference)
{
VariableInfo *closure = ((NodeGetAddress*)((NodeOneOP*)first)->GetFirstNode())->varInfo;
if(closure->nameHash == GetStringHash("this"))
{
fprintf(fOut, "__context");
}else{
char closureName[NULLC_MAX_VARIABLE_NAME_LENGTH];
const char *namePrefix = *closure->name.begin == '$' ? "__" : "";
unsigned int nameShift = *closure->name.begin == '$' ? 1 : 0;
unsigned int length = sprintf(closureName, "%s%.*s_%d", namePrefix, closure->name.end - closure->name.begin-nameShift, closure->name.begin+nameShift, closure->pos);
for(unsigned int k = 0; k < length; k++)
{
if(closureName[k] == ':' || closureName[k] == '$')
closureName[k] = '_';
}
fprintf(fOut, "%s", closureName);
}
}else{
first->TranslateToC(fOut);
}
}
fprintf(fOut, "))");
}
//////////////////////////////////////////////////////////////////////////
// Node that applies binary operation on two values
NodeBinaryOp::NodeBinaryOp(CmdID cmd)
{
// Binary operation
cmdID = cmd;
second = TakeLastNode();
first = TakeLastNode();
bool logicalOp = (cmd >= cmdLess && cmd <= cmdNEqual) || (cmd >= cmdLogAnd && cmd <= cmdLogXor);
// Binary operations on complex types are not present at the moment
if(first->typeInfo->type == TypeInfo::TYPE_COMPLEX || second->typeInfo->type == TypeInfo::TYPE_COMPLEX)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: operation %s is not supported on '%s' and '%s'", binCommandToText[cmdID - cmdAdd], first->typeInfo->GetFullTypeName(), second->typeInfo->GetFullTypeName());
if((first->typeInfo->refLevel != 0 || second->typeInfo->refLevel != 0) && !(first->typeInfo->refLevel == second->typeInfo->refLevel && logicalOp))
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: operation %s is not supported on '%s' and '%s'", binCommandToText[cmdID - cmdAdd], first->typeInfo->GetFullTypeName(), second->typeInfo->GetFullTypeName());
if(first->typeInfo == typeVoid)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: first operator returns void");
if(second->typeInfo == typeVoid)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: second operator returns void");
if((first->typeInfo == typeDouble || first->typeInfo == typeFloat || second->typeInfo == typeDouble || second->typeInfo == typeFloat) && (cmd >= cmdShl && cmd <= cmdLogXor))
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: binary operations are not available on floating-point numbers");
// Find the type or resulting value
typeInfo = ChooseBinaryOpResultType(first->typeInfo, second->typeInfo);
if(first->nodeType == typeNodeNumber && first->typeInfo != typeInfo)
((NodeNumber*)first)->ConvertTo(typeInfo);
if(second->nodeType == typeNodeNumber && second->typeInfo != typeInfo)
((NodeNumber*)second)->ConvertTo(typeInfo);
typeInfo = logicalOp ? typeInt : typeInfo;
nodeType = typeNodeBinaryOp;
}
NodeBinaryOp::~NodeBinaryOp()
{
}
void NodeBinaryOp::Compile()
{
asmStackType fST = first->typeInfo->stackType, sST = second->typeInfo->stackType;
CompileExtra();
if(cmdID == cmdLogOr || cmdID == cmdLogAnd)
{
first->Compile();
// Convert long to int with | operation between parts of long (otherwise, we would've truncated 64 bit value)
if(fST == STYPE_LONG)
cmdList.push_back(VMCmd(cmdBitOr));
// If it's operator || and first argument is true, jump to push 1 as result
// If it's operator ^^ and first argument is false, jump to push 0 as result
cmdList.push_back(VMCmd(cmdID == cmdLogOr ? cmdJmpNZ : cmdJmpZ, ~0ul)); // Jump address will be fixed later on
unsigned int specialJmp1 = cmdList.size() - 1;
second->Compile();
if(sST == STYPE_LONG)
cmdList.push_back(VMCmd(cmdBitOr));
// If it's operator || and first argument is true, jump to push 1 as result
// If it's operator ^^ and first argument is false, jump to push 0 as result
cmdList.push_back(VMCmd(cmdID == cmdLogOr ? cmdJmpNZ : cmdJmpZ, ~0ul)); // Jump address will be fixed later on
unsigned int specialJmp2 = cmdList.size() - 1;
// If it's operator ||, result is zero, and if it's operator &&, result is 1
cmdList.push_back(VMCmd(cmdPushImmt, cmdID == cmdLogOr ? 0 : 1));
// Skip command that sets opposite result
cmdList.push_back(VMCmd(cmdJmp, cmdList.size() + 2));
// Fix up jumps
cmdList[specialJmp1].argument = cmdList.size();
cmdList[specialJmp2].argument = cmdList.size();
// If it's early jump, for operator ||, result is one, and if it's operator &&, result is 0
cmdList.push_back(VMCmd(cmdPushImmt, cmdID == cmdLogOr ? 1 : 0));
}else{
// Compute first value
first->Compile();
// Convert it to the resulting type
fST = ConvertFirstForSecond(fST, sST);
// Compute second value
second->Compile();
// Convert it to the result type
sST = ConvertFirstForSecond(sST, fST);
// Apply binary operation
if(fST == STYPE_INT)
cmdList.push_back(VMCmd((InstructionCode)(cmdID)));
else if(fST == STYPE_LONG)
cmdList.push_back(VMCmd((InstructionCode)(cmdID - cmdAdd + cmdAddL)));
else if(fST == STYPE_DOUBLE)
cmdList.push_back(VMCmd((InstructionCode)(cmdID - cmdAdd + cmdAddD)));
else
assert(!"unknown operator type in NodeTwoAndCmdOp");
}
}
void NodeBinaryOp::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s NodeBinaryOp<%s> :\r\n", typeInfo->GetFullTypeName(), binCommandToText[cmdID-cmdAdd]);
assert(cmdID >= cmdAdd);
assert(cmdID <= cmdNEqualD);
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
GoDownB();
second->LogToStream(fGraph);
GoUp();
}
void NodeBinaryOp::TranslateToC(FILE *fOut)
{
TypeInfo *tmpType = ChooseBinaryOpResultType(first->typeInfo, second->typeInfo);
if(cmdID == cmdPow)
fprintf(fOut, "__nullcPow");
if(cmdID == cmdMod && typeInfo == typeDouble)
fprintf(fOut, "__nullcMod");
fprintf(fOut, "(");
if(cmdID == cmdLogXor)
fprintf(fOut, "!!");
if(tmpType != first->typeInfo)
{
fprintf(fOut, "(");
tmpType->OutputCType(fOut, "");
fprintf(fOut, ")");
}
first->TranslateToC(fOut);
if(!(cmdID == cmdPow || (cmdID == cmdMod && typeInfo == typeDouble)))
fprintf(fOut, ")");
fprintf(fOut, " %s ", cmdID == cmdLogXor ? "!=" : ((cmdID == cmdPow || (cmdID == cmdMod && typeInfo == typeDouble)) ? "," : binCommandToText[cmdID-cmdAdd]));
if(!(cmdID == cmdPow || (cmdID == cmdMod && typeInfo == typeDouble)))
fprintf(fOut, "(");
if(cmdID == cmdLogXor)
fprintf(fOut, "!!");
if(tmpType != second->typeInfo)
{
fprintf(fOut, "(");
tmpType->OutputCType(fOut, "");
fprintf(fOut, ")");
}
second->TranslateToC(fOut);
fprintf(fOut, ")");
}
//////////////////////////////////////////////////////////////////////////
// Node for compilation of if(){}else{} statement and conditional operator ?:
NodeIfElseExpr::NodeIfElseExpr(bool haveElse, bool isTerm)
{
// If else block is present
if(haveElse)
third = TakeLastNode();
second = TakeLastNode();
first = TakeLastNode();
if((first->typeInfo->type == TypeInfo::TYPE_COMPLEX && first->typeInfo != typeObject) || first->typeInfo->type == TypeInfo::TYPE_VOID)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: condition type cannot be '%s'", first->typeInfo->GetFullTypeName());
// If it is a conditional operator, the there is a resulting type different than void
if(isTerm)
typeInfo = second->typeInfo != third->typeInfo ? ChooseBinaryOpResultType(second->typeInfo, third->typeInfo) : second->typeInfo;
nodeType = typeNodeIfElseExpr;
}
NodeIfElseExpr::~NodeIfElseExpr()
{
}
void NodeIfElseExpr::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
// Child node structure: if(first) second; else third;
// Or, for conditional operator: first ? second : third;
// Compute condition
first->Compile();
if(first->typeInfo == typeObject)
cmdList.push_back(VMCmd(cmdPop, 4));
else if(first->typeInfo->stackType != STYPE_INT)
cmdList.push_back(VMCmd(first->typeInfo->stackType == STYPE_DOUBLE ? cmdDtoI : cmdBitOr));
// If false, jump to 'else' block, or out of statement, if there is no 'else'
cmdList.push_back(VMCmd(cmdJmpZ, ~0ul)); // Jump address will be fixed later on
unsigned int jmpOnFalse = cmdList.size()-1;
// Compile block for condition == true
second->Compile();
if(typeInfo != typeVoid)
ConvertFirstForSecond(second->typeInfo->stackType, third->typeInfo->stackType);
cmdList[jmpOnFalse].argument = cmdList.size(); // Fixup jump address
// If 'else' block is present, compile it
if(third)
{
// Put jump to exit statement at the end of main block
cmdList.push_back(VMCmd(cmdJmp, ~0ul)); // Jump address will be fixed later on
unsigned int jmpToEnd = cmdList.size()-1;
cmdList[jmpOnFalse].argument = cmdList.size(); // Fixup jump address
// Compile block for condition == false
third->Compile();
if(typeInfo != typeVoid)
ConvertFirstForSecond(third->typeInfo->stackType, second->typeInfo->stackType);
cmdList[jmpToEnd].argument = cmdList.size(); // Fixup jump address
}
}
void NodeIfElseExpr::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s IfExpression :\r\n", typeInfo->GetFullTypeName());
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
if(!third)
{
GoUp();
GoDownB();
}
second->LogToStream(fGraph);
if(third)
{
GoUp();
GoDownB();
third->LogToStream(fGraph);
}
GoUp();
}
void NodeIfElseExpr::TranslateToC(FILE *fOut)
{
if(typeInfo != typeVoid)
{
first->TranslateToC(fOut);
fprintf(fOut, " ? ");
second->TranslateToC(fOut);
fprintf(fOut, " : ");
third->TranslateToC(fOut);
}else{
OutputIdent(fOut);
fprintf(fOut, "if(");
first->TranslateToC(fOut);
fprintf(fOut, ")\r\n");
OutputIdent(fOut);
fprintf(fOut, "{\r\n");
indentDepth++;
second->TranslateToC(fOut);
indentDepth--;
if(third)
{
OutputIdent(fOut);
fprintf(fOut, "}else{\r\n");
indentDepth++;
third->TranslateToC(fOut);
indentDepth--;
}
OutputIdent(fOut);
fprintf(fOut, "}\r\n");
}
}
//////////////////////////////////////////////////////////////////////////
// Nod for compilation of for(){}
unsigned int currLoopDepth = 0;
const unsigned int TRANSLATE_MAX_LOOP_DEPTH = 64;
unsigned int currLoopID[TRANSLATE_MAX_LOOP_DEPTH];
NodeForExpr::NodeForExpr()
{
fourth = TakeLastNode();
third = TakeLastNode();
second = TakeLastNode();
first = TakeLastNode();
if((second->typeInfo->type == TypeInfo::TYPE_COMPLEX && second->typeInfo != typeObject) || second->typeInfo->type == TypeInfo::TYPE_VOID)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: condition type cannot be '%s'", second->typeInfo->GetFullTypeName());
nodeType = typeNodeForExpr;
}
NodeForExpr::~NodeForExpr()
{
}
void NodeForExpr::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
currLoopDepth++;
// Child node structure: for(first, second, third) fourth;
// Compile initialization node
first->Compile();
unsigned int posTestExpr = cmdList.size();
// Compute condition value
second->Compile();
if(second->typeInfo == typeObject)
cmdList.push_back(VMCmd(cmdPop, 4));
else if(second->typeInfo->stackType != STYPE_INT)
cmdList.push_back(VMCmd(second->typeInfo->stackType == STYPE_DOUBLE ? cmdDtoI : cmdBitOr));
// If condition == false, exit loop
unsigned int exitJmp = cmdList.size();
cmdList.push_back(VMCmd(cmdJmpZ, 0));
// Compile loop contents
fourth->Compile();
unsigned int posPostOp = cmdList.size();
// Compile operation, executed after each cycle
third->Compile();
// Jump to condition check
cmdList.push_back(VMCmd(cmdJmp, posTestExpr));
cmdList[exitJmp].argument = cmdList.size();
NodeContinueOp::SatisfyJumps(posPostOp);
NodeBreakOp::SatisfyJumps(cmdList.size());
currLoopDepth--;
}
void NodeForExpr::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s ForExpression :\r\n", typeInfo->GetFullTypeName());
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
second->LogToStream(fGraph);
third->LogToStream(fGraph);
GoUp();
GoDownB();
fourth->LogToStream(fGraph);
GoUp();
}
void NodeForExpr::TranslateToC(FILE *fOut)
{
currLoopDepth++;
first->TranslateToC(fOut);
OutputIdent(fOut); fprintf(fOut, "while(");
second->TranslateToC(fOut);
fprintf(fOut, ")\r\n");
OutputIdent(fOut); fprintf(fOut, "{\r\n");
indentDepth++;
fourth->TranslateToC(fOut);
OutputIdent(fOut); fprintf(fOut, "continue%d_%d:1;\r\n", currLoopID[currLoopDepth-1], currLoopDepth);
third->TranslateToC(fOut);
indentDepth--;
OutputIdent(fOut); fprintf(fOut, "}\r\n");
OutputIdent(fOut); fprintf(fOut, "break%d_%d:1;\r\n", currLoopID[currLoopDepth-1], currLoopDepth);
currLoopDepth--;
assert(currLoopDepth < TRANSLATE_MAX_LOOP_DEPTH);
currLoopID[currLoopDepth]++;
}
//////////////////////////////////////////////////////////////////////////
// Node for compilation of while(){}
NodeWhileExpr::NodeWhileExpr()
{
second = TakeLastNode();
first = TakeLastNode();
if((first->typeInfo->type == TypeInfo::TYPE_COMPLEX && first->typeInfo != typeObject) || first->typeInfo->type == TypeInfo::TYPE_VOID)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: condition type cannot be '%s'", first->typeInfo->GetFullTypeName());
nodeType = typeNodeWhileExpr;
}
NodeWhileExpr::~NodeWhileExpr()
{
}
void NodeWhileExpr::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
currLoopDepth++;
// Child node structure: while(first) second;
unsigned int posStart = cmdList.size();
// Compute condition value
first->Compile();
if(first->typeInfo == typeObject)
cmdList.push_back(VMCmd(cmdPop, 4));
else if(first->typeInfo->stackType != STYPE_INT)
cmdList.push_back(VMCmd(first->typeInfo->stackType == STYPE_DOUBLE ? cmdDtoI : cmdBitOr));
// If condition == false, exit loop
unsigned int exitJmp = cmdList.size();
cmdList.push_back(VMCmd(cmdJmpZ, 0));
// Compile loop contents
second->Compile();
// Jump to condition check
cmdList.push_back(VMCmd(cmdJmp, posStart));
cmdList[exitJmp].argument = cmdList.size();
NodeContinueOp::SatisfyJumps(posStart);
NodeBreakOp::SatisfyJumps(cmdList.size());
currLoopDepth--;
}
void NodeWhileExpr::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s WhileExpression :\r\n", typeInfo->GetFullTypeName());
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
GoDownB();
second->LogToStream(fGraph);
GoUp();
}
void NodeWhileExpr::TranslateToC(FILE *fOut)
{
currLoopDepth++;
OutputIdent(fOut); fprintf(fOut, "while(");
first->TranslateToC(fOut);
fprintf(fOut, ")\r\n");
OutputIdent(fOut); fprintf(fOut, "{\r\n");
indentDepth++;
second->TranslateToC(fOut);
OutputIdent(fOut); fprintf(fOut, "continue%d_%d:1;\r\n", currLoopID[currLoopDepth-1], currLoopDepth);
indentDepth--;
OutputIdent(fOut); fprintf(fOut, "}\r\n");
OutputIdent(fOut); fprintf(fOut, "break%d_%d:1;\r\n", currLoopID[currLoopDepth-1], currLoopDepth);
currLoopDepth--;
assert(currLoopDepth < TRANSLATE_MAX_LOOP_DEPTH);
currLoopID[currLoopDepth]++;
}
//////////////////////////////////////////////////////////////////////////
// Node for compilation of do{}while()
NodeDoWhileExpr::NodeDoWhileExpr()
{
second = TakeLastNode();
first = TakeLastNode();
if((second->typeInfo->type == TypeInfo::TYPE_COMPLEX && second->typeInfo != typeObject) || second->typeInfo->type == TypeInfo::TYPE_VOID)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: condition type cannot be '%s'", second->typeInfo->GetFullTypeName());
nodeType = typeNodeDoWhileExpr;
}
NodeDoWhileExpr::~NodeDoWhileExpr()
{
}
void NodeDoWhileExpr::Compile()
{
// Child node structure: do{ first; }while(second)
CompileExtra();
currLoopDepth++;
unsigned int posStart = cmdList.size();
// Compile loop contents
first->Compile();
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
unsigned int posCond = cmdList.size();
// Compute condition value
second->Compile();
if(second->typeInfo == typeObject)
cmdList.push_back(VMCmd(cmdPop, 4));
else if(second->typeInfo->stackType != STYPE_INT)
cmdList.push_back(VMCmd(second->typeInfo->stackType == STYPE_DOUBLE ? cmdDtoI : cmdBitOr));
// Jump to beginning if condition == true
cmdList.push_back(VMCmd(cmdJmpNZ, posStart));
NodeContinueOp::SatisfyJumps(posCond);
NodeBreakOp::SatisfyJumps(cmdList.size());
currLoopDepth--;
}
void NodeDoWhileExpr::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s DoWhileExpression :\r\n", typeInfo->GetFullTypeName());
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
GoDownB();
second->LogToStream(fGraph);
GoUp();
}
void NodeDoWhileExpr::TranslateToC(FILE *fOut)
{
currLoopDepth++;
OutputIdent(fOut); fprintf(fOut, "do\r\n");
OutputIdent(fOut); fprintf(fOut, "{\r\n");
indentDepth++;
first->TranslateToC(fOut);
OutputIdent(fOut); fprintf(fOut, "continue%d_%d:1;\r\n", currLoopID[currLoopDepth-1], currLoopDepth);
indentDepth--;
OutputIdent(fOut); fprintf(fOut, "} while(");
second->TranslateToC(fOut);
fprintf(fOut, ");\r\n");
OutputIdent(fOut);
fprintf(fOut, "break%d_%d:1;\r\n", currLoopID[currLoopDepth-1], currLoopDepth);
currLoopDepth--;
assert(currLoopDepth < TRANSLATE_MAX_LOOP_DEPTH);
currLoopID[currLoopDepth]++;
}
//////////////////////////////////////////////////////////////////////////
void SatisfyJumps(FastVector<unsigned int>& jumpList, unsigned int pos)
{
for(unsigned int i = 0; i < jumpList.size();)
{
if(cmdList[jumpList[i]].argument == currLoopDepth)
{
// If level is equal to 1, replace it with jump position
cmdList[jumpList[i]].argument = pos;
// Remove element by replacing with the last one
jumpList[i] = jumpList.back();
jumpList.pop_back();
}else{
i++;
}
}
}
//////////////////////////////////////////////////////////////////////////
// Node for break operation
FastVector<unsigned int> NodeBreakOp::fixQueue;
NodeBreakOp::NodeBreakOp(unsigned int brDepth)
{
nodeType = typeNodeBreakOp;
breakDepth = brDepth;
}
NodeBreakOp::~NodeBreakOp()
{
}
void NodeBreakOp::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
// Break the loop
fixQueue.push_back(cmdList.size());
cmdList.push_back(VMCmd(cmdJmp, currLoopDepth - breakDepth + 1));
}
void NodeBreakOp::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s BreakExpression\r\n", typeInfo->GetFullTypeName());
LogToStreamExtra(fGraph);
}
void NodeBreakOp::TranslateToC(FILE *fOut)
{
OutputIdent(fOut);
if(breakDepth == 1)
fprintf(fOut, "break;\r\n");
else
fprintf(fOut, "goto break%d_%d;\r\n", currLoopID[currLoopDepth-breakDepth], currLoopDepth - breakDepth + 1);
}
void NodeBreakOp::SatisfyJumps(unsigned int pos)
{
::SatisfyJumps(fixQueue, pos);
}
//////////////////////////////////////////////////////////////////////////
// Node for continue operation
FastVector<unsigned int> NodeContinueOp::fixQueue;
NodeContinueOp::NodeContinueOp(unsigned int contDepth)
{
nodeType = typeNodeContinueOp;
continueDepth = contDepth;
}
NodeContinueOp::~NodeContinueOp()
{
}
void NodeContinueOp::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
// Continue the loop
fixQueue.push_back(cmdList.size());
cmdList.push_back(VMCmd(cmdJmp, currLoopDepth - continueDepth + 1));
}
void NodeContinueOp::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s ContinueOp\r\n", typeInfo->GetFullTypeName());
LogToStreamExtra(fGraph);
}
void NodeContinueOp::TranslateToC(FILE *fOut)
{
OutputIdent(fOut);
fprintf(fOut, "goto continue%d_%d;\r\n", currLoopID[currLoopDepth-continueDepth], currLoopDepth - continueDepth + 1);
}
void NodeContinueOp::SatisfyJumps(unsigned int pos)
{
::SatisfyJumps(fixQueue, pos);
}
//////////////////////////////////////////////////////////////////////////
// Node for compilation of switch
FastVector<unsigned int> NodeSwitchExpr::fixQueue;
NodeSwitchExpr::NodeSwitchExpr()
{
// Take node with value
first = TakeLastNode();
conditionHead = conditionTail = NULL;
blockHead = blockTail = NULL;
defaultCase = NULL;
caseCount = 0;
nodeType = typeNodeSwitchExpr;
}
NodeSwitchExpr::~NodeSwitchExpr()
{
}
void NodeSwitchExpr::AddCase()
{
caseCount++;
// Take case block from the top
if(blockTail)
{
blockTail->next = TakeLastNode();
blockTail->next->prev = blockTail;
blockTail = blockTail->next;
}else{
blockHead = blockTail = TakeLastNode();
}
// Take case condition from the top
if(conditionTail)
{
conditionTail->next = TakeLastNode();
conditionTail->next->prev = conditionTail;
conditionTail = conditionTail->next;
}else{
conditionHead = conditionTail = TakeLastNode();
}
}
void NodeSwitchExpr::AddDefault()
{
defaultCase = TakeLastNode();
}
void NodeSwitchExpr::Compile()
{
CompileExtra();
currLoopDepth++;
asmStackType aST = first->typeInfo->stackType;
asmOperType aOT = operTypeForStackType[aST];
unsigned int queueStart = fixQueue.size(), queueCurr = queueStart;
// Compute value
first->Compile();
NodeZeroOP *curr, *currBlock;
// Generate code for all cases
for(curr = conditionHead, currBlock = blockHead; curr; curr = curr->next, currBlock = currBlock->next)
{
if(aOT == OTYPE_INT)
cmdList.push_back(VMCmd(cmdCopyI));
else
cmdList.push_back(VMCmd(cmdCopyDorL));
curr->Compile();
// Compare for equality
if(aOT == OTYPE_INT)
cmdList.push_back(VMCmd(cmdEqual));
else if(aOT == OTYPE_DOUBLE)
cmdList.push_back(VMCmd(cmdEqualD));
else
cmdList.push_back(VMCmd(cmdEqualL));
// If equal, jump to corresponding case block
fixQueue.push_back(cmdList.size());
cmdList.push_back(VMCmd(cmdJmpNZ, 0));
}
// Remove value by which we switched from stack
cmdList.push_back(VMCmd(cmdPop, stackTypeSize[aST]));
fixQueue.push_back(cmdList.size());
cmdList.push_back(VMCmd(cmdJmp, 0));
for(curr = blockHead; curr; curr = curr->next)
{
cmdList[fixQueue[queueCurr++]].argument = cmdList.size();
// Remove value by which we switched from stack
cmdList.push_back(VMCmd(cmdPop, stackTypeSize[aST]));
curr->Compile();
if(curr != blockTail)
cmdList.push_back(VMCmd(cmdJmp, cmdList.size() + 2));
}
cmdList[fixQueue[queueCurr++]].argument = cmdList.size();
if(defaultCase)
defaultCase->Compile();
for(unsigned int i = 0; i < NodeContinueOp::fixQueue.size(); i++)
{
if(cmdList[NodeContinueOp::fixQueue[i]].argument == 1)
ThrowError(NULL, "ERROR: cannot continue inside switch");
}
fixQueue.shrink(queueStart);
NodeBreakOp::SatisfyJumps(cmdList.size());
currLoopDepth--;
}
void NodeSwitchExpr::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s SwitchExpression :\r\n", typeInfo->GetFullTypeName());
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
for(NodeZeroOP *curr = conditionHead, *block = blockHead; curr; curr = curr->next, block = block->next)
{
curr->LogToStream(fGraph);
if(curr == conditionTail)
{
GoUp();
GoDownB();
}
block->LogToStream(fGraph);
}
GoUp();
}
void NodeSwitchExpr::TranslateToC(FILE *fOut)
{
static int switchNum = 0;
int myNum = switchNum++;
OutputIdent(fOut);
fprintf(fOut, "do\r\n");
OutputIdent(fOut);
fprintf(fOut, "{\r\n");
indentDepth++;
char buf[64];
sprintf(buf, "switchVar");
OutputIdent(fOut);
first->typeInfo->OutputCType(fOut, buf);
fprintf(fOut, " = ");
first->TranslateToC(fOut);
fprintf(fOut, ";\r\n");
unsigned int i = 0;
for(NodeZeroOP *curr = conditionHead; curr; curr = curr->next, i++)
{
OutputIdent(fOut);
fprintf(fOut, "if(switchVar == ");
curr->TranslateToC(fOut);
fprintf(fOut, ")\r\n");
OutputIdent(fOut);
fprintf(fOut, "\tgoto case%d_%d;\r\n", myNum, i);
}
OutputIdent(fOut);
fprintf(fOut, "goto defaultCase_%d;\r\n", myNum);
i = 0;
for(NodeZeroOP *block = blockHead; block; block = block->next, i++)
{
OutputIdent(fOut);
fprintf(fOut, "case%d_%d:\r\n", myNum, i);
block->TranslateToC(fOut);
}
OutputIdent(fOut);
fprintf(fOut, "defaultCase_%d:\r\n", myNum);
if(defaultCase)
{
defaultCase->TranslateToC(fOut);
}else{
OutputIdent(fOut);
fprintf(fOut, "0;\r\n");
}
indentDepth--;
OutputIdent(fOut);
fprintf(fOut, "}while(0);\r\n");
}
//////////////////////////////////////////////////////////////////////////
// Node that contains list of expressions
NodeExpressionList::NodeExpressionList(TypeInfo *returnType)
{
typeInfo = returnType;
tail = first = TakeLastNode();
nodeType = typeNodeExpressionList;
}
NodeExpressionList::~NodeExpressionList()
{
}
void NodeExpressionList::AddNode(bool reverse)
{
// If reverse is set, add before the head
if(reverse)
{
NodeZeroOP *firstNext = first;
first = TakeLastNode();
first->next = firstNext;
first->next->prev = first;
}else{
tail->next = TakeLastNode();
tail->next->prev = tail;
tail = tail->next;
}
}
NodeZeroOP* NodeExpressionList::GetFirstNode()
{
assert(first);
return first;
}
void NodeExpressionList::Compile()
{
CompileExtra();
NodeZeroOP *curr = first;
do
{
curr->Compile();
curr = curr->next;
}while(curr);
}
void NodeExpressionList::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s NodeExpressionList :\r\n", typeInfo->GetFullTypeName());
GoDown();
LogToStreamExtra(fGraph);
NodeZeroOP *curr = first;
do
{
if(curr == tail)
{
GoUp();
GoDownB();
}
curr->LogToStream(fGraph);
curr = curr->next;
}while(curr);
GoUp();
}
void NodeExpressionList::TranslateToC(FILE *fOut)
{
if(typeInfo->arrLevel && typeInfo->arrSize != TypeInfo::UNSIZED_ARRAY && typeInfo->subType == typeChar)
{
fprintf(fOut, "\"");
NodeZeroOP *curr = tail->prev;
do
{
assert(curr->nodeType == typeNodeNumber);
NodeNumber *dword = (NodeNumber*)curr;
for(unsigned int i = 0; i < 4; i++)
{
unsigned char ch = (unsigned char)((dword->GetInteger() >> (i * 8)) & 0xff);
if(ch >= ' ' && ch <= 128 && ch != '\"' && ch != '\\' && ch != '\'')
fprintf(fOut, "%c", ch);
else
fprintf(fOut, "\\x%x", ch);
}
curr = curr->prev;
}while(curr);
fprintf(fOut, "\"");
return;
}else if(typeInfo != typeVoid){
NodeZeroOP *end = first;
if(first->nodeType == typeNodePopOp)
{
fprintf(fOut, "(");
((NodePopOp*)first)->GetFirstNode()->TranslateToC(fOut);
fprintf(fOut, ", ");
end = first->next;
}
if(typeInfo->arrLevel && typeInfo->arrSize == TypeInfo::UNSIZED_ARRAY)
fprintf(fOut, "__makeNullcArray(");
else if(first->nodeType != typeNodePopOp){
typeInfo->OutputCType(fOut, "()");
end = first->next;
}
NodeZeroOP *curr = tail;
unsigned int id = 0;
do
{
if(typeInfo->arrLevel && typeInfo->arrSize != TypeInfo::UNSIZED_ARRAY)
fprintf(fOut, ".set(%d, ", id++);
curr->TranslateToC(fOut);
if(typeInfo->arrLevel && typeInfo->arrSize != TypeInfo::UNSIZED_ARRAY)
fprintf(fOut, ")");
else if(curr != end)
fprintf(fOut, ", ");
curr = curr->prev;
}while(curr != end->prev);
if(typeInfo->arrLevel && typeInfo->arrSize == TypeInfo::UNSIZED_ARRAY)
fprintf(fOut, ")");
if(first->nodeType == typeNodePopOp)
fprintf(fOut, ")");
}else{
NodeZeroOP *curr = first;
do
{
curr->TranslateToC(fOut);
if(curr != tail && typeInfo != typeVoid)
fprintf(fOut, ", ");
curr = curr->next;
}while(curr);
}
}
void ResetTreeGlobals()
{
currLoopDepth = 0;
memset(currLoopID, 0, sizeof(unsigned int) * TRANSLATE_MAX_LOOP_DEPTH);
nodeDereferenceEndInComma = false;
NodeBreakOp::fixQueue.clear();
NodeContinueOp::fixQueue.clear();
}
Translation to C improvements.
- support of type as terminal.
#include "stdafx.h"
#include "SyntaxTree.h"
#include "CodeInfo.h"
using CodeInfo::nodeList;
using CodeInfo::cmdList;
using CodeInfo::cmdInfoList;
NodeZeroOP* TakeLastNode()
{
NodeZeroOP* last = nodeList.back();
nodeList.pop_back();
return last;
}
static char* binCommandToText[] = { "+", "-", "*", "/", "**", "%", "<", ">", "<=", ">=", "==", "!=", "<<", ">>", "&", "|", "^", "&&", "||", "^^"};
static char* unaryCommandToText[] = { "-", "-", "-", "~", "~", "!", "!" };
//////////////////////////////////////////////////////////////////////////
unsigned int indentDepth = 1;
void OutputIdent(FILE *fOut)
{
for(unsigned int i = 0; i < indentDepth; i++)
fprintf(fOut, "\t");
}
void OutputCFunctionName(FILE *fOut, FunctionInfo *funcInfo)
{
const char *namePrefix = *funcInfo->name == '$' ? "__" : "";
unsigned int nameShift = *funcInfo->name == '$' ? 1 : 0;
char fName[NULLC_MAX_VARIABLE_NAME_LENGTH];
sprintf(fName, (funcInfo->type == FunctionInfo::LOCAL || !funcInfo->visible) ? "%s%s_%d" : "%s%s", namePrefix, funcInfo->name + nameShift, CodeInfo::FindFunctionByPtr(funcInfo));
if(const char *opName = funcInfo->GetOperatorName())
{
strcpy(fName, opName);
}else{
for(unsigned int k = 0; k < funcInfo->nameLength; k++)
{
if(fName[k] == ':' || fName[k] == '$' || fName[k] == '[' || fName[k] == ']')
fName[k] = '_';
}
for(unsigned int k = 0; k < CodeInfo::classCount; k++)
{
if(CodeInfo::typeInfo[k]->nameHash == funcInfo->nameHash)
{
strcat(fName, "__");
break;
}
}
}
unsigned int length = (unsigned int)strlen(fName);
if(fName[length-1] == '$')
fName[length-1] = '_';
fprintf(fOut, "%s", fName);
}
int level = 0;
char linePrefix[256];
unsigned int prefixSize = 2;
bool preNeedChange = false;
void GoDown()
{
level++;
prefixSize -= 2;
linePrefix[prefixSize] = 0;
sprintf(linePrefix + prefixSize, " |__");
prefixSize += 5;
}
void GoDownB()
{
GoDown();
preNeedChange = true;
}
void GoUp()
{
level--;
prefixSize -= 5;
linePrefix[prefixSize] = 0;
sprintf(linePrefix + prefixSize, "__");
prefixSize += 2;
}
void DrawLine(FILE *fGraph)
{
fprintf(fGraph, "%s", linePrefix);
if(preNeedChange)
{
preNeedChange = false;
GoUp();
level++;
prefixSize -= 2;
linePrefix[prefixSize] = 0;
sprintf(linePrefix + prefixSize, " __");
prefixSize += 5;
}
}
//Functions for work with types
//This function converts a type according to result type of binary operation between types 'first' and 'second'
//For example, int * double = double, so first operand will be transformed to double
// double * int = double, no transformations
asmStackType ConvertFirstForSecond(asmStackType first, asmStackType second)
{
if(first == STYPE_INT && second == STYPE_DOUBLE)
{
cmdList.push_back(VMCmd(cmdItoD));
return second;
}
if(first == STYPE_LONG && second == STYPE_DOUBLE)
{
cmdList.push_back(VMCmd(cmdLtoD));
return second;
}
if(first == STYPE_INT && second == STYPE_LONG)
{
cmdList.push_back(VMCmd(cmdItoL));
return second;
}
return first;
}
//This functions transforms first type to second one
void ConvertFirstToSecond(asmStackType first, asmStackType second)
{
if(second == STYPE_DOUBLE)
{
if(first == STYPE_INT)
cmdList.push_back(VMCmd(cmdItoD));
else if(first == STYPE_LONG)
cmdList.push_back(VMCmd(cmdLtoD));
}else if(second == STYPE_LONG){
if(first == STYPE_INT)
cmdList.push_back(VMCmd(cmdItoL));
else if(first == STYPE_DOUBLE)
cmdList.push_back(VMCmd(cmdDtoL));
}else if(second == STYPE_INT){
if(first == STYPE_DOUBLE)
cmdList.push_back(VMCmd(cmdDtoI));
else if(first == STYPE_LONG)
cmdList.push_back(VMCmd(cmdLtoI));
}
}
TypeInfo* ChooseBinaryOpResultType(TypeInfo* a, TypeInfo* b)
{
if(a->type == TypeInfo::TYPE_DOUBLE)
return a;
if(b->type == TypeInfo::TYPE_DOUBLE)
return b;
if(a->type == TypeInfo::TYPE_FLOAT)
return a;
if(b->type == TypeInfo::TYPE_FLOAT)
return b;
if(a->type == TypeInfo::TYPE_LONG)
return a;
if(b->type == TypeInfo::TYPE_LONG)
return b;
if(a->type == TypeInfo::TYPE_INT)
return a;
if(b->type == TypeInfo::TYPE_INT)
return b;
if(a->type == TypeInfo::TYPE_SHORT)
return a;
if(b->type == TypeInfo::TYPE_SHORT)
return b;
if(a->type == TypeInfo::TYPE_CHAR)
return a;
if(b->type == TypeInfo::TYPE_CHAR)
return b;
assert(false);
return NULL;
}
// class implementation
//////////////////////////////////////////////////////////////////////////
// Node that doesn't have any child nodes
ChunkedStackPool<4092> NodeZeroOP::nodePool;
NodeZeroOP::NodeZeroOP()
{
typeInfo = typeVoid;
sourcePos = NULL;
prev = next = head = NULL;
nodeType = typeNodeZeroOp;
}
NodeZeroOP::NodeZeroOP(TypeInfo* tinfo)
{
typeInfo = tinfo;
sourcePos = NULL;
prev = next = head = NULL;
nodeType = typeNodeZeroOp;
}
NodeZeroOP::~NodeZeroOP()
{
}
void NodeZeroOP::Compile()
{
}
void NodeZeroOP::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s ZeroOp\r\n", typeInfo->GetFullTypeName());
}
void NodeZeroOP::TranslateToC(FILE *fOut)
{
OutputIdent(fOut);
fprintf(fOut, "/* node translation unknown */\r\n");
}
void NodeZeroOP::SetCodeInfo(const char* newSourcePos)
{
sourcePos = newSourcePos;
}
void NodeZeroOP::AddExtraNode()
{
assert(nodeList.size() > 0);
nodeList.back()->next = head;
if(head)
head->prev = nodeList.back();
head = TakeLastNode();
}
void NodeZeroOP::CompileExtra()
{
NodeZeroOP *curr = head;
while(curr)
{
curr->Compile();
curr = curr->next;
}
}
void NodeZeroOP::LogToStreamExtra(FILE *fGraph)
{
NodeZeroOP *curr = head;
while(curr)
{
curr->LogToStream(fGraph);
curr = curr->next;
}
}
void NodeZeroOP::TranslateToCExtra(FILE *fOut)
{
NodeZeroOP *curr = head;
while(curr)
{
curr->TranslateToC(fOut);
curr = curr->next;
}
}
//////////////////////////////////////////////////////////////////////////
// Node that have one child node
NodeOneOP::NodeOneOP()
{
first = NULL;
nodeType = typeNodeOneOp;
}
NodeOneOP::~NodeOneOP()
{
}
void NodeOneOP::Compile()
{
CompileExtra();
first->Compile();
}
void NodeOneOP::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s OneOP :\r\n", typeInfo->GetFullTypeName());
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
}
void NodeOneOP::TranslateToC(FILE *fOut)
{
first->TranslateToC(fOut);
}
//////////////////////////////////////////////////////////////////////////
// Node that have two child nodes
NodeTwoOP::NodeTwoOP()
{
second = NULL;
nodeType = typeNodeTwoOp;
}
NodeTwoOP::~NodeTwoOP()
{
}
void NodeTwoOP::Compile()
{
CompileExtra();
NodeOneOP::Compile();
second->Compile();
}
void NodeTwoOP::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s TwoOp :\r\n", typeInfo->GetFullTypeName());
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
second->LogToStream(fGraph);
GoUp();
}
//////////////////////////////////////////////////////////////////////////
// Node that have three child nodes
NodeThreeOP::NodeThreeOP()
{
third = NULL;
nodeType = typeNodeThreeOp;
}
NodeThreeOP::~NodeThreeOP()
{
}
void NodeThreeOP::Compile()
{
CompileExtra();
NodeTwoOP::Compile();
third->Compile();
}
void NodeThreeOP::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s ThreeOp :\r\n", typeInfo->GetFullTypeName());
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
second->LogToStream(fGraph);
third->LogToStream(fGraph);
GoUp();
}
//////////////////////////////////////////////////////////////////////////
// Node that puts a number on top of the stack
void NodeNumber::Compile()
{
assert(typeInfo->size <= 8);
if(typeInfo->stackType != STYPE_INT)
cmdList.push_back(VMCmd(cmdPushImmt, num.quad.high));
cmdList.push_back(VMCmd(cmdPushImmt, num.quad.low));
}
void NodeNumber::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s Number\r\n", typeInfo->GetFullTypeName());
}
void NodeNumber::TranslateToC(FILE *fOut)
{
if(typeInfo->refLevel)
fprintf(fOut, "(void*)(%d)", num.integer);
else if(typeInfo == typeChar || typeInfo == typeShort || typeInfo == typeInt)
fprintf(fOut, "%d", num.integer);
else if(typeInfo == typeDouble)
fprintf(fOut, "%f", num.real);
else if(typeInfo == typeFloat)
fprintf(fOut, "%ff", num.real);
else if(typeInfo == typeLong)
fprintf(fOut, "%I64dLL", num.integer64);
else
fprintf(fOut, "%%unknown_number%%");
}
bool NodeNumber::ConvertTo(TypeInfo *target)
{
if(target == typeInt)
{
num.integer = GetInteger();
}else if(target == typeDouble || target == typeFloat){
num.real = GetDouble();
}else if(target == typeLong){
num.integer64 = GetLong();
}else{
return false;
}
typeInfo = target;
return true;
}
//////////////////////////////////////////////////////////////////////////
// Node that removes value left on top of the stack by child node
NodePopOp::NodePopOp()
{
first = TakeLastNode();
nodeType = typeNodePopOp;
}
NodePopOp::~NodePopOp()
{
}
void NodePopOp::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
// Child node computes value
first->Compile();
if(first->typeInfo != typeVoid && first->typeInfo->size)
{
// Removing it from top of the stack
cmdList.push_back(VMCmd(cmdPop, first->typeInfo->type == TypeInfo::TYPE_COMPLEX ? first->typeInfo->size : stackTypeSize[first->typeInfo->stackType]));
}
}
void NodePopOp::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s PopOp :\r\n", typeInfo->GetFullTypeName());
GoDownB();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
}
void NodePopOp::TranslateToC(FILE *fOut)
{
OutputIdent(fOut);
first->TranslateToC(fOut);
fprintf(fOut, ";\r\n");
}
//////////////////////////////////////////////////////////////////////////
// Node that applies selected operation on value on top of the stack
NodeUnaryOp::NodeUnaryOp(CmdID cmd)
{
// Unary operation
cmdID = cmd;
first = TakeLastNode();
// Resulting type is the same as source type with exception for logical NOT
bool logicalOp = cmd == cmdLogNot;
typeInfo = logicalOp ? typeInt : first->typeInfo;
if((first->typeInfo->refLevel != 0 && !logicalOp) || (first->typeInfo->type == TypeInfo::TYPE_COMPLEX && first->typeInfo != typeObject))
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: unary operation '%s' is not supported on '%s'", unaryCommandToText[cmdID - cmdNeg], first->typeInfo->GetFullTypeName());
nodeType = typeNodeUnaryOp;
}
NodeUnaryOp::~NodeUnaryOp()
{
}
void NodeUnaryOp::Compile()
{
CompileExtra();
asmOperType aOT = operTypeForStackType[first->typeInfo->stackType];
// Child node computes value
first->Compile();
if(first->typeInfo == typeObject)
cmdList.push_back(VMCmd(cmdPop, 4));
// Execute command
if(aOT == OTYPE_INT || first->typeInfo == typeObject)
cmdList.push_back(VMCmd((InstructionCode)cmdID));
else if(aOT == OTYPE_LONG)
cmdList.push_back(VMCmd((InstructionCode)(cmdID + 1)));
else
cmdList.push_back(VMCmd((InstructionCode)(cmdID + 2)));
}
void NodeUnaryOp::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s UnaryOp :\r\n", typeInfo->GetFullTypeName());
GoDownB();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
}
void NodeUnaryOp::TranslateToC(FILE *fOut)
{
switch(cmdID)
{
case cmdNeg:
fprintf(fOut, "-");
break;
case cmdBitNot:
fprintf(fOut, "~");
break;
case cmdLogNot:
fprintf(fOut, "!");
break;
default:
fprintf(fOut, "%%unknown_unary_command%%");
}
first->TranslateToC(fOut);
}
//////////////////////////////////////////////////////////////////////////
// Node that returns from function or program
NodeReturnOp::NodeReturnOp(bool localRet, TypeInfo* tinfo, FunctionInfo* parentFunc)
{
localReturn = localRet;
parentFunction = parentFunc;
// Result type is set from outside
typeInfo = tinfo;
first = TakeLastNode();
if(first->nodeType == typeNodeNumber && first->typeInfo != typeInfo)
((NodeNumber*)first)->ConvertTo(typeInfo);
nodeType = typeNodeReturnOp;
}
NodeReturnOp::~NodeReturnOp()
{
}
void NodeReturnOp::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
// Compute value that we're going to return
first->Compile();
// Convert it to the return type of the function
if(typeInfo)
ConvertFirstToSecond(first->typeInfo->stackType, typeInfo->stackType);
// Return from function or program
TypeInfo *retType = typeInfo ? typeInfo : first->typeInfo;
asmOperType operType = operTypeForStackType[retType->stackType];
unsigned int retSize = retType == typeFloat ? 8 : retType->size;
if(retSize != 0 && retSize < 4)
retSize = 4;
if(parentFunction && parentFunction->closeUpvals)
cmdList.push_back(VMCmd(cmdCloseUpvals, (unsigned short)CodeInfo::FindFunctionByPtr(parentFunction), 0));
cmdList.push_back(VMCmd(cmdReturn, (unsigned char)operType, (unsigned short)localReturn, retSize));
}
void NodeReturnOp::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
if(typeInfo)
fprintf(fGraph, "%s ReturnOp :\r\n", typeInfo->GetFullTypeName());
else
fprintf(fGraph, "%s ReturnOp :\r\n", first->typeInfo->GetFullTypeName());
GoDownB();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
}
void NodeReturnOp::TranslateToC(FILE *fOut)
{
static unsigned int retVarID = 0;
TranslateToCExtra(fOut);
if(parentFunction && parentFunction->closeUpvals)
{
OutputIdent(fOut);
typeInfo->OutputCType(fOut, "");
fprintf(fOut, "__nullcRetVar%d = ", retVarID);
if(typeInfo != first->typeInfo)
{
fprintf(fOut, "(");
typeInfo->OutputCType(fOut, "");
fprintf(fOut, ")(");
}
first->TranslateToC(fOut);
if(typeInfo != first->typeInfo)
fprintf(fOut, ")");
fprintf(fOut, ";\r\n");
char name[NULLC_MAX_VARIABLE_NAME_LENGTH];
// Glue together parameter list, extra parameter and local list. Every list could be empty.
VariableInfo *curr = parentFunction->firstParam ? parentFunction->firstParam : (parentFunction->firstLocal ? parentFunction->firstLocal : parentFunction->extraParam);
if(parentFunction->firstParam)
parentFunction->lastParam->next = (parentFunction->firstLocal ? parentFunction->firstLocal : parentFunction->extraParam);
if(parentFunction->firstLocal)
parentFunction->lastLocal->next = parentFunction->extraParam;
unsigned int hashThis = GetStringHash("this");
for(; curr; curr = curr->next)
{
if(curr->usedAsExternal)
{
const char *namePrefix = *curr->name.begin == '$' ? "__" : "";
unsigned int nameShift = *curr->name.begin == '$' ? 1 : 0;
sprintf(name, "%s%.*s_%d", namePrefix, curr->name.end - curr->name.begin-nameShift, curr->name.begin+nameShift, curr->pos);
OutputIdent(fOut);
if(curr->nameHash == hashThis)
fprintf(fOut, "__nullcCloseUpvalue(__upvalue_%d___context, &__context);\r\n", CodeInfo::FindFunctionByPtr(curr->parentFunction));
else
fprintf(fOut, "__nullcCloseUpvalue(__upvalue_%d_%s, &%s);\r\n", CodeInfo::FindFunctionByPtr(curr->parentFunction), name, name);
}
}
if(parentFunction->firstParam)
parentFunction->lastParam->next = NULL;
if(parentFunction->firstLocal)
parentFunction->lastLocal->next = NULL;
OutputIdent(fOut);
fprintf(fOut, "return __nullcRetVar%d;\r\n", retVarID++);
return;
}
OutputIdent(fOut);
if(typeInfo == typeVoid || first->typeInfo == typeVoid)
{
fprintf(fOut, "return;\r\n");
}else{
fprintf(fOut, "return ");
if(typeInfo != first->typeInfo)
{
fprintf(fOut, "(");
typeInfo->OutputCType(fOut, "");
fprintf(fOut, ")(");
}
first->TranslateToC(fOut);
if(typeInfo != first->typeInfo)
fprintf(fOut, ")");
fprintf(fOut, ";\r\n");
}
}
//////////////////////////////////////////////////////////////////////////
NodeBlock::NodeBlock(FunctionInfo* parentFunc, unsigned int shift)
{
parentFunction = parentFunc;
stackFrameShift = shift;
first = TakeLastNode();
nodeType = typeNodeBlockOp;
}
NodeBlock::~NodeBlock()
{
}
void NodeBlock::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
// Compute value that we're going to return
first->Compile();
if(parentFunction->closeUpvals)
cmdList.push_back(VMCmd(cmdCloseUpvals, (unsigned short)CodeInfo::FindFunctionByPtr(parentFunction), stackFrameShift));
}
void NodeBlock::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s BlockOp (close upvalues from offset %d of function %s) %s:\r\n", first->typeInfo->GetFullTypeName(), stackFrameShift, parentFunction->name, parentFunction->closeUpvals ? "yes" : "no");
GoDownB();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
}
void NodeBlock::TranslateToC(FILE *fOut)
{
first->TranslateToC(fOut);
char name[NULLC_MAX_VARIABLE_NAME_LENGTH];
// Glue together parameter list, extra parameter and local list. Every list could be empty.
VariableInfo *curr = parentFunction->firstParam ? parentFunction->firstParam : (parentFunction->firstLocal ? parentFunction->firstLocal : parentFunction->extraParam);
if(parentFunction->firstParam)
parentFunction->lastParam->next = (parentFunction->firstLocal ? parentFunction->firstLocal : parentFunction->extraParam);
if(parentFunction->firstLocal)
parentFunction->lastLocal->next = parentFunction->extraParam;
unsigned int hashThis = GetStringHash("this");
for(; curr; curr = curr->next)
{
if(curr->usedAsExternal)
{
const char *namePrefix = *curr->name.begin == '$' ? "__" : "";
unsigned int nameShift = *curr->name.begin == '$' ? 1 : 0;
sprintf(name, "%s%.*s_%d", namePrefix, curr->name.end - curr->name.begin-nameShift, curr->name.begin+nameShift, curr->pos);
OutputIdent(fOut);
if(curr->nameHash == hashThis)
fprintf(fOut, "__nullcCloseUpvalue(__upvalue_%d___context, &__context);\r\n", CodeInfo::FindFunctionByPtr(curr->parentFunction));
else
fprintf(fOut, "__nullcCloseUpvalue(__upvalue_%d_%s, &%s);\r\n", CodeInfo::FindFunctionByPtr(curr->parentFunction), name, name);
}
}
if(parentFunction->firstParam)
parentFunction->lastParam->next = NULL;
if(parentFunction->firstLocal)
parentFunction->lastLocal->next = NULL;
}
//////////////////////////////////////////////////////////////////////////
// Nodes that compiles function
NodeFuncDef::NodeFuncDef(FunctionInfo *info, unsigned int varShift)
{
// Function description
funcInfo = info;
// Size of all local variables
shift = varShift;
disabled = false;
first = TakeLastNode();
nodeType = typeNodeFuncDef;
}
NodeFuncDef::~NodeFuncDef()
{
}
void NodeFuncDef::Enable()
{
disabled = false;
}
void NodeFuncDef::Disable()
{
disabled = true;
}
void NodeFuncDef::Compile()
{
if(disabled)
{
CompileExtra();
return;
}
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
funcInfo->address = cmdList.size();
assert(funcInfo->allParamSize + 4 < 65536);
// Save previous stack frame, and expand current by shift bytes
cmdList.push_back(VMCmd(cmdPushVTop, (unsigned short)(funcInfo->allParamSize + 4), shift));
// Generate function code
first->Compile();
if(funcInfo->retType == typeVoid)
{
// If function returns void, this is implicit return
cmdList.push_back(VMCmd(cmdReturn, 0, 1, 0));
}else{
// Stop program execution if user forgot the return statement
cmdList.push_back(VMCmd(cmdReturn, bitRetError, 1, 0));
}
funcInfo->codeSize = cmdList.size() - funcInfo->address;
}
void NodeFuncDef::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s FuncDef %s %s\r\n", typeInfo->GetFullTypeName(), funcInfo->name, (disabled ? " disabled" : ""));
if(!disabled)
{
GoDownB();
first->LogToStream(fGraph);
GoUp();
}else{
GoDownB();
LogToStreamExtra(fGraph);
GoUp();
}
}
void NodeFuncDef::TranslateToC(FILE *fOut)
{
unsigned int oldIndent = indentDepth;
indentDepth = 0;
if(!disabled)
{
funcInfo->retType->OutputCType(fOut, " ");
OutputCFunctionName(fOut, funcInfo);
fprintf(fOut, "(");
char name[NULLC_MAX_VARIABLE_NAME_LENGTH];
VariableInfo *param = funcInfo->firstParam;
for(; param; param = param->next)
{
sprintf(name, "%.*s_%d", param->name.end - param->name.begin, param->name.begin, param->pos);
param->varType->OutputCType(fOut, name);
fprintf(fOut, ", ");
}
if(funcInfo->type == FunctionInfo::THISCALL)
{
funcInfo->parentClass->OutputCType(fOut, "* __context");
}else if(funcInfo->type == FunctionInfo::LOCAL){
fprintf(fOut, "void* __");
OutputCFunctionName(fOut, funcInfo);
fprintf(fOut, "_ext_%d", funcInfo->allParamSize);
}else{
fprintf(fOut, "void* unused");
}
fprintf(fOut, ")\r\n{\r\n");
indentDepth++;
VariableInfo *local = funcInfo->firstLocal;
for(; local; local = local->next)
{
OutputIdent(fOut);
const char *namePrefix = *local->name.begin == '$' ? "__" : "";
unsigned int nameShift = *local->name.begin == '$' ? 1 : 0;
unsigned int length = sprintf(name, "%s%.*s_%d", namePrefix, local->name.end - local->name.begin-nameShift, local->name.begin+nameShift, local->pos);
for(unsigned int k = 0; k < length; k++)
{
if(name[k] == ':' || name[k] == '$')
name[k] = '_';
}
local->varType->OutputCType(fOut, name);
fprintf(fOut, ";\r\n");
}
first->TranslateToC(fOut);
indentDepth--;
fprintf(fOut, "}\r\n");
}else{
indentDepth++;
TranslateToCExtra(fOut);
indentDepth--;
}
indentDepth = oldIndent;
}
//////////////////////////////////////////////////////////////////////////
// Node that calls function
NodeFuncCall::NodeFuncCall(FunctionInfo *info, FunctionType *type)
{
// Function description
funcInfo = info;
// Function type description
funcType = type;
// Result type is fetched from function type
typeInfo = funcType->retType;
if(funcInfo && funcInfo->type == FunctionInfo::LOCAL)
first = TakeLastNode();
if(!funcInfo)
first = TakeLastNode();
if(funcType->paramCount > 0)
{
paramHead = paramTail = TakeLastNode();
if(paramHead->nodeType == typeNodeNumber && funcType->paramType[0] != paramHead->typeInfo)
((NodeNumber*)paramHead)->ConvertTo(funcType->paramType[0]);
}else{
paramHead = paramTail = NULL;
}
// Take nodes for all parameters
for(unsigned int i = 1; i < funcType->paramCount; i++)
{
paramTail->next = TakeLastNode();
TypeInfo *paramType = funcType->paramType[i];
if(paramTail->next->nodeType == typeNodeNumber && paramType != paramTail->next->typeInfo)
((NodeNumber*)paramTail->next)->ConvertTo(paramType);
paramTail->next->prev = paramTail;
paramTail = paramTail->next;
}
if(funcInfo && funcInfo->type == FunctionInfo::THISCALL)
first = TakeLastNode();
nodeType = typeNodeFuncCall;
}
NodeFuncCall::~NodeFuncCall()
{
}
void NodeFuncCall::Compile()
{
CompileExtra();
// Find parameter values
if(first)
first->Compile();
else if(funcInfo)
cmdList.push_back(VMCmd(cmdPushImmt, 0));
if(funcType->paramCount > 0)
{
NodeZeroOP *curr = paramHead;
TypeInfo **paramType = funcType->paramType + funcType->paramCount - 1;
do
{
if(*paramType == typeFloat && curr->nodeType == typeNodeNumber)
{
float num = (float)((NodeNumber*)curr)->GetDouble();
cmdList.push_back(VMCmd(cmdPushImmt, *(int*)&num));
}else{
// Compute parameter value
curr->Compile();
// Convert it to type that function expects
ConvertFirstToSecond(curr->typeInfo->stackType, (*paramType)->stackType);
if(*paramType == typeFloat)
cmdList.push_back(VMCmd(cmdDtoF));
}
curr = curr->next;
paramType--;
}while(curr);
}
unsigned int ID = CodeInfo::FindFunctionByPtr(funcInfo);
unsigned short helper = (unsigned short)((typeInfo->type == TypeInfo::TYPE_COMPLEX || typeInfo->type == TypeInfo::TYPE_VOID) ? typeInfo->size : (bitRetSimple | operTypeForStackType[typeInfo->stackType]));
if(funcInfo)
cmdList.push_back(VMCmd(cmdCall, helper, ID));
else
cmdList.push_back(VMCmd(cmdCallPtr, helper, funcType->paramSize));
}
void NodeFuncCall::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s FuncCall '%s' %d\r\n", typeInfo->GetFullTypeName(), (funcInfo ? funcInfo->name : "$ptr"), funcType->paramCount);
GoDown();
LogToStreamExtra(fGraph);
if(first)
first->LogToStream(fGraph);
NodeZeroOP *curr = paramTail;
while(curr)
{
if(curr == paramHead)
{
GoUp();
GoDownB();
}
curr->LogToStream(fGraph);
curr = curr->prev;
}
GoUp();
}
void NodeFuncCall::TranslateToC(FILE *fOut)
{
TranslateToCExtra(fOut);
if(funcInfo)
OutputCFunctionName(fOut, funcInfo);
if(!funcInfo)
{
fprintf(fOut, "((");
funcType->retType->OutputCType(fOut, "");
fprintf(fOut, "(*)(");
NodeZeroOP *curr = paramTail;
TypeInfo **paramType = funcType->paramType;
while(curr)
{
(*paramType)->OutputCType(fOut, "");
fprintf(fOut, ", ");
curr = curr->prev;
paramType++;
}
fprintf(fOut, "void*))");
fprintf(fOut, "(");
first->TranslateToC(fOut);
fprintf(fOut, ").ptr)");
}
fprintf(fOut, "(");
NodeZeroOP *curr = paramTail;
TypeInfo **paramType = funcType->paramType;
while(curr)
{
if(*paramType != curr->typeInfo)
{
fprintf(fOut, "(");
(*paramType)->OutputCType(fOut, "");
fprintf(fOut, ")(");
}
curr->TranslateToC(fOut);
if(*paramType != curr->typeInfo)
fprintf(fOut, ")");
fprintf(fOut, ", ");
curr = curr->prev;
paramType++;
}
if(!funcInfo)
fprintf(fOut, "(");
if(first)
first->TranslateToC(fOut);
else if(funcInfo)
fprintf(fOut, "(void*)0");
if(!funcInfo)
fprintf(fOut, ").context");
fprintf(fOut, ")");
}
//////////////////////////////////////////////////////////////////////////
// Node that fetches variable value
NodeGetAddress::NodeGetAddress(VariableInfo* vInfo, int vAddress, bool absAddr, TypeInfo *retInfo)
{
assert(retInfo);
varInfo = vInfo;
addressOriginal = varAddress = vAddress;
absAddress = absAddr;
typeOrig = retInfo;
typeInfo = CodeInfo::GetReferenceType(typeOrig);
nodeType = typeNodeGetAddress;
}
NodeGetAddress::~NodeGetAddress()
{
}
bool NodeGetAddress::IsAbsoluteAddress()
{
return absAddress;
}
void NodeGetAddress::IndexArray(int shift)
{
assert(typeOrig->arrLevel != 0);
varAddress += typeOrig->subType->size * shift;
typeOrig = typeOrig->subType;
typeInfo = CodeInfo::GetReferenceType(typeOrig);
}
void NodeGetAddress::ShiftToMember(TypeInfo::MemberVariable *member)
{
assert(member);
varAddress += member->offset;
typeOrig = member->type;
typeInfo = CodeInfo::GetReferenceType(typeOrig);
}
void NodeGetAddress::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
cmdList.push_back(VMCmd(cmdGetAddr, absAddress ? 0 : 1, varAddress));
}
void NodeGetAddress::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s GetAddress ", typeInfo->GetFullTypeName());
if(varInfo)
fprintf(fGraph, "%s '%.*s'", varInfo->varType->GetFullTypeName(), varInfo->name.end-varInfo->name.begin, varInfo->name.begin);
else
fprintf(fGraph, "$$$");
fprintf(fGraph, " (%d %s)\r\n", (int)varAddress, (absAddress ? " absolute" : " relative"));
LogToStreamExtra(fGraph);
}
void NodeGetAddress::TranslateToC(FILE *fOut)
{
if(head)
fprintf(fOut, "(");
NodeZeroOP *curr = head;
while(curr)
{
assert(curr->nodeType == typeNodePopOp);
((NodePopOp*)curr)->GetFirstNode()->TranslateToC(fOut);
fprintf(fOut, ", ");
curr = curr->next;
}
TranslateToCEx(fOut, true);
if(head)
fprintf(fOut, ")");
}
void NodeGetAddress::TranslateToCEx(FILE *fOut, bool takeAddress)
{
if(takeAddress)
fprintf(fOut, "&");
if(varInfo && varInfo->nameHash != GetStringHash("this"))
{
const char *namePrefix = *varInfo->name.begin == '$' ? "__" : "";
unsigned int nameShift = *varInfo->name.begin == '$' ? 1 : 0;
fprintf(fOut, varAddress - addressOriginal ? "%s%.*s%+d" : "%s%.*s", namePrefix, varInfo->name.end-varInfo->name.begin-nameShift, varInfo->name.begin+nameShift, (varAddress - addressOriginal) / (typeOrig->size ? typeOrig->size : 1));
if(varInfo->blockDepth > 1)
fprintf(fOut, "_%d", varInfo->pos);
}else{
fprintf(fOut, "__context");
}
}
//////////////////////////////////////////////////////////////////////////
NodeGetUpvalue::NodeGetUpvalue(FunctionInfo* functionInfo, int closureOffset, int closureElement, TypeInfo *retInfo)
{
closurePos = closureOffset;
closureElem = closureElement;
typeInfo = retInfo;
parentFunc = functionInfo;
nodeType = typeNodeGetUpvalue;
}
NodeGetUpvalue::~NodeGetUpvalue()
{
}
void NodeGetUpvalue::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
cmdList.push_back(VMCmd(cmdPushInt, ADDRESS_RELATIVE, (unsigned short)typeInfo->size, closurePos));
cmdList.push_back(VMCmd(cmdPushIntStk, 0, (unsigned short)typeInfo->size, closureElem));
}
void NodeGetUpvalue::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s GetUpvalue (base + %d)[%d]\r\n", typeInfo->GetFullTypeName(), closurePos, closureElem);
LogToStreamExtra(fGraph);
}
void NodeGetUpvalue::TranslateToC(FILE *fOut)
{
fprintf(fOut, "(");
typeInfo->OutputCType(fOut, "");
fprintf(fOut, ")");
fprintf(fOut, "((__nullcUpvalue*)((char*)__");
OutputCFunctionName(fOut, parentFunc);
fprintf(fOut, "_ext_%d + %d))->ptr", closurePos, closureElem);
}
//////////////////////////////////////////////////////////////////////////
NodeConvertPtr::NodeConvertPtr(TypeInfo *dstType)
{
assert(dstType);
typeInfo = dstType;
first = TakeLastNode();
nodeType = typeNodeConvertPtr;
}
NodeConvertPtr::~NodeConvertPtr()
{
}
void NodeConvertPtr::Compile()
{
CompileExtra();
first->Compile();
if(typeInfo == typeObject || typeInfo == typeTypeid)
{
cmdList.push_back(VMCmd(cmdPushTypeID, first->typeInfo->subType->typeIndex));
}else{
cmdList.push_back(VMCmd(cmdConvertPtr, typeInfo->subType->typeIndex));
}
}
void NodeConvertPtr::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s ConvertPtr :\r\n", typeInfo->GetFullTypeName());
GoDownB();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
}
void NodeConvertPtr::TranslateToC(FILE *fOut)
{
if(typeInfo == typeTypeid)
{
fprintf(fOut, "%d", first->typeInfo->subType->typeIndex);
return;
}
TranslateToCExtra(fOut);
if(typeInfo == typeObject || typeInfo == typeTypeid)
{
fprintf(fOut, "__nullcMakeAutoRef((void*)");
first->TranslateToC(fOut);
fprintf(fOut, ", %d)", first->typeInfo->subType->typeIndex);
}else{
fprintf(fOut, "(");
typeInfo->OutputCType(fOut, "");
fprintf(fOut, ")");
fprintf(fOut, "__nullcGetAutoRef(");
first->TranslateToC(fOut);
fprintf(fOut, ", %d)", typeInfo->subType->typeIndex);
}
}
//////////////////////////////////////////////////////////////////////////
// Node that sets value to the variable
NodeVariableSet::NodeVariableSet(TypeInfo* targetType, bool firstDefinition, bool swapNodes)
{
assert(targetType);
typeInfo = targetType->subType;
if(swapNodes)
second = TakeLastNode();
// Address of the target variable
first = TakeLastNode();
assert(first->typeInfo->refLevel != 0);
if(!swapNodes)
second = TakeLastNode();
if(typeInfo->arrLevel < 2 && typeInfo->refLevel == 0 && second->nodeType == typeNodeNumber)
static_cast<NodeNumber*>(second)->ConvertTo(typeInfo);
// If this is the first array definition and value is array sub-type, we set it to all array elements
arrSetAll = (firstDefinition && typeInfo->arrLevel == 1 && typeInfo->arrSize != -1 && second->typeInfo->arrLevel == 0 && second->typeInfo->refLevel == 0 && typeInfo->subType->type != TypeInfo::TYPE_COMPLEX && second->typeInfo->type != TypeInfo::TYPE_COMPLEX);
if(second->typeInfo == typeVoid)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: cannot convert from void to %s", typeInfo->GetFullTypeName());
if(typeInfo == typeVoid)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: cannot convert from %s to void", second->typeInfo->GetFullTypeName());
// If types don't match
if(second->typeInfo != typeInfo)
{
// If it is not build-in basic types or if pointers point to different types
if(typeInfo->type == TypeInfo::TYPE_COMPLEX || second->typeInfo->type == TypeInfo::TYPE_COMPLEX || typeInfo->subType != second->typeInfo->subType)
{
if(!(typeInfo->arrLevel != 0 && second->typeInfo->arrLevel == 0 && arrSetAll))
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: cannot convert '%s' to '%s'", second->typeInfo->GetFullTypeName(), typeInfo->GetFullTypeName());
}
}
absAddress = true;
knownAddress = false;
addrShift = 0;
if(first->nodeType == typeNodeGetAddress)
{
absAddress = static_cast<NodeGetAddress*>(first)->IsAbsoluteAddress();
addrShift = static_cast<NodeGetAddress*>(first)->varAddress;
knownAddress = true;
}
#ifndef NULLC_ENABLE_C_TRANSLATION
if(first->nodeType == typeNodeShiftAddress)
{
addrShift = static_cast<NodeShiftAddress*>(first)->memberShift;
NodeZeroOP *oldFirst = first;
first = static_cast<NodeShiftAddress*>(first)->first;
static_cast<NodeShiftAddress*>(oldFirst)->first = NULL;
}
if(first->nodeType == typeNodeArrayIndex && static_cast<NodeArrayIndex*>(first)->knownShift)
{
addrShift = static_cast<NodeArrayIndex*>(first)->shiftValue;
NodeZeroOP *oldFirst = first;
first = static_cast<NodeArrayIndex*>(first)->first;
static_cast<NodeArrayIndex*>(oldFirst)->first = NULL;
}
#endif
if(arrSetAll)
{
elemCount = typeInfo->size / typeInfo->subType->size;
typeInfo = typeInfo->subType;
}
nodeType = typeNodeVariableSet;
}
NodeVariableSet::~NodeVariableSet()
{
}
void NodeVariableSet::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
asmStackType asmST = typeInfo->stackType;
asmDataType asmDT = typeInfo->dataType;
second->Compile();
ConvertFirstToSecond(second->typeInfo->stackType, asmST);
if(!knownAddress)
first->Compile();
if(arrSetAll)
{
assert(knownAddress);
cmdList.push_back(VMCmd(cmdPushImmt, elemCount));
cmdList.push_back(VMCmd(cmdSetRange, absAddress ? ADDRESS_ABOLUTE : ADDRESS_RELATIVE, (unsigned short)(asmDT), addrShift));
}else{
if(knownAddress)
{
cmdList.push_back(VMCmd(cmdMovType[asmDT>>2], absAddress ? ADDRESS_ABOLUTE : ADDRESS_RELATIVE, (unsigned short)typeInfo->size, addrShift));
}else{
cmdList.push_back(VMCmd(cmdMovTypeStk[asmDT>>2], asmST == STYPE_DOUBLE ? 1 : 0, (unsigned short)typeInfo->size, addrShift));
}
}
}
void NodeVariableSet::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s VariableSet %s\r\n", typeInfo->GetFullTypeName(), (arrSetAll ? "set all elements" : ""));
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
GoDownB();
second->LogToStream(fGraph);
GoUp();
}
void NodeVariableSet::TranslateToC(FILE *fOut)
{
TranslateToCExtra(fOut);
if(arrSetAll)
{
if(typeInfo == typeChar)
fprintf(fOut, "memset(*(");
else
fprintf(fOut, "__nullcSetArray(*(");
first->TranslateToC(fOut);
fprintf(fOut, ".ptr), ");
second->TranslateToC(fOut);
fprintf(fOut, ", %d)", elemCount);
}else{
if(second->nodeType == typeNodeExpressionList && second->typeInfo->subType == typeChar && second->typeInfo->arrSize != TypeInfo::UNSIZED_ARRAY)
{
fprintf(fOut, "memcpy((");
first->TranslateToC(fOut);
fprintf(fOut, ")->ptr, ");
second->TranslateToC(fOut);
fprintf(fOut, ", %d)", first->typeInfo->subType->size);
}else{
fprintf(fOut, "*(");
first->TranslateToC(fOut);
fprintf(fOut, ") = ");
if(first->typeInfo->subType != second->typeInfo || (first->typeInfo->subType->refLevel && second->nodeType == typeNodeFuncCall))
{
fprintf(fOut, "(");
first->typeInfo->subType->OutputCType(fOut, "");
fprintf(fOut, ")");
}
second->TranslateToC(fOut);
}
}
}
//////////////////////////////////////////////////////////////////////////
// Node to change variable value with following operations: += -= *= /= **=
NodeVariableModify::NodeVariableModify(TypeInfo* targetType, CmdID cmd)
{
assert(targetType);
typeInfo = targetType->subType;
cmdID = cmd;
second = TakeLastNode();
// Address of the target variable
first = TakeLastNode();
assert(first->typeInfo->refLevel != 0);
if(second->typeInfo == typeVoid)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: cannot convert from void to %s", typeInfo->GetFullTypeName());
if(typeInfo == typeVoid)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: cannot convert from %s to void", second->typeInfo->GetFullTypeName());
if(first->typeInfo->subType->refLevel != 0 || second->typeInfo->refLevel != 0 || typeInfo->type == TypeInfo::TYPE_COMPLEX || second->typeInfo->type == TypeInfo::TYPE_COMPLEX)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: there is no build-in operator for types '%s' and '%s'", typeInfo->GetFullTypeName(), second->typeInfo->GetFullTypeName());
// If types don't match
if(second->typeInfo != typeInfo)
{
// If it is not build-in basic types or if pointers point to different types
if(typeInfo->type == TypeInfo::TYPE_COMPLEX || second->typeInfo->type == TypeInfo::TYPE_COMPLEX || typeInfo->subType != second->typeInfo->subType)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: cannot convert '%s' to '%s'", second->typeInfo->GetFullTypeName(), typeInfo->GetFullTypeName());
}
absAddress = true;
knownAddress = false;
addrShift = 0;
#ifndef NULLC_ENABLE_C_TRANSLATION
if(first->nodeType == typeNodeGetAddress)
{
absAddress = static_cast<NodeGetAddress*>(first)->IsAbsoluteAddress();
addrShift = static_cast<NodeGetAddress*>(first)->varAddress;
knownAddress = true;
}
if(first->nodeType == typeNodeShiftAddress)
{
addrShift = static_cast<NodeShiftAddress*>(first)->memberShift;
NodeZeroOP *oldFirst = first;
first = static_cast<NodeShiftAddress*>(first)->first;
static_cast<NodeShiftAddress*>(oldFirst)->first = NULL;
}
if(first->nodeType == typeNodeArrayIndex && static_cast<NodeArrayIndex*>(first)->knownShift)
{
addrShift = static_cast<NodeArrayIndex*>(first)->shiftValue;
NodeZeroOP *oldFirst = first;
first = static_cast<NodeArrayIndex*>(first)->first;
static_cast<NodeArrayIndex*>(oldFirst)->first = NULL;
}
#endif
nodeType = typeNodeVariableModify;
}
NodeVariableModify::~NodeVariableModify()
{
}
void NodeVariableModify::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
asmStackType asmSTfirst = typeInfo->stackType;
asmDataType asmDT = typeInfo->dataType;
asmStackType asmSTsecond = second->typeInfo->stackType;
// Calculate address of the first operand, if it isn't known
if(!knownAddress)
first->Compile();
// Put first operand on top of the stack
if(knownAddress)
cmdList.push_back(VMCmd(cmdPushType[asmDT>>2], absAddress ? ADDRESS_ABOLUTE : ADDRESS_RELATIVE, (unsigned short)typeInfo->size, addrShift));
else
cmdList.push_back(VMCmd(cmdPushTypeStk[asmDT>>2], asmDT == DTYPE_DOUBLE ? 1 : 0, (unsigned short)typeInfo->size, addrShift));
// Convert it to the type that results from operation made between two operands.
asmStackType asmSTresult = ConvertFirstForSecond(asmSTfirst, asmSTsecond);
// Calculate second operand value
second->Compile();
// Convert it to the type that results from operation made between two operands.
ConvertFirstForSecond(asmSTsecond, asmSTresult);
// Make a binary operation of corresponding type
if(asmSTresult == STYPE_INT)
cmdList.push_back(VMCmd((InstructionCode)(cmdID)));
else if(asmSTresult == STYPE_LONG)
cmdList.push_back(VMCmd((InstructionCode)(cmdID - cmdAdd + cmdAddL)));
else if(asmSTresult == STYPE_DOUBLE)
cmdList.push_back(VMCmd((InstructionCode)(cmdID - cmdAdd + cmdAddD)));
else
assert(!"unknown operator type in NodeVariableModify");
// Convert to the type of first operand
ConvertFirstToSecond(asmSTresult, asmSTfirst);
// Calculate address of the first operand, if it isn't known
if(!knownAddress)
first->Compile();
// Put first operand on top of the stack
if(knownAddress)
{
cmdList.push_back(VMCmd(cmdMovType[asmDT>>2], absAddress ? ADDRESS_ABOLUTE : ADDRESS_RELATIVE, (unsigned short)typeInfo->size, addrShift));
}else{
cmdList.push_back(VMCmd(cmdMovTypeStk[asmDT>>2], asmDT == DTYPE_DOUBLE ? 1 : 0, (unsigned short)typeInfo->size, addrShift));
}
}
void NodeVariableModify::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s VariableModify\r\n", typeInfo->GetFullTypeName());
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
GoDownB();
second->LogToStream(fGraph);
GoUp();
}
void NodeVariableModify::TranslateToC(FILE *fOut)
{
TranslateToCExtra(fOut);
if(cmdID == cmdPow)
{
fprintf(fOut, "__nullcPowSet(");
first->TranslateToC(fOut);
fprintf(fOut, ", ");
second->TranslateToC(fOut);
fprintf(fOut, ")");
}else{
const char *operation = "???";
switch(cmdID)
{
case cmdAdd:
operation = "+=";
break;
case cmdSub:
operation = "-=";
break;
case cmdMul:
operation = "*=";
break;
case cmdDiv:
operation = "/=";
break;
}
fprintf(fOut, "*(");
first->TranslateToC(fOut);
fprintf(fOut, ") %s ", operation);
second->TranslateToC(fOut);
}
}
//////////////////////////////////////////////////////////////////////////
// Node that calculates address of the array element
NodeArrayIndex::NodeArrayIndex(TypeInfo* parentType)
{
assert(parentType);
typeParent = parentType;
typeInfo = CodeInfo::GetReferenceType(parentType->subType);
// Node that calculates array index
second = TakeLastNode();
if(second->typeInfo->type == TypeInfo::TYPE_COMPLEX || second->typeInfo->type == TypeInfo::TYPE_VOID)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: cannot index array with type '%s'", second->typeInfo->GetFullTypeName());
// Node that calculates address of the first array element
first = TakeLastNode();
shiftValue = 0;
knownShift = false;
if(second->nodeType == typeNodeNumber && typeParent->arrSize != TypeInfo::UNSIZED_ARRAY)
{
shiftValue = typeParent->subType->size * static_cast<NodeNumber*>(second)->GetInteger();
knownShift = true;
}
if(!knownShift && typeParent->subType->size > 65535)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: cannot index array when sizeof(%s) exceeds 65535 bytes", typeParent->subType->GetFullTypeName());
nodeType = typeNodeArrayIndex;
}
NodeArrayIndex::~NodeArrayIndex()
{
}
void NodeArrayIndex::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
// Get address of the first array element
first->Compile();
if(knownShift)
{
cmdList.push_back(VMCmd(cmdPushImmt, shiftValue));
// Add it to the address of the first element
cmdList.push_back(VMCmd(cmdAdd));
}else{
// Compute index value
second->Compile();
// Convert it to integer and multiply by the size of the element
if(second->typeInfo->stackType != STYPE_INT)
cmdList.push_back(VMCmd(second->typeInfo->stackType == STYPE_DOUBLE ? cmdDtoI : cmdLtoI));
cmdList.push_back(VMCmd(typeParent->arrSize == TypeInfo::UNSIZED_ARRAY ? cmdIndexStk : cmdIndex, (unsigned short)typeParent->subType->size, typeParent->arrSize));
}
}
void NodeArrayIndex::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s ArrayIndex %s known: %d shiftval: %d\r\n", typeInfo->GetFullTypeName(), typeParent->GetFullTypeName(), knownShift, shiftValue);
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
GoDownB();
second->LogToStream(fGraph);
GoUp();
}
void NodeArrayIndex::TranslateToC(FILE *fOut)
{
if(first->typeInfo->arrSize == TypeInfo::UNSIZED_ARRAY)
{
fprintf(fOut, "(");
fprintf(fOut, "(");
typeInfo->OutputCType(fOut, "");
fprintf(fOut, ")(");
first->TranslateToC(fOut);
fprintf(fOut, ").ptr + ");
if(second->typeInfo != typeInt)
fprintf(fOut, "(unsigned)(");
second->TranslateToC(fOut);
if(second->typeInfo != typeInt)
fprintf(fOut, ")");
fprintf(fOut, ")");
}else{
fprintf(fOut, "&(");
first->TranslateToC(fOut);
fprintf(fOut, ")");
fprintf(fOut, "->ptr");
fprintf(fOut, "[");
if(second->typeInfo != typeInt)
fprintf(fOut, "(unsigned)(");
second->TranslateToC(fOut);
if(second->typeInfo != typeInt)
fprintf(fOut, ")");
fprintf(fOut, "]");
}
}
//////////////////////////////////////////////////////////////////////////
// Node to get value by address (dereference pointer)
NodeDereference::NodeDereference(FunctionInfo* setClosure, unsigned int offsetToPrevClosure)
{
originalNode = first = TakeLastNode();
assert(first->typeInfo);
assert(first->typeInfo->subType);
typeInfo = first->typeInfo->subType;
absAddress = true;
knownAddress = false;
addrShift = 0;
closureFunc = setClosure;
offsetToPreviousClosure = offsetToPrevClosure;
neutralized = false;
#ifndef NULLC_ENABLE_C_TRANSLATION
if(first->nodeType == typeNodeGetAddress)
{
absAddress = static_cast<NodeGetAddress*>(first)->IsAbsoluteAddress();
addrShift = static_cast<NodeGetAddress*>(first)->varAddress;
knownAddress = true;
}
if(first->nodeType == typeNodeShiftAddress)
{
addrShift = static_cast<NodeShiftAddress*>(first)->memberShift;
NodeZeroOP *oldFirst = first;
first = static_cast<NodeShiftAddress*>(first)->first;
static_cast<NodeShiftAddress*>(oldFirst)->first = NULL;
}
if(first->nodeType == typeNodeArrayIndex && static_cast<NodeArrayIndex*>(first)->knownShift)
{
addrShift = static_cast<NodeArrayIndex*>(first)->shiftValue;
NodeZeroOP *oldFirst = first;
first = static_cast<NodeArrayIndex*>(first)->first;
static_cast<NodeArrayIndex*>(oldFirst)->first = NULL;
}
#endif
nodeType = typeNodeDereference;
}
NodeDereference::~NodeDereference()
{
}
void NodeDereference::Neutralize()
{
neutralized = true;
typeInfo = originalNode->typeInfo;
}
void NodeDereference::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
if(typeInfo->size == 0)
return;
asmDataType asmDT = typeInfo->dataType;
if(neutralized)
{
originalNode->Compile();
}else{
if(closureFunc)
{
first->Compile();
cmdList.push_back(VMCmd(cmdCreateClosure, (unsigned short)offsetToPreviousClosure, CodeInfo::FindFunctionByPtr(closureFunc)));
}else{
if(!knownAddress)
first->Compile();
if(knownAddress)
cmdList.push_back(VMCmd(cmdPushType[asmDT>>2], absAddress ? ADDRESS_ABOLUTE : ADDRESS_RELATIVE, (unsigned short)typeInfo->size, addrShift));
else
cmdList.push_back(VMCmd(cmdPushTypeStk[asmDT>>2], asmDT == DTYPE_DOUBLE ? 1 : 0, (unsigned short)typeInfo->size, addrShift));
}
}
}
void NodeDereference::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s Dereference%s", typeInfo->GetFullTypeName(), closureFunc ? " and create closure" : "");
if(knownAddress)
fprintf(fGraph, " at known address [%s%d]\r\n", absAddress ? "" : "base+", addrShift);
else
fprintf(fGraph, " at [ptr+%d]\r\n", addrShift);
GoDownB();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
}
bool nodeDereferenceEndInComma = false;
void NodeDereference::TranslateToC(FILE *fOut)
{
TranslateToCExtra(fOut);
if(closureFunc)
{
OutputIdent(fOut);
assert(first->nodeType == typeNodeVariableSet);
assert(((NodeOneOP*)first)->GetFirstNode()->nodeType == typeNodeGetAddress);
VariableInfo *closure = ((NodeGetAddress*)((NodeOneOP*)first)->GetFirstNode())->varInfo;
char closureName[NULLC_MAX_VARIABLE_NAME_LENGTH];
const char *namePrefix = *closure->name.begin == '$' ? "__" : "";
unsigned int nameShift = *closure->name.begin == '$' ? 1 : 0;
unsigned int length = sprintf(closureName, "%s%.*s_%d", namePrefix, closure->name.end - closure->name.begin-nameShift, closure->name.begin+nameShift, closure->pos);
for(unsigned int k = 0; k < length; k++)
{
if(closureName[k] == ':' || closureName[k] == '$')
closureName[k] = '_';
}
fprintf(fOut, "(%s = (", closureName);
closure->varType->OutputCType(fOut, "");
fprintf(fOut, ")__newS(%d, (void*)0)),\r\n", closure->varType->subType->size);
unsigned int pos = 0;
for(FunctionInfo::ExternalInfo *curr = closureFunc->firstExternal; curr; curr = curr->next)
{
OutputIdent(fOut);
fprintf(fOut, "(%s->ptr[%d] = ", closureName, pos);
VariableInfo *varInfo = curr->variable;
char variableName[NULLC_MAX_VARIABLE_NAME_LENGTH];
if(varInfo->nameHash == GetStringHash("this"))
{
strcpy(variableName, "__context");
}else{
namePrefix = *varInfo->name.begin == '$' ? "__" : "";
nameShift = *varInfo->name.begin == '$' ? 1 : 0;
sprintf(variableName, "%s%.*s_%d", namePrefix, varInfo->name.end-varInfo->name.begin-nameShift, varInfo->name.begin+nameShift, varInfo->pos);
}
if(curr->targetLocal)
{
fprintf(fOut, "(int*)&%s", variableName);
}else{
assert(closureFunc->parentFunc);
fprintf(fOut, "((int**)__%s_%d_ext_%d)[%d]", closureFunc->parentFunc->name, CodeInfo::FindFunctionByPtr(closureFunc->parentFunc), closureFunc->parentFunc->allParamSize, curr->targetPos >> 2);
}
fprintf(fOut, "),\r\n");
OutputIdent(fOut);
fprintf(fOut, "(%s->ptr[%d] = (int*)__upvalue_%d_%s),\r\n", closureName, pos+1, CodeInfo::FindFunctionByPtr(varInfo->parentFunction), variableName);
OutputIdent(fOut);
fprintf(fOut, "(%s->ptr[%d] = (int*)%d),\r\n", closureName, pos+2, curr->variable->varType->size);
OutputIdent(fOut);
fprintf(fOut, "(__upvalue_%d_%s = (__nullcUpvalue*)&%s->ptr[%d])", CodeInfo::FindFunctionByPtr(varInfo->parentFunction), variableName, closureName, pos);
if(curr->next)
fprintf(fOut, ",\r\n");
pos += ((varInfo->varType->size >> 2) < 3 ? 3 : 1 + (varInfo->varType->size >> 2));
}
if(nodeDereferenceEndInComma)
fprintf(fOut, ",\r\n");
else
fprintf(fOut, ";\r\n");
}else{
if(!neutralized)
fprintf(fOut, "*(");
first->TranslateToC(fOut);
if(!neutralized)
fprintf(fOut, ")");
}
}
//////////////////////////////////////////////////////////////////////////
// Node that shifts address to the class member
NodeShiftAddress::NodeShiftAddress(TypeInfo::MemberVariable *classMember)
{
member = classMember;
memberShift = member->offset;
typeInfo = CodeInfo::GetReferenceType(member->type);
first = TakeLastNode();
#ifndef NULLC_ENABLE_C_TRANSLATION
if(first->nodeType == typeNodeShiftAddress)
{
memberShift += static_cast<NodeShiftAddress*>(first)->memberShift;
NodeZeroOP *oldFirst = first;
first = static_cast<NodeShiftAddress*>(first)->first;
static_cast<NodeShiftAddress*>(oldFirst)->first = NULL;
}
#endif
nodeType = typeNodeShiftAddress;
}
NodeShiftAddress::~NodeShiftAddress()
{
}
void NodeShiftAddress::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
// Get variable address
first->Compile();
if(memberShift)
{
cmdList.push_back(VMCmd(cmdPushImmt, memberShift));
// Add the shift to the address
cmdList.push_back(VMCmd(cmdAdd));
}
}
void NodeShiftAddress::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s ShiftAddress [+%d]\r\n", typeInfo->GetFullTypeName(), memberShift);
GoDownB();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
}
void NodeShiftAddress::TranslateToC(FILE *fOut)
{
fprintf(fOut, "&(", member->name);
first->TranslateToC(fOut);
fprintf(fOut, ")->%s", member->name);
}
//////////////////////////////////////////////////////////////////////////
// Node for increment and decrement operations
NodePreOrPostOp::NodePreOrPostOp(bool isInc, bool preOp)
{
first = TakeLastNode();
assert(first->typeInfo->refLevel != 0);
typeInfo = first->typeInfo->subType;
incOp = isInc;
if(typeInfo->type == TypeInfo::TYPE_COMPLEX || typeInfo->refLevel != 0)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: %s is not supported on '%s'", (isInc ? "increment" : "decrement"), typeInfo->GetFullTypeName());
prefixOp = preOp;
optimised = false;
absAddress = true;
knownAddress = false;
addrShift = 0;
#ifndef NULLC_ENABLE_C_TRANSLATION
if(first->nodeType == typeNodeGetAddress)
{
absAddress = static_cast<NodeGetAddress*>(first)->IsAbsoluteAddress();
addrShift = static_cast<NodeGetAddress*>(first)->varAddress;
knownAddress = true;
}
if(first->nodeType == typeNodeShiftAddress)
{
addrShift = static_cast<NodeShiftAddress*>(first)->memberShift;
NodeZeroOP *oldFirst = first;
first = static_cast<NodeShiftAddress*>(first)->first;
static_cast<NodeShiftAddress*>(oldFirst)->first = NULL;
}
if(first->nodeType == typeNodeArrayIndex && static_cast<NodeArrayIndex*>(first)->knownShift)
{
addrShift = static_cast<NodeArrayIndex*>(first)->shiftValue;
NodeZeroOP *oldFirst = first;
first = static_cast<NodeArrayIndex*>(first)->first;
static_cast<NodeArrayIndex*>(oldFirst)->first = NULL;
}
#endif
nodeType = typeNodePreOrPostOp;
}
NodePreOrPostOp::~NodePreOrPostOp()
{
}
void NodePreOrPostOp::SetOptimised(bool doOptimisation)
{
optimised = doOptimisation;
}
void NodePreOrPostOp::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
asmStackType asmST = typeInfo->stackType;
asmDataType asmDT = typeInfo->dataType;
asmOperType aOT = operTypeForStackType[typeInfo->stackType];
InstructionCode pushCmd = knownAddress ? cmdPushType[asmDT>>2] : cmdPushTypeStk[asmDT>>2];
InstructionCode movCmd = knownAddress ? cmdMovType[asmDT>>2] : cmdMovTypeStk[asmDT>>2];
if(!knownAddress)
first->Compile();
cmdList.push_back(VMCmd(pushCmd, absAddress ? ADDRESS_ABOLUTE : ADDRESS_RELATIVE, (unsigned short)typeInfo->size, addrShift));
cmdList.push_back(VMCmd(incOp ? cmdIncType[aOT] : cmdDecType[aOT]));
if(!knownAddress)
first->Compile();
cmdList.push_back(VMCmd(movCmd, absAddress ? ADDRESS_ABOLUTE : ADDRESS_RELATIVE, (unsigned short)typeInfo->size, addrShift));
if(!prefixOp && !optimised)
cmdList.push_back(VMCmd(!incOp ? cmdIncType[aOT] : cmdDecType[aOT]));
if(optimised)
cmdList.push_back(VMCmd(cmdPop, stackTypeSize[asmST]));
}
void NodePreOrPostOp::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s PreOrPostOp %s\r\n", typeInfo->GetFullTypeName(), (prefixOp ? "prefix" : "postfix"));
GoDownB();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
}
void NodePreOrPostOp::TranslateToC(FILE *fOut)
{
if(head)
fprintf(fOut, "(");
NodeZeroOP *curr = head;
while(curr)
{
assert(curr->nodeType == typeNodePopOp);
((NodePopOp*)curr)->GetFirstNode()->TranslateToC(fOut);
fprintf(fOut, ", ");
curr = curr->next;
}
if(typeInfo == typeDouble || typeInfo == typeFloat)
{
if(optimised)
{
OutputIdent(fOut);
fprintf(fOut, "*(");
first->TranslateToC(fOut);
fprintf(fOut, incOp ? ") += 1.0" : ") -= 1.0");
}else{
if(prefixOp)
{
fprintf(fOut, "(*(");
first->TranslateToC(fOut);
fprintf(fOut, incOp ? ") += 1.0)" : ") -= 1.0)");
}else{
fprintf(fOut, "((*(");
first->TranslateToC(fOut);
fprintf(fOut, incOp ? ") += 1.0) - 1.0)" : ") -= 1.0) + 1.0)");
}
}
}else{
if(optimised)
OutputIdent(fOut);
if(prefixOp)
fprintf(fOut, incOp ? "++" : "--");
fprintf(fOut, "(*(");
first->TranslateToC(fOut);
fprintf(fOut, "))");
if(!prefixOp)
fprintf(fOut, incOp ? "++" : "--");
}
if(head)
fprintf(fOut, ")");
if(optimised)
fprintf(fOut, ";\r\n");
}
//////////////////////////////////////////////////////////////////////////
// Node that gets function address
NodeFunctionAddress::NodeFunctionAddress(FunctionInfo* functionInfo)
{
funcInfo = functionInfo;
typeInfo = funcInfo->funcType;
if(funcInfo->type == FunctionInfo::LOCAL || funcInfo->type == FunctionInfo::THISCALL)
first = TakeLastNode();
nodeType = typeNodeFunctionAddress;
}
NodeFunctionAddress::~NodeFunctionAddress()
{
}
void NodeFunctionAddress::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
unsigned int ID = CodeInfo::FindFunctionByPtr(funcInfo);
cmdList.push_back(VMCmd(cmdFuncAddr, ID));
if(funcInfo->type == FunctionInfo::NORMAL)
{
cmdList.push_back(VMCmd(cmdPushImmt, funcInfo->funcPtr ? ~0ul : 0));
}else if(funcInfo->type == FunctionInfo::LOCAL || funcInfo->type == FunctionInfo::THISCALL){
first->Compile();
}
}
void NodeFunctionAddress::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s FunctionAddress %s %s\r\n", typeInfo->GetFullTypeName(), funcInfo->name, (funcInfo->funcPtr ? " external" : ""));
LogToStreamExtra(fGraph);
if(first)
{
GoDownB();
first->LogToStream(fGraph);
GoUp();
}
}
void NodeFunctionAddress::TranslateToC(FILE *fOut)
{
fprintf(fOut, "(");
nodeDereferenceEndInComma = true;
TranslateToCExtra(fOut);
nodeDereferenceEndInComma = false;
OutputIdent(fOut);
fprintf(fOut, "__nullcMakeFunction((void*)");
OutputCFunctionName(fOut, funcInfo);
fprintf(fOut, ", ");
if(funcInfo->type == FunctionInfo::NORMAL)
{
fprintf(fOut, "(void*)%uu", funcInfo->funcPtr ? ~0ul : 0);
}else if(funcInfo->type == FunctionInfo::LOCAL || funcInfo->type == FunctionInfo::THISCALL){
if(first->nodeType == typeNodeDereference)
{
VariableInfo *closure = ((NodeGetAddress*)((NodeOneOP*)first)->GetFirstNode())->varInfo;
if(closure->nameHash == GetStringHash("this"))
{
fprintf(fOut, "__context");
}else{
char closureName[NULLC_MAX_VARIABLE_NAME_LENGTH];
const char *namePrefix = *closure->name.begin == '$' ? "__" : "";
unsigned int nameShift = *closure->name.begin == '$' ? 1 : 0;
unsigned int length = sprintf(closureName, "%s%.*s_%d", namePrefix, closure->name.end - closure->name.begin-nameShift, closure->name.begin+nameShift, closure->pos);
for(unsigned int k = 0; k < length; k++)
{
if(closureName[k] == ':' || closureName[k] == '$')
closureName[k] = '_';
}
fprintf(fOut, "%s", closureName);
}
}else{
first->TranslateToC(fOut);
}
}
fprintf(fOut, "))");
}
//////////////////////////////////////////////////////////////////////////
// Node that applies binary operation on two values
NodeBinaryOp::NodeBinaryOp(CmdID cmd)
{
// Binary operation
cmdID = cmd;
second = TakeLastNode();
first = TakeLastNode();
bool logicalOp = (cmd >= cmdLess && cmd <= cmdNEqual) || (cmd >= cmdLogAnd && cmd <= cmdLogXor);
// Binary operations on complex types are not present at the moment
if(first->typeInfo->type == TypeInfo::TYPE_COMPLEX || second->typeInfo->type == TypeInfo::TYPE_COMPLEX)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: operation %s is not supported on '%s' and '%s'", binCommandToText[cmdID - cmdAdd], first->typeInfo->GetFullTypeName(), second->typeInfo->GetFullTypeName());
if((first->typeInfo->refLevel != 0 || second->typeInfo->refLevel != 0) && !(first->typeInfo->refLevel == second->typeInfo->refLevel && logicalOp))
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: operation %s is not supported on '%s' and '%s'", binCommandToText[cmdID - cmdAdd], first->typeInfo->GetFullTypeName(), second->typeInfo->GetFullTypeName());
if(first->typeInfo == typeVoid)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: first operator returns void");
if(second->typeInfo == typeVoid)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: second operator returns void");
if((first->typeInfo == typeDouble || first->typeInfo == typeFloat || second->typeInfo == typeDouble || second->typeInfo == typeFloat) && (cmd >= cmdShl && cmd <= cmdLogXor))
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: binary operations are not available on floating-point numbers");
// Find the type or resulting value
typeInfo = ChooseBinaryOpResultType(first->typeInfo, second->typeInfo);
if(first->nodeType == typeNodeNumber && first->typeInfo != typeInfo)
((NodeNumber*)first)->ConvertTo(typeInfo);
if(second->nodeType == typeNodeNumber && second->typeInfo != typeInfo)
((NodeNumber*)second)->ConvertTo(typeInfo);
typeInfo = logicalOp ? typeInt : typeInfo;
nodeType = typeNodeBinaryOp;
}
NodeBinaryOp::~NodeBinaryOp()
{
}
void NodeBinaryOp::Compile()
{
asmStackType fST = first->typeInfo->stackType, sST = second->typeInfo->stackType;
CompileExtra();
if(cmdID == cmdLogOr || cmdID == cmdLogAnd)
{
first->Compile();
// Convert long to int with | operation between parts of long (otherwise, we would've truncated 64 bit value)
if(fST == STYPE_LONG)
cmdList.push_back(VMCmd(cmdBitOr));
// If it's operator || and first argument is true, jump to push 1 as result
// If it's operator ^^ and first argument is false, jump to push 0 as result
cmdList.push_back(VMCmd(cmdID == cmdLogOr ? cmdJmpNZ : cmdJmpZ, ~0ul)); // Jump address will be fixed later on
unsigned int specialJmp1 = cmdList.size() - 1;
second->Compile();
if(sST == STYPE_LONG)
cmdList.push_back(VMCmd(cmdBitOr));
// If it's operator || and first argument is true, jump to push 1 as result
// If it's operator ^^ and first argument is false, jump to push 0 as result
cmdList.push_back(VMCmd(cmdID == cmdLogOr ? cmdJmpNZ : cmdJmpZ, ~0ul)); // Jump address will be fixed later on
unsigned int specialJmp2 = cmdList.size() - 1;
// If it's operator ||, result is zero, and if it's operator &&, result is 1
cmdList.push_back(VMCmd(cmdPushImmt, cmdID == cmdLogOr ? 0 : 1));
// Skip command that sets opposite result
cmdList.push_back(VMCmd(cmdJmp, cmdList.size() + 2));
// Fix up jumps
cmdList[specialJmp1].argument = cmdList.size();
cmdList[specialJmp2].argument = cmdList.size();
// If it's early jump, for operator ||, result is one, and if it's operator &&, result is 0
cmdList.push_back(VMCmd(cmdPushImmt, cmdID == cmdLogOr ? 1 : 0));
}else{
// Compute first value
first->Compile();
// Convert it to the resulting type
fST = ConvertFirstForSecond(fST, sST);
// Compute second value
second->Compile();
// Convert it to the result type
sST = ConvertFirstForSecond(sST, fST);
// Apply binary operation
if(fST == STYPE_INT)
cmdList.push_back(VMCmd((InstructionCode)(cmdID)));
else if(fST == STYPE_LONG)
cmdList.push_back(VMCmd((InstructionCode)(cmdID - cmdAdd + cmdAddL)));
else if(fST == STYPE_DOUBLE)
cmdList.push_back(VMCmd((InstructionCode)(cmdID - cmdAdd + cmdAddD)));
else
assert(!"unknown operator type in NodeTwoAndCmdOp");
}
}
void NodeBinaryOp::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s NodeBinaryOp<%s> :\r\n", typeInfo->GetFullTypeName(), binCommandToText[cmdID-cmdAdd]);
assert(cmdID >= cmdAdd);
assert(cmdID <= cmdNEqualD);
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
GoDownB();
second->LogToStream(fGraph);
GoUp();
}
void NodeBinaryOp::TranslateToC(FILE *fOut)
{
TypeInfo *tmpType = ChooseBinaryOpResultType(first->typeInfo, second->typeInfo);
if(cmdID == cmdPow)
fprintf(fOut, "__nullcPow");
if(cmdID == cmdMod && typeInfo == typeDouble)
fprintf(fOut, "__nullcMod");
fprintf(fOut, "(");
if(cmdID == cmdLogXor)
fprintf(fOut, "!!");
if(tmpType != first->typeInfo)
{
fprintf(fOut, "(");
tmpType->OutputCType(fOut, "");
fprintf(fOut, ")");
}
first->TranslateToC(fOut);
if(!(cmdID == cmdPow || (cmdID == cmdMod && typeInfo == typeDouble)))
fprintf(fOut, ")");
fprintf(fOut, " %s ", cmdID == cmdLogXor ? "!=" : ((cmdID == cmdPow || (cmdID == cmdMod && typeInfo == typeDouble)) ? "," : binCommandToText[cmdID-cmdAdd]));
if(!(cmdID == cmdPow || (cmdID == cmdMod && typeInfo == typeDouble)))
fprintf(fOut, "(");
if(cmdID == cmdLogXor)
fprintf(fOut, "!!");
if(tmpType != second->typeInfo)
{
fprintf(fOut, "(");
tmpType->OutputCType(fOut, "");
fprintf(fOut, ")");
}
second->TranslateToC(fOut);
fprintf(fOut, ")");
}
//////////////////////////////////////////////////////////////////////////
// Node for compilation of if(){}else{} statement and conditional operator ?:
NodeIfElseExpr::NodeIfElseExpr(bool haveElse, bool isTerm)
{
// If else block is present
if(haveElse)
third = TakeLastNode();
second = TakeLastNode();
first = TakeLastNode();
if((first->typeInfo->type == TypeInfo::TYPE_COMPLEX && first->typeInfo != typeObject) || first->typeInfo->type == TypeInfo::TYPE_VOID)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: condition type cannot be '%s'", first->typeInfo->GetFullTypeName());
// If it is a conditional operator, the there is a resulting type different than void
if(isTerm)
typeInfo = second->typeInfo != third->typeInfo ? ChooseBinaryOpResultType(second->typeInfo, third->typeInfo) : second->typeInfo;
nodeType = typeNodeIfElseExpr;
}
NodeIfElseExpr::~NodeIfElseExpr()
{
}
void NodeIfElseExpr::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
// Child node structure: if(first) second; else third;
// Or, for conditional operator: first ? second : third;
// Compute condition
first->Compile();
if(first->typeInfo == typeObject)
cmdList.push_back(VMCmd(cmdPop, 4));
else if(first->typeInfo->stackType != STYPE_INT)
cmdList.push_back(VMCmd(first->typeInfo->stackType == STYPE_DOUBLE ? cmdDtoI : cmdBitOr));
// If false, jump to 'else' block, or out of statement, if there is no 'else'
cmdList.push_back(VMCmd(cmdJmpZ, ~0ul)); // Jump address will be fixed later on
unsigned int jmpOnFalse = cmdList.size()-1;
// Compile block for condition == true
second->Compile();
if(typeInfo != typeVoid)
ConvertFirstForSecond(second->typeInfo->stackType, third->typeInfo->stackType);
cmdList[jmpOnFalse].argument = cmdList.size(); // Fixup jump address
// If 'else' block is present, compile it
if(third)
{
// Put jump to exit statement at the end of main block
cmdList.push_back(VMCmd(cmdJmp, ~0ul)); // Jump address will be fixed later on
unsigned int jmpToEnd = cmdList.size()-1;
cmdList[jmpOnFalse].argument = cmdList.size(); // Fixup jump address
// Compile block for condition == false
third->Compile();
if(typeInfo != typeVoid)
ConvertFirstForSecond(third->typeInfo->stackType, second->typeInfo->stackType);
cmdList[jmpToEnd].argument = cmdList.size(); // Fixup jump address
}
}
void NodeIfElseExpr::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s IfExpression :\r\n", typeInfo->GetFullTypeName());
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
if(!third)
{
GoUp();
GoDownB();
}
second->LogToStream(fGraph);
if(third)
{
GoUp();
GoDownB();
third->LogToStream(fGraph);
}
GoUp();
}
void NodeIfElseExpr::TranslateToC(FILE *fOut)
{
if(typeInfo != typeVoid)
{
first->TranslateToC(fOut);
fprintf(fOut, " ? ");
second->TranslateToC(fOut);
fprintf(fOut, " : ");
third->TranslateToC(fOut);
}else{
OutputIdent(fOut);
fprintf(fOut, "if(");
first->TranslateToC(fOut);
fprintf(fOut, ")\r\n");
OutputIdent(fOut);
fprintf(fOut, "{\r\n");
indentDepth++;
second->TranslateToC(fOut);
indentDepth--;
if(third)
{
OutputIdent(fOut);
fprintf(fOut, "}else{\r\n");
indentDepth++;
third->TranslateToC(fOut);
indentDepth--;
}
OutputIdent(fOut);
fprintf(fOut, "}\r\n");
}
}
//////////////////////////////////////////////////////////////////////////
// Nod for compilation of for(){}
unsigned int currLoopDepth = 0;
const unsigned int TRANSLATE_MAX_LOOP_DEPTH = 64;
unsigned int currLoopID[TRANSLATE_MAX_LOOP_DEPTH];
NodeForExpr::NodeForExpr()
{
fourth = TakeLastNode();
third = TakeLastNode();
second = TakeLastNode();
first = TakeLastNode();
if((second->typeInfo->type == TypeInfo::TYPE_COMPLEX && second->typeInfo != typeObject) || second->typeInfo->type == TypeInfo::TYPE_VOID)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: condition type cannot be '%s'", second->typeInfo->GetFullTypeName());
nodeType = typeNodeForExpr;
}
NodeForExpr::~NodeForExpr()
{
}
void NodeForExpr::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
currLoopDepth++;
// Child node structure: for(first, second, third) fourth;
// Compile initialization node
first->Compile();
unsigned int posTestExpr = cmdList.size();
// Compute condition value
second->Compile();
if(second->typeInfo == typeObject)
cmdList.push_back(VMCmd(cmdPop, 4));
else if(second->typeInfo->stackType != STYPE_INT)
cmdList.push_back(VMCmd(second->typeInfo->stackType == STYPE_DOUBLE ? cmdDtoI : cmdBitOr));
// If condition == false, exit loop
unsigned int exitJmp = cmdList.size();
cmdList.push_back(VMCmd(cmdJmpZ, 0));
// Compile loop contents
fourth->Compile();
unsigned int posPostOp = cmdList.size();
// Compile operation, executed after each cycle
third->Compile();
// Jump to condition check
cmdList.push_back(VMCmd(cmdJmp, posTestExpr));
cmdList[exitJmp].argument = cmdList.size();
NodeContinueOp::SatisfyJumps(posPostOp);
NodeBreakOp::SatisfyJumps(cmdList.size());
currLoopDepth--;
}
void NodeForExpr::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s ForExpression :\r\n", typeInfo->GetFullTypeName());
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
second->LogToStream(fGraph);
third->LogToStream(fGraph);
GoUp();
GoDownB();
fourth->LogToStream(fGraph);
GoUp();
}
void NodeForExpr::TranslateToC(FILE *fOut)
{
currLoopDepth++;
first->TranslateToC(fOut);
OutputIdent(fOut); fprintf(fOut, "while(");
second->TranslateToC(fOut);
fprintf(fOut, ")\r\n");
OutputIdent(fOut); fprintf(fOut, "{\r\n");
indentDepth++;
fourth->TranslateToC(fOut);
OutputIdent(fOut); fprintf(fOut, "continue%d_%d:1;\r\n", currLoopID[currLoopDepth-1], currLoopDepth);
third->TranslateToC(fOut);
indentDepth--;
OutputIdent(fOut); fprintf(fOut, "}\r\n");
OutputIdent(fOut); fprintf(fOut, "break%d_%d:1;\r\n", currLoopID[currLoopDepth-1], currLoopDepth);
currLoopDepth--;
assert(currLoopDepth < TRANSLATE_MAX_LOOP_DEPTH);
currLoopID[currLoopDepth]++;
}
//////////////////////////////////////////////////////////////////////////
// Node for compilation of while(){}
NodeWhileExpr::NodeWhileExpr()
{
second = TakeLastNode();
first = TakeLastNode();
if((first->typeInfo->type == TypeInfo::TYPE_COMPLEX && first->typeInfo != typeObject) || first->typeInfo->type == TypeInfo::TYPE_VOID)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: condition type cannot be '%s'", first->typeInfo->GetFullTypeName());
nodeType = typeNodeWhileExpr;
}
NodeWhileExpr::~NodeWhileExpr()
{
}
void NodeWhileExpr::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
currLoopDepth++;
// Child node structure: while(first) second;
unsigned int posStart = cmdList.size();
// Compute condition value
first->Compile();
if(first->typeInfo == typeObject)
cmdList.push_back(VMCmd(cmdPop, 4));
else if(first->typeInfo->stackType != STYPE_INT)
cmdList.push_back(VMCmd(first->typeInfo->stackType == STYPE_DOUBLE ? cmdDtoI : cmdBitOr));
// If condition == false, exit loop
unsigned int exitJmp = cmdList.size();
cmdList.push_back(VMCmd(cmdJmpZ, 0));
// Compile loop contents
second->Compile();
// Jump to condition check
cmdList.push_back(VMCmd(cmdJmp, posStart));
cmdList[exitJmp].argument = cmdList.size();
NodeContinueOp::SatisfyJumps(posStart);
NodeBreakOp::SatisfyJumps(cmdList.size());
currLoopDepth--;
}
void NodeWhileExpr::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s WhileExpression :\r\n", typeInfo->GetFullTypeName());
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
GoDownB();
second->LogToStream(fGraph);
GoUp();
}
void NodeWhileExpr::TranslateToC(FILE *fOut)
{
currLoopDepth++;
OutputIdent(fOut); fprintf(fOut, "while(");
first->TranslateToC(fOut);
fprintf(fOut, ")\r\n");
OutputIdent(fOut); fprintf(fOut, "{\r\n");
indentDepth++;
second->TranslateToC(fOut);
OutputIdent(fOut); fprintf(fOut, "continue%d_%d:1;\r\n", currLoopID[currLoopDepth-1], currLoopDepth);
indentDepth--;
OutputIdent(fOut); fprintf(fOut, "}\r\n");
OutputIdent(fOut); fprintf(fOut, "break%d_%d:1;\r\n", currLoopID[currLoopDepth-1], currLoopDepth);
currLoopDepth--;
assert(currLoopDepth < TRANSLATE_MAX_LOOP_DEPTH);
currLoopID[currLoopDepth]++;
}
//////////////////////////////////////////////////////////////////////////
// Node for compilation of do{}while()
NodeDoWhileExpr::NodeDoWhileExpr()
{
second = TakeLastNode();
first = TakeLastNode();
if((second->typeInfo->type == TypeInfo::TYPE_COMPLEX && second->typeInfo != typeObject) || second->typeInfo->type == TypeInfo::TYPE_VOID)
ThrowError(CodeInfo::lastKnownStartPos, "ERROR: condition type cannot be '%s'", second->typeInfo->GetFullTypeName());
nodeType = typeNodeDoWhileExpr;
}
NodeDoWhileExpr::~NodeDoWhileExpr()
{
}
void NodeDoWhileExpr::Compile()
{
// Child node structure: do{ first; }while(second)
CompileExtra();
currLoopDepth++;
unsigned int posStart = cmdList.size();
// Compile loop contents
first->Compile();
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
unsigned int posCond = cmdList.size();
// Compute condition value
second->Compile();
if(second->typeInfo == typeObject)
cmdList.push_back(VMCmd(cmdPop, 4));
else if(second->typeInfo->stackType != STYPE_INT)
cmdList.push_back(VMCmd(second->typeInfo->stackType == STYPE_DOUBLE ? cmdDtoI : cmdBitOr));
// Jump to beginning if condition == true
cmdList.push_back(VMCmd(cmdJmpNZ, posStart));
NodeContinueOp::SatisfyJumps(posCond);
NodeBreakOp::SatisfyJumps(cmdList.size());
currLoopDepth--;
}
void NodeDoWhileExpr::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s DoWhileExpression :\r\n", typeInfo->GetFullTypeName());
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
GoUp();
GoDownB();
second->LogToStream(fGraph);
GoUp();
}
void NodeDoWhileExpr::TranslateToC(FILE *fOut)
{
currLoopDepth++;
OutputIdent(fOut); fprintf(fOut, "do\r\n");
OutputIdent(fOut); fprintf(fOut, "{\r\n");
indentDepth++;
first->TranslateToC(fOut);
OutputIdent(fOut); fprintf(fOut, "continue%d_%d:1;\r\n", currLoopID[currLoopDepth-1], currLoopDepth);
indentDepth--;
OutputIdent(fOut); fprintf(fOut, "} while(");
second->TranslateToC(fOut);
fprintf(fOut, ");\r\n");
OutputIdent(fOut);
fprintf(fOut, "break%d_%d:1;\r\n", currLoopID[currLoopDepth-1], currLoopDepth);
currLoopDepth--;
assert(currLoopDepth < TRANSLATE_MAX_LOOP_DEPTH);
currLoopID[currLoopDepth]++;
}
//////////////////////////////////////////////////////////////////////////
void SatisfyJumps(FastVector<unsigned int>& jumpList, unsigned int pos)
{
for(unsigned int i = 0; i < jumpList.size();)
{
if(cmdList[jumpList[i]].argument == currLoopDepth)
{
// If level is equal to 1, replace it with jump position
cmdList[jumpList[i]].argument = pos;
// Remove element by replacing with the last one
jumpList[i] = jumpList.back();
jumpList.pop_back();
}else{
i++;
}
}
}
//////////////////////////////////////////////////////////////////////////
// Node for break operation
FastVector<unsigned int> NodeBreakOp::fixQueue;
NodeBreakOp::NodeBreakOp(unsigned int brDepth)
{
nodeType = typeNodeBreakOp;
breakDepth = brDepth;
}
NodeBreakOp::~NodeBreakOp()
{
}
void NodeBreakOp::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
// Break the loop
fixQueue.push_back(cmdList.size());
cmdList.push_back(VMCmd(cmdJmp, currLoopDepth - breakDepth + 1));
}
void NodeBreakOp::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s BreakExpression\r\n", typeInfo->GetFullTypeName());
LogToStreamExtra(fGraph);
}
void NodeBreakOp::TranslateToC(FILE *fOut)
{
OutputIdent(fOut);
if(breakDepth == 1)
fprintf(fOut, "break;\r\n");
else
fprintf(fOut, "goto break%d_%d;\r\n", currLoopID[currLoopDepth-breakDepth], currLoopDepth - breakDepth + 1);
}
void NodeBreakOp::SatisfyJumps(unsigned int pos)
{
::SatisfyJumps(fixQueue, pos);
}
//////////////////////////////////////////////////////////////////////////
// Node for continue operation
FastVector<unsigned int> NodeContinueOp::fixQueue;
NodeContinueOp::NodeContinueOp(unsigned int contDepth)
{
nodeType = typeNodeContinueOp;
continueDepth = contDepth;
}
NodeContinueOp::~NodeContinueOp()
{
}
void NodeContinueOp::Compile()
{
if(sourcePos)
cmdInfoList.AddDescription(cmdList.size(), sourcePos);
CompileExtra();
// Continue the loop
fixQueue.push_back(cmdList.size());
cmdList.push_back(VMCmd(cmdJmp, currLoopDepth - continueDepth + 1));
}
void NodeContinueOp::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s ContinueOp\r\n", typeInfo->GetFullTypeName());
LogToStreamExtra(fGraph);
}
void NodeContinueOp::TranslateToC(FILE *fOut)
{
OutputIdent(fOut);
fprintf(fOut, "goto continue%d_%d;\r\n", currLoopID[currLoopDepth-continueDepth], currLoopDepth - continueDepth + 1);
}
void NodeContinueOp::SatisfyJumps(unsigned int pos)
{
::SatisfyJumps(fixQueue, pos);
}
//////////////////////////////////////////////////////////////////////////
// Node for compilation of switch
FastVector<unsigned int> NodeSwitchExpr::fixQueue;
NodeSwitchExpr::NodeSwitchExpr()
{
// Take node with value
first = TakeLastNode();
conditionHead = conditionTail = NULL;
blockHead = blockTail = NULL;
defaultCase = NULL;
caseCount = 0;
nodeType = typeNodeSwitchExpr;
}
NodeSwitchExpr::~NodeSwitchExpr()
{
}
void NodeSwitchExpr::AddCase()
{
caseCount++;
// Take case block from the top
if(blockTail)
{
blockTail->next = TakeLastNode();
blockTail->next->prev = blockTail;
blockTail = blockTail->next;
}else{
blockHead = blockTail = TakeLastNode();
}
// Take case condition from the top
if(conditionTail)
{
conditionTail->next = TakeLastNode();
conditionTail->next->prev = conditionTail;
conditionTail = conditionTail->next;
}else{
conditionHead = conditionTail = TakeLastNode();
}
}
void NodeSwitchExpr::AddDefault()
{
defaultCase = TakeLastNode();
}
void NodeSwitchExpr::Compile()
{
CompileExtra();
currLoopDepth++;
asmStackType aST = first->typeInfo->stackType;
asmOperType aOT = operTypeForStackType[aST];
unsigned int queueStart = fixQueue.size(), queueCurr = queueStart;
// Compute value
first->Compile();
NodeZeroOP *curr, *currBlock;
// Generate code for all cases
for(curr = conditionHead, currBlock = blockHead; curr; curr = curr->next, currBlock = currBlock->next)
{
if(aOT == OTYPE_INT)
cmdList.push_back(VMCmd(cmdCopyI));
else
cmdList.push_back(VMCmd(cmdCopyDorL));
curr->Compile();
// Compare for equality
if(aOT == OTYPE_INT)
cmdList.push_back(VMCmd(cmdEqual));
else if(aOT == OTYPE_DOUBLE)
cmdList.push_back(VMCmd(cmdEqualD));
else
cmdList.push_back(VMCmd(cmdEqualL));
// If equal, jump to corresponding case block
fixQueue.push_back(cmdList.size());
cmdList.push_back(VMCmd(cmdJmpNZ, 0));
}
// Remove value by which we switched from stack
cmdList.push_back(VMCmd(cmdPop, stackTypeSize[aST]));
fixQueue.push_back(cmdList.size());
cmdList.push_back(VMCmd(cmdJmp, 0));
for(curr = blockHead; curr; curr = curr->next)
{
cmdList[fixQueue[queueCurr++]].argument = cmdList.size();
// Remove value by which we switched from stack
cmdList.push_back(VMCmd(cmdPop, stackTypeSize[aST]));
curr->Compile();
if(curr != blockTail)
cmdList.push_back(VMCmd(cmdJmp, cmdList.size() + 2));
}
cmdList[fixQueue[queueCurr++]].argument = cmdList.size();
if(defaultCase)
defaultCase->Compile();
for(unsigned int i = 0; i < NodeContinueOp::fixQueue.size(); i++)
{
if(cmdList[NodeContinueOp::fixQueue[i]].argument == 1)
ThrowError(NULL, "ERROR: cannot continue inside switch");
}
fixQueue.shrink(queueStart);
NodeBreakOp::SatisfyJumps(cmdList.size());
currLoopDepth--;
}
void NodeSwitchExpr::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s SwitchExpression :\r\n", typeInfo->GetFullTypeName());
GoDown();
LogToStreamExtra(fGraph);
first->LogToStream(fGraph);
for(NodeZeroOP *curr = conditionHead, *block = blockHead; curr; curr = curr->next, block = block->next)
{
curr->LogToStream(fGraph);
if(curr == conditionTail)
{
GoUp();
GoDownB();
}
block->LogToStream(fGraph);
}
GoUp();
}
void NodeSwitchExpr::TranslateToC(FILE *fOut)
{
static int switchNum = 0;
int myNum = switchNum++;
OutputIdent(fOut);
fprintf(fOut, "do\r\n");
OutputIdent(fOut);
fprintf(fOut, "{\r\n");
indentDepth++;
char buf[64];
sprintf(buf, "switchVar");
OutputIdent(fOut);
first->typeInfo->OutputCType(fOut, buf);
fprintf(fOut, " = ");
first->TranslateToC(fOut);
fprintf(fOut, ";\r\n");
unsigned int i = 0;
for(NodeZeroOP *curr = conditionHead; curr; curr = curr->next, i++)
{
OutputIdent(fOut);
fprintf(fOut, "if(switchVar == ");
curr->TranslateToC(fOut);
fprintf(fOut, ")\r\n");
OutputIdent(fOut);
fprintf(fOut, "\tgoto case%d_%d;\r\n", myNum, i);
}
OutputIdent(fOut);
fprintf(fOut, "goto defaultCase_%d;\r\n", myNum);
i = 0;
for(NodeZeroOP *block = blockHead; block; block = block->next, i++)
{
OutputIdent(fOut);
fprintf(fOut, "case%d_%d:\r\n", myNum, i);
block->TranslateToC(fOut);
}
OutputIdent(fOut);
fprintf(fOut, "defaultCase_%d:\r\n", myNum);
if(defaultCase)
{
defaultCase->TranslateToC(fOut);
}else{
OutputIdent(fOut);
fprintf(fOut, "0;\r\n");
}
indentDepth--;
OutputIdent(fOut);
fprintf(fOut, "}while(0);\r\n");
}
//////////////////////////////////////////////////////////////////////////
// Node that contains list of expressions
NodeExpressionList::NodeExpressionList(TypeInfo *returnType)
{
typeInfo = returnType;
tail = first = TakeLastNode();
nodeType = typeNodeExpressionList;
}
NodeExpressionList::~NodeExpressionList()
{
}
void NodeExpressionList::AddNode(bool reverse)
{
// If reverse is set, add before the head
if(reverse)
{
NodeZeroOP *firstNext = first;
first = TakeLastNode();
first->next = firstNext;
first->next->prev = first;
}else{
tail->next = TakeLastNode();
tail->next->prev = tail;
tail = tail->next;
}
}
NodeZeroOP* NodeExpressionList::GetFirstNode()
{
assert(first);
return first;
}
void NodeExpressionList::Compile()
{
CompileExtra();
NodeZeroOP *curr = first;
do
{
curr->Compile();
curr = curr->next;
}while(curr);
}
void NodeExpressionList::LogToStream(FILE *fGraph)
{
DrawLine(fGraph);
fprintf(fGraph, "%s NodeExpressionList :\r\n", typeInfo->GetFullTypeName());
GoDown();
LogToStreamExtra(fGraph);
NodeZeroOP *curr = first;
do
{
if(curr == tail)
{
GoUp();
GoDownB();
}
curr->LogToStream(fGraph);
curr = curr->next;
}while(curr);
GoUp();
}
void NodeExpressionList::TranslateToC(FILE *fOut)
{
if(typeInfo->arrLevel && typeInfo->arrSize != TypeInfo::UNSIZED_ARRAY && typeInfo->subType == typeChar)
{
fprintf(fOut, "\"");
NodeZeroOP *curr = tail->prev;
do
{
assert(curr->nodeType == typeNodeNumber);
NodeNumber *dword = (NodeNumber*)curr;
for(unsigned int i = 0; i < 4; i++)
{
unsigned char ch = (unsigned char)((dword->GetInteger() >> (i * 8)) & 0xff);
if(ch >= ' ' && ch <= 128 && ch != '\"' && ch != '\\' && ch != '\'')
fprintf(fOut, "%c", ch);
else
fprintf(fOut, "\\x%x", ch);
}
curr = curr->prev;
}while(curr);
fprintf(fOut, "\"");
return;
}else if(typeInfo != typeVoid){
NodeZeroOP *end = first;
if(first->nodeType == typeNodePopOp)
{
fprintf(fOut, "(");
((NodePopOp*)first)->GetFirstNode()->TranslateToC(fOut);
fprintf(fOut, ", ");
end = first->next;
}
if(typeInfo->arrLevel && typeInfo->arrSize == TypeInfo::UNSIZED_ARRAY)
fprintf(fOut, "__makeNullcArray(");
else if(first->nodeType != typeNodePopOp){
typeInfo->OutputCType(fOut, "()");
end = first->next;
}
NodeZeroOP *curr = tail;
unsigned int id = 0;
do
{
if(typeInfo->arrLevel && typeInfo->arrSize != TypeInfo::UNSIZED_ARRAY)
fprintf(fOut, ".set(%d, ", id++);
curr->TranslateToC(fOut);
if(typeInfo->arrLevel && typeInfo->arrSize != TypeInfo::UNSIZED_ARRAY)
fprintf(fOut, ")");
else if(curr != end)
fprintf(fOut, ", ");
curr = curr->prev;
}while(curr != end->prev);
if(typeInfo->arrLevel && typeInfo->arrSize == TypeInfo::UNSIZED_ARRAY)
fprintf(fOut, ")");
if(first->nodeType == typeNodePopOp)
fprintf(fOut, ")");
}else{
NodeZeroOP *curr = first;
do
{
curr->TranslateToC(fOut);
if(curr != tail && typeInfo != typeVoid)
fprintf(fOut, ", ");
curr = curr->next;
}while(curr);
}
}
void ResetTreeGlobals()
{
currLoopDepth = 0;
memset(currLoopID, 0, sizeof(unsigned int) * TRANSLATE_MAX_LOOP_DEPTH);
nodeDereferenceEndInComma = false;
NodeBreakOp::fixQueue.clear();
NodeContinueOp::fixQueue.clear();
}
|
/*
* HyPerLayer.cpp
*
* Created on: Jul 29, 2008
*
* The top of the hierarchy for layer classes.
*
* To make it easy to subclass from classes in the HyPerLayer hierarchy,
* please follow the guidelines below when adding subclasses to the HyPerLayer hierarchy:
*
* For a class named DerivedLayer that is derived from a class named BaseLayer,
* the .hpp file should have
*/
#include "HyPerLayer.hpp"
#include "checkpointing/CheckpointEntryPvpBuffer.hpp"
#include "checkpointing/CheckpointEntryRandState.hpp"
#include "columns/HyPerCol.hpp"
#include "connections/BaseConnection.hpp"
#include "connections/TransposeConn.hpp"
#include "include/default_params.h"
#include "include/pv_common.h"
#include "io/FileStream.hpp"
#include "io/io.hpp"
#include <assert.h>
#include <iostream>
#include <sstream>
#include <string.h>
namespace PV {
// This constructor is protected so that only derived classes can call it.
// It should be called as the normal method of object construction by
// derived classes. It should NOT call any virtual methods
HyPerLayer::HyPerLayer() { initialize_base(); }
HyPerLayer::HyPerLayer(const char *name, HyPerCol *hc) {
initialize_base();
initialize(name, hc);
}
// initialize_base should be called only by constructors. It should not
// call any virtual methods, because polymorphism is not available when
// a base class constructor is inherited from a derived class constructor.
// In general, initialize_base should be used only to initialize member variables
// to safe values.
int HyPerLayer::initialize_base() {
name = NULL;
probes = NULL;
nxScale = 1.0f;
nyScale = 1.0f;
numFeatures = 1;
mirrorBCflag = 0;
xmargin = 0;
ymargin = 0;
numProbes = 0;
numChannels = 2;
clayer = NULL;
GSyn = NULL;
marginIndices = NULL;
numMargin = 0;
writeTime = 0;
initialWriteTime = 0;
triggerFlag = false; // Default to update every timestamp
triggerLayer = NULL;
triggerLayerName = NULL;
triggerBehavior = NULL;
triggerBehaviorType = NO_TRIGGER;
triggerResetLayerName = NULL;
triggerOffset = 0;
initializeFromCheckpointFlag = false;
mLastUpdateTime = 0.0;
mLastTriggerTime = 0.0;
phase = 0;
numSynchronizedMarginWidthLayers = 0;
synchronizedMarginWidthLayers = NULL;
dataType = PV_FLOAT;
dataTypeString = NULL;
#ifdef PV_USE_CUDA
allocDeviceV = false;
allocDeviceGSyn = false;
allocDeviceActivity = false;
allocDeviceDatastore = false;
allocDeviceActiveIndices = false;
d_V = NULL;
d_GSyn = NULL;
d_Activity = NULL;
d_Datastore = NULL;
d_ActiveIndices = NULL;
d_numActive = NULL;
updatedDeviceActivity = true; // Start off always updating activity
updatedDeviceDatastore = true;
updatedDeviceGSyn = true;
recvGpu = false;
updateGpu = false;
krUpdate = NULL;
#ifdef PV_USE_CUDNN
cudnn_GSyn = NULL;
cudnn_Datastore = NULL;
#endif // PV_USE_CUDNN
#endif // PV_USE_CUDA
update_timer = NULL;
recvsyn_timer = NULL;
publish_timer = NULL;
timescale_timer = NULL;
io_timer = NULL;
#ifdef PV_USE_CUDA
gpu_recvsyn_timer = NULL;
gpu_update_timer = NULL;
#endif
thread_gSyn = NULL;
recvConns.clear();
return PV_SUCCESS;
}
///////
/// Classes derived from HyPerLayer should call HyPerLayer::initialize themselves
/// to take advantage of virtual methods. Note that the HyPerLayer constructor
/// does not call initialize. This way, HyPerLayer::initialize can call virtual
/// methods and the derived class's method will be the one that gets called.
int HyPerLayer::initialize(const char *name, HyPerCol *hc) {
int status = BaseLayer::initialize(name, hc);
if (status != PV_SUCCESS) {
return status;
}
PVParams *params = hc->parameters();
status = ioParams(PARAMS_IO_READ);
assert(status == PV_SUCCESS);
writeTime = initialWriteTime;
writeActivityCalls = 0;
writeActivitySparseCalls = 0;
numDelayLevels = 1; // If a connection has positive delay so that more delay levels are needed,
// numDelayLevels is increased when BaseConnection::communicateInitInfo calls
// increaseDelayLevels
maxRate = 1000.0f / (float)hc->getDeltaTime();
initClayer();
hc->addLayer(this);
mLastUpdateTime = hc->getDeltaTime();
mLastTriggerTime = hc->getDeltaTime();
return PV_SUCCESS;
}
int HyPerLayer::initClayer() {
clayer = (PVLayer *)calloc(1UL, sizeof(PVLayer));
int status = PV_SUCCESS;
if (clayer == NULL) {
Fatal().printf(
"HyPerLayer \"%s\" error in rank %d process: unable to allocate memory for Clayer.\n",
name,
parent->columnId());
}
PVLayerLoc *loc = &clayer->loc;
setLayerLoc(loc, nxScale, nyScale, numFeatures, parent->getNBatch());
assert(loc->halo.lt == 0 && loc->halo.rt == 0 && loc->halo.dn == 0 && loc->halo.up == 0);
int nBatch = parent->getNBatch();
clayer->numNeurons = loc->nx * loc->ny * loc->nf;
clayer->numExtended = clayer->numNeurons; // initially, margin is zero; it will be updated as
// needed during the communicateInitInfo stage.
clayer->numNeuronsAllBatches = nBatch * loc->nx * loc->ny * loc->nf;
clayer->numExtendedAllBatches = clayer->numNeuronsAllBatches;
double xScaled = -log2((double)nxScale);
double yScaled = -log2((double)nyScale);
int xScale = (int)nearbyint(xScaled);
int yScale = (int)nearbyint(yScaled);
clayer->xScale = xScale;
clayer->yScale = yScale;
// Other fields of clayer will be set in allocateClayerBuffers, or during updateState
return status;
}
HyPerLayer::~HyPerLayer() {
delete recvsyn_timer;
delete update_timer;
delete publish_timer;
delete timescale_timer;
delete io_timer;
#ifdef PV_USE_CUDA
delete gpu_recvsyn_timer;
delete gpu_update_timer;
#endif
delete mOutputStateStream;
delete mInitVObject;
freeClayer();
freeChannels();
#ifdef PV_USE_CUDA
if (krUpdate) {
delete krUpdate;
}
if (d_V) {
delete d_V;
}
if (d_Activity) {
delete d_Activity;
}
if (d_Datastore) {
delete d_Datastore;
}
#ifdef PV_USE_CUDNN
if (cudnn_Datastore) {
delete cudnn_Datastore;
}
#endif // PV_USE_CUDNN
#endif // PV_USE_CUDA
free(marginIndices);
free(probes); // All probes are deleted by the HyPerCol, so probes[i] doesn't need to be deleted,
// only the array itself.
free(synchronizedMarginWidthLayers);
free(triggerLayerName);
free(triggerBehavior);
free(triggerResetLayerName);
free(initVTypeString);
if (thread_gSyn) {
for (int i = 0; i < parent->getNumThreads(); i++) {
free(thread_gSyn[i]);
}
free(thread_gSyn);
}
delete publisher;
}
template <typename T>
int HyPerLayer::freeBuffer(T **buf) {
free(*buf);
*buf = NULL;
return PV_SUCCESS;
}
// Declare the instantiations of allocateBuffer that occur in other .cpp files; otherwise you may
// get linker errors.
template int HyPerLayer::freeBuffer<float>(float **buf);
template int HyPerLayer::freeBuffer<int>(int **buf);
int HyPerLayer::freeRestrictedBuffer(float **buf) { return freeBuffer(buf); }
int HyPerLayer::freeExtendedBuffer(float **buf) { return freeBuffer(buf); }
int HyPerLayer::freeClayer() {
pvcube_delete(clayer->activity);
freeBuffer(&clayer->prevActivity);
freeBuffer(&clayer->V);
free(clayer);
clayer = NULL;
return PV_SUCCESS;
}
void HyPerLayer::freeChannels() {
#ifdef PV_USE_CUDA
if (d_GSyn != NULL) {
delete d_GSyn;
d_GSyn = NULL;
}
#ifdef PV_USE_CUDNN
if (cudnn_GSyn != NULL) {
delete cudnn_GSyn;
}
#endif // PV_USE_CUDNN
#endif // PV_USE_CUDA
// GSyn gets allocated in allocateDataStructures, but only if numChannels>0.
if (GSyn) {
assert(numChannels > 0);
free(GSyn[0]); // conductances allocated contiguously so frees all buffer storage
free(GSyn); // this frees the array pointers to separate conductance channels
GSyn = NULL;
numChannels = 0;
}
}
int HyPerLayer::allocateClayerBuffers() {
// clayer fields numNeurons, numExtended, loc, xScale, yScale,
// dx, dy, xOrigin, yOrigin were set in initClayer().
assert(clayer);
FatalIf(allocateV() != PV_SUCCESS, "%s: allocateV() failed.\n", getName());
FatalIf(allocateActivity() != PV_SUCCESS, "%s: allocateActivity() failed.\n", getName());
// athresher 11-4-16 TODO: Should these be called on non-spiking layers?
FatalIf(allocatePrevActivity() != PV_SUCCESS, "%s: allocatePrevActivity() failed.\n", getName());
for (int k = 0; k < getNumExtendedAllBatches(); k++) {
clayer->prevActivity[k] = -10 * REFRACTORY_PERIOD; // allow neuron to fire at time t==0
}
return PV_SUCCESS;
}
template <typename T>
int HyPerLayer::allocateBuffer(T **buf, int bufsize, const char *bufname) {
int status = PV_SUCCESS;
*buf = (T *)calloc(bufsize, sizeof(T));
if (*buf == NULL) {
ErrorLog().printf(
"%s: rank %d process unable to allocate memory for %s: %s.\n",
getDescription_c(),
parent->columnId(),
bufname,
strerror(errno));
status = PV_FAILURE;
}
return status;
}
// Declare the instantiations of allocateBuffer that occur in other .cpp files; otherwise you may
// get linker errors.
template int HyPerLayer::allocateBuffer<float>(float **buf, int bufsize, const char *bufname);
template int HyPerLayer::allocateBuffer<int>(int **buf, int bufsize, const char *bufname);
int HyPerLayer::allocateRestrictedBuffer(float **buf, char const *bufname) {
return allocateBuffer(buf, getNumNeuronsAllBatches(), bufname);
}
int HyPerLayer::allocateExtendedBuffer(float **buf, char const *bufname) {
return allocateBuffer(buf, getNumExtendedAllBatches(), bufname);
}
int HyPerLayer::allocateV() { return allocateRestrictedBuffer(&clayer->V, "membrane potential V"); }
int HyPerLayer::allocateActivity() {
clayer->activity = pvcube_new(&clayer->loc, getNumExtendedAllBatches());
return clayer->activity != NULL ? PV_SUCCESS : PV_FAILURE;
}
int HyPerLayer::allocatePrevActivity() {
return allocateExtendedBuffer(&clayer->prevActivity, "time of previous activity");
}
int HyPerLayer::setLayerLoc(
PVLayerLoc *layerLoc,
float nxScale,
float nyScale,
int nf,
int numBatches) {
int status = PV_SUCCESS;
Communicator *icComm = parent->getCommunicator();
float nxglobalfloat = nxScale * parent->getNxGlobal();
layerLoc->nxGlobal = (int)nearbyintf(nxglobalfloat);
if (std::fabs(nxglobalfloat - layerLoc->nxGlobal) > 0.0001f) {
if (parent->columnId() == 0) {
ErrorLog(errorMessage);
errorMessage.printf(
"nxScale of layer \"%s\" is incompatible with size of column.\n", getName());
errorMessage.printf(
"Column nx %d multiplied by nxScale %f must be an integer.\n",
(double)parent->getNxGlobal(),
(double)nxScale);
}
status = PV_FAILURE;
}
float nyglobalfloat = nyScale * parent->getNyGlobal();
layerLoc->nyGlobal = (int)nearbyintf(nyglobalfloat);
if (std::fabs(nyglobalfloat - layerLoc->nyGlobal) > 0.0001f) {
if (parent->columnId() == 0) {
ErrorLog(errorMessage);
errorMessage.printf(
"nyScale of layer \"%s\" is incompatible with size of column.\n", getName());
errorMessage.printf(
"Column ny %d multiplied by nyScale %f must be an integer.\n",
(double)parent->getNyGlobal(),
(double)nyScale);
}
status = PV_FAILURE;
}
// partition input space based on the number of processor
// columns and rows
//
if (layerLoc->nxGlobal % icComm->numCommColumns() != 0) {
if (parent->columnId() == 0) {
ErrorLog(errorMessage);
errorMessage.printf(
"Size of HyPerLayer \"%s\" is not compatible with the mpi configuration.\n", name);
errorMessage.printf(
"The layer has %d pixels horizontally, and there are %d mpi processes in a row, but "
"%d does not divide %d.\n",
layerLoc->nxGlobal,
icComm->numCommColumns(),
icComm->numCommColumns(),
layerLoc->nxGlobal);
}
status = PV_FAILURE;
}
if (layerLoc->nyGlobal % icComm->numCommRows() != 0) {
if (parent->columnId() == 0) {
ErrorLog(errorMessage);
errorMessage.printf(
"Size of HyPerLayer \"%s\" is not compatible with the mpi configuration.\n", name);
errorMessage.printf(
"The layer has %d pixels vertically, and there are %d mpi processes in a column, "
"but %d does not divide %d.\n",
layerLoc->nyGlobal,
icComm->numCommRows(),
icComm->numCommRows(),
layerLoc->nyGlobal);
}
status = PV_FAILURE;
}
MPI_Barrier(icComm->communicator()); // If there is an error, make sure that MPI doesn't kill the
// run before process 0 reports the error.
if (status != PV_SUCCESS) {
if (parent->columnId() == 0) {
ErrorLog().printf("setLayerLoc failed for %s.\n", getDescription_c());
}
exit(EXIT_FAILURE);
}
layerLoc->nx = layerLoc->nxGlobal / icComm->numCommColumns();
layerLoc->ny = layerLoc->nyGlobal / icComm->numCommRows();
assert(layerLoc->nxGlobal == layerLoc->nx * icComm->numCommColumns());
assert(layerLoc->nyGlobal == layerLoc->ny * icComm->numCommRows());
layerLoc->kx0 = layerLoc->nx * icComm->commColumn();
layerLoc->ky0 = layerLoc->ny * icComm->commRow();
layerLoc->nf = nf;
layerLoc->nbatch = numBatches;
layerLoc->kb0 = parent->commBatch() * numBatches;
layerLoc->nbatchGlobal = parent->numCommBatches() * numBatches;
// halo is set in calls to updateClayerMargin
layerLoc->halo.lt = 0;
layerLoc->halo.rt = 0;
layerLoc->halo.dn = 0;
layerLoc->halo.up = 0;
return 0;
}
void HyPerLayer::calcNumExtended() {
PVLayerLoc const *loc = getLayerLoc();
clayer->numExtended = (loc->nx + loc->halo.lt + loc->halo.rt)
* (loc->ny + loc->halo.dn + loc->halo.up) * loc->nf;
clayer->numExtendedAllBatches = clayer->numExtended * loc->nbatch;
}
int HyPerLayer::allocateBuffers() {
// allocate memory for input buffers. For HyPerLayer, allocates GSyn
// virtual so that subclasses can initialize additional buffers if needed.
// Typically an overriding allocateBuffers should call HyPerLayer::allocateBuffers
// Specialized subclasses that don't use GSyn (e.g. CloneVLayer) should override
// allocateGSyn to do nothing.
return allocateGSyn();
}
int HyPerLayer::allocateGSyn() {
int status = PV_SUCCESS;
GSyn = NULL;
if (numChannels > 0) {
GSyn = (float **)malloc(numChannels * sizeof(float *));
if (GSyn == NULL) {
status = PV_FAILURE;
return status;
}
GSyn[0] = (float *)calloc(getNumNeuronsAllBatches() * numChannels, sizeof(float));
// All channels allocated at once and contiguously. resetGSynBuffers_HyPerLayer() assumes
// this is true, to make it easier to port to GPU.
if (GSyn[0] == NULL) {
status = PV_FAILURE;
return status;
}
for (int m = 1; m < numChannels; m++) {
GSyn[m] = GSyn[0] + m * getNumNeuronsAllBatches();
}
}
return status;
}
void HyPerLayer::addPublisher() {
MPIBlock const *mpiBlock = parent->getCommunicator()->getLocalMPIBlock();
publisher = new Publisher(*mpiBlock, clayer->activity, getNumDelayLevels(), getSparseFlag());
}
void HyPerLayer::checkpointPvpActivityFloat(
Checkpointer *checkpointer,
char const *bufferName,
float *pvpBuffer,
bool extended) {
bool registerSucceeded = checkpointer->registerCheckpointEntry(
std::make_shared<CheckpointEntryPvpBuffer<float>>(
getName(),
bufferName,
checkpointer->getMPIBlock(),
pvpBuffer,
getLayerLoc(),
extended));
FatalIf(
!registerSucceeded,
"%s failed to register %s for checkpointing.\n",
getDescription_c(),
bufferName);
}
void HyPerLayer::checkpointRandState(
Checkpointer *checkpointer,
char const *bufferName,
Random *randState,
bool extendedFlag) {
bool registerSucceeded = checkpointer->registerCheckpointEntry(
std::make_shared<CheckpointEntryRandState>(
getName(),
bufferName,
checkpointer->getMPIBlock(),
randState->getRNG(0),
getLayerLoc(),
extendedFlag));
FatalIf(
!registerSucceeded,
"%s failed to register %s for checkpointing.\n",
getDescription_c(),
bufferName);
}
int HyPerLayer::initializeState() {
int status = setInitialValues();
return status;
}
#ifdef PV_USE_CUDA
int HyPerLayer::copyInitialStateToGPU() {
if (updateGpu) {
float *h_V = getV();
if (h_V != NULL) {
PVCuda::CudaBuffer *d_V = getDeviceV();
assert(d_V);
d_V->copyToDevice(h_V);
}
PVCuda::CudaBuffer *d_activity = getDeviceActivity();
assert(d_activity);
float *h_activity = getCLayer()->activity->data;
d_activity->copyToDevice(h_activity);
}
return PV_SUCCESS;
}
#endif // PV_USE_CUDA
int HyPerLayer::setInitialValues() {
int status = PV_SUCCESS;
status = initializeV();
if (status == PV_SUCCESS)
initializeActivity();
return status;
}
int HyPerLayer::initializeV() {
int status = PV_SUCCESS;
if (getV() != nullptr && mInitVObject != nullptr) {
status = mInitVObject->calcV(getV(), getLayerLoc());
}
return status;
}
int HyPerLayer::initializeActivity() {
int status = setActivity();
return status;
}
int HyPerLayer::ioParams(enum ParamsIOFlag ioFlag) {
parent->ioParamsStartGroup(ioFlag, name);
ioParamsFillGroup(ioFlag);
parent->ioParamsFinishGroup(ioFlag);
return PV_SUCCESS;
}
int HyPerLayer::ioParamsFillGroup(enum ParamsIOFlag ioFlag) {
// Derived classes with new params behavior should override ioParamsFillGroup
// and the overriding method should call the base class's ioParamsFillGroup.
ioParam_nxScale(ioFlag);
ioParam_nyScale(ioFlag);
ioParam_nf(ioFlag);
ioParam_phase(ioFlag);
ioParam_mirrorBCflag(ioFlag);
ioParam_valueBC(ioFlag);
ioParam_initializeFromCheckpointFlag(ioFlag);
ioParam_InitVType(ioFlag);
ioParam_triggerLayerName(ioFlag);
ioParam_triggerFlag(ioFlag);
ioParam_triggerOffset(ioFlag);
ioParam_triggerBehavior(ioFlag);
ioParam_triggerResetLayerName(ioFlag);
ioParam_writeStep(ioFlag);
ioParam_initialWriteTime(ioFlag);
ioParam_sparseLayer(ioFlag);
ioParam_writeSparseValues(ioFlag);
// GPU-specific parameter. If not using GPUs, this flag
// can be set to false or left out, but it is an error
// to set updateGpu to true if compiling without GPUs.
ioParam_updateGpu(ioFlag);
ioParam_dataType(ioFlag);
return PV_SUCCESS;
}
void HyPerLayer::ioParam_dataType(enum ParamsIOFlag ioFlag) {
this->getParent()->parameters()->ioParamString(
ioFlag, this->getName(), "dataType", &dataTypeString, NULL, false /*warnIfAbsent*/);
if (dataTypeString == NULL) {
// Default value
dataType = PV_FLOAT;
return;
}
if (!strcmp(dataTypeString, "float")) {
dataType = PV_FLOAT;
}
else if (!strcmp(dataTypeString, "int")) {
dataType = PV_INT;
}
else {
Fatal() << "BaseLayer \"" << name
<< "\": dataType not recognized, can be \"float\" or \"int\"\n";
}
}
void HyPerLayer::ioParam_updateGpu(enum ParamsIOFlag ioFlag) {
#ifdef PV_USE_CUDA
parent->parameters()->ioParamValue(
ioFlag, name, "updateGpu", &updateGpu, updateGpu, true /*warnIfAbsent*/);
mUsingGPUFlag = updateGpu;
#else // PV_USE_CUDA
bool updateGpu = false;
parent->parameters()->ioParamValue(
ioFlag, name, "updateGpu", &updateGpu, updateGpu, false /*warnIfAbsent*/);
if (ioFlag == PARAMS_IO_READ && updateGpu) {
if (parent->columnId() == 0) {
WarnLog().printf(
"%s: updateGpu is set to true, but PetaVision was compiled without GPU "
"acceleration. uphadeGpu has been set to false.\n",
getDescription_c());
}
}
#endif // PV_USE_CUDA
}
void HyPerLayer::ioParam_nxScale(enum ParamsIOFlag ioFlag) {
parent->parameters()->ioParamValue(ioFlag, name, "nxScale", &nxScale, nxScale);
}
void HyPerLayer::ioParam_nyScale(enum ParamsIOFlag ioFlag) {
parent->parameters()->ioParamValue(ioFlag, name, "nyScale", &nyScale, nyScale);
}
void HyPerLayer::ioParam_nf(enum ParamsIOFlag ioFlag) {
parent->parameters()->ioParamValue(ioFlag, name, "nf", &numFeatures, numFeatures);
}
void HyPerLayer::ioParam_phase(enum ParamsIOFlag ioFlag) {
parent->parameters()->ioParamValue(ioFlag, name, "phase", &phase, phase);
if (ioFlag == PARAMS_IO_READ && phase < 0) {
if (parent->columnId() == 0)
Fatal().printf(
"%s: phase must be >= 0 (given value was %d).\n", getDescription_c(), phase);
}
}
void HyPerLayer::ioParam_mirrorBCflag(enum ParamsIOFlag ioFlag) {
parent->parameters()->ioParamValue(ioFlag, name, "mirrorBCflag", &mirrorBCflag, mirrorBCflag);
}
void HyPerLayer::ioParam_valueBC(enum ParamsIOFlag ioFlag) {
assert(!parent->parameters()->presentAndNotBeenRead(name, "mirrorBCflag"));
if (!mirrorBCflag) {
parent->parameters()->ioParamValue(ioFlag, name, "valueBC", &valueBC, (float)0);
}
}
void HyPerLayer::ioParam_initializeFromCheckpointFlag(enum ParamsIOFlag ioFlag) {
assert(parent->getInitializeFromCheckpointDir());
if (parent->getInitializeFromCheckpointDir() && parent->getInitializeFromCheckpointDir()[0]) {
parent->parameters()->ioParamValue(
ioFlag,
name,
"initializeFromCheckpointFlag",
&initializeFromCheckpointFlag,
parent->getDefaultInitializeFromCheckpointFlag(),
true /*warnIfAbsent*/);
}
}
void HyPerLayer::ioParam_InitVType(enum ParamsIOFlag ioFlag) {
parent->parameters()->ioParamString(
ioFlag, name, "InitVType", &initVTypeString, "ConstantV", true /*warnIfAbsent*/);
if (ioFlag == PARAMS_IO_READ) {
BaseObject *object = Factory::instance()->createByKeyword(initVTypeString, name, parent);
mInitVObject = dynamic_cast<BaseInitV *>(object);
if (mInitVObject == nullptr) {
ErrorLog().printf("%s: unable to create InitV object\n", getDescription_c());
abort();
}
}
if (mInitVObject != nullptr) {
mInitVObject->ioParamsFillGroup(ioFlag);
}
}
void HyPerLayer::ioParam_triggerLayerName(enum ParamsIOFlag ioFlag) {
parent->parameters()->ioParamString(
ioFlag, name, "triggerLayerName", &triggerLayerName, NULL, false /*warnIfAbsent*/);
if (ioFlag == PARAMS_IO_READ) {
if (triggerLayerName && !strcmp(name, triggerLayerName)) {
if (parent->columnId() == 0) {
ErrorLog().printf(
"%s: triggerLayerName cannot be the same as the name of the layer itself.\n",
getDescription_c());
}
MPI_Barrier(parent->getCommunicator()->communicator());
exit(EXIT_FAILURE);
}
triggerFlag = (triggerLayerName != NULL && triggerLayerName[0] != '\0');
}
}
// triggerFlag was deprecated Aug 7, 2015.
// Setting triggerLayerName to a nonempty string has the effect of triggerFlag=true, and
// setting triggerLayerName to NULL or "" has the effect of triggerFlag=false.
// While triggerFlag is being deprecated, it is an error for triggerFlag to be false
// and triggerLayerName to be a nonempty string.
void HyPerLayer::ioParam_triggerFlag(enum ParamsIOFlag ioFlag) {
pvAssert(!parent->parameters()->presentAndNotBeenRead(name, "triggerLayerName"));
if (ioFlag == PARAMS_IO_READ && parent->parameters()->present(name, "triggerFlag")) {
bool flagFromParams = false;
parent->parameters()->ioParamValue(
ioFlag, name, "triggerFlag", &flagFromParams, flagFromParams);
if (parent->columnId() == 0) {
WarnLog(triggerFlagMessage);
triggerFlagMessage.printf("%s: triggerFlag has been deprecated.\n", getDescription_c());
triggerFlagMessage.printf(
" If triggerLayerName is a nonempty string, triggering will be on;\n");
triggerFlagMessage.printf(
" if triggerLayerName is empty or null, triggering will be off.\n");
if (parent->columnId() == 0) {
if (flagFromParams != triggerFlag) {
ErrorLog(errorMessage);
errorMessage.printf("triggerLayerName=", name);
if (triggerLayerName) {
errorMessage.printf("\"%s\"", triggerLayerName);
}
else {
errorMessage.printf("NULL");
}
errorMessage.printf(
" implies triggerFlag=%s but triggerFlag was set in params to %s\n",
triggerFlag ? "true" : "false",
flagFromParams ? "true" : "false");
}
}
}
if (flagFromParams != triggerFlag) {
MPI_Barrier(parent->getCommunicator()->communicator());
exit(EXIT_FAILURE);
}
}
}
void HyPerLayer::ioParam_triggerOffset(enum ParamsIOFlag ioFlag) {
assert(!parent->parameters()->presentAndNotBeenRead(name, "triggerLayerName"));
if (triggerFlag) {
parent->parameters()->ioParamValue(
ioFlag, name, "triggerOffset", &triggerOffset, triggerOffset);
if (triggerOffset < 0) {
if (parent->columnId() == 0) {
Fatal().printf(
"%s: TriggerOffset (%f) must be positive\n", getDescription_c(), triggerOffset);
}
}
}
}
void HyPerLayer::ioParam_triggerBehavior(enum ParamsIOFlag ioFlag) {
assert(!parent->parameters()->presentAndNotBeenRead(name, "triggerLayerName"));
if (triggerFlag) {
parent->parameters()->ioParamString(
ioFlag,
name,
"triggerBehavior",
&triggerBehavior,
"updateOnlyOnTrigger",
true /*warnIfAbsent*/);
if (triggerBehavior == NULL || !strcmp(triggerBehavior, "")) {
free(triggerBehavior);
triggerBehavior = strdup("updateOnlyOnTrigger");
triggerBehaviorType = UPDATEONLY_TRIGGER;
}
else if (!strcmp(triggerBehavior, "updateOnlyOnTrigger")) {
triggerBehaviorType = UPDATEONLY_TRIGGER;
}
else if (!strcmp(triggerBehavior, "resetStateOnTrigger")) {
triggerBehaviorType = RESETSTATE_TRIGGER;
}
else if (!strcmp(triggerBehavior, "ignore")) {
triggerBehaviorType = NO_TRIGGER;
}
else {
if (parent->columnId() == 0) {
ErrorLog().printf(
"%s: triggerBehavior=\"%s\" is unrecognized.\n",
getDescription_c(),
triggerBehavior);
}
MPI_Barrier(parent->getCommunicator()->communicator());
exit(EXIT_FAILURE);
}
}
else {
triggerBehaviorType = NO_TRIGGER;
}
}
void HyPerLayer::ioParam_triggerResetLayerName(enum ParamsIOFlag ioFlag) {
assert(!parent->parameters()->presentAndNotBeenRead(name, "triggerLayerName"));
if (triggerFlag) {
assert(!parent->parameters()->presentAndNotBeenRead(name, "triggerBehavior"));
if (!strcmp(triggerBehavior, "resetStateOnTrigger")) {
parent->parameters()->ioParamStringRequired(
ioFlag, name, "triggerResetLayerName", &triggerResetLayerName);
}
}
}
void HyPerLayer::ioParam_writeStep(enum ParamsIOFlag ioFlag) {
parent->parameters()->ioParamValue(
ioFlag, name, "writeStep", &writeStep, parent->getDeltaTime());
}
void HyPerLayer::ioParam_initialWriteTime(enum ParamsIOFlag ioFlag) {
assert(!parent->parameters()->presentAndNotBeenRead(name, "writeStep"));
if (writeStep >= 0.0) {
double start_time = parent->getStartTime();
parent->parameters()->ioParamValue(
ioFlag, name, "initialWriteTime", &initialWriteTime, start_time);
if (ioFlag == PARAMS_IO_READ && writeStep > 0.0 && initialWriteTime < start_time) {
double storeInitialWriteTime = initialWriteTime;
while (initialWriteTime < start_time) {
initialWriteTime += writeStep;
}
if (parent->columnId() == 0) {
WarnLog(warningMessage);
warningMessage.printf(
"%s: initialWriteTime %f is earlier than start time %f. Adjusting "
"initialWriteTime:\n",
getDescription_c(),
initialWriteTime,
start_time);
warningMessage.printf(" initialWriteTime adjusted to %f\n", initialWriteTime);
}
}
}
}
void HyPerLayer::ioParam_sparseLayer(enum ParamsIOFlag ioFlag) {
if (ioFlag == PARAMS_IO_READ && !parent->parameters()->present(name, "sparseLayer")
&& parent->parameters()->present(name, "writeSparseActivity")) {
Fatal().printf("writeSparseActivity is obsolete. Use sparseLayer instead.\n");
}
// writeSparseActivity was deprecated Nov 4, 2014 and marked obsolete Mar 14, 2017.
parent->parameters()->ioParamValue(ioFlag, name, "sparseLayer", &sparseLayer, false);
}
// writeSparseValues is obsolete as of Mar 14, 2017.
void HyPerLayer::ioParam_writeSparseValues(enum ParamsIOFlag ioFlag) {
if (ioFlag == PARAMS_IO_READ) {
assert(!parent->parameters()->presentAndNotBeenRead(name, "sparseLayer"));
if (sparseLayer && parent->parameters()->present(name, "writeSparseValues")) {
WarnLog() << "writeSparseValues parameter, defined in " << getDescription()
<< ", is obsolete.\n";
bool writeSparseValues;
parent->parameters()->ioParamValue(
ioFlag, name, "writeSparseValues", &writeSparseValues, true /*default value*/);
if (!writeSparseValues) {
WarnLog() << "The sparse-values format is used for all sparse layers.\n";
}
}
}
}
int HyPerLayer::respond(std::shared_ptr<BaseMessage const> message) {
int status = BaseLayer::respond(message);
if (status != PV_SUCCESS) {
return status;
}
else if (
LayerUpdateStateMessage const *castMessage =
dynamic_cast<LayerUpdateStateMessage const *>(message.get())) {
return respondLayerUpdateState(castMessage);
}
else if (
LayerRecvSynapticInputMessage const *castMessage =
dynamic_cast<LayerRecvSynapticInputMessage const *>(message.get())) {
return respondLayerRecvSynapticInput(castMessage);
}
#ifdef PV_USE_CUDA
else if (
LayerCopyFromGpuMessage const *castMessage =
dynamic_cast<LayerCopyFromGpuMessage const *>(message.get())) {
return respondLayerCopyFromGpu(castMessage);
}
#endif // PV_USE_CUDA
else if (
LayerAdvanceDataStoreMessage const *castMessage =
dynamic_cast<LayerAdvanceDataStoreMessage const *>(message.get())) {
return respondLayerAdvanceDataStore(castMessage);
}
else if (
LayerPublishMessage const *castMessage =
dynamic_cast<LayerPublishMessage const *>(message.get())) {
return respondLayerPublish(castMessage);
}
else if (
LayerOutputStateMessage const *castMessage =
dynamic_cast<LayerOutputStateMessage const *>(message.get())) {
return respondLayerOutputState(castMessage);
}
else if (
LayerCheckNotANumberMessage const *castMessage =
dynamic_cast<LayerCheckNotANumberMessage const *>(message.get())) {
return respondLayerCheckNotANumber(castMessage);
}
else {
return status;
}
}
int HyPerLayer::respondLayerRecvSynapticInput(LayerRecvSynapticInputMessage const *message) {
int status = PV_SUCCESS;
if (message->mPhase != getPhase()) {
return status;
}
#ifdef PV_USE_CUDA
if (message->mRecvOnGpuFlag != getRecvGpu()) {
return status;
}
#endif // PV_USE_CUDA
if (mHasReceived) {
return status;
}
if (!isAllInputReady()) {
return PV_POSTPONE;
}
resetGSynBuffers(message->mTime, message->mDeltaT); // deltaTimeAdapt is not used
message->mTimer->start();
recvAllSynapticInput();
message->mTimer->stop();
mHasReceived = true;
return status;
}
int HyPerLayer::respondLayerUpdateState(LayerUpdateStateMessage const *message) {
int status = PV_SUCCESS;
if (message->mPhase != getPhase()) {
return status;
}
#ifdef PV_USE_CUDA
if (message->mRecvOnGpuFlag != getRecvGpu()) {
return status;
}
if (message->mUpdateOnGpuFlag != getUpdateGpu()) {
return status;
}
#endif // PV_USE_CUDA
if (!mHasReceived) {
return PV_POSTPONE;
}
status = callUpdateState(message->mTime, message->mDeltaT);
mHasUpdated = true;
return status;
}
#ifdef PV_USE_CUDA
int HyPerLayer::respondLayerCopyFromGpu(LayerCopyFromGpuMessage const *message) {
int status = PV_SUCCESS;
if (message->mPhase != getPhase()) {
return status;
}
message->mTimer->start();
copyAllActivityFromDevice();
copyAllVFromDevice();
copyAllGSynFromDevice();
addGpuTimers();
message->mTimer->stop();
return status;
}
#endif // PV_USE_CUDA
int HyPerLayer::respondLayerAdvanceDataStore(LayerAdvanceDataStoreMessage const *message) {
if (message->mPhase < 0 || message->mPhase == getPhase()) {
publisher->increaseTimeLevel();
}
return PV_SUCCESS;
}
int HyPerLayer::respondLayerPublish(LayerPublishMessage const *message) {
int status = PV_SUCCESS;
if (message->mPhase != getPhase()) {
return status;
}
publish(getParent()->getCommunicator(), message->mTime);
return status;
}
int HyPerLayer::respondLayerCheckNotANumber(LayerCheckNotANumberMessage const *message) {
int status = PV_SUCCESS;
if (message->mPhase != getPhase()) {
return status;
}
auto layerData = getLayerData();
int const N = getNumExtendedAllBatches();
for (int n = 0; n < N; n++) {
float a = layerData[n];
if (a != a) {
status = PV_FAILURE;
break;
}
}
if (status != PV_SUCCESS) {
if (parent->columnId() == 0) {
ErrorLog() << getDescription()
<< " has not-a-number values in the activity buffer. Exiting.\n";
}
MPI_Barrier(parent->getCommunicator()->communicator());
exit(EXIT_FAILURE);
}
return status;
}
int HyPerLayer::respondLayerOutputState(LayerOutputStateMessage const *message) {
int status = PV_SUCCESS;
if (message->mPhase != getPhase()) {
return status;
}
status = outputState(message->mTime); // also calls layer probes' outputState
return status;
}
void HyPerLayer::clearProgressFlags() {
mHasReceived = false;
mHasUpdated = false;
}
#ifdef PV_USE_CUDA
int HyPerLayer::allocateUpdateKernel() {
Fatal() << "Layer \"" << name << "\" of type " << getKeyword()
<< " does not support updating on gpus yet\n";
return -1;
}
/**
* Allocate GPU buffers. This must be called after PVLayer data have
* been allocated.
*/
int HyPerLayer::allocateDeviceBuffers() {
int status = 0;
const size_t size = getNumNeuronsAllBatches() * sizeof(float);
const size_t size_ex = getNumExtendedAllBatches() * sizeof(float);
PVCuda::CudaDevice *device = parent->getDevice();
// Allocate based on which flags are set
if (allocDeviceV) {
d_V = device->createBuffer(size, &description);
}
if (allocDeviceDatastore) {
d_Datastore = device->createBuffer(size_ex, &description);
assert(d_Datastore);
#ifdef PV_USE_CUDNN
cudnn_Datastore = device->createBuffer(size_ex, &description);
assert(cudnn_Datastore);
#endif
}
if (allocDeviceActiveIndices) {
d_numActive = device->createBuffer(parent->getNBatch() * sizeof(long), &description);
d_ActiveIndices = device->createBuffer(
getNumExtendedAllBatches() * sizeof(SparseList<float>::Entry), &description);
assert(d_ActiveIndices);
}
if (allocDeviceActivity) {
d_Activity = device->createBuffer(size_ex, &description);
}
// d_GSyn is the entire gsyn buffer. cudnn_GSyn is only one gsyn channel
if (allocDeviceGSyn) {
d_GSyn = device->createBuffer(size * numChannels, &description);
assert(d_GSyn);
#ifdef PV_USE_CUDNN
cudnn_GSyn = device->createBuffer(size, &description);
#endif
}
return status;
}
#endif // PV_USE_CUDA
int HyPerLayer::communicateInitInfo() {
// HyPerLayers need to tell the parent HyPerCol how many random number
// seeds they need. At the start of HyPerCol::run, the parent HyPerCol
// calls each layer's communicateInitInfo() sequentially in a repeatable order
// (probably the order the layers appear in the params file) to make sure
// that the same runs use the same RNG seeds in the same way.
//
// If any other object in the column needs the layer to have a certain minimum
// margin width (e.g. a HyPerConn with patch size bigger than one), it should
// call the layer's requireMarginWidth() method during its communicateInitInfo
// stage.
//
// Since all communicateInitInfo() methods are called before any allocateDataStructures()
// methods, HyPerLayer knows its marginWidth before it has to allocate
// anything. So the margin width does not have to be specified in params.
if (triggerFlag) {
triggerLayer = parent->getLayerFromName(triggerLayerName);
if (triggerLayer == NULL) {
if (parent->columnId() == 0) {
ErrorLog().printf(
"%s: triggerLayerName \"%s\" is not a layer in the HyPerCol.\n",
getDescription_c(),
triggerLayerName);
}
MPI_Barrier(parent->getCommunicator()->communicator());
exit(EXIT_FAILURE);
}
if (triggerBehaviorType == RESETSTATE_TRIGGER) {
char const *resetLayerName = NULL; // Will point to name of actual resetLayer, whether
// triggerResetLayerName is blank (in which case
// resetLayerName==triggerLayerName) or not
if (triggerResetLayerName == NULL || triggerResetLayerName[0] == '\0') {
resetLayerName = triggerLayerName;
triggerResetLayer = triggerLayer;
}
else {
resetLayerName = triggerResetLayerName;
triggerResetLayer = parent->getLayerFromName(triggerResetLayerName);
if (triggerResetLayer == NULL) {
if (parent->columnId() == 0) {
ErrorLog().printf(
"%s: triggerResetLayerName \"%s\" is not a layer in the HyPerCol.\n",
getDescription_c(),
triggerResetLayerName);
}
MPI_Barrier(parent->getCommunicator()->communicator());
exit(EXIT_FAILURE);
}
}
// Check that triggerResetLayer and this layer have the same (restricted) dimensions.
// Do we need to postpone until triggerResetLayer has finished its communicateInitInfo?
PVLayerLoc const *triggerLoc = triggerResetLayer->getLayerLoc();
PVLayerLoc const *localLoc = this->getLayerLoc();
if (triggerLoc->nxGlobal != localLoc->nxGlobal
|| triggerLoc->nyGlobal != localLoc->nyGlobal
|| triggerLoc->nf != localLoc->nf) {
if (parent->columnId() == 0) {
Fatal(errorMessage);
errorMessage.printf(
"%s: triggerResetLayer \"%s\" has incompatible dimensions.\n",
getDescription_c(),
resetLayerName);
errorMessage.printf(
" \"%s\" is %d-by-%d-by-%d and \"%s\" is %d-by-%d-by-%d.\n",
name,
localLoc->nxGlobal,
localLoc->nyGlobal,
localLoc->nf,
resetLayerName,
triggerLoc->nxGlobal,
triggerLoc->nyGlobal,
triggerLoc->nf);
}
}
}
}
#ifdef PV_USE_CUDA
// Here, the connection tells all participating recev layers to allocate memory on gpu
// if receive from gpu is set. These buffers should be set in allocate
if (updateGpu) {
this->setAllocDeviceGSyn();
this->setAllocDeviceV();
this->setAllocDeviceActivity();
}
#endif
int status = PV_SUCCESS;
return status;
}
int HyPerLayer::openOutputStateFile(Checkpointer *checkpointer) {
pvAssert(writeStep >= 0);
if (checkpointer->getMPIBlock()->getRank() == 0) {
std::string outputStatePath(getName());
outputStatePath.append(".pvp");
std::string checkpointLabel(getName());
checkpointLabel.append("_filepos");
bool createFlag = checkpointer->getCheckpointReadDirectory().empty();
mOutputStateStream = new CheckpointableFileStream(
outputStatePath.c_str(), createFlag, checkpointer, checkpointLabel);
}
return PV_SUCCESS;
}
void HyPerLayer::synchronizeMarginWidth(HyPerLayer *layer) {
if (layer == this) {
return;
}
assert(layer->getLayerLoc() != NULL && this->getLayerLoc() != NULL);
HyPerLayer **newSynchronizedMarginWidthLayers =
(HyPerLayer **)calloc(numSynchronizedMarginWidthLayers + 1, sizeof(HyPerLayer *));
assert(newSynchronizedMarginWidthLayers);
if (numSynchronizedMarginWidthLayers > 0) {
for (int k = 0; k < numSynchronizedMarginWidthLayers; k++) {
newSynchronizedMarginWidthLayers[k] = synchronizedMarginWidthLayers[k];
}
free(synchronizedMarginWidthLayers);
}
else {
assert(synchronizedMarginWidthLayers == NULL);
}
synchronizedMarginWidthLayers = newSynchronizedMarginWidthLayers;
synchronizedMarginWidthLayers[numSynchronizedMarginWidthLayers] = layer;
numSynchronizedMarginWidthLayers++;
equalizeMargins(this, layer);
return;
}
int HyPerLayer::equalizeMargins(HyPerLayer *layer1, HyPerLayer *layer2) {
int border1, border2, maxborder, result;
int status = PV_SUCCESS;
border1 = layer1->getLayerLoc()->halo.lt;
border2 = layer2->getLayerLoc()->halo.lt;
maxborder = border1 > border2 ? border1 : border2;
layer1->requireMarginWidth(maxborder, &result, 'x');
if (result != maxborder) {
status = PV_FAILURE;
}
layer2->requireMarginWidth(maxborder, &result, 'x');
if (result != maxborder) {
status = PV_FAILURE;
}
if (status != PV_SUCCESS) {
Fatal().printf(
"Error in rank %d process: unable to synchronize x-margin widths of layers \"%s\" and "
"\"%s\" to %d\n",
layer1->getParent()->columnId(),
layer1->getName(),
layer2->getName(),
maxborder);
;
}
assert(
layer1->getLayerLoc()->halo.lt == layer2->getLayerLoc()->halo.lt
&& layer1->getLayerLoc()->halo.rt == layer2->getLayerLoc()->halo.rt
&& layer1->getLayerLoc()->halo.lt == layer1->getLayerLoc()->halo.rt
&& layer1->getLayerLoc()->halo.lt == maxborder);
border1 = layer1->getLayerLoc()->halo.dn;
border2 = layer2->getLayerLoc()->halo.dn;
maxborder = border1 > border2 ? border1 : border2;
layer1->requireMarginWidth(maxborder, &result, 'y');
if (result != maxborder) {
status = PV_FAILURE;
}
layer2->requireMarginWidth(maxborder, &result, 'y');
if (result != maxborder) {
status = PV_FAILURE;
}
if (status != PV_SUCCESS) {
Fatal().printf(
"Error in rank %d process: unable to synchronize y-margin widths of layers \"%s\" and "
"\"%s\" to %d\n",
layer1->getParent()->columnId(),
layer1->getName(),
layer2->getName(),
maxborder);
;
}
assert(
layer1->getLayerLoc()->halo.dn == layer2->getLayerLoc()->halo.dn
&& layer1->getLayerLoc()->halo.up == layer2->getLayerLoc()->halo.up
&& layer1->getLayerLoc()->halo.dn == layer1->getLayerLoc()->halo.up
&& layer1->getLayerLoc()->halo.dn == maxborder);
return status;
}
int HyPerLayer::allocateDataStructures() {
// Once initialize and communicateInitInfo have been called, HyPerLayer has the
// information it needs to allocate the membrane potential buffer V, the
// activity buffer activity->data, and the data store.
int status = PV_SUCCESS;
// Doing this check here, since trigger layers are being set up in communicateInitInfo
// If the magnitude of the trigger offset is bigger than the delta update time, then error
if (triggerFlag) {
double deltaUpdateTime = getDeltaUpdateTime();
if (deltaUpdateTime != -1 && triggerOffset >= deltaUpdateTime) {
Fatal().printf(
"%s error in rank %d process: TriggerOffset (%f) must be lower than the change in "
"update time (%f) \n",
getDescription_c(),
parent->columnId(),
triggerOffset,
deltaUpdateTime);
}
}
allocateClayerBuffers();
const PVLayerLoc *loc = getLayerLoc();
int nx = loc->nx;
int ny = loc->ny;
int nf = loc->nf;
PVHalo const *halo = &loc->halo;
// If not mirroring, fill the boundaries with the value in the valueBC param
if (!useMirrorBCs() && getValueBC() != 0.0f) {
int idx = 0;
for (int batch = 0; batch < loc->nbatch; batch++) {
for (int b = 0; b < halo->up; b++) {
for (int k = 0; k < (nx + halo->lt + halo->rt) * nf; k++) {
clayer->activity->data[idx] = getValueBC();
idx++;
}
}
for (int y = 0; y < ny; y++) {
for (int k = 0; k < halo->lt * nf; k++) {
clayer->activity->data[idx] = getValueBC();
idx++;
}
idx += nx * nf;
for (int k = 0; k < halo->rt * nf; k++) {
clayer->activity->data[idx] = getValueBC();
idx++;
}
}
for (int b = 0; b < halo->dn; b++) {
for (int k = 0; k < (nx + halo->lt + halo->rt) * nf; k++) {
clayer->activity->data[idx] = getValueBC();
idx++;
}
}
}
assert(idx == getNumExtendedAllBatches());
}
// allocate storage for the input conductance arrays
status = allocateBuffers();
assert(status == PV_SUCCESS);
// Allocate temp buffers if needed, 1 for each thread
if (parent->getNumThreads() > 1) {
thread_gSyn = (float **)malloc(sizeof(float *) * parent->getNumThreads());
assert(thread_gSyn);
// Assign thread_gSyn to different points of tempMem
for (int i = 0; i < parent->getNumThreads(); i++) {
float *tempMem = (float *)malloc(sizeof(float) * getNumNeuronsAllBatches());
if (!tempMem) {
Fatal().printf(
"HyPerLayer \"%s\" error: rank %d unable to allocate %zu memory for thread_gSyn: "
"%s\n",
name,
parent->columnId(),
sizeof(float) * getNumNeuronsAllBatches(),
strerror(errno));
}
thread_gSyn[i] = tempMem;
}
}
// Allocate cuda stuff on gpu if set
#ifdef PV_USE_CUDA
status = allocateDeviceBuffers();
// Allocate receive from post kernel
if (status == 0) {
status = PV_SUCCESS;
}
else {
Fatal().printf(
"%s unable to allocate device memory in rank %d process: %s\n",
getDescription_c(),
getParent()->columnId(),
strerror(errno));
}
if (updateGpu) {
// This function needs to be overwritten as needed on a subclass basis
status = allocateUpdateKernel();
if (status == 0) {
status = PV_SUCCESS;
}
}
#endif
// Make a data structure that stores the connections (in order of execution) this layer needs to
// recv from
// CPU connections must run first to avoid race conditions
int numConnections = parent->numberOfConnections();
for (int c = 0; c < numConnections; c++) {
BaseConnection *baseConn = parent->getConnection(c);
HyPerConn *conn = dynamic_cast<HyPerConn *>(baseConn);
if (conn->postSynapticLayer() != this)
continue;
#ifdef PV_USE_CUDA
// If not recv from gpu, execute first
if (!conn->getReceiveGpu()) {
recvConns.insert(recvConns.begin(), conn);
}
// Otherwise, add to the back. If no gpus at all, just add to back
else
#endif
{
recvConns.push_back(conn);
#ifdef PV_USE_CUDA
// If it is receiving from gpu, set layer flag as such
recvGpu = true;
#endif
}
}
addPublisher();
return status;
}
/*
* Call this routine to increase the number of levels in the data store ring buffer.
* Calls to this routine after the data store has been initialized will have no effect.
* The routine returns the new value of numDelayLevels
*/
int HyPerLayer::increaseDelayLevels(int neededDelay) {
if (numDelayLevels < neededDelay + 1)
numDelayLevels = neededDelay + 1;
if (numDelayLevels > MAX_F_DELAY)
numDelayLevels = MAX_F_DELAY;
return numDelayLevels;
}
int HyPerLayer::requireMarginWidth(int marginWidthNeeded, int *marginWidthResult, char axis) {
// TODO: Is there a good way to handle x- and y-axis margins without so much duplication of code?
// Navigating through the halo makes it difficult to combine cases.
PVLayerLoc *loc = &clayer->loc;
PVHalo *halo = &loc->halo;
switch (axis) {
case 'x':
*marginWidthResult = xmargin;
if (xmargin < marginWidthNeeded) {
assert(clayer);
if (parent->columnId() == 0) {
InfoLog().printf(
"%s: adjusting x-margin width from %d to %d\n",
getDescription_c(),
xmargin,
marginWidthNeeded);
}
xmargin = marginWidthNeeded;
halo->lt = xmargin;
halo->rt = xmargin;
calcNumExtended();
assert(axis == 'x' && getLayerLoc()->halo.lt == getLayerLoc()->halo.rt);
*marginWidthResult = xmargin;
if (synchronizedMarginWidthLayers != NULL) {
for (int k = 0; k < numSynchronizedMarginWidthLayers; k++) {
HyPerLayer *l = synchronizedMarginWidthLayers[k];
if (l->getLayerLoc()->halo.lt < marginWidthNeeded) {
synchronizedMarginWidthLayers[k]->requireMarginWidth(
marginWidthNeeded, marginWidthResult, axis);
}
assert(l->getLayerLoc()->halo.lt == getLayerLoc()->halo.lt);
assert(l->getLayerLoc()->halo.rt == getLayerLoc()->halo.rt);
}
}
}
break;
case 'y':
*marginWidthResult = ymargin;
if (ymargin < marginWidthNeeded) {
assert(clayer);
if (parent->columnId() == 0) {
InfoLog().printf(
"%s: adjusting y-margin width from %d to %d\n",
getDescription_c(),
ymargin,
marginWidthNeeded);
}
ymargin = marginWidthNeeded;
halo->dn = ymargin;
halo->up = ymargin;
calcNumExtended();
assert(axis == 'y' && getLayerLoc()->halo.dn == getLayerLoc()->halo.up);
*marginWidthResult = ymargin;
if (synchronizedMarginWidthLayers != NULL) {
for (int k = 0; k < numSynchronizedMarginWidthLayers; k++) {
HyPerLayer *l = synchronizedMarginWidthLayers[k];
if (l->getLayerLoc()->halo.up < marginWidthNeeded) {
synchronizedMarginWidthLayers[k]->requireMarginWidth(
marginWidthNeeded, marginWidthResult, axis);
}
assert(l->getLayerLoc()->halo.dn == getLayerLoc()->halo.dn);
assert(l->getLayerLoc()->halo.up == getLayerLoc()->halo.up);
}
}
}
break;
default: assert(0); break;
}
return PV_SUCCESS;
}
int HyPerLayer::requireChannel(int channelNeeded, int *numChannelsResult) {
if (channelNeeded >= numChannels) {
int numOldChannels = numChannels;
numChannels = channelNeeded + 1;
}
*numChannelsResult = numChannels;
return PV_SUCCESS;
}
/**
* Returns the activity data for the layer. This data is in the
* extended space (with margins).
*/
const float *HyPerLayer::getLayerData(int delay) {
PVLayerCube cube = publisher->createCube(delay);
return cube.data;
}
int HyPerLayer::mirrorInteriorToBorder(PVLayerCube *cube, PVLayerCube *border) {
assert(cube->numItems == border->numItems);
assert(localDimensionsEqual(&cube->loc, &border->loc));
mirrorToNorthWest(border, cube);
mirrorToNorth(border, cube);
mirrorToNorthEast(border, cube);
mirrorToWest(border, cube);
mirrorToEast(border, cube);
mirrorToSouthWest(border, cube);
mirrorToSouth(border, cube);
mirrorToSouthEast(border, cube);
return 0;
}
int HyPerLayer::registerData(Checkpointer *checkpointer, std::string const &objName) {
int status = BaseLayer::registerData(checkpointer, objName);
checkpointPvpActivityFloat(checkpointer, "A", getActivity(), true /*extended*/);
if (getV() != nullptr) {
checkpointPvpActivityFloat(checkpointer, "V", getV(), false /*not extended*/);
}
publisher->checkpointDataStore(checkpointer, getName(), "Delays");
checkpointer->registerCheckpointData(
std::string(getName()),
std::string("lastUpdateTime"),
&mLastUpdateTime,
(std::size_t)1,
true /*broadcast*/);
checkpointer->registerCheckpointData(
std::string(getName()),
std::string("nextWrite"),
&writeTime,
(std::size_t)1,
true /*broadcast*/);
mMPIBlock = checkpointer->getMPIBlock();
if (writeStep >= 0.0) {
openOutputStateFile(checkpointer);
if (sparseLayer) {
checkpointer->registerCheckpointData(
std::string(getName()),
std::string("numframes_sparse"),
&writeActivitySparseCalls,
(std::size_t)1,
true /*broadcast*/);
}
else {
checkpointer->registerCheckpointData(
std::string(getName()),
std::string("numframes"),
&writeActivityCalls,
(std::size_t)1,
true /*broadcast*/);
}
}
if (getNumDelayLevels() > 1) {
checkpointer->addObserver(this, BaseMessage());
}
// Timers
update_timer = new Timer(getName(), "layer", "update ");
checkpointer->registerTimer(update_timer);
recvsyn_timer = new Timer(getName(), "layer", "recvsyn");
checkpointer->registerTimer(recvsyn_timer);
#ifdef PV_USE_CUDA
auto cudaDevice = parent->getDevice();
if (cudaDevice) {
gpu_update_timer = new PVCuda::CudaTimer(getName(), "layer", "gpuupdate");
gpu_update_timer->setStream(cudaDevice->getStream());
checkpointer->registerTimer(gpu_update_timer);
gpu_recvsyn_timer = new PVCuda::CudaTimer(getName(), "layer", "gpurecvsyn");
gpu_recvsyn_timer->setStream(cudaDevice->getStream());
checkpointer->registerTimer(gpu_recvsyn_timer);
}
#endif // PV_USE_CUDA
publish_timer = new Timer(getName(), "layer", "publish");
checkpointer->registerTimer(publish_timer);
timescale_timer = new Timer(getName(), "layer", "timescale");
checkpointer->registerTimer(timescale_timer);
io_timer = new Timer(getName(), "layer", "io ");
checkpointer->registerTimer(io_timer);
if (mInitVObject) {
auto message = std::make_shared<RegisterDataMessage<Checkpointer>>(checkpointer);
mInitVObject->respond(message);
}
return PV_SUCCESS;
}
double HyPerLayer::getDeltaUpdateTime() {
if (triggerLayer != NULL && triggerBehaviorType == UPDATEONLY_TRIGGER) {
return getDeltaTriggerTime();
}
else {
return parent->getDeltaTime();
}
}
double HyPerLayer::getDeltaTriggerTime() {
if (triggerLayer != NULL) {
return triggerLayer->getDeltaUpdateTime();
}
else {
return -1;
}
}
bool HyPerLayer::needUpdate(double simTime, double dt) {
if (getDeltaUpdateTime() <= 0) {
return false;
}
if (mLastUpdateTime == simTime + triggerOffset) {
return true;
}
double timeToCheck = mLastUpdateTime;
if (triggerLayer != nullptr && triggerBehaviorType == UPDATEONLY_TRIGGER) {
timeToCheck = triggerLayer->getLastUpdateTime();
// If our target layer updates this tick, so do we
if (timeToCheck == simTime && triggerOffset == 0) {
return true;
}
}
if (simTime + triggerOffset >= timeToCheck + getDeltaUpdateTime()
&& simTime + triggerOffset + dt <= timeToCheck + getDeltaUpdateTime() + dt) {
return true;
}
return false;
}
bool HyPerLayer::needReset(double simTime, double dt) {
if (triggerLayer == nullptr) {
return false;
}
if (triggerBehaviorType != RESETSTATE_TRIGGER) {
return false;
}
if (getDeltaTriggerTime() <= 0) {
return false;
}
if (simTime >= mLastTriggerTime + getDeltaTriggerTime()) {
// TODO: test "simTime > mLastTriggerTime + getDeltaTriggerTime() - 0.5 * dt",
// to avoid roundoff issues.
return true;
}
return false;
}
int HyPerLayer::callUpdateState(double simTime, double dt) {
int status = PV_SUCCESS;
if (needUpdate(simTime, dt)) {
if (needReset(simTime, dt)) {
status = resetStateOnTrigger();
mLastTriggerTime = simTime;
}
update_timer->start();
#ifdef PV_USE_CUDA
if (updateGpu) {
gpu_update_timer->start();
float *gSynHead = GSyn == NULL ? NULL : GSyn[0];
assert(updateGpu);
status = updateStateGpu(simTime, dt);
gpu_update_timer->stop();
}
else {
#endif
status = updateState(simTime, dt);
#ifdef PV_USE_CUDA
}
// Activity updated, set flag to true
updatedDeviceActivity = true;
updatedDeviceDatastore = true;
#endif
update_timer->stop();
mNeedToPublish = true;
mLastUpdateTime = simTime;
}
return status;
}
int HyPerLayer::resetStateOnTrigger() {
assert(triggerResetLayer != NULL);
float *V = getV();
if (V == NULL) {
if (parent->columnId() == 0) {
ErrorLog().printf(
"%s: triggerBehavior is \"resetStateOnTrigger\" but layer does not have a membrane "
"potential.\n",
getDescription_c());
}
MPI_Barrier(parent->getCommunicator()->communicator());
exit(EXIT_FAILURE);
}
float const *resetV = triggerResetLayer->getV();
if (resetV != NULL) {
#ifdef PV_USE_OPENMP_THREADS
#pragma omp parallel for
#endif // PV_USE_OPENMP_THREADS
for (int k = 0; k < getNumNeuronsAllBatches(); k++) {
V[k] = resetV[k];
}
}
else {
float const *resetA = triggerResetLayer->getActivity();
PVLayerLoc const *loc = triggerResetLayer->getLayerLoc();
PVHalo const *halo = &loc->halo;
for (int b = 0; b < parent->getNBatch(); b++) {
float const *resetABatch = resetA + (b * triggerResetLayer->getNumExtended());
float *VBatch = V + (b * triggerResetLayer->getNumNeurons());
#ifdef PV_USE_OPENMP_THREADS
#pragma omp parallel for
#endif // PV_USE_OPENMP_THREADS
for (int k = 0; k < getNumNeurons(); k++) {
int kex = kIndexExtended(
k, loc->nx, loc->ny, loc->nf, halo->lt, halo->rt, halo->dn, halo->up);
VBatch[k] = resetABatch[kex];
}
}
}
int status = setActivity();
// Update V on GPU after CPU V gets set
#ifdef PV_USE_CUDA
if (updateGpu) {
getDeviceV()->copyToDevice(V);
// Right now, we're setting the activity on the CPU and memsetting the GPU memory
// TODO calculate this on the GPU
getDeviceActivity()->copyToDevice(clayer->activity->data);
// We need to updateDeviceActivity and Datastore if we're resetting V
updatedDeviceActivity = true;
updatedDeviceDatastore = true;
}
#endif
return status;
}
int HyPerLayer::resetGSynBuffers(double timef, double dt) {
int status = PV_SUCCESS;
if (GSyn == NULL)
return PV_SUCCESS;
resetGSynBuffers_HyPerLayer(
parent->getNBatch(), this->getNumNeurons(), getNumChannels(), GSyn[0]);
return status;
}
#ifdef PV_USE_CUDA
int HyPerLayer::runUpdateKernel() {
#ifdef PV_USE_CUDA
assert(updateGpu);
if (updatedDeviceGSyn) {
copyAllGSynToDevice();
updatedDeviceGSyn = false;
}
// V and Activity are write only buffers, so we don't need to do anything with them
assert(krUpdate);
// Sync all buffers before running
syncGpu();
// Run kernel
krUpdate->run();
#endif
return PV_SUCCESS;
}
int HyPerLayer::updateStateGpu(double timef, double dt) {
Fatal() << "Update state for layer " << name << " is not implemented\n";
return -1;
}
#endif
int HyPerLayer::updateState(double timef, double dt) {
// just copy accumulation buffer to membrane potential
// and activity buffer (nonspiking)
const PVLayerLoc *loc = getLayerLoc();
float *A = getCLayer()->activity->data;
float *V = getV();
int num_channels = getNumChannels();
float *gSynHead = GSyn == NULL ? NULL : GSyn[0];
int nx = loc->nx;
int ny = loc->ny;
int nf = loc->nf;
int nbatch = loc->nbatch;
int num_neurons = nx * ny * nf;
if (num_channels == 1) {
applyGSyn_HyPerLayer1Channel(nbatch, num_neurons, V, gSynHead);
}
else {
applyGSyn_HyPerLayer(nbatch, num_neurons, V, gSynHead);
}
setActivity_HyPerLayer(
nbatch,
num_neurons,
A,
V,
nx,
ny,
nf,
loc->halo.lt,
loc->halo.rt,
loc->halo.dn,
loc->halo.up);
return PV_SUCCESS;
}
int HyPerLayer::setActivity() {
const PVLayerLoc *loc = getLayerLoc();
return setActivity_HyPerLayer(
loc->nbatch,
getNumNeurons(),
clayer->activity->data,
getV(),
loc->nx,
loc->ny,
loc->nf,
loc->halo.lt,
loc->halo.rt,
loc->halo.dn,
loc->halo.up);
}
// Updates active indices for all levels (delays) here
int HyPerLayer::updateAllActiveIndices() { return publisher->updateAllActiveIndices(); }
int HyPerLayer::updateActiveIndices() { return publisher->updateActiveIndices(0); }
bool HyPerLayer::isExchangeFinished(int delay) { return publisher->isExchangeFinished(delay); }
bool HyPerLayer::isAllInputReady() {
bool isReady = true;
for (auto &c : recvConns) {
for (int a = 0; a < c->numberOfAxonalArborLists(); a++) {
isReady &= c->getPre()->isExchangeFinished(c->getDelay(a));
}
}
return isReady;
}
int HyPerLayer::recvAllSynapticInput() {
int status = PV_SUCCESS;
// Only recvAllSynapticInput if we need an update
if (needUpdate(parent->simulationTime(), parent->getDeltaTime())) {
bool switchGpu = false;
// Start CPU timer here
recvsyn_timer->start();
for (auto &conn : recvConns) {
pvAssert(conn != NULL);
#ifdef PV_USE_CUDA
// Check if it's done with cpu connections
if (!switchGpu && conn->getReceiveGpu()) {
// Copy GSyn over to GPU
copyAllGSynToDevice();
// Start gpu timer
gpu_recvsyn_timer->start();
switchGpu = true;
}
#endif
conn->deliver();
}
#ifdef PV_USE_CUDA
if (switchGpu) {
// Stop timer
gpu_recvsyn_timer->stop();
}
#endif
recvsyn_timer->stop();
}
return status;
}
#ifdef PV_USE_CUDA
double HyPerLayer::addGpuTimers() {
double simTime = 0;
bool updateNeeded = needUpdate(parent->simulationTime(), parent->getDeltaTime());
if (recvGpu && updateNeeded) {
simTime += gpu_recvsyn_timer->accumulateTime();
}
if (updateGpu && updateNeeded) {
simTime += gpu_update_timer->accumulateTime();
}
return simTime;
}
void HyPerLayer::syncGpu() {
if (recvGpu || updateGpu) {
parent->getDevice()->syncDevice();
}
}
void HyPerLayer::copyAllGSynToDevice() {
if (recvGpu || updateGpu) {
// Copy it to device
// Allocated as a big chunk, this should work
float *h_postGSyn = GSyn[0];
PVCuda::CudaBuffer *d_postGSyn = this->getDeviceGSyn();
assert(d_postGSyn);
d_postGSyn->copyToDevice(h_postGSyn);
}
}
void HyPerLayer::copyAllGSynFromDevice() {
// Only copy if recving
if (recvGpu) {
// Allocated as a big chunk, this should work
float *h_postGSyn = GSyn[0];
PVCuda::CudaBuffer *d_postGSyn = this->getDeviceGSyn();
assert(d_postGSyn);
d_postGSyn->copyFromDevice(h_postGSyn);
}
}
void HyPerLayer::copyAllVFromDevice() {
// Only copy if updating
if (updateGpu) {
// Allocated as a big chunk, this should work
float *h_V = getV();
PVCuda::CudaBuffer *d_V = this->getDeviceV();
assert(d_V);
d_V->copyFromDevice(h_V);
}
}
void HyPerLayer::copyAllActivityFromDevice() {
// Only copy if updating
if (updateGpu) {
// Allocated as a big chunk, this should work
float *h_activity = getCLayer()->activity->data;
PVCuda::CudaBuffer *d_activity = this->getDeviceActivity();
assert(d_activity);
d_activity->copyFromDevice(h_activity);
}
}
#endif
int HyPerLayer::publish(Communicator *comm, double simTime) {
publish_timer->start();
int status = PV_SUCCESS;
if (mNeedToPublish) {
if (useMirrorBCs()) {
mirrorInteriorToBorder(clayer->activity, clayer->activity);
}
status = publisher->publish(mLastUpdateTime);
mNeedToPublish = false;
}
else {
publisher->copyForward(mLastUpdateTime);
}
publish_timer->stop();
return status;
}
int HyPerLayer::waitOnPublish(Communicator *comm) {
publish_timer->start();
// wait for MPI border transfers to complete
//
int status = publisher->wait();
publish_timer->stop();
return status;
}
/******************************************************************
* FileIO
*****************************************************************/
/* Inserts a new probe into an array of LayerProbes.
*
*
*
*/
int HyPerLayer::insertProbe(LayerProbe *p) {
if (p->getTargetLayer() != this) {
WarnLog().printf(
"HyPerLayer \"%s\": insertProbe called with probe %p, whose targetLayer is not this "
"layer. Probe was not inserted.\n",
name,
p);
return numProbes;
}
for (int i = 0; i < numProbes; i++) {
if (p == probes[i]) {
WarnLog().printf(
"HyPerLayer \"%s\": insertProbe called with probe %p, which has already been "
"inserted as probe %d.\n",
name,
p,
i);
return numProbes;
}
}
// malloc'ing a new buffer, copying data over, and freeing the old buffer could be replaced by
// malloc
LayerProbe **tmp;
tmp = (LayerProbe **)malloc((numProbes + 1) * sizeof(LayerProbe *));
assert(tmp != NULL);
for (int i = 0; i < numProbes; i++) {
tmp[i] = probes[i];
}
free(probes);
probes = tmp;
probes[numProbes] = p;
return ++numProbes;
}
int HyPerLayer::outputProbeParams() {
int status = PV_SUCCESS;
for (int p = 0; p < numProbes; p++) {
int status1 = probes[p]->ioParams(PARAMS_IO_WRITE);
if (status1 != PV_SUCCESS) {
status = PV_FAILURE;
}
}
return status;
}
int HyPerLayer::outputState(double timef) {
int status = PV_SUCCESS;
io_timer->start();
for (int i = 0; i < numProbes; i++) {
probes[i]->outputStateWrapper(timef, parent->getDeltaTime());
}
if (timef >= (writeTime - (parent->getDeltaTime() / 2)) && writeStep >= 0) {
writeTime += writeStep;
if (sparseLayer) {
status = writeActivitySparse(timef);
}
else {
status = writeActivity(timef);
}
}
if (status != PV_SUCCESS) {
Fatal().printf(
"%s: outputState failed on rank %d process.\n", getDescription_c(), parent->columnId());
}
io_timer->stop();
return status;
}
int HyPerLayer::readStateFromCheckpoint(Checkpointer *checkpointer) {
int status = PV_SUCCESS;
if (initializeFromCheckpointFlag) {
status = readActivityFromCheckpoint(checkpointer);
status = readVFromCheckpoint(checkpointer);
status = readDelaysFromCheckpoint(checkpointer);
updateAllActiveIndices();
}
return status;
}
int HyPerLayer::readActivityFromCheckpoint(Checkpointer *checkpointer) {
checkpointer->readNamedCheckpointEntry(std::string(name), std::string("A"));
return PV_SUCCESS;
}
int HyPerLayer::readVFromCheckpoint(Checkpointer *checkpointer) {
if (getV() != nullptr) {
checkpointer->readNamedCheckpointEntry(std::string(name), std::string("V"));
}
return PV_SUCCESS;
}
int HyPerLayer::readDelaysFromCheckpoint(Checkpointer *checkpointer) {
checkpointer->readNamedCheckpointEntry(std::string(name), std::string("Delays"));
return PV_SUCCESS;
}
// readBufferFile and readDataStoreFromFile were removed Jan 23, 2017.
// They were only used by checkpointing, which is now handled by the
// CheckpointEntry class hierarchy.
int HyPerLayer::processCheckpointRead() {
if (mOutputStateStream) {
long fpos = mOutputStateStream->getInPos();
if (fpos > 0L) {
BufferUtils::ActivityHeader header = BufferUtils::readActivityHeader(*mOutputStateStream);
if (sparseLayer) {
writeActivitySparseCalls = header.nBands;
}
else {
writeActivityCalls = header.nBands;
}
}
mOutputStateStream->setInPos(fpos, true);
}
return updateAllActiveIndices();
}
int HyPerLayer::writeActivitySparse(double timed) {
PVLayerCube cube = publisher->createCube(0);
PVLayerLoc const *loc = getLayerLoc();
pvAssert(cube.numItems == loc->nbatch * getNumExtended());
int const mpiBatchDimension = mMPIBlock->getBatchDimension();
int const numFrames = mpiBatchDimension * loc->nbatch;
for (int frame = 0; frame < numFrames; frame++) {
int const localBatchIndex = frame % loc->nbatch;
int const mpiBatchIndex = frame / loc->nbatch; // Integer division
pvAssert(mpiBatchIndex * loc->nbatch + localBatchIndex == frame);
SparseList<float> list;
auto *activeIndices = (SparseList<float>::Entry const *)cube.activeIndices;
PVLayerLoc const *loc = getLayerLoc();
int nxExt = loc->nx + loc->halo.lt + loc->halo.rt;
int nyExt = loc->ny + loc->halo.dn + loc->halo.up;
int nf = loc->nf;
for (long int k = 0; k < cube.numActive[localBatchIndex]; k++) {
SparseList<float>::Entry entry = activeIndices[k];
int index = (int)entry.index;
// Location is local extended; need global restricted.
int x = kxPos(index, nxExt, nyExt, nf) - loc->halo.lt + loc->kx0;
if (x < 0 or x >= loc->nxGlobal) {
continue;
}
int y = kyPos(index, nxExt, nyExt, nf) - loc->halo.up + loc->ky0;
if (y < 0 or y >= loc->nyGlobal) {
continue;
}
int f = featureIndex(index, nxExt, nyExt, nf);
entry.index = (uint32_t)kIndex(x, y, f, loc->nxGlobal, loc->nyGlobal, nf);
list.addEntry(entry);
}
auto gatheredList =
BufferUtils::gatherSparse(mMPIBlock, list, mpiBatchIndex, 0 /*root process*/);
if (mMPIBlock->getRank() == 0) {
long fpos = mOutputStateStream->getOutPos();
if (fpos == 0L) {
BufferUtils::ActivityHeader header = BufferUtils::buildSparseActivityHeader<float>(
loc->nx * mMPIBlock->getNumColumns(),
loc->ny * mMPIBlock->getNumRows(),
loc->nf,
0 /* numBands */); // numBands will be set by call to incrementNBands.
header.timestamp = timed;
BufferUtils::writeActivityHeader(*mOutputStateStream, header);
}
BufferUtils::writeSparseFrame(*mOutputStateStream, &gatheredList, timed);
}
}
writeActivitySparseCalls += numFrames;
updateNBands(writeActivitySparseCalls);
return PV_SUCCESS;
}
// write non-spiking activity
int HyPerLayer::writeActivity(double timed) {
PVLayerCube cube = publisher->createCube(0);
PVLayerLoc const *loc = getLayerLoc();
pvAssert(cube.numItems == loc->nbatch * getNumExtended());
PVHalo const &halo = loc->halo;
int const nxExtLocal = loc->nx + halo.lt + halo.rt;
int const nyExtLocal = loc->ny + halo.dn + halo.up;
int const nf = loc->nf;
int const mpiBatchDimension = mMPIBlock->getBatchDimension();
int const numFrames = mpiBatchDimension * loc->nbatch;
for (int frame = 0; frame < numFrames; frame++) {
int const localBatchIndex = frame % loc->nbatch;
int const mpiBatchIndex = frame / loc->nbatch; // Integer division
pvAssert(mpiBatchIndex * loc->nbatch + localBatchIndex == frame);
float *data = &cube.data[localBatchIndex * getNumExtended()];
Buffer<float> localBuffer(data, nxExtLocal, nyExtLocal, nf);
localBuffer.crop(loc->nx, loc->ny, Buffer<float>::CENTER);
Buffer<float> blockBuffer = BufferUtils::gather<float>(
mMPIBlock, localBuffer, loc->nx, loc->ny, mpiBatchIndex, 0 /*root process*/);
// At this point, the rank-zero process has the entire block for the batch element,
// regardless of what the mpiBatchIndex is.
if (mMPIBlock->getRank() == 0) {
long fpos = mOutputStateStream->getOutPos();
if (fpos == 0L) {
BufferUtils::ActivityHeader header = BufferUtils::buildActivityHeader<float>(
loc->nx * mMPIBlock->getNumColumns(),
loc->ny * mMPIBlock->getNumRows(),
loc->nf,
0 /* numBands */); // numBands will be set by call to incrementNBands.
header.timestamp = timed;
BufferUtils::writeActivityHeader(*mOutputStateStream, header);
}
BufferUtils::writeFrame<float>(*mOutputStateStream, &blockBuffer, timed);
}
}
writeActivityCalls += numFrames;
updateNBands(writeActivityCalls);
return PV_SUCCESS;
}
void HyPerLayer::updateNBands(int const numCalls) {
// Only the root process needs to maintain INDEX_NBANDS, so only the root process modifies
// numCalls
// This way, writeActivityCalls does not need to be coordinated across MPI
if (mOutputStateStream != nullptr) {
long int fpos = mOutputStateStream->getOutPos();
mOutputStateStream->setOutPos(sizeof(int) * INDEX_NBANDS, true /*fromBeginning*/);
mOutputStateStream->write(&numCalls, (long)sizeof(numCalls));
mOutputStateStream->setOutPos(fpos, true /*fromBeginning*/);
}
}
bool HyPerLayer::localDimensionsEqual(PVLayerLoc const *loc1, PVLayerLoc const *loc2) {
return loc1->nbatch == loc2->nbatch && loc1->nx == loc2->nx && loc1->ny == loc2->ny
&& loc1->nf == loc2->nf && loc1->halo.lt == loc2->halo.lt
&& loc1->halo.rt == loc2->halo.rt && loc1->halo.dn == loc2->halo.dn
&& loc1->halo.up == loc2->halo.up;
}
int HyPerLayer::mirrorToNorthWest(PVLayerCube *dest, PVLayerCube *src) {
if (!localDimensionsEqual(&dest->loc, &src->loc)) {
return -1;
}
int nbatch = dest->loc.nbatch;
int nf = dest->loc.nf;
int leftBorder = dest->loc.halo.lt;
int topBorder = dest->loc.halo.up;
size_t sb = strideBExtended(&dest->loc);
size_t sf = strideFExtended(&dest->loc);
size_t sx = strideXExtended(&dest->loc);
size_t sy = strideYExtended(&dest->loc);
for (int b = 0; b < nbatch; b++) {
float *srcData = src->data + b * sb;
float *destData = dest->data + b * sb;
float *src0 = srcData + topBorder * sy + leftBorder * sx;
float *dst0 = srcData + (topBorder - 1) * sy + (leftBorder - 1) * sx;
for (int ky = 0; ky < topBorder; ky++) {
float *to = dst0 - ky * sy;
float *from = src0 + ky * sy;
for (int kx = 0; kx < leftBorder; kx++) {
for (int kf = 0; kf < nf; kf++) {
to[kf * sf] = from[kf * sf];
}
to -= nf;
from += nf;
}
}
}
return 0;
}
int HyPerLayer::mirrorToNorth(PVLayerCube *dest, PVLayerCube *src) {
if (!localDimensionsEqual(&dest->loc, &src->loc)) {
return -1;
}
int nx = clayer->loc.nx;
int nf = clayer->loc.nf;
int leftBorder = dest->loc.halo.lt;
int topBorder = dest->loc.halo.up;
int nbatch = dest->loc.nbatch;
size_t sb = strideBExtended(&dest->loc);
size_t sf = strideFExtended(&dest->loc);
size_t sx = strideXExtended(&dest->loc);
size_t sy = strideYExtended(&dest->loc);
for (int b = 0; b < nbatch; b++) {
float *srcData = src->data + b * sb;
float *destData = dest->data + b * sb;
float *src0 = srcData + topBorder * sy + leftBorder * sx;
float *dst0 = destData + (topBorder - 1) * sy + leftBorder * sx;
for (int ky = 0; ky < topBorder; ky++) {
float *to = dst0 - ky * sy;
float *from = src0 + ky * sy;
for (int kx = 0; kx < nx; kx++) {
for (int kf = 0; kf < nf; kf++) {
to[kf * sf] = from[kf * sf];
}
to += nf;
from += nf;
}
}
}
return 0;
}
int HyPerLayer::mirrorToNorthEast(PVLayerCube *dest, PVLayerCube *src) {
if (!localDimensionsEqual(&dest->loc, &src->loc)) {
return -1;
}
int nx = dest->loc.nx;
int nf = dest->loc.nf;
int leftBorder = dest->loc.halo.lt;
int rightBorder = dest->loc.halo.rt;
int topBorder = dest->loc.halo.up;
int nbatch = dest->loc.nbatch;
size_t sb = strideBExtended(&dest->loc);
size_t sf = strideFExtended(&dest->loc);
size_t sx = strideXExtended(&dest->loc);
size_t sy = strideYExtended(&dest->loc);
for (int b = 0; b < nbatch; b++) {
float *srcData = src->data + b * sb;
float *destData = dest->data + b * sb;
float *src0 = srcData + topBorder * sy + (nx + leftBorder - 1) * sx;
float *dst0 = destData + (topBorder - 1) * sy + (nx + leftBorder) * sx;
for (int ky = 0; ky < topBorder; ky++) {
float *to = dst0 - ky * sy;
float *from = src0 + ky * sy;
for (int kx = 0; kx < rightBorder; kx++) {
for (int kf = 0; kf < nf; kf++) {
to[kf * sf] = from[kf * sf];
}
to += nf;
from -= nf;
}
}
}
return 0;
}
int HyPerLayer::mirrorToWest(PVLayerCube *dest, PVLayerCube *src) {
if (!localDimensionsEqual(&dest->loc, &src->loc)) {
return -1;
}
int ny = dest->loc.ny;
int nf = dest->loc.nf;
int leftBorder = dest->loc.halo.lt;
int topBorder = dest->loc.halo.up;
int nbatch = dest->loc.nbatch;
size_t sb = strideBExtended(&dest->loc);
size_t sf = strideFExtended(&dest->loc);
size_t sx = strideXExtended(&dest->loc);
size_t sy = strideYExtended(&dest->loc);
for (int b = 0; b < nbatch; b++) {
float *srcData = src->data + b * sb;
float *destData = dest->data + b * sb;
float *src0 = srcData + topBorder * sy + leftBorder * sx;
float *dst0 = destData + topBorder * sy + (leftBorder - 1) * sx;
for (int ky = 0; ky < ny; ky++) {
float *to = dst0 + ky * sy;
float *from = src0 + ky * sy;
for (int kx = 0; kx < leftBorder; kx++) {
for (int kf = 0; kf < nf; kf++) {
to[kf * sf] = from[kf * sf];
}
to -= nf;
from += nf;
}
}
}
return 0;
}
int HyPerLayer::mirrorToEast(PVLayerCube *dest, PVLayerCube *src) {
if (!localDimensionsEqual(&dest->loc, &src->loc)) {
return -1;
}
int nx = clayer->loc.nx;
int ny = clayer->loc.ny;
int nf = clayer->loc.nf;
int leftBorder = dest->loc.halo.lt;
int rightBorder = dest->loc.halo.rt;
int topBorder = dest->loc.halo.up;
int nbatch = dest->loc.nbatch;
size_t sb = strideBExtended(&dest->loc);
size_t sf = strideFExtended(&dest->loc);
size_t sx = strideXExtended(&dest->loc);
size_t sy = strideYExtended(&dest->loc);
for (int b = 0; b < nbatch; b++) {
float *srcData = src->data + b * sb;
float *destData = dest->data + b * sb;
float *src0 = srcData + topBorder * sy + (nx + leftBorder - 1) * sx;
float *dst0 = destData + topBorder * sy + (nx + leftBorder) * sx;
for (int ky = 0; ky < ny; ky++) {
float *to = dst0 + ky * sy;
float *from = src0 + ky * sy;
for (int kx = 0; kx < rightBorder; kx++) {
for (int kf = 0; kf < nf; kf++) {
to[kf * sf] = from[kf * sf];
}
to += nf;
from -= nf;
}
}
}
return 0;
}
int HyPerLayer::mirrorToSouthWest(PVLayerCube *dest, PVLayerCube *src) {
if (!localDimensionsEqual(&dest->loc, &src->loc)) {
return -1;
}
int ny = dest->loc.ny;
int nf = dest->loc.nf;
int leftBorder = dest->loc.halo.lt;
int topBorder = dest->loc.halo.up;
int bottomBorder = dest->loc.halo.dn;
int nbatch = dest->loc.nbatch;
size_t sb = strideBExtended(&dest->loc);
size_t sf = strideFExtended(&dest->loc);
size_t sx = strideXExtended(&dest->loc);
size_t sy = strideYExtended(&dest->loc);
for (int b = 0; b < nbatch; b++) {
float *srcData = src->data + b * sb;
float *destData = dest->data + b * sb;
float *src0 = srcData + (ny + topBorder - 1) * sy + leftBorder * sx;
float *dst0 = destData + (ny + topBorder) * sy + (leftBorder - 1) * sx;
for (int ky = 0; ky < bottomBorder; ky++) {
float *to = dst0 + ky * sy;
float *from = src0 - ky * sy;
for (int kx = 0; kx < leftBorder; kx++) {
for (int kf = 0; kf < nf; kf++) {
to[kf * sf] = from[kf * sf];
}
to -= nf;
from += nf;
}
}
}
return 0;
}
int HyPerLayer::mirrorToSouth(PVLayerCube *dest, PVLayerCube *src) {
if (!localDimensionsEqual(&dest->loc, &src->loc)) {
return -1;
}
int nx = dest->loc.nx;
int ny = dest->loc.ny;
int nf = dest->loc.nf;
int leftBorder = dest->loc.halo.lt;
int rightBorder = dest->loc.halo.rt;
int topBorder = dest->loc.halo.up;
int bottomBorder = dest->loc.halo.dn;
int nbatch = dest->loc.nbatch;
size_t sb = strideBExtended(&dest->loc);
size_t sf = strideFExtended(&dest->loc);
size_t sx = strideXExtended(&dest->loc);
size_t sy = strideYExtended(&dest->loc);
for (int b = 0; b < nbatch; b++) {
float *srcData = src->data + b * sb;
float *destData = dest->data + b * sb;
float *src0 = srcData + (ny + topBorder - 1) * sy + leftBorder * sx;
float *dst0 = destData + (ny + topBorder) * sy + leftBorder * sx;
for (int ky = 0; ky < bottomBorder; ky++) {
float *to = dst0 + ky * sy;
float *from = src0 - ky * sy;
for (int kx = 0; kx < nx; kx++) {
for (int kf = 0; kf < nf; kf++) {
to[kf * sf] = from[kf * sf];
}
to += nf;
from += nf;
}
}
}
return 0;
}
int HyPerLayer::mirrorToSouthEast(PVLayerCube *dest, PVLayerCube *src) {
if (!localDimensionsEqual(&dest->loc, &src->loc)) {
return -1;
}
int nx = dest->loc.nx;
int ny = dest->loc.ny;
int nf = dest->loc.nf;
int leftBorder = dest->loc.halo.lt;
int rightBorder = dest->loc.halo.rt;
int topBorder = dest->loc.halo.up;
int bottomBorder = dest->loc.halo.dn;
int nbatch = dest->loc.nbatch;
size_t sb = strideBExtended(&dest->loc);
size_t sf = strideFExtended(&dest->loc);
size_t sx = strideXExtended(&dest->loc);
size_t sy = strideYExtended(&dest->loc);
for (int b = 0; b < nbatch; b++) {
float *srcData = src->data + b * sb;
float *destData = dest->data + b * sb;
float *src0 = srcData + (ny + topBorder - 1) * sy + (nx + leftBorder - 1) * sx;
float *dst0 = destData + (ny + topBorder) * sy + (nx + leftBorder) * sx;
for (int ky = 0; ky < bottomBorder; ky++) {
float *to = dst0 + ky * sy;
float *from = src0 - ky * sy;
for (int kx = 0; kx < rightBorder; kx++) {
for (int kf = 0; kf < nf; kf++) {
to[kf * sf] = from[kf * sf];
}
to += nf;
from -= nf;
}
}
}
return 0;
}
} // end of PV namespace
Bugfix for writeActivitySparse when using batches
/*
* HyPerLayer.cpp
*
* Created on: Jul 29, 2008
*
* The top of the hierarchy for layer classes.
*
* To make it easy to subclass from classes in the HyPerLayer hierarchy,
* please follow the guidelines below when adding subclasses to the HyPerLayer hierarchy:
*
* For a class named DerivedLayer that is derived from a class named BaseLayer,
* the .hpp file should have
*/
#include "HyPerLayer.hpp"
#include "checkpointing/CheckpointEntryPvpBuffer.hpp"
#include "checkpointing/CheckpointEntryRandState.hpp"
#include "columns/HyPerCol.hpp"
#include "connections/BaseConnection.hpp"
#include "connections/TransposeConn.hpp"
#include "include/default_params.h"
#include "include/pv_common.h"
#include "io/FileStream.hpp"
#include "io/io.hpp"
#include <assert.h>
#include <iostream>
#include <sstream>
#include <string.h>
namespace PV {
// This constructor is protected so that only derived classes can call it.
// It should be called as the normal method of object construction by
// derived classes. It should NOT call any virtual methods
HyPerLayer::HyPerLayer() { initialize_base(); }
HyPerLayer::HyPerLayer(const char *name, HyPerCol *hc) {
initialize_base();
initialize(name, hc);
}
// initialize_base should be called only by constructors. It should not
// call any virtual methods, because polymorphism is not available when
// a base class constructor is inherited from a derived class constructor.
// In general, initialize_base should be used only to initialize member variables
// to safe values.
int HyPerLayer::initialize_base() {
name = NULL;
probes = NULL;
nxScale = 1.0f;
nyScale = 1.0f;
numFeatures = 1;
mirrorBCflag = 0;
xmargin = 0;
ymargin = 0;
numProbes = 0;
numChannels = 2;
clayer = NULL;
GSyn = NULL;
marginIndices = NULL;
numMargin = 0;
writeTime = 0;
initialWriteTime = 0;
triggerFlag = false; // Default to update every timestamp
triggerLayer = NULL;
triggerLayerName = NULL;
triggerBehavior = NULL;
triggerBehaviorType = NO_TRIGGER;
triggerResetLayerName = NULL;
triggerOffset = 0;
initializeFromCheckpointFlag = false;
mLastUpdateTime = 0.0;
mLastTriggerTime = 0.0;
phase = 0;
numSynchronizedMarginWidthLayers = 0;
synchronizedMarginWidthLayers = NULL;
dataType = PV_FLOAT;
dataTypeString = NULL;
#ifdef PV_USE_CUDA
allocDeviceV = false;
allocDeviceGSyn = false;
allocDeviceActivity = false;
allocDeviceDatastore = false;
allocDeviceActiveIndices = false;
d_V = NULL;
d_GSyn = NULL;
d_Activity = NULL;
d_Datastore = NULL;
d_ActiveIndices = NULL;
d_numActive = NULL;
updatedDeviceActivity = true; // Start off always updating activity
updatedDeviceDatastore = true;
updatedDeviceGSyn = true;
recvGpu = false;
updateGpu = false;
krUpdate = NULL;
#ifdef PV_USE_CUDNN
cudnn_GSyn = NULL;
cudnn_Datastore = NULL;
#endif // PV_USE_CUDNN
#endif // PV_USE_CUDA
update_timer = NULL;
recvsyn_timer = NULL;
publish_timer = NULL;
timescale_timer = NULL;
io_timer = NULL;
#ifdef PV_USE_CUDA
gpu_recvsyn_timer = NULL;
gpu_update_timer = NULL;
#endif
thread_gSyn = NULL;
recvConns.clear();
return PV_SUCCESS;
}
///////
/// Classes derived from HyPerLayer should call HyPerLayer::initialize themselves
/// to take advantage of virtual methods. Note that the HyPerLayer constructor
/// does not call initialize. This way, HyPerLayer::initialize can call virtual
/// methods and the derived class's method will be the one that gets called.
int HyPerLayer::initialize(const char *name, HyPerCol *hc) {
int status = BaseLayer::initialize(name, hc);
if (status != PV_SUCCESS) {
return status;
}
PVParams *params = hc->parameters();
status = ioParams(PARAMS_IO_READ);
assert(status == PV_SUCCESS);
writeTime = initialWriteTime;
writeActivityCalls = 0;
writeActivitySparseCalls = 0;
numDelayLevels = 1; // If a connection has positive delay so that more delay levels are needed,
// numDelayLevels is increased when BaseConnection::communicateInitInfo calls
// increaseDelayLevels
maxRate = 1000.0f / (float)hc->getDeltaTime();
initClayer();
hc->addLayer(this);
mLastUpdateTime = hc->getDeltaTime();
mLastTriggerTime = hc->getDeltaTime();
return PV_SUCCESS;
}
int HyPerLayer::initClayer() {
clayer = (PVLayer *)calloc(1UL, sizeof(PVLayer));
int status = PV_SUCCESS;
if (clayer == NULL) {
Fatal().printf(
"HyPerLayer \"%s\" error in rank %d process: unable to allocate memory for Clayer.\n",
name,
parent->columnId());
}
PVLayerLoc *loc = &clayer->loc;
setLayerLoc(loc, nxScale, nyScale, numFeatures, parent->getNBatch());
assert(loc->halo.lt == 0 && loc->halo.rt == 0 && loc->halo.dn == 0 && loc->halo.up == 0);
int nBatch = parent->getNBatch();
clayer->numNeurons = loc->nx * loc->ny * loc->nf;
clayer->numExtended = clayer->numNeurons; // initially, margin is zero; it will be updated as
// needed during the communicateInitInfo stage.
clayer->numNeuronsAllBatches = nBatch * loc->nx * loc->ny * loc->nf;
clayer->numExtendedAllBatches = clayer->numNeuronsAllBatches;
double xScaled = -log2((double)nxScale);
double yScaled = -log2((double)nyScale);
int xScale = (int)nearbyint(xScaled);
int yScale = (int)nearbyint(yScaled);
clayer->xScale = xScale;
clayer->yScale = yScale;
// Other fields of clayer will be set in allocateClayerBuffers, or during updateState
return status;
}
HyPerLayer::~HyPerLayer() {
delete recvsyn_timer;
delete update_timer;
delete publish_timer;
delete timescale_timer;
delete io_timer;
#ifdef PV_USE_CUDA
delete gpu_recvsyn_timer;
delete gpu_update_timer;
#endif
delete mOutputStateStream;
delete mInitVObject;
freeClayer();
freeChannels();
#ifdef PV_USE_CUDA
if (krUpdate) {
delete krUpdate;
}
if (d_V) {
delete d_V;
}
if (d_Activity) {
delete d_Activity;
}
if (d_Datastore) {
delete d_Datastore;
}
#ifdef PV_USE_CUDNN
if (cudnn_Datastore) {
delete cudnn_Datastore;
}
#endif // PV_USE_CUDNN
#endif // PV_USE_CUDA
free(marginIndices);
free(probes); // All probes are deleted by the HyPerCol, so probes[i] doesn't need to be deleted,
// only the array itself.
free(synchronizedMarginWidthLayers);
free(triggerLayerName);
free(triggerBehavior);
free(triggerResetLayerName);
free(initVTypeString);
if (thread_gSyn) {
for (int i = 0; i < parent->getNumThreads(); i++) {
free(thread_gSyn[i]);
}
free(thread_gSyn);
}
delete publisher;
}
template <typename T>
int HyPerLayer::freeBuffer(T **buf) {
free(*buf);
*buf = NULL;
return PV_SUCCESS;
}
// Declare the instantiations of allocateBuffer that occur in other .cpp files; otherwise you may
// get linker errors.
template int HyPerLayer::freeBuffer<float>(float **buf);
template int HyPerLayer::freeBuffer<int>(int **buf);
int HyPerLayer::freeRestrictedBuffer(float **buf) { return freeBuffer(buf); }
int HyPerLayer::freeExtendedBuffer(float **buf) { return freeBuffer(buf); }
int HyPerLayer::freeClayer() {
pvcube_delete(clayer->activity);
freeBuffer(&clayer->prevActivity);
freeBuffer(&clayer->V);
free(clayer);
clayer = NULL;
return PV_SUCCESS;
}
void HyPerLayer::freeChannels() {
#ifdef PV_USE_CUDA
if (d_GSyn != NULL) {
delete d_GSyn;
d_GSyn = NULL;
}
#ifdef PV_USE_CUDNN
if (cudnn_GSyn != NULL) {
delete cudnn_GSyn;
}
#endif // PV_USE_CUDNN
#endif // PV_USE_CUDA
// GSyn gets allocated in allocateDataStructures, but only if numChannels>0.
if (GSyn) {
assert(numChannels > 0);
free(GSyn[0]); // conductances allocated contiguously so frees all buffer storage
free(GSyn); // this frees the array pointers to separate conductance channels
GSyn = NULL;
numChannels = 0;
}
}
int HyPerLayer::allocateClayerBuffers() {
// clayer fields numNeurons, numExtended, loc, xScale, yScale,
// dx, dy, xOrigin, yOrigin were set in initClayer().
assert(clayer);
FatalIf(allocateV() != PV_SUCCESS, "%s: allocateV() failed.\n", getName());
FatalIf(allocateActivity() != PV_SUCCESS, "%s: allocateActivity() failed.\n", getName());
// athresher 11-4-16 TODO: Should these be called on non-spiking layers?
FatalIf(allocatePrevActivity() != PV_SUCCESS, "%s: allocatePrevActivity() failed.\n", getName());
for (int k = 0; k < getNumExtendedAllBatches(); k++) {
clayer->prevActivity[k] = -10 * REFRACTORY_PERIOD; // allow neuron to fire at time t==0
}
return PV_SUCCESS;
}
template <typename T>
int HyPerLayer::allocateBuffer(T **buf, int bufsize, const char *bufname) {
int status = PV_SUCCESS;
*buf = (T *)calloc(bufsize, sizeof(T));
if (*buf == NULL) {
ErrorLog().printf(
"%s: rank %d process unable to allocate memory for %s: %s.\n",
getDescription_c(),
parent->columnId(),
bufname,
strerror(errno));
status = PV_FAILURE;
}
return status;
}
// Declare the instantiations of allocateBuffer that occur in other .cpp files; otherwise you may
// get linker errors.
template int HyPerLayer::allocateBuffer<float>(float **buf, int bufsize, const char *bufname);
template int HyPerLayer::allocateBuffer<int>(int **buf, int bufsize, const char *bufname);
int HyPerLayer::allocateRestrictedBuffer(float **buf, char const *bufname) {
return allocateBuffer(buf, getNumNeuronsAllBatches(), bufname);
}
int HyPerLayer::allocateExtendedBuffer(float **buf, char const *bufname) {
return allocateBuffer(buf, getNumExtendedAllBatches(), bufname);
}
int HyPerLayer::allocateV() { return allocateRestrictedBuffer(&clayer->V, "membrane potential V"); }
int HyPerLayer::allocateActivity() {
clayer->activity = pvcube_new(&clayer->loc, getNumExtendedAllBatches());
return clayer->activity != NULL ? PV_SUCCESS : PV_FAILURE;
}
int HyPerLayer::allocatePrevActivity() {
return allocateExtendedBuffer(&clayer->prevActivity, "time of previous activity");
}
int HyPerLayer::setLayerLoc(
PVLayerLoc *layerLoc,
float nxScale,
float nyScale,
int nf,
int numBatches) {
int status = PV_SUCCESS;
Communicator *icComm = parent->getCommunicator();
float nxglobalfloat = nxScale * parent->getNxGlobal();
layerLoc->nxGlobal = (int)nearbyintf(nxglobalfloat);
if (std::fabs(nxglobalfloat - layerLoc->nxGlobal) > 0.0001f) {
if (parent->columnId() == 0) {
ErrorLog(errorMessage);
errorMessage.printf(
"nxScale of layer \"%s\" is incompatible with size of column.\n", getName());
errorMessage.printf(
"Column nx %d multiplied by nxScale %f must be an integer.\n",
(double)parent->getNxGlobal(),
(double)nxScale);
}
status = PV_FAILURE;
}
float nyglobalfloat = nyScale * parent->getNyGlobal();
layerLoc->nyGlobal = (int)nearbyintf(nyglobalfloat);
if (std::fabs(nyglobalfloat - layerLoc->nyGlobal) > 0.0001f) {
if (parent->columnId() == 0) {
ErrorLog(errorMessage);
errorMessage.printf(
"nyScale of layer \"%s\" is incompatible with size of column.\n", getName());
errorMessage.printf(
"Column ny %d multiplied by nyScale %f must be an integer.\n",
(double)parent->getNyGlobal(),
(double)nyScale);
}
status = PV_FAILURE;
}
// partition input space based on the number of processor
// columns and rows
//
if (layerLoc->nxGlobal % icComm->numCommColumns() != 0) {
if (parent->columnId() == 0) {
ErrorLog(errorMessage);
errorMessage.printf(
"Size of HyPerLayer \"%s\" is not compatible with the mpi configuration.\n", name);
errorMessage.printf(
"The layer has %d pixels horizontally, and there are %d mpi processes in a row, but "
"%d does not divide %d.\n",
layerLoc->nxGlobal,
icComm->numCommColumns(),
icComm->numCommColumns(),
layerLoc->nxGlobal);
}
status = PV_FAILURE;
}
if (layerLoc->nyGlobal % icComm->numCommRows() != 0) {
if (parent->columnId() == 0) {
ErrorLog(errorMessage);
errorMessage.printf(
"Size of HyPerLayer \"%s\" is not compatible with the mpi configuration.\n", name);
errorMessage.printf(
"The layer has %d pixels vertically, and there are %d mpi processes in a column, "
"but %d does not divide %d.\n",
layerLoc->nyGlobal,
icComm->numCommRows(),
icComm->numCommRows(),
layerLoc->nyGlobal);
}
status = PV_FAILURE;
}
MPI_Barrier(icComm->communicator()); // If there is an error, make sure that MPI doesn't kill the
// run before process 0 reports the error.
if (status != PV_SUCCESS) {
if (parent->columnId() == 0) {
ErrorLog().printf("setLayerLoc failed for %s.\n", getDescription_c());
}
exit(EXIT_FAILURE);
}
layerLoc->nx = layerLoc->nxGlobal / icComm->numCommColumns();
layerLoc->ny = layerLoc->nyGlobal / icComm->numCommRows();
assert(layerLoc->nxGlobal == layerLoc->nx * icComm->numCommColumns());
assert(layerLoc->nyGlobal == layerLoc->ny * icComm->numCommRows());
layerLoc->kx0 = layerLoc->nx * icComm->commColumn();
layerLoc->ky0 = layerLoc->ny * icComm->commRow();
layerLoc->nf = nf;
layerLoc->nbatch = numBatches;
layerLoc->kb0 = parent->commBatch() * numBatches;
layerLoc->nbatchGlobal = parent->numCommBatches() * numBatches;
// halo is set in calls to updateClayerMargin
layerLoc->halo.lt = 0;
layerLoc->halo.rt = 0;
layerLoc->halo.dn = 0;
layerLoc->halo.up = 0;
return 0;
}
void HyPerLayer::calcNumExtended() {
PVLayerLoc const *loc = getLayerLoc();
clayer->numExtended = (loc->nx + loc->halo.lt + loc->halo.rt)
* (loc->ny + loc->halo.dn + loc->halo.up) * loc->nf;
clayer->numExtendedAllBatches = clayer->numExtended * loc->nbatch;
}
int HyPerLayer::allocateBuffers() {
// allocate memory for input buffers. For HyPerLayer, allocates GSyn
// virtual so that subclasses can initialize additional buffers if needed.
// Typically an overriding allocateBuffers should call HyPerLayer::allocateBuffers
// Specialized subclasses that don't use GSyn (e.g. CloneVLayer) should override
// allocateGSyn to do nothing.
return allocateGSyn();
}
int HyPerLayer::allocateGSyn() {
int status = PV_SUCCESS;
GSyn = NULL;
if (numChannels > 0) {
GSyn = (float **)malloc(numChannels * sizeof(float *));
if (GSyn == NULL) {
status = PV_FAILURE;
return status;
}
GSyn[0] = (float *)calloc(getNumNeuronsAllBatches() * numChannels, sizeof(float));
// All channels allocated at once and contiguously. resetGSynBuffers_HyPerLayer() assumes
// this is true, to make it easier to port to GPU.
if (GSyn[0] == NULL) {
status = PV_FAILURE;
return status;
}
for (int m = 1; m < numChannels; m++) {
GSyn[m] = GSyn[0] + m * getNumNeuronsAllBatches();
}
}
return status;
}
void HyPerLayer::addPublisher() {
MPIBlock const *mpiBlock = parent->getCommunicator()->getLocalMPIBlock();
publisher = new Publisher(*mpiBlock, clayer->activity, getNumDelayLevels(), getSparseFlag());
}
void HyPerLayer::checkpointPvpActivityFloat(
Checkpointer *checkpointer,
char const *bufferName,
float *pvpBuffer,
bool extended) {
bool registerSucceeded = checkpointer->registerCheckpointEntry(
std::make_shared<CheckpointEntryPvpBuffer<float>>(
getName(),
bufferName,
checkpointer->getMPIBlock(),
pvpBuffer,
getLayerLoc(),
extended));
FatalIf(
!registerSucceeded,
"%s failed to register %s for checkpointing.\n",
getDescription_c(),
bufferName);
}
void HyPerLayer::checkpointRandState(
Checkpointer *checkpointer,
char const *bufferName,
Random *randState,
bool extendedFlag) {
bool registerSucceeded = checkpointer->registerCheckpointEntry(
std::make_shared<CheckpointEntryRandState>(
getName(),
bufferName,
checkpointer->getMPIBlock(),
randState->getRNG(0),
getLayerLoc(),
extendedFlag));
FatalIf(
!registerSucceeded,
"%s failed to register %s for checkpointing.\n",
getDescription_c(),
bufferName);
}
int HyPerLayer::initializeState() {
int status = setInitialValues();
return status;
}
#ifdef PV_USE_CUDA
int HyPerLayer::copyInitialStateToGPU() {
if (updateGpu) {
float *h_V = getV();
if (h_V != NULL) {
PVCuda::CudaBuffer *d_V = getDeviceV();
assert(d_V);
d_V->copyToDevice(h_V);
}
PVCuda::CudaBuffer *d_activity = getDeviceActivity();
assert(d_activity);
float *h_activity = getCLayer()->activity->data;
d_activity->copyToDevice(h_activity);
}
return PV_SUCCESS;
}
#endif // PV_USE_CUDA
int HyPerLayer::setInitialValues() {
int status = PV_SUCCESS;
status = initializeV();
if (status == PV_SUCCESS)
initializeActivity();
return status;
}
int HyPerLayer::initializeV() {
int status = PV_SUCCESS;
if (getV() != nullptr && mInitVObject != nullptr) {
status = mInitVObject->calcV(getV(), getLayerLoc());
}
return status;
}
int HyPerLayer::initializeActivity() {
int status = setActivity();
return status;
}
int HyPerLayer::ioParams(enum ParamsIOFlag ioFlag) {
parent->ioParamsStartGroup(ioFlag, name);
ioParamsFillGroup(ioFlag);
parent->ioParamsFinishGroup(ioFlag);
return PV_SUCCESS;
}
int HyPerLayer::ioParamsFillGroup(enum ParamsIOFlag ioFlag) {
// Derived classes with new params behavior should override ioParamsFillGroup
// and the overriding method should call the base class's ioParamsFillGroup.
ioParam_nxScale(ioFlag);
ioParam_nyScale(ioFlag);
ioParam_nf(ioFlag);
ioParam_phase(ioFlag);
ioParam_mirrorBCflag(ioFlag);
ioParam_valueBC(ioFlag);
ioParam_initializeFromCheckpointFlag(ioFlag);
ioParam_InitVType(ioFlag);
ioParam_triggerLayerName(ioFlag);
ioParam_triggerFlag(ioFlag);
ioParam_triggerOffset(ioFlag);
ioParam_triggerBehavior(ioFlag);
ioParam_triggerResetLayerName(ioFlag);
ioParam_writeStep(ioFlag);
ioParam_initialWriteTime(ioFlag);
ioParam_sparseLayer(ioFlag);
ioParam_writeSparseValues(ioFlag);
// GPU-specific parameter. If not using GPUs, this flag
// can be set to false or left out, but it is an error
// to set updateGpu to true if compiling without GPUs.
ioParam_updateGpu(ioFlag);
ioParam_dataType(ioFlag);
return PV_SUCCESS;
}
void HyPerLayer::ioParam_dataType(enum ParamsIOFlag ioFlag) {
this->getParent()->parameters()->ioParamString(
ioFlag, this->getName(), "dataType", &dataTypeString, NULL, false /*warnIfAbsent*/);
if (dataTypeString == NULL) {
// Default value
dataType = PV_FLOAT;
return;
}
if (!strcmp(dataTypeString, "float")) {
dataType = PV_FLOAT;
}
else if (!strcmp(dataTypeString, "int")) {
dataType = PV_INT;
}
else {
Fatal() << "BaseLayer \"" << name
<< "\": dataType not recognized, can be \"float\" or \"int\"\n";
}
}
void HyPerLayer::ioParam_updateGpu(enum ParamsIOFlag ioFlag) {
#ifdef PV_USE_CUDA
parent->parameters()->ioParamValue(
ioFlag, name, "updateGpu", &updateGpu, updateGpu, true /*warnIfAbsent*/);
mUsingGPUFlag = updateGpu;
#else // PV_USE_CUDA
bool updateGpu = false;
parent->parameters()->ioParamValue(
ioFlag, name, "updateGpu", &updateGpu, updateGpu, false /*warnIfAbsent*/);
if (ioFlag == PARAMS_IO_READ && updateGpu) {
if (parent->columnId() == 0) {
WarnLog().printf(
"%s: updateGpu is set to true, but PetaVision was compiled without GPU "
"acceleration. uphadeGpu has been set to false.\n",
getDescription_c());
}
}
#endif // PV_USE_CUDA
}
void HyPerLayer::ioParam_nxScale(enum ParamsIOFlag ioFlag) {
parent->parameters()->ioParamValue(ioFlag, name, "nxScale", &nxScale, nxScale);
}
void HyPerLayer::ioParam_nyScale(enum ParamsIOFlag ioFlag) {
parent->parameters()->ioParamValue(ioFlag, name, "nyScale", &nyScale, nyScale);
}
void HyPerLayer::ioParam_nf(enum ParamsIOFlag ioFlag) {
parent->parameters()->ioParamValue(ioFlag, name, "nf", &numFeatures, numFeatures);
}
void HyPerLayer::ioParam_phase(enum ParamsIOFlag ioFlag) {
parent->parameters()->ioParamValue(ioFlag, name, "phase", &phase, phase);
if (ioFlag == PARAMS_IO_READ && phase < 0) {
if (parent->columnId() == 0)
Fatal().printf(
"%s: phase must be >= 0 (given value was %d).\n", getDescription_c(), phase);
}
}
void HyPerLayer::ioParam_mirrorBCflag(enum ParamsIOFlag ioFlag) {
parent->parameters()->ioParamValue(ioFlag, name, "mirrorBCflag", &mirrorBCflag, mirrorBCflag);
}
void HyPerLayer::ioParam_valueBC(enum ParamsIOFlag ioFlag) {
assert(!parent->parameters()->presentAndNotBeenRead(name, "mirrorBCflag"));
if (!mirrorBCflag) {
parent->parameters()->ioParamValue(ioFlag, name, "valueBC", &valueBC, (float)0);
}
}
void HyPerLayer::ioParam_initializeFromCheckpointFlag(enum ParamsIOFlag ioFlag) {
assert(parent->getInitializeFromCheckpointDir());
if (parent->getInitializeFromCheckpointDir() && parent->getInitializeFromCheckpointDir()[0]) {
parent->parameters()->ioParamValue(
ioFlag,
name,
"initializeFromCheckpointFlag",
&initializeFromCheckpointFlag,
parent->getDefaultInitializeFromCheckpointFlag(),
true /*warnIfAbsent*/);
}
}
void HyPerLayer::ioParam_InitVType(enum ParamsIOFlag ioFlag) {
parent->parameters()->ioParamString(
ioFlag, name, "InitVType", &initVTypeString, "ConstantV", true /*warnIfAbsent*/);
if (ioFlag == PARAMS_IO_READ) {
BaseObject *object = Factory::instance()->createByKeyword(initVTypeString, name, parent);
mInitVObject = dynamic_cast<BaseInitV *>(object);
if (mInitVObject == nullptr) {
ErrorLog().printf("%s: unable to create InitV object\n", getDescription_c());
abort();
}
}
if (mInitVObject != nullptr) {
mInitVObject->ioParamsFillGroup(ioFlag);
}
}
void HyPerLayer::ioParam_triggerLayerName(enum ParamsIOFlag ioFlag) {
parent->parameters()->ioParamString(
ioFlag, name, "triggerLayerName", &triggerLayerName, NULL, false /*warnIfAbsent*/);
if (ioFlag == PARAMS_IO_READ) {
if (triggerLayerName && !strcmp(name, triggerLayerName)) {
if (parent->columnId() == 0) {
ErrorLog().printf(
"%s: triggerLayerName cannot be the same as the name of the layer itself.\n",
getDescription_c());
}
MPI_Barrier(parent->getCommunicator()->communicator());
exit(EXIT_FAILURE);
}
triggerFlag = (triggerLayerName != NULL && triggerLayerName[0] != '\0');
}
}
// triggerFlag was deprecated Aug 7, 2015.
// Setting triggerLayerName to a nonempty string has the effect of triggerFlag=true, and
// setting triggerLayerName to NULL or "" has the effect of triggerFlag=false.
// While triggerFlag is being deprecated, it is an error for triggerFlag to be false
// and triggerLayerName to be a nonempty string.
void HyPerLayer::ioParam_triggerFlag(enum ParamsIOFlag ioFlag) {
pvAssert(!parent->parameters()->presentAndNotBeenRead(name, "triggerLayerName"));
if (ioFlag == PARAMS_IO_READ && parent->parameters()->present(name, "triggerFlag")) {
bool flagFromParams = false;
parent->parameters()->ioParamValue(
ioFlag, name, "triggerFlag", &flagFromParams, flagFromParams);
if (parent->columnId() == 0) {
WarnLog(triggerFlagMessage);
triggerFlagMessage.printf("%s: triggerFlag has been deprecated.\n", getDescription_c());
triggerFlagMessage.printf(
" If triggerLayerName is a nonempty string, triggering will be on;\n");
triggerFlagMessage.printf(
" if triggerLayerName is empty or null, triggering will be off.\n");
if (parent->columnId() == 0) {
if (flagFromParams != triggerFlag) {
ErrorLog(errorMessage);
errorMessage.printf("triggerLayerName=", name);
if (triggerLayerName) {
errorMessage.printf("\"%s\"", triggerLayerName);
}
else {
errorMessage.printf("NULL");
}
errorMessage.printf(
" implies triggerFlag=%s but triggerFlag was set in params to %s\n",
triggerFlag ? "true" : "false",
flagFromParams ? "true" : "false");
}
}
}
if (flagFromParams != triggerFlag) {
MPI_Barrier(parent->getCommunicator()->communicator());
exit(EXIT_FAILURE);
}
}
}
void HyPerLayer::ioParam_triggerOffset(enum ParamsIOFlag ioFlag) {
assert(!parent->parameters()->presentAndNotBeenRead(name, "triggerLayerName"));
if (triggerFlag) {
parent->parameters()->ioParamValue(
ioFlag, name, "triggerOffset", &triggerOffset, triggerOffset);
if (triggerOffset < 0) {
if (parent->columnId() == 0) {
Fatal().printf(
"%s: TriggerOffset (%f) must be positive\n", getDescription_c(), triggerOffset);
}
}
}
}
void HyPerLayer::ioParam_triggerBehavior(enum ParamsIOFlag ioFlag) {
assert(!parent->parameters()->presentAndNotBeenRead(name, "triggerLayerName"));
if (triggerFlag) {
parent->parameters()->ioParamString(
ioFlag,
name,
"triggerBehavior",
&triggerBehavior,
"updateOnlyOnTrigger",
true /*warnIfAbsent*/);
if (triggerBehavior == NULL || !strcmp(triggerBehavior, "")) {
free(triggerBehavior);
triggerBehavior = strdup("updateOnlyOnTrigger");
triggerBehaviorType = UPDATEONLY_TRIGGER;
}
else if (!strcmp(triggerBehavior, "updateOnlyOnTrigger")) {
triggerBehaviorType = UPDATEONLY_TRIGGER;
}
else if (!strcmp(triggerBehavior, "resetStateOnTrigger")) {
triggerBehaviorType = RESETSTATE_TRIGGER;
}
else if (!strcmp(triggerBehavior, "ignore")) {
triggerBehaviorType = NO_TRIGGER;
}
else {
if (parent->columnId() == 0) {
ErrorLog().printf(
"%s: triggerBehavior=\"%s\" is unrecognized.\n",
getDescription_c(),
triggerBehavior);
}
MPI_Barrier(parent->getCommunicator()->communicator());
exit(EXIT_FAILURE);
}
}
else {
triggerBehaviorType = NO_TRIGGER;
}
}
void HyPerLayer::ioParam_triggerResetLayerName(enum ParamsIOFlag ioFlag) {
assert(!parent->parameters()->presentAndNotBeenRead(name, "triggerLayerName"));
if (triggerFlag) {
assert(!parent->parameters()->presentAndNotBeenRead(name, "triggerBehavior"));
if (!strcmp(triggerBehavior, "resetStateOnTrigger")) {
parent->parameters()->ioParamStringRequired(
ioFlag, name, "triggerResetLayerName", &triggerResetLayerName);
}
}
}
void HyPerLayer::ioParam_writeStep(enum ParamsIOFlag ioFlag) {
parent->parameters()->ioParamValue(
ioFlag, name, "writeStep", &writeStep, parent->getDeltaTime());
}
void HyPerLayer::ioParam_initialWriteTime(enum ParamsIOFlag ioFlag) {
assert(!parent->parameters()->presentAndNotBeenRead(name, "writeStep"));
if (writeStep >= 0.0) {
double start_time = parent->getStartTime();
parent->parameters()->ioParamValue(
ioFlag, name, "initialWriteTime", &initialWriteTime, start_time);
if (ioFlag == PARAMS_IO_READ && writeStep > 0.0 && initialWriteTime < start_time) {
double storeInitialWriteTime = initialWriteTime;
while (initialWriteTime < start_time) {
initialWriteTime += writeStep;
}
if (parent->columnId() == 0) {
WarnLog(warningMessage);
warningMessage.printf(
"%s: initialWriteTime %f is earlier than start time %f. Adjusting "
"initialWriteTime:\n",
getDescription_c(),
initialWriteTime,
start_time);
warningMessage.printf(" initialWriteTime adjusted to %f\n", initialWriteTime);
}
}
}
}
void HyPerLayer::ioParam_sparseLayer(enum ParamsIOFlag ioFlag) {
if (ioFlag == PARAMS_IO_READ && !parent->parameters()->present(name, "sparseLayer")
&& parent->parameters()->present(name, "writeSparseActivity")) {
Fatal().printf("writeSparseActivity is obsolete. Use sparseLayer instead.\n");
}
// writeSparseActivity was deprecated Nov 4, 2014 and marked obsolete Mar 14, 2017.
parent->parameters()->ioParamValue(ioFlag, name, "sparseLayer", &sparseLayer, false);
}
// writeSparseValues is obsolete as of Mar 14, 2017.
void HyPerLayer::ioParam_writeSparseValues(enum ParamsIOFlag ioFlag) {
if (ioFlag == PARAMS_IO_READ) {
assert(!parent->parameters()->presentAndNotBeenRead(name, "sparseLayer"));
if (sparseLayer && parent->parameters()->present(name, "writeSparseValues")) {
WarnLog() << "writeSparseValues parameter, defined in " << getDescription()
<< ", is obsolete.\n";
bool writeSparseValues;
parent->parameters()->ioParamValue(
ioFlag, name, "writeSparseValues", &writeSparseValues, true /*default value*/);
if (!writeSparseValues) {
WarnLog() << "The sparse-values format is used for all sparse layers.\n";
}
}
}
}
int HyPerLayer::respond(std::shared_ptr<BaseMessage const> message) {
int status = BaseLayer::respond(message);
if (status != PV_SUCCESS) {
return status;
}
else if (
LayerUpdateStateMessage const *castMessage =
dynamic_cast<LayerUpdateStateMessage const *>(message.get())) {
return respondLayerUpdateState(castMessage);
}
else if (
LayerRecvSynapticInputMessage const *castMessage =
dynamic_cast<LayerRecvSynapticInputMessage const *>(message.get())) {
return respondLayerRecvSynapticInput(castMessage);
}
#ifdef PV_USE_CUDA
else if (
LayerCopyFromGpuMessage const *castMessage =
dynamic_cast<LayerCopyFromGpuMessage const *>(message.get())) {
return respondLayerCopyFromGpu(castMessage);
}
#endif // PV_USE_CUDA
else if (
LayerAdvanceDataStoreMessage const *castMessage =
dynamic_cast<LayerAdvanceDataStoreMessage const *>(message.get())) {
return respondLayerAdvanceDataStore(castMessage);
}
else if (
LayerPublishMessage const *castMessage =
dynamic_cast<LayerPublishMessage const *>(message.get())) {
return respondLayerPublish(castMessage);
}
else if (
LayerOutputStateMessage const *castMessage =
dynamic_cast<LayerOutputStateMessage const *>(message.get())) {
return respondLayerOutputState(castMessage);
}
else if (
LayerCheckNotANumberMessage const *castMessage =
dynamic_cast<LayerCheckNotANumberMessage const *>(message.get())) {
return respondLayerCheckNotANumber(castMessage);
}
else {
return status;
}
}
int HyPerLayer::respondLayerRecvSynapticInput(LayerRecvSynapticInputMessage const *message) {
int status = PV_SUCCESS;
if (message->mPhase != getPhase()) {
return status;
}
#ifdef PV_USE_CUDA
if (message->mRecvOnGpuFlag != getRecvGpu()) {
return status;
}
#endif // PV_USE_CUDA
if (mHasReceived) {
return status;
}
if (!isAllInputReady()) {
return PV_POSTPONE;
}
resetGSynBuffers(message->mTime, message->mDeltaT); // deltaTimeAdapt is not used
message->mTimer->start();
recvAllSynapticInput();
message->mTimer->stop();
mHasReceived = true;
return status;
}
int HyPerLayer::respondLayerUpdateState(LayerUpdateStateMessage const *message) {
int status = PV_SUCCESS;
if (message->mPhase != getPhase()) {
return status;
}
#ifdef PV_USE_CUDA
if (message->mRecvOnGpuFlag != getRecvGpu()) {
return status;
}
if (message->mUpdateOnGpuFlag != getUpdateGpu()) {
return status;
}
#endif // PV_USE_CUDA
if (!mHasReceived) {
return PV_POSTPONE;
}
status = callUpdateState(message->mTime, message->mDeltaT);
mHasUpdated = true;
return status;
}
#ifdef PV_USE_CUDA
int HyPerLayer::respondLayerCopyFromGpu(LayerCopyFromGpuMessage const *message) {
int status = PV_SUCCESS;
if (message->mPhase != getPhase()) {
return status;
}
message->mTimer->start();
copyAllActivityFromDevice();
copyAllVFromDevice();
copyAllGSynFromDevice();
addGpuTimers();
message->mTimer->stop();
return status;
}
#endif // PV_USE_CUDA
int HyPerLayer::respondLayerAdvanceDataStore(LayerAdvanceDataStoreMessage const *message) {
if (message->mPhase < 0 || message->mPhase == getPhase()) {
publisher->increaseTimeLevel();
}
return PV_SUCCESS;
}
int HyPerLayer::respondLayerPublish(LayerPublishMessage const *message) {
int status = PV_SUCCESS;
if (message->mPhase != getPhase()) {
return status;
}
publish(getParent()->getCommunicator(), message->mTime);
return status;
}
int HyPerLayer::respondLayerCheckNotANumber(LayerCheckNotANumberMessage const *message) {
int status = PV_SUCCESS;
if (message->mPhase != getPhase()) {
return status;
}
auto layerData = getLayerData();
int const N = getNumExtendedAllBatches();
for (int n = 0; n < N; n++) {
float a = layerData[n];
if (a != a) {
status = PV_FAILURE;
break;
}
}
if (status != PV_SUCCESS) {
if (parent->columnId() == 0) {
ErrorLog() << getDescription()
<< " has not-a-number values in the activity buffer. Exiting.\n";
}
MPI_Barrier(parent->getCommunicator()->communicator());
exit(EXIT_FAILURE);
}
return status;
}
int HyPerLayer::respondLayerOutputState(LayerOutputStateMessage const *message) {
int status = PV_SUCCESS;
if (message->mPhase != getPhase()) {
return status;
}
status = outputState(message->mTime); // also calls layer probes' outputState
return status;
}
void HyPerLayer::clearProgressFlags() {
mHasReceived = false;
mHasUpdated = false;
}
#ifdef PV_USE_CUDA
int HyPerLayer::allocateUpdateKernel() {
Fatal() << "Layer \"" << name << "\" of type " << getKeyword()
<< " does not support updating on gpus yet\n";
return -1;
}
/**
* Allocate GPU buffers. This must be called after PVLayer data have
* been allocated.
*/
int HyPerLayer::allocateDeviceBuffers() {
int status = 0;
const size_t size = getNumNeuronsAllBatches() * sizeof(float);
const size_t size_ex = getNumExtendedAllBatches() * sizeof(float);
PVCuda::CudaDevice *device = parent->getDevice();
// Allocate based on which flags are set
if (allocDeviceV) {
d_V = device->createBuffer(size, &description);
}
if (allocDeviceDatastore) {
d_Datastore = device->createBuffer(size_ex, &description);
assert(d_Datastore);
#ifdef PV_USE_CUDNN
cudnn_Datastore = device->createBuffer(size_ex, &description);
assert(cudnn_Datastore);
#endif
}
if (allocDeviceActiveIndices) {
d_numActive = device->createBuffer(parent->getNBatch() * sizeof(long), &description);
d_ActiveIndices = device->createBuffer(
getNumExtendedAllBatches() * sizeof(SparseList<float>::Entry), &description);
assert(d_ActiveIndices);
}
if (allocDeviceActivity) {
d_Activity = device->createBuffer(size_ex, &description);
}
// d_GSyn is the entire gsyn buffer. cudnn_GSyn is only one gsyn channel
if (allocDeviceGSyn) {
d_GSyn = device->createBuffer(size * numChannels, &description);
assert(d_GSyn);
#ifdef PV_USE_CUDNN
cudnn_GSyn = device->createBuffer(size, &description);
#endif
}
return status;
}
#endif // PV_USE_CUDA
int HyPerLayer::communicateInitInfo() {
// HyPerLayers need to tell the parent HyPerCol how many random number
// seeds they need. At the start of HyPerCol::run, the parent HyPerCol
// calls each layer's communicateInitInfo() sequentially in a repeatable order
// (probably the order the layers appear in the params file) to make sure
// that the same runs use the same RNG seeds in the same way.
//
// If any other object in the column needs the layer to have a certain minimum
// margin width (e.g. a HyPerConn with patch size bigger than one), it should
// call the layer's requireMarginWidth() method during its communicateInitInfo
// stage.
//
// Since all communicateInitInfo() methods are called before any allocateDataStructures()
// methods, HyPerLayer knows its marginWidth before it has to allocate
// anything. So the margin width does not have to be specified in params.
if (triggerFlag) {
triggerLayer = parent->getLayerFromName(triggerLayerName);
if (triggerLayer == NULL) {
if (parent->columnId() == 0) {
ErrorLog().printf(
"%s: triggerLayerName \"%s\" is not a layer in the HyPerCol.\n",
getDescription_c(),
triggerLayerName);
}
MPI_Barrier(parent->getCommunicator()->communicator());
exit(EXIT_FAILURE);
}
if (triggerBehaviorType == RESETSTATE_TRIGGER) {
char const *resetLayerName = NULL; // Will point to name of actual resetLayer, whether
// triggerResetLayerName is blank (in which case
// resetLayerName==triggerLayerName) or not
if (triggerResetLayerName == NULL || triggerResetLayerName[0] == '\0') {
resetLayerName = triggerLayerName;
triggerResetLayer = triggerLayer;
}
else {
resetLayerName = triggerResetLayerName;
triggerResetLayer = parent->getLayerFromName(triggerResetLayerName);
if (triggerResetLayer == NULL) {
if (parent->columnId() == 0) {
ErrorLog().printf(
"%s: triggerResetLayerName \"%s\" is not a layer in the HyPerCol.\n",
getDescription_c(),
triggerResetLayerName);
}
MPI_Barrier(parent->getCommunicator()->communicator());
exit(EXIT_FAILURE);
}
}
// Check that triggerResetLayer and this layer have the same (restricted) dimensions.
// Do we need to postpone until triggerResetLayer has finished its communicateInitInfo?
PVLayerLoc const *triggerLoc = triggerResetLayer->getLayerLoc();
PVLayerLoc const *localLoc = this->getLayerLoc();
if (triggerLoc->nxGlobal != localLoc->nxGlobal
|| triggerLoc->nyGlobal != localLoc->nyGlobal
|| triggerLoc->nf != localLoc->nf) {
if (parent->columnId() == 0) {
Fatal(errorMessage);
errorMessage.printf(
"%s: triggerResetLayer \"%s\" has incompatible dimensions.\n",
getDescription_c(),
resetLayerName);
errorMessage.printf(
" \"%s\" is %d-by-%d-by-%d and \"%s\" is %d-by-%d-by-%d.\n",
name,
localLoc->nxGlobal,
localLoc->nyGlobal,
localLoc->nf,
resetLayerName,
triggerLoc->nxGlobal,
triggerLoc->nyGlobal,
triggerLoc->nf);
}
}
}
}
#ifdef PV_USE_CUDA
// Here, the connection tells all participating recev layers to allocate memory on gpu
// if receive from gpu is set. These buffers should be set in allocate
if (updateGpu) {
this->setAllocDeviceGSyn();
this->setAllocDeviceV();
this->setAllocDeviceActivity();
}
#endif
int status = PV_SUCCESS;
return status;
}
int HyPerLayer::openOutputStateFile(Checkpointer *checkpointer) {
pvAssert(writeStep >= 0);
if (checkpointer->getMPIBlock()->getRank() == 0) {
std::string outputStatePath(getName());
outputStatePath.append(".pvp");
std::string checkpointLabel(getName());
checkpointLabel.append("_filepos");
bool createFlag = checkpointer->getCheckpointReadDirectory().empty();
mOutputStateStream = new CheckpointableFileStream(
outputStatePath.c_str(), createFlag, checkpointer, checkpointLabel);
}
return PV_SUCCESS;
}
void HyPerLayer::synchronizeMarginWidth(HyPerLayer *layer) {
if (layer == this) {
return;
}
assert(layer->getLayerLoc() != NULL && this->getLayerLoc() != NULL);
HyPerLayer **newSynchronizedMarginWidthLayers =
(HyPerLayer **)calloc(numSynchronizedMarginWidthLayers + 1, sizeof(HyPerLayer *));
assert(newSynchronizedMarginWidthLayers);
if (numSynchronizedMarginWidthLayers > 0) {
for (int k = 0; k < numSynchronizedMarginWidthLayers; k++) {
newSynchronizedMarginWidthLayers[k] = synchronizedMarginWidthLayers[k];
}
free(synchronizedMarginWidthLayers);
}
else {
assert(synchronizedMarginWidthLayers == NULL);
}
synchronizedMarginWidthLayers = newSynchronizedMarginWidthLayers;
synchronizedMarginWidthLayers[numSynchronizedMarginWidthLayers] = layer;
numSynchronizedMarginWidthLayers++;
equalizeMargins(this, layer);
return;
}
int HyPerLayer::equalizeMargins(HyPerLayer *layer1, HyPerLayer *layer2) {
int border1, border2, maxborder, result;
int status = PV_SUCCESS;
border1 = layer1->getLayerLoc()->halo.lt;
border2 = layer2->getLayerLoc()->halo.lt;
maxborder = border1 > border2 ? border1 : border2;
layer1->requireMarginWidth(maxborder, &result, 'x');
if (result != maxborder) {
status = PV_FAILURE;
}
layer2->requireMarginWidth(maxborder, &result, 'x');
if (result != maxborder) {
status = PV_FAILURE;
}
if (status != PV_SUCCESS) {
Fatal().printf(
"Error in rank %d process: unable to synchronize x-margin widths of layers \"%s\" and "
"\"%s\" to %d\n",
layer1->getParent()->columnId(),
layer1->getName(),
layer2->getName(),
maxborder);
;
}
assert(
layer1->getLayerLoc()->halo.lt == layer2->getLayerLoc()->halo.lt
&& layer1->getLayerLoc()->halo.rt == layer2->getLayerLoc()->halo.rt
&& layer1->getLayerLoc()->halo.lt == layer1->getLayerLoc()->halo.rt
&& layer1->getLayerLoc()->halo.lt == maxborder);
border1 = layer1->getLayerLoc()->halo.dn;
border2 = layer2->getLayerLoc()->halo.dn;
maxborder = border1 > border2 ? border1 : border2;
layer1->requireMarginWidth(maxborder, &result, 'y');
if (result != maxborder) {
status = PV_FAILURE;
}
layer2->requireMarginWidth(maxborder, &result, 'y');
if (result != maxborder) {
status = PV_FAILURE;
}
if (status != PV_SUCCESS) {
Fatal().printf(
"Error in rank %d process: unable to synchronize y-margin widths of layers \"%s\" and "
"\"%s\" to %d\n",
layer1->getParent()->columnId(),
layer1->getName(),
layer2->getName(),
maxborder);
;
}
assert(
layer1->getLayerLoc()->halo.dn == layer2->getLayerLoc()->halo.dn
&& layer1->getLayerLoc()->halo.up == layer2->getLayerLoc()->halo.up
&& layer1->getLayerLoc()->halo.dn == layer1->getLayerLoc()->halo.up
&& layer1->getLayerLoc()->halo.dn == maxborder);
return status;
}
int HyPerLayer::allocateDataStructures() {
// Once initialize and communicateInitInfo have been called, HyPerLayer has the
// information it needs to allocate the membrane potential buffer V, the
// activity buffer activity->data, and the data store.
int status = PV_SUCCESS;
// Doing this check here, since trigger layers are being set up in communicateInitInfo
// If the magnitude of the trigger offset is bigger than the delta update time, then error
if (triggerFlag) {
double deltaUpdateTime = getDeltaUpdateTime();
if (deltaUpdateTime != -1 && triggerOffset >= deltaUpdateTime) {
Fatal().printf(
"%s error in rank %d process: TriggerOffset (%f) must be lower than the change in "
"update time (%f) \n",
getDescription_c(),
parent->columnId(),
triggerOffset,
deltaUpdateTime);
}
}
allocateClayerBuffers();
const PVLayerLoc *loc = getLayerLoc();
int nx = loc->nx;
int ny = loc->ny;
int nf = loc->nf;
PVHalo const *halo = &loc->halo;
// If not mirroring, fill the boundaries with the value in the valueBC param
if (!useMirrorBCs() && getValueBC() != 0.0f) {
int idx = 0;
for (int batch = 0; batch < loc->nbatch; batch++) {
for (int b = 0; b < halo->up; b++) {
for (int k = 0; k < (nx + halo->lt + halo->rt) * nf; k++) {
clayer->activity->data[idx] = getValueBC();
idx++;
}
}
for (int y = 0; y < ny; y++) {
for (int k = 0; k < halo->lt * nf; k++) {
clayer->activity->data[idx] = getValueBC();
idx++;
}
idx += nx * nf;
for (int k = 0; k < halo->rt * nf; k++) {
clayer->activity->data[idx] = getValueBC();
idx++;
}
}
for (int b = 0; b < halo->dn; b++) {
for (int k = 0; k < (nx + halo->lt + halo->rt) * nf; k++) {
clayer->activity->data[idx] = getValueBC();
idx++;
}
}
}
assert(idx == getNumExtendedAllBatches());
}
// allocate storage for the input conductance arrays
status = allocateBuffers();
assert(status == PV_SUCCESS);
// Allocate temp buffers if needed, 1 for each thread
if (parent->getNumThreads() > 1) {
thread_gSyn = (float **)malloc(sizeof(float *) * parent->getNumThreads());
assert(thread_gSyn);
// Assign thread_gSyn to different points of tempMem
for (int i = 0; i < parent->getNumThreads(); i++) {
float *tempMem = (float *)malloc(sizeof(float) * getNumNeuronsAllBatches());
if (!tempMem) {
Fatal().printf(
"HyPerLayer \"%s\" error: rank %d unable to allocate %zu memory for thread_gSyn: "
"%s\n",
name,
parent->columnId(),
sizeof(float) * getNumNeuronsAllBatches(),
strerror(errno));
}
thread_gSyn[i] = tempMem;
}
}
// Allocate cuda stuff on gpu if set
#ifdef PV_USE_CUDA
status = allocateDeviceBuffers();
// Allocate receive from post kernel
if (status == 0) {
status = PV_SUCCESS;
}
else {
Fatal().printf(
"%s unable to allocate device memory in rank %d process: %s\n",
getDescription_c(),
getParent()->columnId(),
strerror(errno));
}
if (updateGpu) {
// This function needs to be overwritten as needed on a subclass basis
status = allocateUpdateKernel();
if (status == 0) {
status = PV_SUCCESS;
}
}
#endif
// Make a data structure that stores the connections (in order of execution) this layer needs to
// recv from
// CPU connections must run first to avoid race conditions
int numConnections = parent->numberOfConnections();
for (int c = 0; c < numConnections; c++) {
BaseConnection *baseConn = parent->getConnection(c);
HyPerConn *conn = dynamic_cast<HyPerConn *>(baseConn);
if (conn->postSynapticLayer() != this)
continue;
#ifdef PV_USE_CUDA
// If not recv from gpu, execute first
if (!conn->getReceiveGpu()) {
recvConns.insert(recvConns.begin(), conn);
}
// Otherwise, add to the back. If no gpus at all, just add to back
else
#endif
{
recvConns.push_back(conn);
#ifdef PV_USE_CUDA
// If it is receiving from gpu, set layer flag as such
recvGpu = true;
#endif
}
}
addPublisher();
return status;
}
/*
* Call this routine to increase the number of levels in the data store ring buffer.
* Calls to this routine after the data store has been initialized will have no effect.
* The routine returns the new value of numDelayLevels
*/
int HyPerLayer::increaseDelayLevels(int neededDelay) {
if (numDelayLevels < neededDelay + 1)
numDelayLevels = neededDelay + 1;
if (numDelayLevels > MAX_F_DELAY)
numDelayLevels = MAX_F_DELAY;
return numDelayLevels;
}
int HyPerLayer::requireMarginWidth(int marginWidthNeeded, int *marginWidthResult, char axis) {
// TODO: Is there a good way to handle x- and y-axis margins without so much duplication of code?
// Navigating through the halo makes it difficult to combine cases.
PVLayerLoc *loc = &clayer->loc;
PVHalo *halo = &loc->halo;
switch (axis) {
case 'x':
*marginWidthResult = xmargin;
if (xmargin < marginWidthNeeded) {
assert(clayer);
if (parent->columnId() == 0) {
InfoLog().printf(
"%s: adjusting x-margin width from %d to %d\n",
getDescription_c(),
xmargin,
marginWidthNeeded);
}
xmargin = marginWidthNeeded;
halo->lt = xmargin;
halo->rt = xmargin;
calcNumExtended();
assert(axis == 'x' && getLayerLoc()->halo.lt == getLayerLoc()->halo.rt);
*marginWidthResult = xmargin;
if (synchronizedMarginWidthLayers != NULL) {
for (int k = 0; k < numSynchronizedMarginWidthLayers; k++) {
HyPerLayer *l = synchronizedMarginWidthLayers[k];
if (l->getLayerLoc()->halo.lt < marginWidthNeeded) {
synchronizedMarginWidthLayers[k]->requireMarginWidth(
marginWidthNeeded, marginWidthResult, axis);
}
assert(l->getLayerLoc()->halo.lt == getLayerLoc()->halo.lt);
assert(l->getLayerLoc()->halo.rt == getLayerLoc()->halo.rt);
}
}
}
break;
case 'y':
*marginWidthResult = ymargin;
if (ymargin < marginWidthNeeded) {
assert(clayer);
if (parent->columnId() == 0) {
InfoLog().printf(
"%s: adjusting y-margin width from %d to %d\n",
getDescription_c(),
ymargin,
marginWidthNeeded);
}
ymargin = marginWidthNeeded;
halo->dn = ymargin;
halo->up = ymargin;
calcNumExtended();
assert(axis == 'y' && getLayerLoc()->halo.dn == getLayerLoc()->halo.up);
*marginWidthResult = ymargin;
if (synchronizedMarginWidthLayers != NULL) {
for (int k = 0; k < numSynchronizedMarginWidthLayers; k++) {
HyPerLayer *l = synchronizedMarginWidthLayers[k];
if (l->getLayerLoc()->halo.up < marginWidthNeeded) {
synchronizedMarginWidthLayers[k]->requireMarginWidth(
marginWidthNeeded, marginWidthResult, axis);
}
assert(l->getLayerLoc()->halo.dn == getLayerLoc()->halo.dn);
assert(l->getLayerLoc()->halo.up == getLayerLoc()->halo.up);
}
}
}
break;
default: assert(0); break;
}
return PV_SUCCESS;
}
int HyPerLayer::requireChannel(int channelNeeded, int *numChannelsResult) {
if (channelNeeded >= numChannels) {
int numOldChannels = numChannels;
numChannels = channelNeeded + 1;
}
*numChannelsResult = numChannels;
return PV_SUCCESS;
}
/**
* Returns the activity data for the layer. This data is in the
* extended space (with margins).
*/
const float *HyPerLayer::getLayerData(int delay) {
PVLayerCube cube = publisher->createCube(delay);
return cube.data;
}
int HyPerLayer::mirrorInteriorToBorder(PVLayerCube *cube, PVLayerCube *border) {
assert(cube->numItems == border->numItems);
assert(localDimensionsEqual(&cube->loc, &border->loc));
mirrorToNorthWest(border, cube);
mirrorToNorth(border, cube);
mirrorToNorthEast(border, cube);
mirrorToWest(border, cube);
mirrorToEast(border, cube);
mirrorToSouthWest(border, cube);
mirrorToSouth(border, cube);
mirrorToSouthEast(border, cube);
return 0;
}
int HyPerLayer::registerData(Checkpointer *checkpointer, std::string const &objName) {
int status = BaseLayer::registerData(checkpointer, objName);
checkpointPvpActivityFloat(checkpointer, "A", getActivity(), true /*extended*/);
if (getV() != nullptr) {
checkpointPvpActivityFloat(checkpointer, "V", getV(), false /*not extended*/);
}
publisher->checkpointDataStore(checkpointer, getName(), "Delays");
checkpointer->registerCheckpointData(
std::string(getName()),
std::string("lastUpdateTime"),
&mLastUpdateTime,
(std::size_t)1,
true /*broadcast*/);
checkpointer->registerCheckpointData(
std::string(getName()),
std::string("nextWrite"),
&writeTime,
(std::size_t)1,
true /*broadcast*/);
mMPIBlock = checkpointer->getMPIBlock();
if (writeStep >= 0.0) {
openOutputStateFile(checkpointer);
if (sparseLayer) {
checkpointer->registerCheckpointData(
std::string(getName()),
std::string("numframes_sparse"),
&writeActivitySparseCalls,
(std::size_t)1,
true /*broadcast*/);
}
else {
checkpointer->registerCheckpointData(
std::string(getName()),
std::string("numframes"),
&writeActivityCalls,
(std::size_t)1,
true /*broadcast*/);
}
}
if (getNumDelayLevels() > 1) {
checkpointer->addObserver(this, BaseMessage());
}
// Timers
update_timer = new Timer(getName(), "layer", "update ");
checkpointer->registerTimer(update_timer);
recvsyn_timer = new Timer(getName(), "layer", "recvsyn");
checkpointer->registerTimer(recvsyn_timer);
#ifdef PV_USE_CUDA
auto cudaDevice = parent->getDevice();
if (cudaDevice) {
gpu_update_timer = new PVCuda::CudaTimer(getName(), "layer", "gpuupdate");
gpu_update_timer->setStream(cudaDevice->getStream());
checkpointer->registerTimer(gpu_update_timer);
gpu_recvsyn_timer = new PVCuda::CudaTimer(getName(), "layer", "gpurecvsyn");
gpu_recvsyn_timer->setStream(cudaDevice->getStream());
checkpointer->registerTimer(gpu_recvsyn_timer);
}
#endif // PV_USE_CUDA
publish_timer = new Timer(getName(), "layer", "publish");
checkpointer->registerTimer(publish_timer);
timescale_timer = new Timer(getName(), "layer", "timescale");
checkpointer->registerTimer(timescale_timer);
io_timer = new Timer(getName(), "layer", "io ");
checkpointer->registerTimer(io_timer);
if (mInitVObject) {
auto message = std::make_shared<RegisterDataMessage<Checkpointer>>(checkpointer);
mInitVObject->respond(message);
}
return PV_SUCCESS;
}
double HyPerLayer::getDeltaUpdateTime() {
if (triggerLayer != NULL && triggerBehaviorType == UPDATEONLY_TRIGGER) {
return getDeltaTriggerTime();
}
else {
return parent->getDeltaTime();
}
}
double HyPerLayer::getDeltaTriggerTime() {
if (triggerLayer != NULL) {
return triggerLayer->getDeltaUpdateTime();
}
else {
return -1;
}
}
bool HyPerLayer::needUpdate(double simTime, double dt) {
if (getDeltaUpdateTime() <= 0) {
return false;
}
if (mLastUpdateTime == simTime + triggerOffset) {
return true;
}
double timeToCheck = mLastUpdateTime;
if (triggerLayer != nullptr && triggerBehaviorType == UPDATEONLY_TRIGGER) {
timeToCheck = triggerLayer->getLastUpdateTime();
// If our target layer updates this tick, so do we
if (timeToCheck == simTime && triggerOffset == 0) {
return true;
}
}
if (simTime + triggerOffset >= timeToCheck + getDeltaUpdateTime()
&& simTime + triggerOffset + dt <= timeToCheck + getDeltaUpdateTime() + dt) {
return true;
}
return false;
}
bool HyPerLayer::needReset(double simTime, double dt) {
if (triggerLayer == nullptr) {
return false;
}
if (triggerBehaviorType != RESETSTATE_TRIGGER) {
return false;
}
if (getDeltaTriggerTime() <= 0) {
return false;
}
if (simTime >= mLastTriggerTime + getDeltaTriggerTime()) {
// TODO: test "simTime > mLastTriggerTime + getDeltaTriggerTime() - 0.5 * dt",
// to avoid roundoff issues.
return true;
}
return false;
}
int HyPerLayer::callUpdateState(double simTime, double dt) {
int status = PV_SUCCESS;
if (needUpdate(simTime, dt)) {
if (needReset(simTime, dt)) {
status = resetStateOnTrigger();
mLastTriggerTime = simTime;
}
update_timer->start();
#ifdef PV_USE_CUDA
if (updateGpu) {
gpu_update_timer->start();
float *gSynHead = GSyn == NULL ? NULL : GSyn[0];
assert(updateGpu);
status = updateStateGpu(simTime, dt);
gpu_update_timer->stop();
}
else {
#endif
status = updateState(simTime, dt);
#ifdef PV_USE_CUDA
}
// Activity updated, set flag to true
updatedDeviceActivity = true;
updatedDeviceDatastore = true;
#endif
update_timer->stop();
mNeedToPublish = true;
mLastUpdateTime = simTime;
}
return status;
}
int HyPerLayer::resetStateOnTrigger() {
assert(triggerResetLayer != NULL);
float *V = getV();
if (V == NULL) {
if (parent->columnId() == 0) {
ErrorLog().printf(
"%s: triggerBehavior is \"resetStateOnTrigger\" but layer does not have a membrane "
"potential.\n",
getDescription_c());
}
MPI_Barrier(parent->getCommunicator()->communicator());
exit(EXIT_FAILURE);
}
float const *resetV = triggerResetLayer->getV();
if (resetV != NULL) {
#ifdef PV_USE_OPENMP_THREADS
#pragma omp parallel for
#endif // PV_USE_OPENMP_THREADS
for (int k = 0; k < getNumNeuronsAllBatches(); k++) {
V[k] = resetV[k];
}
}
else {
float const *resetA = triggerResetLayer->getActivity();
PVLayerLoc const *loc = triggerResetLayer->getLayerLoc();
PVHalo const *halo = &loc->halo;
for (int b = 0; b < parent->getNBatch(); b++) {
float const *resetABatch = resetA + (b * triggerResetLayer->getNumExtended());
float *VBatch = V + (b * triggerResetLayer->getNumNeurons());
#ifdef PV_USE_OPENMP_THREADS
#pragma omp parallel for
#endif // PV_USE_OPENMP_THREADS
for (int k = 0; k < getNumNeurons(); k++) {
int kex = kIndexExtended(
k, loc->nx, loc->ny, loc->nf, halo->lt, halo->rt, halo->dn, halo->up);
VBatch[k] = resetABatch[kex];
}
}
}
int status = setActivity();
// Update V on GPU after CPU V gets set
#ifdef PV_USE_CUDA
if (updateGpu) {
getDeviceV()->copyToDevice(V);
// Right now, we're setting the activity on the CPU and memsetting the GPU memory
// TODO calculate this on the GPU
getDeviceActivity()->copyToDevice(clayer->activity->data);
// We need to updateDeviceActivity and Datastore if we're resetting V
updatedDeviceActivity = true;
updatedDeviceDatastore = true;
}
#endif
return status;
}
int HyPerLayer::resetGSynBuffers(double timef, double dt) {
int status = PV_SUCCESS;
if (GSyn == NULL)
return PV_SUCCESS;
resetGSynBuffers_HyPerLayer(
parent->getNBatch(), this->getNumNeurons(), getNumChannels(), GSyn[0]);
return status;
}
#ifdef PV_USE_CUDA
int HyPerLayer::runUpdateKernel() {
#ifdef PV_USE_CUDA
assert(updateGpu);
if (updatedDeviceGSyn) {
copyAllGSynToDevice();
updatedDeviceGSyn = false;
}
// V and Activity are write only buffers, so we don't need to do anything with them
assert(krUpdate);
// Sync all buffers before running
syncGpu();
// Run kernel
krUpdate->run();
#endif
return PV_SUCCESS;
}
int HyPerLayer::updateStateGpu(double timef, double dt) {
Fatal() << "Update state for layer " << name << " is not implemented\n";
return -1;
}
#endif
int HyPerLayer::updateState(double timef, double dt) {
// just copy accumulation buffer to membrane potential
// and activity buffer (nonspiking)
const PVLayerLoc *loc = getLayerLoc();
float *A = getCLayer()->activity->data;
float *V = getV();
int num_channels = getNumChannels();
float *gSynHead = GSyn == NULL ? NULL : GSyn[0];
int nx = loc->nx;
int ny = loc->ny;
int nf = loc->nf;
int nbatch = loc->nbatch;
int num_neurons = nx * ny * nf;
if (num_channels == 1) {
applyGSyn_HyPerLayer1Channel(nbatch, num_neurons, V, gSynHead);
}
else {
applyGSyn_HyPerLayer(nbatch, num_neurons, V, gSynHead);
}
setActivity_HyPerLayer(
nbatch,
num_neurons,
A,
V,
nx,
ny,
nf,
loc->halo.lt,
loc->halo.rt,
loc->halo.dn,
loc->halo.up);
return PV_SUCCESS;
}
int HyPerLayer::setActivity() {
const PVLayerLoc *loc = getLayerLoc();
return setActivity_HyPerLayer(
loc->nbatch,
getNumNeurons(),
clayer->activity->data,
getV(),
loc->nx,
loc->ny,
loc->nf,
loc->halo.lt,
loc->halo.rt,
loc->halo.dn,
loc->halo.up);
}
// Updates active indices for all levels (delays) here
int HyPerLayer::updateAllActiveIndices() { return publisher->updateAllActiveIndices(); }
int HyPerLayer::updateActiveIndices() { return publisher->updateActiveIndices(0); }
bool HyPerLayer::isExchangeFinished(int delay) { return publisher->isExchangeFinished(delay); }
bool HyPerLayer::isAllInputReady() {
bool isReady = true;
for (auto &c : recvConns) {
for (int a = 0; a < c->numberOfAxonalArborLists(); a++) {
isReady &= c->getPre()->isExchangeFinished(c->getDelay(a));
}
}
return isReady;
}
int HyPerLayer::recvAllSynapticInput() {
int status = PV_SUCCESS;
// Only recvAllSynapticInput if we need an update
if (needUpdate(parent->simulationTime(), parent->getDeltaTime())) {
bool switchGpu = false;
// Start CPU timer here
recvsyn_timer->start();
for (auto &conn : recvConns) {
pvAssert(conn != NULL);
#ifdef PV_USE_CUDA
// Check if it's done with cpu connections
if (!switchGpu && conn->getReceiveGpu()) {
// Copy GSyn over to GPU
copyAllGSynToDevice();
// Start gpu timer
gpu_recvsyn_timer->start();
switchGpu = true;
}
#endif
conn->deliver();
}
#ifdef PV_USE_CUDA
if (switchGpu) {
// Stop timer
gpu_recvsyn_timer->stop();
}
#endif
recvsyn_timer->stop();
}
return status;
}
#ifdef PV_USE_CUDA
double HyPerLayer::addGpuTimers() {
double simTime = 0;
bool updateNeeded = needUpdate(parent->simulationTime(), parent->getDeltaTime());
if (recvGpu && updateNeeded) {
simTime += gpu_recvsyn_timer->accumulateTime();
}
if (updateGpu && updateNeeded) {
simTime += gpu_update_timer->accumulateTime();
}
return simTime;
}
void HyPerLayer::syncGpu() {
if (recvGpu || updateGpu) {
parent->getDevice()->syncDevice();
}
}
void HyPerLayer::copyAllGSynToDevice() {
if (recvGpu || updateGpu) {
// Copy it to device
// Allocated as a big chunk, this should work
float *h_postGSyn = GSyn[0];
PVCuda::CudaBuffer *d_postGSyn = this->getDeviceGSyn();
assert(d_postGSyn);
d_postGSyn->copyToDevice(h_postGSyn);
}
}
void HyPerLayer::copyAllGSynFromDevice() {
// Only copy if recving
if (recvGpu) {
// Allocated as a big chunk, this should work
float *h_postGSyn = GSyn[0];
PVCuda::CudaBuffer *d_postGSyn = this->getDeviceGSyn();
assert(d_postGSyn);
d_postGSyn->copyFromDevice(h_postGSyn);
}
}
void HyPerLayer::copyAllVFromDevice() {
// Only copy if updating
if (updateGpu) {
// Allocated as a big chunk, this should work
float *h_V = getV();
PVCuda::CudaBuffer *d_V = this->getDeviceV();
assert(d_V);
d_V->copyFromDevice(h_V);
}
}
void HyPerLayer::copyAllActivityFromDevice() {
// Only copy if updating
if (updateGpu) {
// Allocated as a big chunk, this should work
float *h_activity = getCLayer()->activity->data;
PVCuda::CudaBuffer *d_activity = this->getDeviceActivity();
assert(d_activity);
d_activity->copyFromDevice(h_activity);
}
}
#endif
int HyPerLayer::publish(Communicator *comm, double simTime) {
publish_timer->start();
int status = PV_SUCCESS;
if (mNeedToPublish) {
if (useMirrorBCs()) {
mirrorInteriorToBorder(clayer->activity, clayer->activity);
}
status = publisher->publish(mLastUpdateTime);
mNeedToPublish = false;
}
else {
publisher->copyForward(mLastUpdateTime);
}
publish_timer->stop();
return status;
}
int HyPerLayer::waitOnPublish(Communicator *comm) {
publish_timer->start();
// wait for MPI border transfers to complete
//
int status = publisher->wait();
publish_timer->stop();
return status;
}
/******************************************************************
* FileIO
*****************************************************************/
/* Inserts a new probe into an array of LayerProbes.
*
*
*
*/
int HyPerLayer::insertProbe(LayerProbe *p) {
if (p->getTargetLayer() != this) {
WarnLog().printf(
"HyPerLayer \"%s\": insertProbe called with probe %p, whose targetLayer is not this "
"layer. Probe was not inserted.\n",
name,
p);
return numProbes;
}
for (int i = 0; i < numProbes; i++) {
if (p == probes[i]) {
WarnLog().printf(
"HyPerLayer \"%s\": insertProbe called with probe %p, which has already been "
"inserted as probe %d.\n",
name,
p,
i);
return numProbes;
}
}
// malloc'ing a new buffer, copying data over, and freeing the old buffer could be replaced by
// malloc
LayerProbe **tmp;
tmp = (LayerProbe **)malloc((numProbes + 1) * sizeof(LayerProbe *));
assert(tmp != NULL);
for (int i = 0; i < numProbes; i++) {
tmp[i] = probes[i];
}
free(probes);
probes = tmp;
probes[numProbes] = p;
return ++numProbes;
}
int HyPerLayer::outputProbeParams() {
int status = PV_SUCCESS;
for (int p = 0; p < numProbes; p++) {
int status1 = probes[p]->ioParams(PARAMS_IO_WRITE);
if (status1 != PV_SUCCESS) {
status = PV_FAILURE;
}
}
return status;
}
int HyPerLayer::outputState(double timef) {
int status = PV_SUCCESS;
io_timer->start();
for (int i = 0; i < numProbes; i++) {
probes[i]->outputStateWrapper(timef, parent->getDeltaTime());
}
if (timef >= (writeTime - (parent->getDeltaTime() / 2)) && writeStep >= 0) {
writeTime += writeStep;
if (sparseLayer) {
status = writeActivitySparse(timef);
}
else {
status = writeActivity(timef);
}
}
if (status != PV_SUCCESS) {
Fatal().printf(
"%s: outputState failed on rank %d process.\n", getDescription_c(), parent->columnId());
}
io_timer->stop();
return status;
}
int HyPerLayer::readStateFromCheckpoint(Checkpointer *checkpointer) {
int status = PV_SUCCESS;
if (initializeFromCheckpointFlag) {
status = readActivityFromCheckpoint(checkpointer);
status = readVFromCheckpoint(checkpointer);
status = readDelaysFromCheckpoint(checkpointer);
updateAllActiveIndices();
}
return status;
}
int HyPerLayer::readActivityFromCheckpoint(Checkpointer *checkpointer) {
checkpointer->readNamedCheckpointEntry(std::string(name), std::string("A"));
return PV_SUCCESS;
}
int HyPerLayer::readVFromCheckpoint(Checkpointer *checkpointer) {
if (getV() != nullptr) {
checkpointer->readNamedCheckpointEntry(std::string(name), std::string("V"));
}
return PV_SUCCESS;
}
int HyPerLayer::readDelaysFromCheckpoint(Checkpointer *checkpointer) {
checkpointer->readNamedCheckpointEntry(std::string(name), std::string("Delays"));
return PV_SUCCESS;
}
// readBufferFile and readDataStoreFromFile were removed Jan 23, 2017.
// They were only used by checkpointing, which is now handled by the
// CheckpointEntry class hierarchy.
int HyPerLayer::processCheckpointRead() {
if (mOutputStateStream) {
long fpos = mOutputStateStream->getInPos();
if (fpos > 0L) {
BufferUtils::ActivityHeader header = BufferUtils::readActivityHeader(*mOutputStateStream);
if (sparseLayer) {
writeActivitySparseCalls = header.nBands;
}
else {
writeActivityCalls = header.nBands;
}
}
mOutputStateStream->setInPos(fpos, true);
}
return updateAllActiveIndices();
}
int HyPerLayer::writeActivitySparse(double timed) {
PVLayerCube cube = publisher->createCube(0 /*delay*/);
PVLayerLoc const *loc = getLayerLoc();
pvAssert(cube.numItems == loc->nbatch * getNumExtended());
int const mpiBatchDimension = mMPIBlock->getBatchDimension();
int const numFrames = mpiBatchDimension * loc->nbatch;
for (int frame = 0; frame < numFrames; frame++) {
int const localBatchIndex = frame % loc->nbatch;
int const mpiBatchIndex = frame / loc->nbatch; // Integer division
pvAssert(mpiBatchIndex * loc->nbatch + localBatchIndex == frame);
SparseList<float> list;
auto *activeIndicesBatch = (SparseList<float>::Entry const *)cube.activeIndices;
auto *activeIndicesElement = &activeIndicesBatch[localBatchIndex * getNumExtended()];
PVLayerLoc const *loc = getLayerLoc();
int nxExt = loc->nx + loc->halo.lt + loc->halo.rt;
int nyExt = loc->ny + loc->halo.dn + loc->halo.up;
int nf = loc->nf;
for (long int k = 0; k < cube.numActive[localBatchIndex]; k++) {
SparseList<float>::Entry entry = activeIndicesElement[k];
int index = (int)entry.index;
// Location is local extended; need global restricted.
int x = kxPos(index, nxExt, nyExt, nf) - loc->halo.lt + loc->kx0;
if (x < 0 or x >= loc->nxGlobal) {
continue;
}
int y = kyPos(index, nxExt, nyExt, nf) - loc->halo.up + loc->ky0;
if (y < 0 or y >= loc->nyGlobal) {
continue;
}
int f = featureIndex(index, nxExt, nyExt, nf);
entry.index = (uint32_t)kIndex(x, y, f, loc->nxGlobal, loc->nyGlobal, nf);
list.addEntry(entry);
}
auto gatheredList =
BufferUtils::gatherSparse(mMPIBlock, list, mpiBatchIndex, 0 /*root process*/);
if (mMPIBlock->getRank() == 0) {
long fpos = mOutputStateStream->getOutPos();
if (fpos == 0L) {
BufferUtils::ActivityHeader header = BufferUtils::buildSparseActivityHeader<float>(
loc->nx * mMPIBlock->getNumColumns(),
loc->ny * mMPIBlock->getNumRows(),
loc->nf,
0 /* numBands */); // numBands will be set by call to incrementNBands.
header.timestamp = timed;
BufferUtils::writeActivityHeader(*mOutputStateStream, header);
}
BufferUtils::writeSparseFrame(*mOutputStateStream, &gatheredList, timed);
}
}
writeActivitySparseCalls += numFrames;
updateNBands(writeActivitySparseCalls);
return PV_SUCCESS;
}
// write non-spiking activity
int HyPerLayer::writeActivity(double timed) {
PVLayerCube cube = publisher->createCube(0);
PVLayerLoc const *loc = getLayerLoc();
pvAssert(cube.numItems == loc->nbatch * getNumExtended());
PVHalo const &halo = loc->halo;
int const nxExtLocal = loc->nx + halo.lt + halo.rt;
int const nyExtLocal = loc->ny + halo.dn + halo.up;
int const nf = loc->nf;
int const mpiBatchDimension = mMPIBlock->getBatchDimension();
int const numFrames = mpiBatchDimension * loc->nbatch;
for (int frame = 0; frame < numFrames; frame++) {
int const localBatchIndex = frame % loc->nbatch;
int const mpiBatchIndex = frame / loc->nbatch; // Integer division
pvAssert(mpiBatchIndex * loc->nbatch + localBatchIndex == frame);
float *data = &cube.data[localBatchIndex * getNumExtended()];
Buffer<float> localBuffer(data, nxExtLocal, nyExtLocal, nf);
localBuffer.crop(loc->nx, loc->ny, Buffer<float>::CENTER);
Buffer<float> blockBuffer = BufferUtils::gather<float>(
mMPIBlock, localBuffer, loc->nx, loc->ny, mpiBatchIndex, 0 /*root process*/);
// At this point, the rank-zero process has the entire block for the batch element,
// regardless of what the mpiBatchIndex is.
if (mMPIBlock->getRank() == 0) {
long fpos = mOutputStateStream->getOutPos();
if (fpos == 0L) {
BufferUtils::ActivityHeader header = BufferUtils::buildActivityHeader<float>(
loc->nx * mMPIBlock->getNumColumns(),
loc->ny * mMPIBlock->getNumRows(),
loc->nf,
0 /* numBands */); // numBands will be set by call to incrementNBands.
header.timestamp = timed;
BufferUtils::writeActivityHeader(*mOutputStateStream, header);
}
BufferUtils::writeFrame<float>(*mOutputStateStream, &blockBuffer, timed);
}
}
writeActivityCalls += numFrames;
updateNBands(writeActivityCalls);
return PV_SUCCESS;
}
void HyPerLayer::updateNBands(int const numCalls) {
// Only the root process needs to maintain INDEX_NBANDS, so only the root process modifies
// numCalls
// This way, writeActivityCalls does not need to be coordinated across MPI
if (mOutputStateStream != nullptr) {
long int fpos = mOutputStateStream->getOutPos();
mOutputStateStream->setOutPos(sizeof(int) * INDEX_NBANDS, true /*fromBeginning*/);
mOutputStateStream->write(&numCalls, (long)sizeof(numCalls));
mOutputStateStream->setOutPos(fpos, true /*fromBeginning*/);
}
}
bool HyPerLayer::localDimensionsEqual(PVLayerLoc const *loc1, PVLayerLoc const *loc2) {
return loc1->nbatch == loc2->nbatch && loc1->nx == loc2->nx && loc1->ny == loc2->ny
&& loc1->nf == loc2->nf && loc1->halo.lt == loc2->halo.lt
&& loc1->halo.rt == loc2->halo.rt && loc1->halo.dn == loc2->halo.dn
&& loc1->halo.up == loc2->halo.up;
}
int HyPerLayer::mirrorToNorthWest(PVLayerCube *dest, PVLayerCube *src) {
if (!localDimensionsEqual(&dest->loc, &src->loc)) {
return -1;
}
int nbatch = dest->loc.nbatch;
int nf = dest->loc.nf;
int leftBorder = dest->loc.halo.lt;
int topBorder = dest->loc.halo.up;
size_t sb = strideBExtended(&dest->loc);
size_t sf = strideFExtended(&dest->loc);
size_t sx = strideXExtended(&dest->loc);
size_t sy = strideYExtended(&dest->loc);
for (int b = 0; b < nbatch; b++) {
float *srcData = src->data + b * sb;
float *destData = dest->data + b * sb;
float *src0 = srcData + topBorder * sy + leftBorder * sx;
float *dst0 = srcData + (topBorder - 1) * sy + (leftBorder - 1) * sx;
for (int ky = 0; ky < topBorder; ky++) {
float *to = dst0 - ky * sy;
float *from = src0 + ky * sy;
for (int kx = 0; kx < leftBorder; kx++) {
for (int kf = 0; kf < nf; kf++) {
to[kf * sf] = from[kf * sf];
}
to -= nf;
from += nf;
}
}
}
return 0;
}
int HyPerLayer::mirrorToNorth(PVLayerCube *dest, PVLayerCube *src) {
if (!localDimensionsEqual(&dest->loc, &src->loc)) {
return -1;
}
int nx = clayer->loc.nx;
int nf = clayer->loc.nf;
int leftBorder = dest->loc.halo.lt;
int topBorder = dest->loc.halo.up;
int nbatch = dest->loc.nbatch;
size_t sb = strideBExtended(&dest->loc);
size_t sf = strideFExtended(&dest->loc);
size_t sx = strideXExtended(&dest->loc);
size_t sy = strideYExtended(&dest->loc);
for (int b = 0; b < nbatch; b++) {
float *srcData = src->data + b * sb;
float *destData = dest->data + b * sb;
float *src0 = srcData + topBorder * sy + leftBorder * sx;
float *dst0 = destData + (topBorder - 1) * sy + leftBorder * sx;
for (int ky = 0; ky < topBorder; ky++) {
float *to = dst0 - ky * sy;
float *from = src0 + ky * sy;
for (int kx = 0; kx < nx; kx++) {
for (int kf = 0; kf < nf; kf++) {
to[kf * sf] = from[kf * sf];
}
to += nf;
from += nf;
}
}
}
return 0;
}
int HyPerLayer::mirrorToNorthEast(PVLayerCube *dest, PVLayerCube *src) {
if (!localDimensionsEqual(&dest->loc, &src->loc)) {
return -1;
}
int nx = dest->loc.nx;
int nf = dest->loc.nf;
int leftBorder = dest->loc.halo.lt;
int rightBorder = dest->loc.halo.rt;
int topBorder = dest->loc.halo.up;
int nbatch = dest->loc.nbatch;
size_t sb = strideBExtended(&dest->loc);
size_t sf = strideFExtended(&dest->loc);
size_t sx = strideXExtended(&dest->loc);
size_t sy = strideYExtended(&dest->loc);
for (int b = 0; b < nbatch; b++) {
float *srcData = src->data + b * sb;
float *destData = dest->data + b * sb;
float *src0 = srcData + topBorder * sy + (nx + leftBorder - 1) * sx;
float *dst0 = destData + (topBorder - 1) * sy + (nx + leftBorder) * sx;
for (int ky = 0; ky < topBorder; ky++) {
float *to = dst0 - ky * sy;
float *from = src0 + ky * sy;
for (int kx = 0; kx < rightBorder; kx++) {
for (int kf = 0; kf < nf; kf++) {
to[kf * sf] = from[kf * sf];
}
to += nf;
from -= nf;
}
}
}
return 0;
}
int HyPerLayer::mirrorToWest(PVLayerCube *dest, PVLayerCube *src) {
if (!localDimensionsEqual(&dest->loc, &src->loc)) {
return -1;
}
int ny = dest->loc.ny;
int nf = dest->loc.nf;
int leftBorder = dest->loc.halo.lt;
int topBorder = dest->loc.halo.up;
int nbatch = dest->loc.nbatch;
size_t sb = strideBExtended(&dest->loc);
size_t sf = strideFExtended(&dest->loc);
size_t sx = strideXExtended(&dest->loc);
size_t sy = strideYExtended(&dest->loc);
for (int b = 0; b < nbatch; b++) {
float *srcData = src->data + b * sb;
float *destData = dest->data + b * sb;
float *src0 = srcData + topBorder * sy + leftBorder * sx;
float *dst0 = destData + topBorder * sy + (leftBorder - 1) * sx;
for (int ky = 0; ky < ny; ky++) {
float *to = dst0 + ky * sy;
float *from = src0 + ky * sy;
for (int kx = 0; kx < leftBorder; kx++) {
for (int kf = 0; kf < nf; kf++) {
to[kf * sf] = from[kf * sf];
}
to -= nf;
from += nf;
}
}
}
return 0;
}
int HyPerLayer::mirrorToEast(PVLayerCube *dest, PVLayerCube *src) {
if (!localDimensionsEqual(&dest->loc, &src->loc)) {
return -1;
}
int nx = clayer->loc.nx;
int ny = clayer->loc.ny;
int nf = clayer->loc.nf;
int leftBorder = dest->loc.halo.lt;
int rightBorder = dest->loc.halo.rt;
int topBorder = dest->loc.halo.up;
int nbatch = dest->loc.nbatch;
size_t sb = strideBExtended(&dest->loc);
size_t sf = strideFExtended(&dest->loc);
size_t sx = strideXExtended(&dest->loc);
size_t sy = strideYExtended(&dest->loc);
for (int b = 0; b < nbatch; b++) {
float *srcData = src->data + b * sb;
float *destData = dest->data + b * sb;
float *src0 = srcData + topBorder * sy + (nx + leftBorder - 1) * sx;
float *dst0 = destData + topBorder * sy + (nx + leftBorder) * sx;
for (int ky = 0; ky < ny; ky++) {
float *to = dst0 + ky * sy;
float *from = src0 + ky * sy;
for (int kx = 0; kx < rightBorder; kx++) {
for (int kf = 0; kf < nf; kf++) {
to[kf * sf] = from[kf * sf];
}
to += nf;
from -= nf;
}
}
}
return 0;
}
int HyPerLayer::mirrorToSouthWest(PVLayerCube *dest, PVLayerCube *src) {
if (!localDimensionsEqual(&dest->loc, &src->loc)) {
return -1;
}
int ny = dest->loc.ny;
int nf = dest->loc.nf;
int leftBorder = dest->loc.halo.lt;
int topBorder = dest->loc.halo.up;
int bottomBorder = dest->loc.halo.dn;
int nbatch = dest->loc.nbatch;
size_t sb = strideBExtended(&dest->loc);
size_t sf = strideFExtended(&dest->loc);
size_t sx = strideXExtended(&dest->loc);
size_t sy = strideYExtended(&dest->loc);
for (int b = 0; b < nbatch; b++) {
float *srcData = src->data + b * sb;
float *destData = dest->data + b * sb;
float *src0 = srcData + (ny + topBorder - 1) * sy + leftBorder * sx;
float *dst0 = destData + (ny + topBorder) * sy + (leftBorder - 1) * sx;
for (int ky = 0; ky < bottomBorder; ky++) {
float *to = dst0 + ky * sy;
float *from = src0 - ky * sy;
for (int kx = 0; kx < leftBorder; kx++) {
for (int kf = 0; kf < nf; kf++) {
to[kf * sf] = from[kf * sf];
}
to -= nf;
from += nf;
}
}
}
return 0;
}
int HyPerLayer::mirrorToSouth(PVLayerCube *dest, PVLayerCube *src) {
if (!localDimensionsEqual(&dest->loc, &src->loc)) {
return -1;
}
int nx = dest->loc.nx;
int ny = dest->loc.ny;
int nf = dest->loc.nf;
int leftBorder = dest->loc.halo.lt;
int rightBorder = dest->loc.halo.rt;
int topBorder = dest->loc.halo.up;
int bottomBorder = dest->loc.halo.dn;
int nbatch = dest->loc.nbatch;
size_t sb = strideBExtended(&dest->loc);
size_t sf = strideFExtended(&dest->loc);
size_t sx = strideXExtended(&dest->loc);
size_t sy = strideYExtended(&dest->loc);
for (int b = 0; b < nbatch; b++) {
float *srcData = src->data + b * sb;
float *destData = dest->data + b * sb;
float *src0 = srcData + (ny + topBorder - 1) * sy + leftBorder * sx;
float *dst0 = destData + (ny + topBorder) * sy + leftBorder * sx;
for (int ky = 0; ky < bottomBorder; ky++) {
float *to = dst0 + ky * sy;
float *from = src0 - ky * sy;
for (int kx = 0; kx < nx; kx++) {
for (int kf = 0; kf < nf; kf++) {
to[kf * sf] = from[kf * sf];
}
to += nf;
from += nf;
}
}
}
return 0;
}
int HyPerLayer::mirrorToSouthEast(PVLayerCube *dest, PVLayerCube *src) {
if (!localDimensionsEqual(&dest->loc, &src->loc)) {
return -1;
}
int nx = dest->loc.nx;
int ny = dest->loc.ny;
int nf = dest->loc.nf;
int leftBorder = dest->loc.halo.lt;
int rightBorder = dest->loc.halo.rt;
int topBorder = dest->loc.halo.up;
int bottomBorder = dest->loc.halo.dn;
int nbatch = dest->loc.nbatch;
size_t sb = strideBExtended(&dest->loc);
size_t sf = strideFExtended(&dest->loc);
size_t sx = strideXExtended(&dest->loc);
size_t sy = strideYExtended(&dest->loc);
for (int b = 0; b < nbatch; b++) {
float *srcData = src->data + b * sb;
float *destData = dest->data + b * sb;
float *src0 = srcData + (ny + topBorder - 1) * sy + (nx + leftBorder - 1) * sx;
float *dst0 = destData + (ny + topBorder) * sy + (nx + leftBorder) * sx;
for (int ky = 0; ky < bottomBorder; ky++) {
float *to = dst0 + ky * sy;
float *from = src0 - ky * sy;
for (int kx = 0; kx < rightBorder; kx++) {
for (int kf = 0; kf < nf; kf++) {
to[kf * sf] = from[kf * sf];
}
to += nf;
from -= nf;
}
}
}
return 0;
}
} // end of PV namespace
|
/**
* @file BoxPacketTest.cpp
* @brief BoxPacket class tester.
* @author zer0
* @date 2019-05-22
*/
#include <gtest/gtest.h>
#include <libtbag/box/BoxPacket.hpp>
using namespace libtbag;
using namespace libtbag::box;
using namespace libtbag::box::details;
TEST(BoxPacketTest, Default)
{
box_data box;
box_clear(&box);
ASSERT_EQ(E_SUCCESS, box_resize_args(&box, BT_INT32, BD_CPU, nullptr, 3, 4, 3, 2));
ui32 i = 0;
for (i = 0; i < 24; ++i) {
box_data_set(&box, &i, BT_INT32, BD_CPU, nullptr, i);
ASSERT_EQ(i, ((si32*)box.data)[i]);
}
ASSERT_EQ(BT_INT32, box.type);
ASSERT_EQ(BD_CPU, box.device);
ASSERT_EQ(0, box.ext[0]);
ASSERT_EQ(0, box.ext[1]);
ASSERT_EQ(0, box.ext[2]);
ASSERT_EQ(0, box.ext[3]);
ASSERT_NE(nullptr, box.data);
ASSERT_EQ(4*3*2, box.size);
ASSERT_EQ(4*3*2*sizeof(ui32), box.total_data_byte);
ASSERT_NE(nullptr, box.dims);
ASSERT_EQ(3, box.rank);
ASSERT_EQ(3*sizeof(ui32), box.total_dims_byte);
BoxPacket packet;
ASSERT_EQ(E_SUCCESS, packet.build(&box));
auto * pointer = packet.point();
ASSERT_NE(nullptr, pointer);
auto size = packet.size();
ASSERT_LT(1, size);
box_data box2;
box_clear(&box2);
BoxPacket packet2;
std::size_t computed_size = 0;
ASSERT_EQ(E_SUCCESS, packet2.parse((char const *)pointer, size, &box2, &computed_size));
ASSERT_LT(1, computed_size);
ASSERT_EQ(computed_size, size);
ASSERT_EQ(box.type, box2.type);
ASSERT_EQ(box.device, box2.device);
ASSERT_EQ(box.ext[0], box2.ext[0]);
ASSERT_EQ(box.ext[1], box2.ext[1]);
ASSERT_EQ(box.ext[2], box2.ext[2]);
ASSERT_EQ(box.ext[3], box2.ext[3]);
ASSERT_NE(box.data, box2.data);
ASSERT_EQ(box.total_data_byte, box2.total_data_byte);
ASSERT_EQ(box.size, box2.size);
ASSERT_NE(box.dims, box2.dims);
ASSERT_EQ(box.total_dims_byte, box2.total_dims_byte);
ASSERT_EQ(box.rank, box2.rank);
for (i = 0; i < 24; ++i) {
si32 box_data;
box_data_get(&box, &box_data, BT_INT32, BD_CPU, nullptr, i);
ASSERT_EQ(i, box_data);
si32 box2_data;
box_data_get(&box2, &box2_data, BT_INT32, BD_CPU, nullptr, i);
ASSERT_EQ(i, box2_data);
ASSERT_EQ(i, ((si32*)box2.data)[i]);
}
box_free(&box);
box_free(&box2);
}
Create BoxPacketTest.ToJson tester.
/**
* @file BoxPacketTest.cpp
* @brief BoxPacket class tester.
* @author zer0
* @date 2019-05-22
*/
#include <gtest/gtest.h>
#include <libtbag/3rd/jsoncpp/json.h>
#include <libtbag/box/BoxPacket.hpp>
using namespace libtbag;
using namespace libtbag::box;
using namespace libtbag::box::details;
TEST(BoxPacketTest, Default)
{
box_data box;
box_clear(&box);
ASSERT_EQ(E_SUCCESS, box_resize_args(&box, BT_INT32, BD_CPU, nullptr, 3, 4, 3, 2));
ui32 i = 0;
for (i = 0; i < 24; ++i) {
box_data_set(&box, &i, BT_INT32, BD_CPU, nullptr, i);
ASSERT_EQ(i, ((si32*)box.data)[i]);
}
ASSERT_EQ(BT_INT32, box.type);
ASSERT_EQ(BD_CPU, box.device);
ASSERT_EQ(0, box.ext[0]);
ASSERT_EQ(0, box.ext[1]);
ASSERT_EQ(0, box.ext[2]);
ASSERT_EQ(0, box.ext[3]);
ASSERT_NE(nullptr, box.data);
ASSERT_EQ(4*3*2, box.size);
ASSERT_EQ(4*3*2*sizeof(ui32), box.total_data_byte);
ASSERT_NE(nullptr, box.dims);
ASSERT_EQ(3, box.rank);
ASSERT_EQ(3*sizeof(ui32), box.total_dims_byte);
BoxPacket packet;
ASSERT_EQ(E_SUCCESS, packet.build(&box));
auto * pointer = packet.point();
ASSERT_NE(nullptr, pointer);
auto size = packet.size();
ASSERT_LT(1, size);
box_data box2;
box_clear(&box2);
BoxPacket packet2;
std::size_t computed_size = 0;
ASSERT_EQ(E_SUCCESS, packet2.parse((char const *)pointer, size, &box2, &computed_size));
ASSERT_LT(1, computed_size);
ASSERT_EQ(computed_size, size);
ASSERT_EQ(box.type, box2.type);
ASSERT_EQ(box.device, box2.device);
ASSERT_EQ(box.ext[0], box2.ext[0]);
ASSERT_EQ(box.ext[1], box2.ext[1]);
ASSERT_EQ(box.ext[2], box2.ext[2]);
ASSERT_EQ(box.ext[3], box2.ext[3]);
ASSERT_NE(box.data, box2.data);
ASSERT_EQ(box.total_data_byte, box2.total_data_byte);
ASSERT_EQ(box.size, box2.size);
ASSERT_NE(box.dims, box2.dims);
ASSERT_EQ(box.total_dims_byte, box2.total_dims_byte);
ASSERT_EQ(box.rank, box2.rank);
for (i = 0; i < 24; ++i) {
si32 box_data;
box_data_get(&box, &box_data, BT_INT32, BD_CPU, nullptr, i);
ASSERT_EQ(i, box_data);
si32 box2_data;
box_data_get(&box2, &box2_data, BT_INT32, BD_CPU, nullptr, i);
ASSERT_EQ(i, box2_data);
ASSERT_EQ(i, ((si32*)box2.data)[i]);
}
box_free(&box);
box_free(&box2);
}
TEST(BoxPacketTest, ToJson)
{
box_data box;
box_clear(&box);
ASSERT_EQ(E_SUCCESS, box_resize_args(&box, BT_INT32, BD_CPU, nullptr, 3, 4, 3, 2));
ui32 i = 0;
for (i = 0; i < 24; ++i) {
box_data_set(&box, &i, BT_INT32, BD_CPU, nullptr, i);
ASSERT_EQ(i, ((si32*)box.data)[i]);
}
BoxPacket packet;
ASSERT_EQ(E_SUCCESS, packet.build(&box));
ASSERT_FALSE(packet.toJsonString().empty());
// Json::Value root;
// Json::Reader reader;
// ASSERT_TRUE(reader.parse(packet.toJsonString(), root));
// ASSERT_TRUE(root["dims"].isArray());
// ASSERT_EQ(3, root["dims"].size());
// ASSERT_EQ(4, root["dims"][0].asInt());
// ASSERT_EQ(3, root["dims"][1].asInt());
// ASSERT_EQ(2, root["dims"][2].asInt());
box_free(&box);
}
|
/**
* \ file FixedDelayLineFilter.cpp
*/
#include <iostream>
#include <ATK/Delay/FixedDelayLineFilter.h>
#include <ATK/Core/InPointerFilter.h>
#include <ATK/Core/OutPointerFilter.h>
#include <ATK/Mock/SimpleSinusGeneratorFilter.h>
#include <ATK/Mock/TriangleCheckerFilter.h>
#include <ATK/Tools/SumFilter.h>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>
#include <boost/math/constants/constants.hpp>
#define PROCESSSIZE (1024*64)
BOOST_AUTO_TEST_CASE( FixedDelayLineFilter_line100_delay_1_test )
{
ATK::FixedDelayLineFilter<float> filter(100);
BOOST_CHECK_THROW(filter.set_delay(-1), std::out_of_range);
}
BOOST_AUTO_TEST_CASE( FixedDelayLineFilter_line100_delay_100_test )
{
ATK::FixedDelayLineFilter<float> filter(100);
BOOST_CHECK_THROW(filter.set_delay(100), std::out_of_range);
}
BOOST_AUTO_TEST_CASE( FixedDelayLineFilter_sinus_line100_delay50_test )
{
std::array<float, PROCESSSIZE> data;
for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i)
{
data[i] = std::sin(2 * boost::math::constants::pi<float>() * (i+1.)/48000 * 1000);
}
ATK::InPointerFilter<float> generator(data.data(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
std::array<float, PROCESSSIZE> outdata;
ATK::FixedDelayLineFilter<float> filter(100);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_delay(50);
ATK::OutPointerFilter<float> output(outdata.data(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(1);
output.process(49);
output.process(51);
output.process(PROCESSSIZE - 1 - 49 -51);
for(ptrdiff_t i = 0; i < 50; ++i)
{
BOOST_REQUIRE_EQUAL(0, outdata[i]);
}
for(ptrdiff_t i = 50; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_EQUAL(data[i - 50], outdata[i]);
}
}
BOOST_AUTO_TEST_CASE(FixedDelayLineFilter_sinus_line100_delay50_progressive_test)
{
ATK::SimpleSinusGeneratorFilter<float> generator;
generator.set_output_sampling_rate(48000);
generator.set_frequency(480);
ATK::FixedDelayLineFilter<float> filter(100);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_delay(50);
filter.process(50);
ATK::SumFilter<float> sum;
sum.set_input_sampling_rate(48000);
sum.set_input_port(0, &filter, 0);
sum.set_input_port(1, &generator, 0);
ATK::TriangleCheckerFilter<float> output;
output.set_input_sampling_rate(48000);
output.set_input_port(0, &sum, 0);
output.set_amplitude(0);
for (std::size_t i = 1; i < 100; ++i)
{
output.process(i);
}
}
BOOST_AUTO_TEST_CASE(FixedDelayLineFilter_sinus_line1000_delay50_progressive_test)
{
ATK::SimpleSinusGeneratorFilter<float> generator;
generator.set_output_sampling_rate(48000);
generator.set_frequency(480);
ATK::FixedDelayLineFilter<float> filter(1000);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_delay(50);
filter.process(50);
ATK::SumFilter<float> sum;
sum.set_input_sampling_rate(48000);
sum.set_input_port(0, &filter, 0);
sum.set_input_port(1, &generator, 0);
ATK::TriangleCheckerFilter<float> output;
output.set_input_sampling_rate(48000);
output.set_input_port(0, &sum, 0);
output.set_amplitude(0);
for (std::size_t i = 50; i < 1000; ++i)
{
output.process(i);
}
}
BOOST_AUTO_TEST_CASE(FixedDelayLineFilter_sinus_delay_test )
{
ATK::FixedDelayLineFilter<float> filter(128);
filter.set_delay(10);
BOOST_CHECK_EQUAL(filter.get_delay(), 10);
}
Fix check for zero delay
/**
* \ file FixedDelayLineFilter.cpp
*/
#include <iostream>
#include <ATK/Delay/FixedDelayLineFilter.h>
#include <ATK/Core/InPointerFilter.h>
#include <ATK/Core/OutPointerFilter.h>
#include <ATK/Mock/SimpleSinusGeneratorFilter.h>
#include <ATK/Mock/TriangleCheckerFilter.h>
#include <ATK/Tools/SumFilter.h>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>
#include <boost/math/constants/constants.hpp>
#define PROCESSSIZE (1024*64)
BOOST_AUTO_TEST_CASE( FixedDelayLineFilter_line100_delay_1_test )
{
ATK::FixedDelayLineFilter<float> filter(100);
BOOST_CHECK_THROW(filter.set_delay(0), std::out_of_range);
}
BOOST_AUTO_TEST_CASE( FixedDelayLineFilter_line100_delay_100_test )
{
ATK::FixedDelayLineFilter<float> filter(100);
BOOST_CHECK_THROW(filter.set_delay(100), std::out_of_range);
}
BOOST_AUTO_TEST_CASE( FixedDelayLineFilter_sinus_line100_delay50_test )
{
std::array<float, PROCESSSIZE> data;
for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i)
{
data[i] = std::sin(2 * boost::math::constants::pi<float>() * (i+1.)/48000 * 1000);
}
ATK::InPointerFilter<float> generator(data.data(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
std::array<float, PROCESSSIZE> outdata;
ATK::FixedDelayLineFilter<float> filter(100);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_delay(50);
ATK::OutPointerFilter<float> output(outdata.data(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(1);
output.process(49);
output.process(51);
output.process(PROCESSSIZE - 1 - 49 -51);
for(ptrdiff_t i = 0; i < 50; ++i)
{
BOOST_REQUIRE_EQUAL(0, outdata[i]);
}
for(ptrdiff_t i = 50; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_EQUAL(data[i - 50], outdata[i]);
}
}
BOOST_AUTO_TEST_CASE(FixedDelayLineFilter_sinus_line100_delay50_progressive_test)
{
ATK::SimpleSinusGeneratorFilter<float> generator;
generator.set_output_sampling_rate(48000);
generator.set_frequency(480);
ATK::FixedDelayLineFilter<float> filter(100);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_delay(50);
filter.process(50);
ATK::SumFilter<float> sum;
sum.set_input_sampling_rate(48000);
sum.set_input_port(0, &filter, 0);
sum.set_input_port(1, &generator, 0);
ATK::TriangleCheckerFilter<float> output;
output.set_input_sampling_rate(48000);
output.set_input_port(0, &sum, 0);
output.set_amplitude(0);
for (std::size_t i = 1; i < 100; ++i)
{
output.process(i);
}
}
BOOST_AUTO_TEST_CASE(FixedDelayLineFilter_sinus_line1000_delay50_progressive_test)
{
ATK::SimpleSinusGeneratorFilter<float> generator;
generator.set_output_sampling_rate(48000);
generator.set_frequency(480);
ATK::FixedDelayLineFilter<float> filter(1000);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_delay(50);
filter.process(50);
ATK::SumFilter<float> sum;
sum.set_input_sampling_rate(48000);
sum.set_input_port(0, &filter, 0);
sum.set_input_port(1, &generator, 0);
ATK::TriangleCheckerFilter<float> output;
output.set_input_sampling_rate(48000);
output.set_input_port(0, &sum, 0);
output.set_amplitude(0);
for (std::size_t i = 50; i < 1000; ++i)
{
output.process(i);
}
}
BOOST_AUTO_TEST_CASE(FixedDelayLineFilter_sinus_delay_test )
{
ATK::FixedDelayLineFilter<float> filter(128);
filter.set_delay(10);
BOOST_CHECK_EQUAL(filter.get_delay(), 10);
}
|
#include <Nazara/Core/File.hpp>
#include <Nazara/Core/StringExt.hpp>
#include <Nazara/Shader/GlslWriter.hpp>
#include <Nazara/Shader/ShaderBuilder.hpp>
#include <Nazara/Shader/SpirvPrinter.hpp>
#include <Nazara/Shader/SpirvWriter.hpp>
#include <Catch/catch.hpp>
#include <cctype>
void ExpectingGLSL(Nz::ShaderAst::StatementPtr& shader, std::string_view expectedOutput)
{
Nz::GlslWriter writer;
std::string output = writer.Generate(shader);
std::size_t funcOffset = output.find("void main()");
std::string_view subset = Nz::Trim(output).substr(funcOffset);
expectedOutput = Nz::Trim(expectedOutput);
REQUIRE(subset == expectedOutput);
}
void ExpectingSpirV(Nz::ShaderAst::StatementPtr& shader, std::string_view expectedOutput)
{
Nz::SpirvWriter writer;
auto spirv = writer.Generate(shader);
Nz::SpirvPrinter printer;
Nz::SpirvPrinter::Settings settings;
settings.printHeader = false;
settings.printParameters = false;
std::string output = printer.Print(spirv.data(), spirv.size(), settings);
std::size_t funcOffset = output.find("OpFunction");
std::string_view subset = Nz::Trim(output).substr(funcOffset);
expectedOutput = Nz::Trim(expectedOutput);
REQUIRE(subset == expectedOutput);
}
SCENARIO("Shader generation", "[Shader]")
{
SECTION("Nested member loading")
{
std::vector<Nz::ShaderAst::StatementPtr> statements;
Nz::ShaderAst::StructDescription innerStructDesc;
{
innerStructDesc.name = "innerStruct";
auto& member = innerStructDesc.members.emplace_back();
member.name = "field";
member.type = Nz::ShaderAst::VectorType{ 3, Nz::ShaderAst::PrimitiveType::Float32 };
}
statements.push_back(Nz::ShaderBuilder::DeclareStruct(std::move(innerStructDesc)));
Nz::ShaderAst::StructDescription outerStruct;
{
outerStruct.name = "outerStruct";
auto& member = outerStruct.members.emplace_back();
member.name = "s";
member.type = Nz::ShaderAst::IdentifierType{ "innerStruct" };
}
statements.push_back(Nz::ShaderBuilder::DeclareStruct(std::move(outerStruct)));
auto external = std::make_unique<Nz::ShaderAst::DeclareExternalStatement>();
external->externalVars.push_back({
std::nullopt,
"ubo",
Nz::ShaderAst::UniformType{ Nz::ShaderAst::IdentifierType{ "outerStruct" } }
});
statements.push_back(std::move(external));
SECTION("Nested AccessMember")
{
auto ubo = Nz::ShaderBuilder::Identifier("ubo");
auto firstAccess = Nz::ShaderBuilder::AccessMember(std::move(ubo), { "s" });
auto secondAccess = Nz::ShaderBuilder::AccessMember(std::move(firstAccess), { "field" });
auto swizzle = Nz::ShaderBuilder::Swizzle(std::move(secondAccess), { Nz::ShaderAst::SwizzleComponent::Third });
auto varDecl = Nz::ShaderBuilder::DeclareVariable("result", Nz::ShaderAst::PrimitiveType::Float32, std::move(swizzle));
statements.push_back(Nz::ShaderBuilder::DeclareFunction("main", std::move(varDecl)));
Nz::ShaderAst::StatementPtr shader = Nz::ShaderBuilder::MultiStatement(std::move(statements));
SECTION("Generating GLSL")
{
ExpectingGLSL(shader, R"(
void main()
{
float result = ubo.s.field.z;
}
)");
}
SECTION("Generating Spir-V")
{
ExpectingSpirV(shader, R"(
OpFunction
OpLabel
OpVariable
OpAccessChain
OpAccessChain
OpLoad
OpCompositeExtract
OpStore
OpReturn
OpFunctionEnd)");
}
}
SECTION("AccessMember with multiples fields")
{
auto ubo = Nz::ShaderBuilder::Identifier("ubo");
auto access = Nz::ShaderBuilder::AccessMember(std::move(ubo), { "s", "field" });
auto swizzle = Nz::ShaderBuilder::Swizzle(std::move(access), { Nz::ShaderAst::SwizzleComponent::Third });
auto varDecl = Nz::ShaderBuilder::DeclareVariable("result", Nz::ShaderAst::PrimitiveType::Float32, std::move(swizzle));
statements.push_back(Nz::ShaderBuilder::DeclareFunction("main", std::move(varDecl)));
Nz::ShaderAst::StatementPtr shader = Nz::ShaderBuilder::MultiStatement(std::move(statements));
SECTION("Generating GLSL")
{
ExpectingGLSL(shader, R"(
void main()
{
float result = ubo.s.field.z;
}
)");
}
SECTION("Generating Spir-V")
{
ExpectingSpirV(shader, R"(
OpFunction
OpLabel
OpVariable
OpAccessChain
OpLoad
OpCompositeExtract
OpStore
OpReturn
OpFunctionEnd)");
}
}
}
}
Tests: Fix Shader/AccessMember
It turns out the Sanitizer AccessMember refactor also optimized the SPIRV output by merging the resulting AccessIndex
#include <Nazara/Core/File.hpp>
#include <Nazara/Core/StringExt.hpp>
#include <Nazara/Shader/GlslWriter.hpp>
#include <Nazara/Shader/ShaderBuilder.hpp>
#include <Nazara/Shader/SpirvPrinter.hpp>
#include <Nazara/Shader/SpirvWriter.hpp>
#include <Catch/catch.hpp>
#include <cctype>
void ExpectingGLSL(Nz::ShaderAst::StatementPtr& shader, std::string_view expectedOutput)
{
Nz::GlslWriter writer;
std::string output = writer.Generate(shader);
std::size_t funcOffset = output.find("void main()");
std::string_view subset = Nz::Trim(output).substr(funcOffset);
expectedOutput = Nz::Trim(expectedOutput);
REQUIRE(subset == expectedOutput);
}
void ExpectingSpirV(Nz::ShaderAst::StatementPtr& shader, std::string_view expectedOutput)
{
Nz::SpirvWriter writer;
auto spirv = writer.Generate(shader);
Nz::SpirvPrinter printer;
Nz::SpirvPrinter::Settings settings;
settings.printHeader = false;
settings.printParameters = false;
std::string output = printer.Print(spirv.data(), spirv.size(), settings);
std::size_t funcOffset = output.find("OpFunction");
std::string_view subset = Nz::Trim(output).substr(funcOffset);
expectedOutput = Nz::Trim(expectedOutput);
REQUIRE(subset == expectedOutput);
}
SCENARIO("Shader generation", "[Shader]")
{
SECTION("Nested member loading")
{
std::vector<Nz::ShaderAst::StatementPtr> statements;
Nz::ShaderAst::StructDescription innerStructDesc;
{
innerStructDesc.name = "innerStruct";
auto& member = innerStructDesc.members.emplace_back();
member.name = "field";
member.type = Nz::ShaderAst::VectorType{ 3, Nz::ShaderAst::PrimitiveType::Float32 };
}
statements.push_back(Nz::ShaderBuilder::DeclareStruct(std::move(innerStructDesc)));
Nz::ShaderAst::StructDescription outerStruct;
{
outerStruct.name = "outerStruct";
auto& member = outerStruct.members.emplace_back();
member.name = "s";
member.type = Nz::ShaderAst::IdentifierType{ "innerStruct" };
}
statements.push_back(Nz::ShaderBuilder::DeclareStruct(std::move(outerStruct)));
auto external = std::make_unique<Nz::ShaderAst::DeclareExternalStatement>();
external->externalVars.push_back({
std::nullopt,
"ubo",
Nz::ShaderAst::UniformType{ Nz::ShaderAst::IdentifierType{ "outerStruct" } }
});
statements.push_back(std::move(external));
SECTION("Nested AccessMember")
{
auto ubo = Nz::ShaderBuilder::Identifier("ubo");
auto firstAccess = Nz::ShaderBuilder::AccessMember(std::move(ubo), { "s" });
auto secondAccess = Nz::ShaderBuilder::AccessMember(std::move(firstAccess), { "field" });
auto swizzle = Nz::ShaderBuilder::Swizzle(std::move(secondAccess), { Nz::ShaderAst::SwizzleComponent::Third });
auto varDecl = Nz::ShaderBuilder::DeclareVariable("result", Nz::ShaderAst::PrimitiveType::Float32, std::move(swizzle));
statements.push_back(Nz::ShaderBuilder::DeclareFunction("main", std::move(varDecl)));
Nz::ShaderAst::StatementPtr shader = Nz::ShaderBuilder::MultiStatement(std::move(statements));
SECTION("Generating GLSL")
{
ExpectingGLSL(shader, R"(
void main()
{
float result = ubo.s.field.z;
}
)");
}
SECTION("Generating Spir-V")
{
ExpectingSpirV(shader, R"(
OpFunction
OpLabel
OpVariable
OpAccessChain
OpLoad
OpCompositeExtract
OpStore
OpReturn
OpFunctionEnd)");
}
}
SECTION("AccessMember with multiples fields")
{
auto ubo = Nz::ShaderBuilder::Identifier("ubo");
auto access = Nz::ShaderBuilder::AccessMember(std::move(ubo), { "s", "field" });
auto swizzle = Nz::ShaderBuilder::Swizzle(std::move(access), { Nz::ShaderAst::SwizzleComponent::Third });
auto varDecl = Nz::ShaderBuilder::DeclareVariable("result", Nz::ShaderAst::PrimitiveType::Float32, std::move(swizzle));
statements.push_back(Nz::ShaderBuilder::DeclareFunction("main", std::move(varDecl)));
Nz::ShaderAst::StatementPtr shader = Nz::ShaderBuilder::MultiStatement(std::move(statements));
SECTION("Generating GLSL")
{
ExpectingGLSL(shader, R"(
void main()
{
float result = ubo.s.field.z;
}
)");
}
SECTION("Generating Spir-V")
{
ExpectingSpirV(shader, R"(
OpFunction
OpLabel
OpVariable
OpAccessChain
OpLoad
OpCompositeExtract
OpStore
OpReturn
OpFunctionEnd)");
}
}
}
}
|
#if !defined(__CINT__) || defined(__MAKECINT__)
// ROOT includes
#include "TTree.h"
#include "TBranch.h"
#include "TClonesArray.h"
#include "TLorentzVector.h"
#include "TFile.h"
#include "TH1.h"
#include "TH2.h"
#include "TParticle.h"
#include "TTree.h"
#include <Riostream.h>
// STEER includes
#include "AliRun.h"
#include "AliRunLoader.h"
#include "AliHeader.h"
#include "AliLoader.h"
#include "AliStack.h"
#include "AliMagF.h"
#include "AliESD.h"
// MUON includes
#include "AliESDMuonTrack.h"
#endif
//
// Macro MUONmassPlot.C for ESD
// Ch. Finck, Subatech, April. 2004
//
// macro to make invariant mass plots
// for combinations of 2 muons with opposite charges,
// from root file "MUON.tracks.root" containing the result of track reconstruction.
// Histograms are stored on the "MUONmassPlot.root" file.
// introducing TLorentzVector for parameter calculations (Pt, P,rap,etc...)
// using Invariant Mass for rapidity.
// Arguments:
// FirstEvent (default 0)
// LastEvent (default 0)
// ResType (default 553)
// 553 for Upsilon, anything else for J/Psi
// Chi2Cut (default 100)
// to keep only tracks with chi2 per d.o.f. < Chi2Cut
// PtCutMin (default 1)
// to keep only tracks with transverse momentum > PtCutMin
// PtCutMax (default 10000)
// to keep only tracks with transverse momentum < PtCutMax
// massMin (default 9.17 for Upsilon)
// & massMax (default 9.77 for Upsilon)
// to calculate the reconstruction efficiency for resonances with invariant mass
// massMin < mass < massMax.
// Add parameters and histograms for analysis
Bool_t MUONmassPlot(char* filename = "galice.root", Int_t FirstEvent = 0, Int_t LastEvent = 10000,
char* esdFileName = "AliESDs.root", Int_t ResType = 553,
Float_t Chi2Cut = 100., Float_t PtCutMin = 1., Float_t PtCutMax = 10000.,
Float_t massMin = 9.17,Float_t massMax = 9.77)
{
cout << "MUONmassPlot " << endl;
cout << "FirstEvent " << FirstEvent << endl;
cout << "LastEvent " << LastEvent << endl;
cout << "ResType " << ResType << endl;
cout << "Chi2Cut " << Chi2Cut << endl;
cout << "PtCutMin " << PtCutMin << endl;
cout << "PtCutMax " << PtCutMax << endl;
cout << "massMin " << massMin << endl;
cout << "massMax " << massMax << endl;
//Reset ROOT and connect tree file
gROOT->Reset();
// File for histograms and histogram booking
TFile *histoFile = new TFile("MUONmassPlot.root", "RECREATE");
TH1F *hPtMuon = new TH1F("hPtMuon", "Muon Pt (GeV/c)", 100, 0., 20.);
TH1F *hPtMuonPlus = new TH1F("hPtMuonPlus", "Muon+ Pt (GeV/c)", 100, 0., 20.);
TH1F *hPtMuonMinus = new TH1F("hPtMuonMinus", "Muon- Pt (GeV/c)", 100, 0., 20.);
TH1F *hPMuon = new TH1F("hPMuon", "Muon P (GeV/c)", 100, 0., 200.);
TH1F *hChi2PerDof = new TH1F("hChi2PerDof", "Muon track chi2/d.o.f.", 100, 0., 20.);
TH1F *hInvMassAll = new TH1F("hInvMassAll", "Mu+Mu- invariant mass (GeV/c2)", 480, 0., 12.);
TH1F *hInvMassBg = new TH1F("hInvMassBg", "Mu+Mu- invariant mass BG(GeV/c2)", 480, 0., 12.);
TH2F *hInvMassAll_vs_Pt = new TH2F("hInvMassAll_vs_Pt","hInvMassAll_vs_Pt",480,0.,12.,80,0.,20.);
TH2F *hInvMassBgk_vs_Pt = new TH2F("hInvMassBgk_vs_Pt","hInvMassBgk_vs_Pt",480,0.,12.,80,0.,20.);
TH1F *hInvMassRes;
TH1F *hPrimaryVertex = new TH1F("hPrimaryVertex","SPD reconstructed Z vertex",120,-12,12);
if (ResType == 553) {
hInvMassRes = new TH1F("hInvMassRes", "Mu+Mu- invariant mass (GeV/c2) around Upsilon", 60, 8., 11.);
} else {
hInvMassRes = new TH1F("hInvMassRes", "Mu+Mu- invariant mass (GeV/c2) around J/Psi", 80, 0., 5.);
}
TH1F *hNumberOfTrack = new TH1F("hNumberOfTrack","nb of track /evt ",20,-0.5,19.5);
TH1F *hRapMuon = new TH1F("hRapMuon"," Muon Rapidity",50,-4.5,-2);
TH1F *hRapResonance = new TH1F("hRapResonance"," Resonance Rapidity",50,-4.5,-2);
TH1F *hPtResonance = new TH1F("hPtResonance", "Resonance Pt (GeV/c)", 100, 0., 20.);
TH2F *hThetaPhiPlus = new TH2F("hThetaPhiPlus", "Theta vs Phi +", 760, -190., 190., 400, 160., 180.);
TH2F *hThetaPhiMinus = new TH2F("hThetaPhiMinus", "Theta vs Phi -", 760, -190., 190., 400, 160., 180.);
// settings
Int_t EventInMass = 0;
Int_t EventInMassMatch = 0;
Int_t NbTrigger = 0;
Float_t muonMass = 0.105658389;
// Float_t UpsilonMass = 9.46037;
// Float_t JPsiMass = 3.097;
Double_t thetaX, thetaY, pYZ;
Double_t fPxRec1, fPyRec1, fPzRec1, fE1;
Double_t fPxRec2, fPyRec2, fPzRec2, fE2;
Int_t fCharge, fCharge2;
Int_t ntrackhits, nevents;
Double_t fitfmin;
Double_t fZVertex;
TLorentzVector fV1, fV2, fVtot;
// set off mag field
AliMagF::SetReadField(kFALSE);
// open run loader and load gAlice, kinematics and header
AliRunLoader* runLoader = AliRunLoader::Open(filename);
if (!runLoader) {
Error("MUONmass_ESD", "getting run loader from file %s failed",
filename);
return kFALSE;
}
if (!gAlice) {
Error("MUONmass_ESD", "no galice object found");
return kFALSE;
}
// open the ESD file
TFile* esdFile = TFile::Open(esdFileName);
if (!esdFile || !esdFile->IsOpen()) {
Error("MUONmass_ESD", "opening ESD file %s failed", esdFileName);
return kFALSE;
}
AliESD* esd = new AliESD();
TTree* tree = (TTree*) esdFile->Get("esdTree");
if (!tree) {
Error("CheckESD", "no ESD tree found");
return kFALSE;
}
tree->SetBranchAddress("ESD", &esd);
AliESDVertex* Vertex = (AliESDVertex*) esd->AliESD::GetVertex();
runLoader->LoadHeader();
nevents = runLoader->GetNumberOfEvents();
// Loop over events
for (Int_t iEvent = FirstEvent; iEvent <= TMath::Min(LastEvent, nevents - 1); iEvent++) {
// get current event
runLoader->GetEvent(iEvent);
// get the event summary data
tree->GetEvent(iEvent);
if (!esd) {
Error("CheckESD", "no ESD object found for event %d", iEvent);
return kFALSE;
}
// get the SPD reconstructed vertex (vertexer) and fill the histogram
fZVertex = Vertex->GetZv();
hPrimaryVertex->Fill(fZVertex);
Int_t nTracks = (Int_t)esd->GetNumberOfMuonTracks() ;
// printf("\n Nb of events analysed: %d\r",iEvent);
// cout << " number of tracks: " << nTracks <<endl;
// loop over all reconstructed tracks (also first track of combination)
for (Int_t iTrack = 0; iTrack < nTracks; iTrack++) {
AliESDMuonTrack* muonTrack = esd->GetMuonTrack(iTrack);
thetaX = muonTrack->GetThetaX();
thetaY = muonTrack->GetThetaY();
pYZ = 1./TMath::Abs(muonTrack->GetInverseBendingMomentum());
fPzRec1 = - pYZ / TMath::Sqrt(1.0 + TMath::Tan(thetaY)*TMath::Tan(thetaY));
fPxRec1 = fPzRec1 * TMath::Tan(thetaX);
fPyRec1 = fPzRec1 * TMath::Tan(thetaY);
fCharge = Int_t(TMath::Sign(1.,muonTrack->GetInverseBendingMomentum()));
fE1 = TMath::Sqrt(muonMass * muonMass + fPxRec1 * fPxRec1 + fPyRec1 * fPyRec1 + fPzRec1 * fPzRec1);
fV1.SetPxPyPzE(fPxRec1, fPyRec1, fPzRec1, fE1);
ntrackhits = muonTrack->GetNHit();
fitfmin = muonTrack->GetChi2();
// transverse momentum
Float_t pt1 = fV1.Pt();
// total momentum
Float_t p1 = fV1.P();
// Rapidity
Float_t rapMuon1 = fV1.Rapidity();
// chi2 per d.o.f.
Float_t ch1 = fitfmin / (2.0 * ntrackhits - 5);
// printf(" px %f py %f pz %f NHits %d Norm.chi2 %f charge %d\n",
// fPxRec1, fPyRec1, fPzRec1, ntrackhits, ch1, fCharge);
// condition for good track (Chi2Cut and PtCut)
if ((ch1 < Chi2Cut) && (pt1 > PtCutMin) && (pt1 < PtCutMax)) {
// fill histos hPtMuon and hChi2PerDof
hPtMuon->Fill(pt1);
hPMuon->Fill(p1);
hChi2PerDof->Fill(ch1);
hRapMuon->Fill(rapMuon1);
if (fCharge > 0) {
hPtMuonPlus->Fill(pt1);
hThetaPhiPlus->Fill(TMath::ATan2(fPyRec1,fPxRec1)*180./TMath::Pi(),TMath::ATan2(pt1,fPzRec1)*180./3.1415);
} else {
hPtMuonMinus->Fill(pt1);
hThetaPhiMinus->Fill(TMath::ATan2(fPyRec1,fPxRec1)*180./TMath::Pi(),TMath::ATan2(pt1,fPzRec1)*180./3.1415);
}
// loop over second track of combination
for (Int_t iTrack2 = iTrack + 1; iTrack2 < nTracks; iTrack2++) {
AliESDMuonTrack* muonTrack = esd->GetMuonTrack(iTrack2);
thetaX = muonTrack->GetThetaX();
thetaY = muonTrack->GetThetaY();
pYZ = 1./TMath::Abs(muonTrack->GetInverseBendingMomentum());
fPzRec2 = - pYZ / TMath::Sqrt(1.0 + TMath::Tan(thetaY)*TMath::Tan(thetaY));
fPxRec2 = fPzRec2 * TMath::Tan(thetaX);
fPyRec2 = fPzRec2 * TMath::Tan(thetaY);
fCharge2 = Int_t(TMath::Sign(1.,muonTrack->GetInverseBendingMomentum()));
fE2 = TMath::Sqrt(muonMass * muonMass + fPxRec2 * fPxRec2 + fPyRec2 * fPyRec2 + fPzRec2 * fPzRec2);
fV2.SetPxPyPzE(fPxRec2, fPyRec2, fPzRec2, fE2);
ntrackhits = muonTrack->GetNHit();
fitfmin = muonTrack->GetChi2();
// transverse momentum
Float_t pt2 = fV2.Pt();
// chi2 per d.o.f.
Float_t ch2 = fitfmin / (2.0 * ntrackhits - 5);
// condition for good track (Chi2Cut and PtCut)
if ((ch2 < Chi2Cut) && (pt2 > PtCutMin) && (pt2 < PtCutMax)) {
// condition for opposite charges
if ((fCharge * fCharge2) == -1) {
// invariant mass
fVtot = fV1 + fV2;
Float_t invMass = fVtot.M();
// fill histos hInvMassAll and hInvMassRes
hInvMassAll->Fill(invMass);
hInvMassRes->Fill(invMass);
hInvMassAll_vs_Pt->Fill(invMass,fVtot.Pt());
Int_t ptTrig;
if (ResType == 553)
ptTrig = 0x400;// mask for Hpt unlike sign pair
else
ptTrig = 0x200;// mask for Lpt unlike sign pair
if (esd->GetTriggerMask() & ptTrig) NbTrigger++;
if (invMass > massMin && invMass < massMax) {
EventInMass++;
if (muonTrack->GetMatchTrigger() && (esd->GetTriggerMask() & ptTrig))// match with trigger
EventInMassMatch++;
hRapResonance->Fill(fVtot.Rapidity());
hPtResonance->Fill(fVtot.Pt());
}
} // if (fCharge * fCharge2) == -1)
} // if ((ch2 < Chi2Cut) && (pt2 > PtCutMin) && (pt2 < PtCutMax))
} // for (Int_t iTrack2 = iTrack + 1; iTrack2 < iTrack; iTrack2++)
} // if (ch1 < Chi2Cut) && (pt1 > PtCutMin)&& (pt1 < PtCutMax) )
} // for (Int_t iTrack = 0; iTrack < nrectracks; iTrack++)
hNumberOfTrack->Fill(nTracks);
// esdFile->Delete();
} // for (Int_t iEvent = FirstEvent;
// Loop over events for bg event
Double_t thetaPlus, phiPlus;
Double_t thetaMinus, phiMinus;
Float_t PtMinus, PtPlus;
for (Int_t iEvent = 0; iEvent < hInvMassAll->Integral(); iEvent++) {
hThetaPhiPlus->GetRandom2(phiPlus, thetaPlus);
hThetaPhiMinus->GetRandom2(phiMinus,thetaMinus);
PtPlus = hPtMuonPlus->GetRandom();
PtMinus = hPtMuonMinus->GetRandom();
fPxRec1 = PtPlus * TMath::Cos(TMath::Pi()/180.*phiPlus);
fPyRec1 = PtPlus * TMath::Sin(TMath::Pi()/180.*phiPlus);
fPzRec1 = PtPlus / TMath::Tan(TMath::Pi()/180.*thetaPlus);
fE1 = TMath::Sqrt(muonMass * muonMass + fPxRec1 * fPxRec1 + fPyRec1 * fPyRec1 + fPzRec1 * fPzRec1);
fV1.SetPxPyPzE(fPxRec1, fPyRec1, fPzRec1, fE1);
fPxRec2 = PtMinus * TMath::Cos(TMath::Pi()/180.*phiMinus);
fPyRec2 = PtMinus * TMath::Sin(TMath::Pi()/180.*phiMinus);
fPzRec2 = PtMinus / TMath::Tan(TMath::Pi()/180.*thetaMinus);
fE2 = TMath::Sqrt(muonMass * muonMass + fPxRec2 * fPxRec2 + fPyRec2 * fPyRec2 + fPzRec2 * fPzRec2);
fV2.SetPxPyPzE(fPxRec2, fPyRec2, fPzRec2, fE2);
// invariant mass
fVtot = fV1 + fV2;
// fill histos hInvMassAll and hInvMassRes
hInvMassBg->Fill(fVtot.M());
hInvMassBgk_vs_Pt->Fill( fVtot.M(), fVtot.Pt() );
}
histoFile->Write();
histoFile->Close();
cout << endl;
cout << "EventInMass " << EventInMass << endl;
cout << "NbTrigger " << NbTrigger << endl;
cout << "EventInMass match with trigger " << EventInMassMatch << endl;
return kTRUE;
}
Added test for existence of the vertex (fixes crash)
(Philippe)
#if !defined(__CINT__) || defined(__MAKECINT__)
// ROOT includes
#include "TTree.h"
#include "TBranch.h"
#include "TClonesArray.h"
#include "TLorentzVector.h"
#include "TFile.h"
#include "TH1.h"
#include "TH2.h"
#include "TParticle.h"
#include "TTree.h"
#include <Riostream.h>
// STEER includes
#include "AliRun.h"
#include "AliRunLoader.h"
#include "AliHeader.h"
#include "AliLoader.h"
#include "AliStack.h"
#include "AliMagF.h"
#include "AliESD.h"
// MUON includes
#include "AliESDMuonTrack.h"
#endif
//
// Macro MUONmassPlot.C for ESD
// Ch. Finck, Subatech, April. 2004
//
// macro to make invariant mass plots
// for combinations of 2 muons with opposite charges,
// from root file "MUON.tracks.root" containing the result of track reconstruction.
// Histograms are stored on the "MUONmassPlot.root" file.
// introducing TLorentzVector for parameter calculations (Pt, P,rap,etc...)
// using Invariant Mass for rapidity.
// Arguments:
// FirstEvent (default 0)
// LastEvent (default 0)
// ResType (default 553)
// 553 for Upsilon, anything else for J/Psi
// Chi2Cut (default 100)
// to keep only tracks with chi2 per d.o.f. < Chi2Cut
// PtCutMin (default 1)
// to keep only tracks with transverse momentum > PtCutMin
// PtCutMax (default 10000)
// to keep only tracks with transverse momentum < PtCutMax
// massMin (default 9.17 for Upsilon)
// & massMax (default 9.77 for Upsilon)
// to calculate the reconstruction efficiency for resonances with invariant mass
// massMin < mass < massMax.
// Add parameters and histograms for analysis
Bool_t MUONmassPlot(char* filename = "galice.root", Int_t FirstEvent = 0, Int_t LastEvent = 10000,
char* esdFileName = "AliESDs.root", Int_t ResType = 553,
Float_t Chi2Cut = 100., Float_t PtCutMin = 1., Float_t PtCutMax = 10000.,
Float_t massMin = 9.17,Float_t massMax = 9.77)
{
cout << "MUONmassPlot " << endl;
cout << "FirstEvent " << FirstEvent << endl;
cout << "LastEvent " << LastEvent << endl;
cout << "ResType " << ResType << endl;
cout << "Chi2Cut " << Chi2Cut << endl;
cout << "PtCutMin " << PtCutMin << endl;
cout << "PtCutMax " << PtCutMax << endl;
cout << "massMin " << massMin << endl;
cout << "massMax " << massMax << endl;
//Reset ROOT and connect tree file
gROOT->Reset();
// File for histograms and histogram booking
TFile *histoFile = new TFile("MUONmassPlot.root", "RECREATE");
TH1F *hPtMuon = new TH1F("hPtMuon", "Muon Pt (GeV/c)", 100, 0., 20.);
TH1F *hPtMuonPlus = new TH1F("hPtMuonPlus", "Muon+ Pt (GeV/c)", 100, 0., 20.);
TH1F *hPtMuonMinus = new TH1F("hPtMuonMinus", "Muon- Pt (GeV/c)", 100, 0., 20.);
TH1F *hPMuon = new TH1F("hPMuon", "Muon P (GeV/c)", 100, 0., 200.);
TH1F *hChi2PerDof = new TH1F("hChi2PerDof", "Muon track chi2/d.o.f.", 100, 0., 20.);
TH1F *hInvMassAll = new TH1F("hInvMassAll", "Mu+Mu- invariant mass (GeV/c2)", 480, 0., 12.);
TH1F *hInvMassBg = new TH1F("hInvMassBg", "Mu+Mu- invariant mass BG(GeV/c2)", 480, 0., 12.);
TH2F *hInvMassAll_vs_Pt = new TH2F("hInvMassAll_vs_Pt","hInvMassAll_vs_Pt",480,0.,12.,80,0.,20.);
TH2F *hInvMassBgk_vs_Pt = new TH2F("hInvMassBgk_vs_Pt","hInvMassBgk_vs_Pt",480,0.,12.,80,0.,20.);
TH1F *hInvMassRes;
TH1F *hPrimaryVertex = new TH1F("hPrimaryVertex","SPD reconstructed Z vertex",120,-12,12);
if (ResType == 553) {
hInvMassRes = new TH1F("hInvMassRes", "Mu+Mu- invariant mass (GeV/c2) around Upsilon", 60, 8., 11.);
} else {
hInvMassRes = new TH1F("hInvMassRes", "Mu+Mu- invariant mass (GeV/c2) around J/Psi", 80, 0., 5.);
}
TH1F *hNumberOfTrack = new TH1F("hNumberOfTrack","nb of track /evt ",20,-0.5,19.5);
TH1F *hRapMuon = new TH1F("hRapMuon"," Muon Rapidity",50,-4.5,-2);
TH1F *hRapResonance = new TH1F("hRapResonance"," Resonance Rapidity",50,-4.5,-2);
TH1F *hPtResonance = new TH1F("hPtResonance", "Resonance Pt (GeV/c)", 100, 0., 20.);
TH2F *hThetaPhiPlus = new TH2F("hThetaPhiPlus", "Theta vs Phi +", 760, -190., 190., 400, 160., 180.);
TH2F *hThetaPhiMinus = new TH2F("hThetaPhiMinus", "Theta vs Phi -", 760, -190., 190., 400, 160., 180.);
// settings
Int_t EventInMass = 0;
Int_t EventInMassMatch = 0;
Int_t NbTrigger = 0;
Float_t muonMass = 0.105658389;
// Float_t UpsilonMass = 9.46037;
// Float_t JPsiMass = 3.097;
Double_t thetaX, thetaY, pYZ;
Double_t fPxRec1, fPyRec1, fPzRec1, fE1;
Double_t fPxRec2, fPyRec2, fPzRec2, fE2;
Int_t fCharge, fCharge2;
Int_t ntrackhits, nevents;
Double_t fitfmin;
Double_t fZVertex=0;
TLorentzVector fV1, fV2, fVtot;
// set off mag field
AliMagF::SetReadField(kFALSE);
// open run loader and load gAlice, kinematics and header
AliRunLoader* runLoader = AliRunLoader::Open(filename);
if (!runLoader) {
Error("MUONmass_ESD", "getting run loader from file %s failed",
filename);
return kFALSE;
}
if (!gAlice) {
Error("MUONmass_ESD", "no galice object found");
return kFALSE;
}
// open the ESD file
TFile* esdFile = TFile::Open(esdFileName);
if (!esdFile || !esdFile->IsOpen()) {
Error("MUONmass_ESD", "opening ESD file %s failed", esdFileName);
return kFALSE;
}
AliESD* esd = new AliESD();
TTree* tree = (TTree*) esdFile->Get("esdTree");
if (!tree) {
Error("CheckESD", "no ESD tree found");
return kFALSE;
}
tree->SetBranchAddress("ESD", &esd);
AliESDVertex* Vertex = (AliESDVertex*) esd->AliESD::GetVertex();
runLoader->LoadHeader();
nevents = runLoader->GetNumberOfEvents();
// Loop over events
for (Int_t iEvent = FirstEvent; iEvent <= TMath::Min(LastEvent, nevents - 1); iEvent++) {
// get current event
runLoader->GetEvent(iEvent);
// get the event summary data
tree->GetEvent(iEvent);
if (!esd) {
Error("CheckESD", "no ESD object found for event %d", iEvent);
return kFALSE;
}
// get the SPD reconstructed vertex (vertexer) and fill the histogram
if (Vertex) fZVertex = Vertex->GetZv();
hPrimaryVertex->Fill(fZVertex);
Int_t nTracks = (Int_t)esd->GetNumberOfMuonTracks() ;
// printf("\n Nb of events analysed: %d\r",iEvent);
// cout << " number of tracks: " << nTracks <<endl;
// loop over all reconstructed tracks (also first track of combination)
for (Int_t iTrack = 0; iTrack < nTracks; iTrack++) {
AliESDMuonTrack* muonTrack = esd->GetMuonTrack(iTrack);
thetaX = muonTrack->GetThetaX();
thetaY = muonTrack->GetThetaY();
pYZ = 1./TMath::Abs(muonTrack->GetInverseBendingMomentum());
fPzRec1 = - pYZ / TMath::Sqrt(1.0 + TMath::Tan(thetaY)*TMath::Tan(thetaY));
fPxRec1 = fPzRec1 * TMath::Tan(thetaX);
fPyRec1 = fPzRec1 * TMath::Tan(thetaY);
fCharge = Int_t(TMath::Sign(1.,muonTrack->GetInverseBendingMomentum()));
fE1 = TMath::Sqrt(muonMass * muonMass + fPxRec1 * fPxRec1 + fPyRec1 * fPyRec1 + fPzRec1 * fPzRec1);
fV1.SetPxPyPzE(fPxRec1, fPyRec1, fPzRec1, fE1);
ntrackhits = muonTrack->GetNHit();
fitfmin = muonTrack->GetChi2();
// transverse momentum
Float_t pt1 = fV1.Pt();
// total momentum
Float_t p1 = fV1.P();
// Rapidity
Float_t rapMuon1 = fV1.Rapidity();
// chi2 per d.o.f.
Float_t ch1 = fitfmin / (2.0 * ntrackhits - 5);
// printf(" px %f py %f pz %f NHits %d Norm.chi2 %f charge %d\n",
// fPxRec1, fPyRec1, fPzRec1, ntrackhits, ch1, fCharge);
// condition for good track (Chi2Cut and PtCut)
if ((ch1 < Chi2Cut) && (pt1 > PtCutMin) && (pt1 < PtCutMax)) {
// fill histos hPtMuon and hChi2PerDof
hPtMuon->Fill(pt1);
hPMuon->Fill(p1);
hChi2PerDof->Fill(ch1);
hRapMuon->Fill(rapMuon1);
if (fCharge > 0) {
hPtMuonPlus->Fill(pt1);
hThetaPhiPlus->Fill(TMath::ATan2(fPyRec1,fPxRec1)*180./TMath::Pi(),TMath::ATan2(pt1,fPzRec1)*180./3.1415);
} else {
hPtMuonMinus->Fill(pt1);
hThetaPhiMinus->Fill(TMath::ATan2(fPyRec1,fPxRec1)*180./TMath::Pi(),TMath::ATan2(pt1,fPzRec1)*180./3.1415);
}
// loop over second track of combination
for (Int_t iTrack2 = iTrack + 1; iTrack2 < nTracks; iTrack2++) {
AliESDMuonTrack* muonTrack = esd->GetMuonTrack(iTrack2);
thetaX = muonTrack->GetThetaX();
thetaY = muonTrack->GetThetaY();
pYZ = 1./TMath::Abs(muonTrack->GetInverseBendingMomentum());
fPzRec2 = - pYZ / TMath::Sqrt(1.0 + TMath::Tan(thetaY)*TMath::Tan(thetaY));
fPxRec2 = fPzRec2 * TMath::Tan(thetaX);
fPyRec2 = fPzRec2 * TMath::Tan(thetaY);
fCharge2 = Int_t(TMath::Sign(1.,muonTrack->GetInverseBendingMomentum()));
fE2 = TMath::Sqrt(muonMass * muonMass + fPxRec2 * fPxRec2 + fPyRec2 * fPyRec2 + fPzRec2 * fPzRec2);
fV2.SetPxPyPzE(fPxRec2, fPyRec2, fPzRec2, fE2);
ntrackhits = muonTrack->GetNHit();
fitfmin = muonTrack->GetChi2();
// transverse momentum
Float_t pt2 = fV2.Pt();
// chi2 per d.o.f.
Float_t ch2 = fitfmin / (2.0 * ntrackhits - 5);
// condition for good track (Chi2Cut and PtCut)
if ((ch2 < Chi2Cut) && (pt2 > PtCutMin) && (pt2 < PtCutMax)) {
// condition for opposite charges
if ((fCharge * fCharge2) == -1) {
// invariant mass
fVtot = fV1 + fV2;
Float_t invMass = fVtot.M();
// fill histos hInvMassAll and hInvMassRes
hInvMassAll->Fill(invMass);
hInvMassRes->Fill(invMass);
hInvMassAll_vs_Pt->Fill(invMass,fVtot.Pt());
Int_t ptTrig;
if (ResType == 553)
ptTrig = 0x400;// mask for Hpt unlike sign pair
else
ptTrig = 0x200;// mask for Lpt unlike sign pair
if (esd->GetTriggerMask() & ptTrig) NbTrigger++;
if (invMass > massMin && invMass < massMax) {
EventInMass++;
if (muonTrack->GetMatchTrigger() && (esd->GetTriggerMask() & ptTrig))// match with trigger
EventInMassMatch++;
hRapResonance->Fill(fVtot.Rapidity());
hPtResonance->Fill(fVtot.Pt());
}
} // if (fCharge * fCharge2) == -1)
} // if ((ch2 < Chi2Cut) && (pt2 > PtCutMin) && (pt2 < PtCutMax))
} // for (Int_t iTrack2 = iTrack + 1; iTrack2 < iTrack; iTrack2++)
} // if (ch1 < Chi2Cut) && (pt1 > PtCutMin)&& (pt1 < PtCutMax) )
} // for (Int_t iTrack = 0; iTrack < nrectracks; iTrack++)
hNumberOfTrack->Fill(nTracks);
// esdFile->Delete();
} // for (Int_t iEvent = FirstEvent;
// Loop over events for bg event
Double_t thetaPlus, phiPlus;
Double_t thetaMinus, phiMinus;
Float_t PtMinus, PtPlus;
for (Int_t iEvent = 0; iEvent < hInvMassAll->Integral(); iEvent++) {
hThetaPhiPlus->GetRandom2(phiPlus, thetaPlus);
hThetaPhiMinus->GetRandom2(phiMinus,thetaMinus);
PtPlus = hPtMuonPlus->GetRandom();
PtMinus = hPtMuonMinus->GetRandom();
fPxRec1 = PtPlus * TMath::Cos(TMath::Pi()/180.*phiPlus);
fPyRec1 = PtPlus * TMath::Sin(TMath::Pi()/180.*phiPlus);
fPzRec1 = PtPlus / TMath::Tan(TMath::Pi()/180.*thetaPlus);
fE1 = TMath::Sqrt(muonMass * muonMass + fPxRec1 * fPxRec1 + fPyRec1 * fPyRec1 + fPzRec1 * fPzRec1);
fV1.SetPxPyPzE(fPxRec1, fPyRec1, fPzRec1, fE1);
fPxRec2 = PtMinus * TMath::Cos(TMath::Pi()/180.*phiMinus);
fPyRec2 = PtMinus * TMath::Sin(TMath::Pi()/180.*phiMinus);
fPzRec2 = PtMinus / TMath::Tan(TMath::Pi()/180.*thetaMinus);
fE2 = TMath::Sqrt(muonMass * muonMass + fPxRec2 * fPxRec2 + fPyRec2 * fPyRec2 + fPzRec2 * fPzRec2);
fV2.SetPxPyPzE(fPxRec2, fPyRec2, fPzRec2, fE2);
// invariant mass
fVtot = fV1 + fV2;
// fill histos hInvMassAll and hInvMassRes
hInvMassBg->Fill(fVtot.M());
hInvMassBgk_vs_Pt->Fill( fVtot.M(), fVtot.Pt() );
}
histoFile->Write();
histoFile->Close();
cout << endl;
cout << "EventInMass " << EventInMass << endl;
cout << "NbTrigger " << NbTrigger << endl;
cout << "EventInMass match with trigger " << EventInMassMatch << endl;
return kTRUE;
}
|
#define SEPERATE_GLOBAL_TRACKS
#include "AliHLTTPCCADef.h"
#ifdef R__WIN32
#include <winbase.h>
#include <windows.h> // Header File For Windows
#include <windowsx.h>
HDC hDC = NULL; // Private GDI Device Context
HGLRC hRC = NULL; // Permanent Rendering Context
HWND hWnd = NULL; // Holds Our Window Handle
HINSTANCE hInstance; // Holds The Instance Of The Application
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // Declaration For WndProc
bool active = TRUE; // Window Active Flag Set To TRUE By Default
bool fullscreen = TRUE; // Fullscreen Flag Set To Fullscreen Mode By Default
HANDLE semLockDisplay = NULL;
POINT mouseCursorPos;
volatile int mouseReset = false;
#else
#include "bitmapfile.h"
#include <GL/glx.h> // This includes the necessary X headers
#include <pthread.h>
Display *g_pDisplay = NULL;
Window g_window;
bool g_bDoubleBuffered = GL_TRUE;
GLuint g_textureID = 0;
float g_fSpinX = 0.0f;
float g_fSpinY = 0.0f;
int g_nLastMousePositX = 0;
int g_nLastMousePositY = 0;
bool g_bMousing = false;
pthread_mutex_t semLockDisplay = PTHREAD_MUTEX_INITIALIZER;
#endif
#include <GL/gl.h> // Header File For The OpenGL32 Library
#include <GL/glu.h> // Header File For The GLu32 Library
#include "AliHLTTPCCASliceData.h"
#include "AliHLTTPCCAStandaloneFramework.h"
#include "AliHLTTPCCATrack.h"
#include "AliHLTTPCCATracker.h"
#include "AliHLTTPCCATrackerFramework.h"
#ifdef HLTCA_STANDALONE_OLD_MERGER
#include "AliHLTTPCCAMergerOutput.h"
#else
#include "AliHLTTPCGMMergedTrack.h"
#endif
#include "include.h"
#define fgkNSlices 36
bool keys[256]; // Array Used For The Keyboard Routine
#ifdef SEPERATE_GLOBAL_TRACKS
#define SEPERATE_GLOBAL_TRACKS_MAXID 5
#else
#define SEPERATE_GLOBAL_TRACKS_MAXID 100
#endif
#define SEPERATE_GLOBAL_TRACKS_DISTINGUISH_TYPES 6
float rotateX = 0, rotateY = 0;
float mouseDnX, mouseDnY;
float mouseMvX, mouseMvY;
bool mouseDn = false;
bool mouseDnR = false;
int mouseWheel = 0;
volatile int buttonPressed = 0;
GLfloat currentMatrice[16];
int drawClusters = true;
int drawLinks = false;
int drawSeeds = false;
int drawInitLinks = false;
int drawTracklets = false;
int drawTracks = false;
int drawGlobalTracks = false;
int drawFinal = false;
int drawSlice = -1;
int drawGrid = 0;
int excludeClusters = 0;
float Xscale = 1;
float Zadd = 0;
float4 *globalPos = NULL;
int maxClusters = 0;
int currentClusters = 0;
volatile int displayEventNr = 0;
int currentEventNr = -1;
int glDLrecent = 0;
int updateDLList = 0;
float pointSize = 2.0;
float lineWidth = 1.5;
int animate = 0;
volatile int resetScene = 0;
inline void SetColorClusters() { glColor3f(0, 0.7, 1.0); }
inline void SetColorInitLinks() { glColor3f(0.62, 0.1, 0.1); }
inline void SetColorLinks() { glColor3f(0.8, 0.2, 0.2); }
inline void SetColorSeeds() { glColor3f(0.8, 0.1, 0.85); }
inline void SetColorTracklets() { glColor3f(1, 1, 1); }
#ifdef SEPERATE_GLOBAL_TRACKSa
inline void SetColorTracks()
{
glColor3f(1., 1., 0.15);
}
inline void SetColorGlobalTracks() { glColor3f(1., 0.15, 0.15); }
#else
inline void SetColorTracks()
{
glColor3f(0.4, 1, 0);
}
inline void SetColorGlobalTracks() { glColor3f(1.0, 0.4, 0); }
#endif
inline void SetColorFinal()
{
glColor3f(0, 0.7, 0.2);
}
inline void SetColorGrid() { glColor3f(0.7, 0.7, 0.0); }
void ReSizeGLScene(GLsizei width, GLsizei height) // Resize And Initialize The GL Window
{
if (height == 0) // Prevent A Divide By Zero By
{
height = 1; // Making Height Equal One
}
static int init = 1;
GLfloat tmp[16];
glGetFloatv(GL_MODELVIEW_MATRIX, tmp);
glViewport(0, 0, width, height); // Reset The Current Viewport
glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity(); // Reset The Projection Matrix
// Calculate The Aspect Ratio Of The Window
gluPerspective(45.0f, (GLfloat) width / (GLfloat) height, 0.1f, 100.0f);
glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity(); // Reset The Modelview Matrix
if (init)
{
glTranslatef(0, 0, -16);
init = 0;
}
else
{
glLoadMatrixf(tmp);
}
glGetFloatv(GL_MODELVIEW_MATRIX, currentMatrice);
}
int InitGL() // All Setup For OpenGL Goes Here
{
glShadeModel(GL_SMOOTH); // Enable Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
glClearDepth(1.0f); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations
return (true); // Initialization Went OK
}
inline void drawPointLinestrip(int cid, int id, int id_limit = 100)
{
glVertex3f(globalPos[cid].x, globalPos[cid].y, globalPos[cid].z);
if (globalPos[cid].w < id_limit) globalPos[cid].w = id;
}
void DrawClusters(AliHLTTPCCATracker &tracker, int id)
{
glBegin(GL_POINTS);
for (int i = 0; i < tracker.Param().NRows(); i++)
{
const AliHLTTPCCARow &row = tracker.Data().Row(i);
for (int j = 0; j < row.NHits(); j++)
{
const int cid = tracker.ClusterData()->Id(tracker.Data().ClusterDataIndex(row, j));
if (globalPos[cid].w == id)
{
glVertex3f(globalPos[cid].x, globalPos[cid].y, globalPos[cid].z);
}
}
}
glEnd();
}
void DrawLinks(AliHLTTPCCATracker &tracker, int id, bool dodown = false)
{
glBegin(GL_LINES);
for (int i = 0; i < tracker.Param().NRows(); i++)
{
const AliHLTTPCCARow &row = tracker.Data().Row(i);
if (i < tracker.Param().NRows() - 2)
{
const AliHLTTPCCARow &rowUp = tracker.Data().Row(i + 2);
for (int j = 0; j < row.NHits(); j++)
{
if (tracker.Data().HitLinkUpData(row, j) != -1)
{
const int cid1 = tracker.ClusterData()->Id(tracker.Data().ClusterDataIndex(row, j));
const int cid2 = tracker.ClusterData()->Id(tracker.Data().ClusterDataIndex(rowUp, tracker.Data().HitLinkUpData(row, j)));
drawPointLinestrip(cid1, id);
drawPointLinestrip(cid2, id);
}
}
}
if (dodown && i >= 2)
{
const AliHLTTPCCARow &rowDown = tracker.Data().Row(i - 2);
for (int j = 0; j < row.NHits(); j++)
{
if (tracker.Data().HitLinkDownData(row, j) != -1)
{
const int cid1 = tracker.ClusterData()->Id(tracker.Data().ClusterDataIndex(row, j));
const int cid2 = tracker.ClusterData()->Id(tracker.Data().ClusterDataIndex(rowDown, tracker.Data().HitLinkDownData(row, j)));
drawPointLinestrip(cid1, id);
drawPointLinestrip(cid2, id);
}
}
}
}
glEnd();
}
void DrawSeeds(AliHLTTPCCATracker &tracker)
{
for (int i = 0; i < *tracker.NTracklets(); i++)
{
const AliHLTTPCCAHitId &hit = tracker.TrackletStartHit(i);
glBegin(GL_LINE_STRIP);
int ir = hit.RowIndex();
int ih = hit.HitIndex();
do
{
const AliHLTTPCCARow &row = tracker.Data().Row(ir);
const int cid = tracker.ClusterData()->Id(tracker.Data().ClusterDataIndex(row, ih));
drawPointLinestrip(cid, 3);
ir += 2;
ih = tracker.Data().HitLinkUpData(row, ih);
} while (ih != -1);
glEnd();
}
}
void DrawTracklets(AliHLTTPCCATracker &tracker)
{
for (int i = 0; i < *tracker.NTracklets(); i++)
{
const AliHLTTPCCATracklet &tracklet = tracker.Tracklet(i);
if (tracklet.NHits() == 0) continue;
glBegin(GL_LINE_STRIP);
float4 oldpos;
for (int j = tracklet.FirstRow(); j <= tracklet.LastRow(); j++)
{
#ifdef EXTERN_ROW_HITS
const int rowHit = tracker.TrackletRowHits()[j * *tracker.NTracklets() + i];
#else
const int rowHit = tracklet.RowHit(j);
#endif
if (rowHit != -1)
{
const AliHLTTPCCARow &row = tracker.Data().Row(j);
const int cid = tracker.ClusterData()->Id(tracker.Data().ClusterDataIndex(row, rowHit));
/*if (j != tracklet.FirstRow())
{
float dist = (oldpos.x - globalPos[cid].x) * (oldpos.x - globalPos[cid].x) + (oldpos.y - globalPos[cid].y) * (oldpos.y - globalPos[cid].y) + (oldpos.z - globalPos[cid].z) * (oldpos.z - globalPos[cid].z);
}*/
oldpos = globalPos[cid];
drawPointLinestrip(cid, 4);
}
}
glEnd();
}
}
void DrawTracks(AliHLTTPCCATracker &tracker, int global)
{
for (int i = (global ? tracker.CommonMemory()->fNLocalTracks : 0); i < (global ? *tracker.NTracks() : tracker.CommonMemory()->fNLocalTracks); i++)
{
AliHLTTPCCATrack &track = tracker.Tracks()[i];
glBegin(GL_LINE_STRIP);
for (int j = 0; j < track.NHits(); j++)
{
const AliHLTTPCCAHitId &hit = tracker.TrackHits()[track.FirstHitID() + j];
const AliHLTTPCCARow &row = tracker.Data().Row(hit.RowIndex());
const int cid = tracker.ClusterData()->Id(tracker.Data().ClusterDataIndex(row, hit.HitIndex()));
drawPointLinestrip(cid, 5 + global);
}
glEnd();
}
}
void DrawFinal(AliHLTTPCCAStandaloneFramework &hlt)
{
#ifdef HLTCA_STANDALONE_OLD_MERGER
const AliHLTTPCCAMerger &merger = hlt.Merger();
const AliHLTTPCCAMergerOutput &mergerOut = *merger.Output();
for (int i = 0; i < mergerOut.NTracks(); i++)
{
const AliHLTTPCCAMergedTrack &track = mergerOut.Track(i);
glBegin(GL_LINE_STRIP);
for (int j = 0; j < track.NClusters(); j++)
{
int cid = mergerOut.ClusterId(track.FirstClusterRef() + j);
drawPointLinestrip(cid, 7);
}
glEnd();
}
#else
const AliHLTTPCGMMerger &merger = hlt.Merger();
for (int i = 0; i < merger.NOutputTracks(); i++)
{
const AliHLTTPCGMMergedTrack &track = merger.OutputTracks()[i];
if (track.NClusters() == 0) continue;
int *clusterused = new int[track.NClusters()];
for (int j = 0; j < track.NClusters(); j++)
clusterused[j] = 0;
if (!track.OK()) continue;
glBegin(GL_LINE_STRIP);
float smallest = 1e20;
int bestk = 0;
for (int k = 0; k < track.NClusters(); k++)
{
int cid = merger.OutputClusterIds()[track.FirstClusterRef() + k];
float dist = globalPos[cid].x * globalPos[cid].x + globalPos[cid].y * globalPos[cid].y + globalPos[cid].z * globalPos[cid].z;
if (dist < smallest)
{
smallest = dist;
bestk = k;
}
}
int lastcid = merger.OutputClusterIds()[track.FirstClusterRef() + bestk];
clusterused[bestk] = 1;
#ifdef SEPERATE_GLOBAL_TRACKS
bool linestarted = (globalPos[lastcid].w < SEPERATE_GLOBAL_TRACKS_DISTINGUISH_TYPES);
if (linestarted)
#endif
{
drawPointLinestrip(lastcid, 7, SEPERATE_GLOBAL_TRACKS_MAXID);
}
for (int j = 1; j < track.NClusters(); j++)
{
int bestcid = 0;
int bestk = 0;
float bestdist = 1e20;
for (int k = 0; k < track.NClusters(); k++)
{
if (clusterused[k]) continue;
int cid = merger.OutputClusterIds()[track.FirstClusterRef() + k];
float dist = (globalPos[cid].x - globalPos[lastcid].x) * (globalPos[cid].x - globalPos[lastcid].x) +
(globalPos[cid].y - globalPos[lastcid].y) * (globalPos[cid].y - globalPos[lastcid].y) +
(globalPos[cid].z - globalPos[lastcid].z) * (globalPos[cid].z - globalPos[lastcid].z);
if (dist < bestdist)
{
bestdist = dist;
bestcid = cid;
bestk = k;
}
}
#ifdef SEPERATE_GLOBAL_TRACKS
if (!linestarted && globalPos[bestcid].w < SEPERATE_GLOBAL_TRACKS_DISTINGUISH_TYPES)
{
drawPointLinestrip(lastcid, 7, SEPERATE_GLOBAL_TRACKS_MAXID);
linestarted = true;
}
if (linestarted)
#endif
{
drawPointLinestrip(bestcid, 7, SEPERATE_GLOBAL_TRACKS_MAXID);
}
#ifdef SEPERATE_GLOBAL_TRACKS
if (linestarted && !(globalPos[bestcid].w < SEPERATE_GLOBAL_TRACKS_DISTINGUISH_TYPES)) linestarted = false;
#endif
clusterused[bestk] = 1;
lastcid = bestcid;
}
glEnd();
delete[] clusterused;
}
#endif
}
void DrawGrid(AliHLTTPCCATracker &tracker)
{
glBegin(GL_LINES);
for (int i = 0; i < tracker.Param().NRows(); i++)
{
const AliHLTTPCCARow &row = tracker.Data().Row(i);
for (int j = 0; j <= (signed) row.Grid().Ny(); j++)
{
float z1 = row.Grid().ZMin();
float z2 = row.Grid().ZMax();
float x = row.X() * Xscale;
float y = row.Grid().YMin() + (float) j / row.Grid().StepYInv();
float zz1, zz2, yy1, yy2, xx1, xx2;
tracker.Param().Slice2Global(x, y, z1, &xx1, &yy1, &zz1);
tracker.Param().Slice2Global(x, y, z2, &xx2, &yy2, &zz2);
if (zz1 >= 0)
{
zz1 += Zadd;
zz2 += Zadd;
}
else
{
zz1 -= Zadd;
zz2 -= Zadd;
}
glVertex3f(xx1 / 50, yy1 / 50, zz1 / 50);
glVertex3f(xx2 / 50, yy2 / 50, zz2 / 50);
}
for (int j = 0; j <= (signed) row.Grid().Nz(); j++)
{
float y1 = row.Grid().YMin();
float y2 = row.Grid().YMax();
float x = row.X() * Xscale;
float z = row.Grid().ZMin() + (float) j / row.Grid().StepZInv();
float zz1, zz2, yy1, yy2, xx1, xx2;
tracker.Param().Slice2Global(x, y1, z, &xx1, &yy1, &zz1);
tracker.Param().Slice2Global(x, y2, z, &xx2, &yy2, &zz2);
if (zz1 >= 0)
{
zz1 += Zadd;
zz2 += Zadd;
}
else
{
zz1 -= Zadd;
zz2 -= Zadd;
}
glVertex3f(xx1 / 50, yy1 / 50, zz1 / 50);
glVertex3f(xx2 / 50, yy2 / 50, zz2 / 50);
}
}
glEnd();
}
int DrawGLScene(bool doAnimation = false) // Here's Where We Do All The Drawing
{
static float fpsscale = 1;
static int framesDone = 0;
static unsigned long long int startTime, displayFpsTime, timeFreq;
static GLuint glDLlines[fgkNSlices][6];
static GLuint glDLlinesFinal;
static GLuint glDLpoints[fgkNSlices][8];
static GLuint glDLgrid[fgkNSlices];
static int glDLcreated = 0;
AliHLTTPCCAStandaloneFramework &hlt = AliHLTTPCCAStandaloneFramework::Instance();
//Initialize
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
glLoadIdentity(); // Reset The Current Modelview Matrix
int mouseWheelTmp = mouseWheel;
mouseWheel = 0;
//Calculate rotation / translation scaling factors
float scalefactor = keys[16] ? 0.2 : 1.0;
float rotatescalefactor = 1;
float sqrdist = sqrt(sqrt(currentMatrice[12] * currentMatrice[12] + currentMatrice[13] * currentMatrice[13] + currentMatrice[14] * currentMatrice[14]) / 50) * 0.8;
if (sqrdist < 0.2) sqrdist = 0.2;
if (sqrdist > 5) sqrdist = 5;
scalefactor *= sqrdist;
if (drawSlice != -1)
{
scalefactor /= 5;
rotatescalefactor = 3;
}
//Perform new rotation / translation
if (doAnimation)
{
float moveY = scalefactor * -0.14 * 0.25;
float moveX = scalefactor * -0.14;
static int nFrame = 0;
nFrame++;
float moveZ = 0;
if (nFrame > 570)
{
moveZ = scalefactor * 1.;
}
else if (nFrame > 510)
{
moveZ = scalefactor * 1.f * (nFrame - 510) / 60.f;
}
glTranslatef(moveX, moveY, moveZ);
}
else
{
float moveZ = scalefactor * ((float) mouseWheelTmp / 150 + (float) (keys['W'] - keys['S']) * 0.2 * fpsscale);
float moveX = scalefactor * ((float) (keys['A'] - keys['D']) * 0.2 * fpsscale);
glTranslatef(moveX, 0, moveZ);
}
if (doAnimation)
{
glRotatef(scalefactor * rotatescalefactor * -0.5, 0, 1, 0);
glRotatef(scalefactor * rotatescalefactor * 0.5 * 0.25, 1, 0, 0);
glRotatef(scalefactor * 0.2, 0, 0, 1);
}
else if (mouseDnR && mouseDn)
{
glTranslatef(0, 0, -scalefactor * ((float) mouseMvY - (float) mouseDnY) / 4);
glRotatef(scalefactor * ((float) mouseMvX - (float) mouseDnX), 0, 0, 1);
}
else if (mouseDnR)
{
glTranslatef(-scalefactor * 0.5 * ((float) mouseDnX - (float) mouseMvX) / 4, -scalefactor * 0.5 * ((float) mouseMvY - (float) mouseDnY) / 4, 0);
}
else if (mouseDn)
{
glRotatef(scalefactor * rotatescalefactor * ((float) mouseMvX - (float) mouseDnX), 0, 1, 0);
glRotatef(scalefactor * rotatescalefactor * ((float) mouseMvY - (float) mouseDnY), 1, 0, 0);
}
if (keys['E'] ^ keys['F'])
{
glRotatef(scalefactor * fpsscale * 2, 0, 0, keys['E'] - keys['F']);
}
if (mouseDn || mouseDnR)
{
#ifdef R__WIN32a
mouseReset = true;
SetCursorPos(mouseCursorPos.x, mouseCursorPos.y);
#else
mouseDnX = mouseMvX;
mouseDnY = mouseMvY;
#endif
}
//Apply standard translation / rotation
glMultMatrixf(currentMatrice);
//Graphichs Options
pointSize += (float) (keys[107] - keys[109] + keys[187] - keys[189]) * fpsscale * 0.05;
if (pointSize <= 0.01) pointSize = 0.01;
//Reset position
if (resetScene)
{
glLoadIdentity();
glTranslatef(0, 0, -16);
AliHLTTPCCATracker::StandaloneQueryTime(&startTime);
displayFpsTime = startTime;
framesDone = 0;
pointSize = 2.0;
drawSlice = -1;
Xscale = 1;
Zadd = 0;
resetScene = 0;
updateDLList = true;
}
//Store position
glGetFloatv(GL_MODELVIEW_MATRIX, currentMatrice);
//Make sure event gets not overwritten during display
#ifdef R__WIN32
WaitForSingleObject(semLockDisplay, INFINITE);
#else
pthread_mutex_lock(&semLockDisplay);
#endif
//Open GL Default Values
glEnable(GL_POINT_SMOOTH);
glEnable(GL_LINE_SMOOTH);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glPointSize(pointSize);
glLineWidth(lineWidth);
//Extract global cluster information
if (updateDLList || displayEventNr != currentEventNr)
{
currentClusters = 0;
for (int iSlice = 0; iSlice < fgkNSlices; iSlice++)
{
currentClusters += hlt.fTracker.fCPUTrackers[iSlice].NHitsTotal();
}
if (maxClusters < currentClusters)
{
if (globalPos) delete[] globalPos;
maxClusters = currentClusters;
globalPos = new float4[maxClusters];
}
for (int iSlice = 0; iSlice < fgkNSlices; iSlice++)
{
const AliHLTTPCCAClusterData &cdata = hlt.fClusterData[iSlice];
for (int i = 0; i < cdata.NumberOfClusters(); i++)
{
const int cid = cdata.Id(i);
if (cid >= maxClusters)
{
printf("Cluster Buffer Size exceeded (id %d max %d)\n", cid, maxClusters);
exit(1);
}
float4 *ptr = &globalPos[cid];
hlt.fTracker.fCPUTrackers[iSlice].Param().Slice2Global(cdata.X(i) * Xscale, cdata.Y(i), cdata.Z(i), &ptr->x, &ptr->y, &ptr->z);
if (ptr->z >= 0)
{
ptr->z += Zadd;
ptr->z += Zadd;
}
else
{
ptr->z -= Zadd;
ptr->z -= Zadd;
}
ptr->x /= 50;
ptr->y /= 50;
ptr->z /= 50;
ptr->w = 1;
}
}
currentEventNr = displayEventNr;
AliHLTTPCCATracker::StandaloneQueryFreq(&timeFreq);
AliHLTTPCCATracker::StandaloneQueryTime(&startTime);
displayFpsTime = startTime;
framesDone = 0;
glDLrecent = 0;
updateDLList = 0;
}
//Prepare Event
if (!glDLrecent)
{
for (int iSlice = 0; iSlice < fgkNSlices; iSlice++)
{
if (glDLcreated)
{
for (int i = 0; i < 6; i++)
glDeleteLists(glDLlines[iSlice][i], 1);
for (int i = 0; i < 8; i++)
glDeleteLists(glDLpoints[iSlice][i], 1);
glDeleteLists(glDLgrid[iSlice], 1);
}
else
{
for (int i = 0; i < 6; i++)
glDLlines[iSlice][i] = glGenLists(1);
for (int i = 0; i < 8; i++)
glDLpoints[iSlice][i] = glGenLists(1);
glDLgrid[iSlice] = glGenLists(1);
}
}
if (glDLcreated)
{
glDeleteLists(glDLlinesFinal, 1);
}
else
{
glDLlinesFinal = glGenLists(1);
}
for (int i = 0; i < currentClusters; i++)
globalPos[i].w = 0;
for (int iSlice = 0; iSlice < fgkNSlices; iSlice++)
{
AliHLTTPCCATracker &tracker = hlt.fTracker.fCPUTrackers[iSlice];
glNewList(glDLlines[iSlice][0], GL_COMPILE);
if (drawInitLinks)
{
char *tmpMem[fgkNSlices];
for (int i = 0; i < fgkNSlices; i++)
{
AliHLTTPCCATracker &tracker = hlt.fTracker.fCPUTrackers[i];
tmpMem[i] = tracker.Data().Memory();
tracker.SetGPUSliceDataMemory((void *) tracker.LinkTmpMemory(), tracker.Data().Rows());
tracker.SetPointersSliceData(tracker.ClusterData());
}
DrawLinks(tracker, 1, true);
for (int i = 0; i < fgkNSlices; i++)
{
AliHLTTPCCATracker &tracker = hlt.fTracker.fCPUTrackers[i];
tracker.SetGPUSliceDataMemory(tmpMem[i], tracker.Data().Rows());
tracker.SetPointersSliceData(tracker.ClusterData());
}
}
glEndList();
glNewList(glDLlines[iSlice][1], GL_COMPILE);
DrawLinks(tracker, 2);
glEndList();
glNewList(glDLlines[iSlice][2], GL_COMPILE);
DrawSeeds(tracker);
glEndList();
glNewList(glDLlines[iSlice][3], GL_COMPILE);
DrawTracklets(tracker);
glEndList();
glNewList(glDLlines[iSlice][4], GL_COMPILE);
DrawTracks(tracker, 0);
glEndList();
glNewList(glDLlines[iSlice][5], GL_COMPILE);
DrawTracks(tracker, 1);
glEndList();
glNewList(glDLgrid[iSlice], GL_COMPILE);
DrawGrid(tracker);
glEndList();
}
glNewList(glDLlinesFinal, GL_COMPILE);
//#ifndef SEPERATE_GLOBAL_TRACKS
DrawFinal(hlt);
//#endif
glEndList();
for (int iSlice = 0; iSlice < fgkNSlices; iSlice++)
{
AliHLTTPCCATracker &tracker = hlt.fTracker.fCPUTrackers[iSlice];
for (int i = 0; i < 8; i++)
{
glNewList(glDLpoints[iSlice][i], GL_COMPILE);
DrawClusters(tracker, i);
glEndList();
}
}
int errCode;
if ((errCode = glGetError()) != GL_NO_ERROR)
{
printf("Error creating OpenGL display list: %s\n", gluErrorString(errCode));
resetScene = 1;
}
else
{
glDLrecent = 1;
}
}
++framesDone;
unsigned long long int tmpTime;
AliHLTTPCCATracker::StandaloneQueryTime(&tmpTime);
if (tmpTime - displayFpsTime > timeFreq)
{
displayFpsTime = tmpTime;
float fps = (double) framesDone * (double) timeFreq / (double) (tmpTime - startTime);
printf("FPS: %f (%d frames, Slice: %d, 1:Clusters %d, 2:Prelinks %d, 3:Links %d, 4:Seeds %d, 5:Tracklets %d, 6:Tracks %d, 7:GTracks %d, 8:Merger %d)\n", fps, framesDone, drawSlice, drawClusters, drawInitLinks, drawLinks, drawSeeds, drawTracklets, drawTracks, drawGlobalTracks, drawFinal);
fpsscale = 60 / fps;
}
//Draw Event
if (glDLrecent)
{
for (int iSlice = 0; iSlice < fgkNSlices; iSlice++)
{
if (drawSlice != -1 && drawSlice != iSlice) continue;
if (drawGrid)
{
SetColorGrid();
glCallList(glDLgrid[iSlice]);
}
if (drawClusters)
{
SetColorClusters();
glCallList(glDLpoints[iSlice][0]);
if (drawInitLinks)
{
if (excludeClusters) goto skip1;
SetColorInitLinks();
}
glCallList(glDLpoints[iSlice][1]);
if (drawLinks)
{
if (excludeClusters) goto skip1;
SetColorLinks();
}
glCallList(glDLpoints[iSlice][2]);
if (drawSeeds)
{
if (excludeClusters) goto skip1;
SetColorSeeds();
}
glCallList(glDLpoints[iSlice][3]);
skip1:
glColor3f(0, 0.7, 1.0);
if (drawTracklets)
{
if (excludeClusters) goto skip2;
SetColorTracklets();
}
glCallList(glDLpoints[iSlice][4]);
if (drawTracks)
{
if (excludeClusters) goto skip2;
SetColorTracks();
}
glCallList(glDLpoints[iSlice][5]);
skip2:
if (drawGlobalTracks)
{
if (excludeClusters) goto skip3;
SetColorGlobalTracks();
}
glCallList(glDLpoints[iSlice][6]);
if (drawFinal)
{
if (excludeClusters) goto skip3;
SetColorFinal();
}
glCallList(glDLpoints[iSlice][7]);
skip3:;
}
if (!excludeClusters)
{
if (drawInitLinks) {
SetColorInitLinks();
glCallList(glDLlines[iSlice][0]);
}
if (drawLinks) {
SetColorLinks();
glCallList(glDLlines[iSlice][1]);
}
if (drawSeeds) {
SetColorSeeds();
glCallList(glDLlines[iSlice][2]);
}
if (drawTracklets) {
SetColorTracklets();
glCallList(glDLlines[iSlice][3]);
}
if (drawTracks) {
SetColorTracks();
glCallList(glDLlines[iSlice][4]);
}
if (drawGlobalTracks) {
SetColorGlobalTracks();
glCallList(glDLlines[iSlice][5]);
}
}
}
if (!excludeClusters && drawFinal) {
SetColorFinal();
if (!drawClusters)
{
for (int iSlice = 0; iSlice < fgkNSlices; iSlice++)
{
glCallList(glDLpoints[iSlice][7]);
}
}
glCallList(glDLlinesFinal);
}
}
//Free event
#ifdef R__WIN32
ReleaseSemaphore(semLockDisplay, 1, NULL);
#else
pthread_mutex_unlock(&semLockDisplay);
#endif
return true; // Keep Going
}
void DoScreenshot(char *filename, int SCALE_X, unsigned char **mixBuffer = NULL, float mixFactor = 0.)
{
//#define SCALE_X 3
#define SCALE_Y SCALE_X
if (mixFactor < 0.f) mixFactor = 0.f;
if (mixFactor > 1.f) mixFactor = 1.f;
float tmpPointSize = pointSize;
float tmpLineWidth = lineWidth;
//pointSize *= (float) (SCALE_X + SCALE_Y) / 2. * 2.;
//lineWidth *= (float) (SCALE_X + SCALE_Y) / 2. * 2.;
if (animate)
{
}
else
{
pointSize *= 2;
}
GLint view[4], viewold[4];
glGetIntegerv(GL_VIEWPORT, viewold);
glGetIntegerv(GL_VIEWPORT, view);
view[2] *= SCALE_X;
view[3] *= SCALE_Y;
unsigned char *pixels = (unsigned char *) malloc(4 * view[2] * view[3]);
memset(pixels, 0, 4 * view[2] * view[3]);
unsigned char *pixels2 = (unsigned char *) malloc(4 * view[2] * view[3]);
for (int i = 0; i < SCALE_X; i++)
{
for (int j = 0; j < SCALE_Y; j++)
{
glViewport(-i * viewold[2], -j * viewold[3], view[2], view[3]);
DrawGLScene();
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadBuffer(GL_BACK);
glReadPixels(0, 0, view[2], view[3], GL_RGBA, GL_UNSIGNED_BYTE, pixels2);
for (int k = 0; k < viewold[2]; k++)
{
for (int l = 0; l < viewold[3]; l++)
{
pixels[((j * viewold[3] + l) * view[2] + i * viewold[2] + k) * 4] = pixels2[(l * view[2] + k) * 4 + 2];
pixels[((j * viewold[3] + l) * view[2] + i * viewold[2] + k) * 4 + 1] = pixels2[(l * view[2] + k) * 4 + 1];
pixels[((j * viewold[3] + l) * view[2] + i * viewold[2] + k) * 4 + 2] = pixels2[(l * view[2] + k) * 4];
pixels[((j * viewold[3] + l) * view[2] + i * viewold[2] + k) * 4 + 3] = 0;
}
}
}
}
free(pixels2);
if (mixBuffer)
{
if (*mixBuffer == NULL)
{
*mixBuffer = (unsigned char *) malloc(4 * view[2] * view[3]);
memcpy(*mixBuffer, pixels, 4 * view[2] * view[3]);
}
else
{
for (int i = 0; i < 4 * view[2] * view[3]; i++)
{
pixels[i] = (*mixBuffer)[i] = (mixFactor * pixels[i] + (1.f - mixFactor) * (*mixBuffer)[i]);
}
}
}
if (filename)
{
FILE *fp = fopen(filename, "w+b");
BITMAPFILEHEADER bmpFH;
BITMAPINFOHEADER bmpIH;
memset(&bmpFH, 0, sizeof(bmpFH));
memset(&bmpIH, 0, sizeof(bmpIH));
bmpFH.bfType = 19778; //"BM"
bmpFH.bfSize = sizeof(bmpFH) + sizeof(bmpIH) + 3 * view[2] * view[3];
bmpFH.bfOffBits = sizeof(bmpFH) + sizeof(bmpIH);
bmpIH.biSize = sizeof(bmpIH);
bmpIH.biWidth = view[2];
bmpIH.biHeight = view[3];
bmpIH.biPlanes = 1;
bmpIH.biBitCount = 32;
fwrite(&bmpFH, 1, sizeof(bmpFH), fp);
fwrite(&bmpIH, 1, sizeof(bmpIH), fp);
fwrite(pixels, view[2] * view[3], 4, fp);
fclose(fp);
}
free(pixels);
glViewport(0, 0, viewold[2], viewold[3]);
pointSize = tmpPointSize;
lineWidth = tmpLineWidth;
DrawGLScene();
}
void PrintHelp()
{
printf("[N]/[SPACE]\tNext event\n");
printf("[Q]/[ESC]\tQuit\n");
printf("[R]\t\tReset Display Settings\n");
printf("[L]\t\tDraw single slice (next slice)\n");
printf("[K]\t\tDraw single slice (previous slice)\n");
printf("[Z]\t\tShow splitting of TPC in slices\n");
printf("[Y]\t\tStart Animation\n");
printf("[G]\t\tDraw Grid\n");
printf("[X]\t\tExclude Clusters used in the tracking steps enabled for visualization ([1]-[8])");
printf("[1]\t\tShow Clusters\n");
printf("[2]\t\tShow Links that were removed\n");
printf("[3]\t\tShow Links that remained in Neighbors Cleaner\n");
printf("[4]\t\tShow Seeds (Start Hits)\n");
printf("[5]\t\tShow Tracklets\n");
printf("[6]\t\tShow Tracks (after Tracklet Selector)\n");
printf("[7]\t\tShow Global Track Segments\n");
printf("[8]\t\tShow Final Merged Tracks (after Track Merger)\n");
printf("[T]\t\tTake Screenshot\n");
printf("[O]\t\tSave current camera position\n");
printf("[P]\t\tRestore camera position\n");
printf("[H]\t\tPrint Help\n");
printf("[W]/[S]/[A]/[D]\tZoom / Move Left Right\n");
printf("[E]/[F]\t\tRotate\n");
printf("[+]/[-]\t\tMake points thicker / fainter\n");
printf("[MOUSE1]\tLook around\n");
printf("[MOUSE2]\tShift camera\n");
printf("[MOUSE1+2]\tZoom / Rotate\n");
printf("[SHIFT]\tSlow Zoom / Move / Rotate\n");
}
void HandleKeyRelease(int wParam)
{
keys[wParam] = false;
if (wParam == 13 || wParam == 'N') buttonPressed = 1;
else if (wParam == 'Q') buttonPressed = 2;
else if (wParam == 'R') resetScene = 1;
else if (wParam == 'L')
{
if (drawSlice == fgkNSlices - 1)
drawSlice = -1;
else
drawSlice++;
}
else if (wParam == 'K')
{
if (drawSlice == -1)
drawSlice = fgkNSlices - 1;
else
drawSlice--;
}
else if (wParam == 'Z')
{
updateDLList = true;
Xscale++;
Zadd += 60;
}
else if (wParam == 'Y')
{
animate = 1;
}
else if (wParam == 'G') drawGrid ^= 1;
else if (wParam == 'X') excludeClusters ^= 1;
else if (wParam == '1')
drawClusters ^= 1;
else if (wParam == '2')
drawInitLinks ^= 1;
else if (wParam == '3')
drawLinks ^= 1;
else if (wParam == '4')
drawSeeds ^= 1;
else if (wParam == '5')
drawTracklets ^= 1;
else if (wParam == '6')
drawTracks ^= 1;
else if (wParam == '7')
drawGlobalTracks ^= 1;
else if (wParam == '8')
drawFinal ^= 1;
#ifdef R__WIN32
else if (wParam == 'T')
{
printf("Taking Screenshot\n");
DoScreenshot("screenshot.bmp", 3);
}
#endif
else if (wParam == 'O')
{
GLfloat tmp[16];
glGetFloatv(GL_MODELVIEW_MATRIX, tmp);
FILE *ftmp = fopen("glpos.tmp", "w+b");
if (ftmp)
{
int retval = fwrite(&tmp[0], sizeof(GLfloat), 16, ftmp);
if (retval != 16)
printf("Error writing position to file\n");
else
printf("Position stored to file\n");
fclose(ftmp);
}
else
{
printf("Error opening file\n");
}
}
else if (wParam == 'P')
{
GLfloat tmp[16];
FILE *ftmp = fopen("glpos.tmp", "rb");
if (ftmp)
{
int retval = fread(&tmp[0], sizeof(GLfloat), 16, ftmp);
if (retval == 16)
{
glLoadMatrixf(tmp);
glGetFloatv(GL_MODELVIEW_MATRIX, currentMatrice);
printf("Position read from file\n");
}
else
{
printf("Error reading position from file\n");
}
fclose(ftmp);
}
else
{
printf("Error opening file\n");
}
}
else if (wParam == 'H')
{
PrintHelp();
}
}
#ifdef R__WIN32
void KillGLWindow() // Properly Kill The Window
{
if (fullscreen) // Are We In Fullscreen Mode?
{
ChangeDisplaySettings(NULL, 0); // If So Switch Back To The Desktop
ShowCursor(TRUE); // Show Mouse Pointer
}
if (hRC) // Do We Have A Rendering Context?
{
if (!wglMakeCurrent(NULL, NULL)) // Are We Able To Release The DC And RC Contexts?
{
MessageBox(NULL, "Release Of DC And RC Failed.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
}
if (!wglDeleteContext(hRC)) // Are We Able To Delete The RC?
{
MessageBox(NULL, "Release Rendering Context Failed.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
}
hRC = NULL; // Set RC To NULL
}
if (hDC && !ReleaseDC(hWnd, hDC)) // Are We Able To Release The DC
{
MessageBox(NULL, "Release Device Context Failed.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
hDC = NULL; // Set DC To NULL
}
if (hWnd && !DestroyWindow(hWnd)) // Are We Able To Destroy The Window?
{
MessageBox(NULL, "Could Not Release hWnd.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
hWnd = NULL; // Set hWnd To NULL
}
if (!UnregisterClass("OpenGL", hInstance)) // Are We Able To Unregister Class
{
MessageBox(NULL, "Could Not Unregister Class.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
hInstance = NULL; // Set hInstance To NULL
}
}
/* This Code Creates Our OpenGL Window. Parameters Are: *
* title - Title To Appear At The Top Of The Window *
* width - Width Of The GL Window Or Fullscreen Mode *
* height - Height Of The GL Window Or Fullscreen Mode *
* bits - Number Of Bits To Use For Color (8/16/24/32) *
* fullscreenflag - Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE) */
BOOL CreateGLWindow(char *title, int width, int height, int bits, bool fullscreenflag)
{
GLuint PixelFormat; // Holds The Results After Searching For A Match
WNDCLASS wc; // Windows Class Structure
DWORD dwExStyle; // Window Extended Style
DWORD dwStyle; // Window Style
RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values
WindowRect.left = (long) 0; // Set Left Value To 0
WindowRect.right = (long) width; // Set Right Value To Requested Width
WindowRect.top = (long) 0; // Set Top Value To 0
WindowRect.bottom = (long) height; // Set Bottom Value To Requested Height
fullscreen = fullscreenflag; // Set The Global Fullscreen Flag
hInstance = GetModuleHandle(NULL); // Grab An Instance For Our Window
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw On Size, And Own DC For Window.
wc.lpfnWndProc = (WNDPROC) WndProc; // WndProc Handles Messages
wc.cbClsExtra = 0; // No Extra Window Data
wc.cbWndExtra = 0; // No Extra Window Data
wc.hInstance = hInstance; // Set The Instance
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load The Default Icon
wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load The Arrow Pointer
wc.hbrBackground = NULL; // No Background Required For GL
wc.lpszMenuName = NULL; // We Don't Want A Menu
wc.lpszClassName = "OpenGL"; // Set The Class Name
if (!RegisterClass(&wc)) // Attempt To Register The Window Class
{
MessageBox(NULL, "Failed To Register The Window Class.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (fullscreen) // Attempt Fullscreen Mode?
{
DEVMODE dmScreenSettings; // Device Mode
memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared
dmScreenSettings.dmSize = sizeof(dmScreenSettings); // Size Of The Devmode Structure
dmScreenSettings.dmPelsWidth = width; // Selected Screen Width
dmScreenSettings.dmPelsHeight = height; // Selected Screen Height
dmScreenSettings.dmBitsPerPel = bits; // Selected Bits Per Pixel
dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
// Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
{
// If The Mode Fails, Offer Two Options. Quit Or Use Windowed Mode.
if (MessageBox(NULL, "The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?", "NeHe GL", MB_YESNO | MB_ICONEXCLAMATION) == IDYES)
{
fullscreen = FALSE; // Windowed Mode Selected. Fullscreen = FALSE
}
else
{
// Pop Up A Message Box Letting User Know The Program Is Closing.
MessageBox(NULL, "Program Will Now Close.", "ERROR", MB_OK | MB_ICONSTOP);
return FALSE; // Return FALSE
}
}
}
if (fullscreen) // Are We Still In Fullscreen Mode?
{
dwExStyle = WS_EX_APPWINDOW; // Window Extended Style
dwStyle = WS_POPUP; // Windows Style
ShowCursor(FALSE); // Hide Mouse Pointer
}
else
{
dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style
dwStyle = WS_OVERLAPPEDWINDOW; // Windows Style
}
AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size
// Create The Window
if (!(hWnd = CreateWindowEx(dwExStyle, // Extended Style For The Window
"OpenGL", // Class Name
title, // Window Title
dwStyle | // Defined Window Style
WS_CLIPSIBLINGS | // Required Window Style
WS_CLIPCHILDREN, // Required Window Style
0,
0, // Window Position
WindowRect.right - WindowRect.left, // Calculate Window Width
WindowRect.bottom - WindowRect.top, // Calculate Window Height
NULL, // No Parent Window
NULL, // No Menu
hInstance, // Instance
NULL))) // Dont Pass Anything To WM_CREATE
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, "Window Creation Error.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
static PIXELFORMATDESCRIPTOR pfd = // pfd Tells Windows How We Want Things To Be
{
sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
1, // Version Number
PFD_DRAW_TO_WINDOW | // Format Must Support Window
PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
PFD_DOUBLEBUFFER, // Must Support Double Buffering
PFD_TYPE_RGBA, // Request An RGBA Format
(unsigned char) bits, // Select Our Color Depth
0,
0, 0, 0, 0, 0, // Color Bits Ignored
0, // No Alpha Buffer
0, // Shift Bit Ignored
0, // No Accumulation Buffer
0, 0, 0, 0, // Accumulation Bits Ignored
16, // 16Bit Z-Buffer (Depth Buffer)
0, // No Stencil Buffer
0, // No Auxiliary Buffer
PFD_MAIN_PLANE, // Main Drawing Layer
0, // Reserved
0, 0, 0 // Layer Masks Ignored
};
if (!(hDC = GetDC(hWnd))) // Did We Get A Device Context?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, "Can't Create A GL Device Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) // Did Windows Find A Matching Pixel Format?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, "Can't Find A Suitable PixelFormat.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!SetPixelFormat(hDC, PixelFormat, &pfd)) // Are We Able To Set The Pixel Format?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, "Can't Set The PixelFormat.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!(hRC = wglCreateContext(hDC))) // Are We Able To Get A Rendering Context?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, "Can't Create A GL Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!wglMakeCurrent(hDC, hRC)) // Try To Activate The Rendering Context
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, "Can't Activate The GL Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
ShowWindow(hWnd, SW_SHOW); // Show The Window
SetForegroundWindow(hWnd); // Slightly Higher Priority
SetFocus(hWnd); // Sets Keyboard Focus To The Window
ReSizeGLScene(width, height); // Set Up Our Perspective GL Screen
if (!InitGL()) // Initialize Our Newly Created GL Window
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, "Initialization Failed.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
return TRUE; // Success
}
LRESULT CALLBACK WndProc(HWND hWnd, // Handle For This Window
UINT uMsg, // Message For This Window
WPARAM wParam, // Additional Message Information
LPARAM lParam) // Additional Message Information
{
switch (uMsg) // Check For Windows Messages
{
case WM_ACTIVATE: // Watch For Window Activate Message
{
if (!HIWORD(wParam)) // Check Minimization State
{
active = TRUE; // Program Is Active
}
else
{
active = FALSE; // Program Is No Longer Active
}
return 0; // Return To The Message Loop
}
case WM_SYSCOMMAND: // Intercept System Commands
{
switch (wParam) // Check System Calls
{
case SC_SCREENSAVE: // Screensaver Trying To Start?
case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
return 0; // Prevent From Happening
}
break; // Exit
}
case WM_CLOSE: // Did We Receive A Close Message?
{
PostQuitMessage(0); // Send A Quit Message
return 0; // Jump Back
}
case WM_KEYDOWN: // Is A Key Being Held Down?
{
keys[wParam] = TRUE; // If So, Mark It As TRUE
return 0; // Jump Back
}
case WM_KEYUP: // Has A Key Been Released?
{
HandleKeyRelease(wParam);
printf("Key: %d\n", wParam);
return 0; // Jump Back
}
case WM_SIZE: // Resize The OpenGL Window
{
ReSizeGLScene(LOWORD(lParam), HIWORD(lParam)); // LoWord=Width, HiWord=Height
return 0; // Jump Back
}
case WM_LBUTTONDOWN:
{
mouseDnX = GET_X_LPARAM(lParam);
mouseDnY = GET_Y_LPARAM(lParam);
mouseDn = true;
GetCursorPos(&mouseCursorPos);
//ShowCursor(false);
return 0;
}
case WM_LBUTTONUP:
{
mouseDn = false;
//ShowCursor(true);
return 0;
}
case WM_RBUTTONDOWN:
{
mouseDnX = GET_X_LPARAM(lParam);
mouseDnY = GET_Y_LPARAM(lParam);
mouseDnR = true;
GetCursorPos(&mouseCursorPos);
//ShowCursor(false);
return 0;
}
case WM_RBUTTONUP:
{
mouseDnR = false;
//ShowCursor(true);
return 0;
}
case WM_MOUSEMOVE:
{
if (mouseReset)
{
mouseDnX = GET_X_LPARAM(lParam);
mouseDnY = GET_Y_LPARAM(lParam);
mouseReset = 0;
}
mouseMvX = GET_X_LPARAM(lParam);
mouseMvY = GET_Y_LPARAM(lParam);
return 0;
}
case WM_MOUSEWHEEL:
{
mouseWheel += GET_WHEEL_DELTA_WPARAM(wParam);
return 0;
}
}
// Pass All Unhandled Messages To DefWindowProc
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
DWORD WINAPI OpenGLMain(LPVOID tmp)
{
MSG msg; // Windows Message Structure
BOOL done = FALSE; // Bool Variable To Exit Loop
// Ask The User Which Screen Mode They Prefer
fullscreen = FALSE; // Windowed Mode
// Create Our OpenGL Window
if (!CreateGLWindow("Alice HLT TPC CA Event Display", 1280, 1080, 32, fullscreen))
{
return 0; // Quit If Window Was Not Created
}
while (!done) // Loop That Runs While done=FALSE
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) // Is There A Message Waiting?
{
if (msg.message == WM_QUIT) // Have We Received A Quit Message?
{
done = TRUE; // If So done=TRUE
}
else // If Not, Deal With Window Messages
{
TranslateMessage(&msg); // Translate The Message
DispatchMessage(&msg); // Dispatch The Message
}
}
else // If There Are No Messages
{
// Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene()
if (active) // Program Active?
{
if (keys[VK_ESCAPE]) // Was ESC Pressed?
{
done = TRUE; // ESC Signalled A Quit
}
else // Not Time To Quit, Update Screen
{
if (animate)
{
static int nFrame = 0;
DrawGLScene(true);
char filename[16];
sprintf(filename, "video%05d.bmp", nFrame++);
unsigned char *mixBuffer = NULL;
drawClusters = nFrame < 240;
drawSeeds = nFrame >= 90 && nFrame < 210;
drawTracklets = nFrame >= 210 && nFrame < 300;
pointSize = nFrame >= 90 ? 1.0 : 2.0;
drawTracks = nFrame >= 300 && nFrame < 390;
drawFinal = nFrame >= 390;
drawGlobalTracks = nFrame >= 480;
DoScreenshot(NULL, 1, &mixBuffer);
drawClusters = nFrame < 210;
drawSeeds = nFrame > 60 && nFrame < 180;
drawTracklets = nFrame >= 180 && nFrame < 270;
pointSize = nFrame > 60 ? 1.0 : 2.0;
drawTracks = nFrame > 270 && nFrame < 360;
drawFinal = nFrame > 360;
drawGlobalTracks = nFrame > 450;
DoScreenshot(filename, 1, &mixBuffer, (float) (nFrame % 30) / 30.f);
free(mixBuffer);
printf("Wrote video frame %s\n\n", filename);
}
else
{
DrawGLScene(); // Draw The Scene
}
SwapBuffers(hDC); // Swap Buffers (Double Buffering)
}
}
/*if (keys[VK_F1]) // Is F1 Being Pressed?
{
keys[VK_F1]=FALSE; // If So Make Key FALSE
KillGLWindow(); // Kill Our Current Window
fullscreen=!fullscreen; // Toggle Fullscreen / Windowed Mode
// Recreate Our OpenGL Window
if (!CreateGLWindow("NeHe's OpenGL Framework",640,480,16,fullscreen))
{
return 0; // Quit If Window Was Not Created
}
}*/
}
}
// Shutdown
KillGLWindow(); // Kill The Window
return (msg.wParam); // Exit The Program
}
#else
void render(void);
void init(void);
int GetKey(int key)
{
int wParam = 0;
switch (key)
{
case 50:
wParam = 16;
break;
case 10:
wParam = '1';
break;
case 11:
wParam = '2';
break;
case 12:
wParam = '3';
break;
case 13:
wParam = '4';
break;
case 14:
wParam = '5';
break;
case 15:
wParam = '6';
break;
case 16:
wParam = '7';
break;
case 17:
wParam = '8';
break;
case 18:
wParam = '9';
break;
case 57:
wParam = 'N';
break;
case 24:
case 9:
wParam = 'Q';
break;
case 27:
wParam = 'R';
break;
case 65:
wParam = 13;
break;
case 25:
wParam = 'W';
break;
case 38:
wParam = 'A';
break;
case 39:
wParam = 'S';
break;
case 40:
wParam = 'D';
break;
case 26:
wParam = 'E';
break;
case 41:
wParam = 'F';
break;
case 43:
wParam = 'H';
break;
case 33:
wParam = 'P';
break;
case 32:
wParam = 'O';
break;
case 42:
wParam = 'G';
break;
case 29:
wParam = 'Z';
break;
case 45:
wParam = 'K';
break;
case 46:
wParam = 'L';
break;
case 53:
wParam = 'X';
break;
case 35:
case 86:
wParam = 107;
break;
case 61:
case 82:
wParam = 109;
break;
}
return (wParam);
}
volatile static int needUpdate = 0;
void *OpenGLMain(void *ptr)
{
XSetWindowAttributes windowAttributes;
XVisualInfo *visualInfo = NULL;
XEvent event;
Colormap colorMap;
GLXContext glxContext;
int errorBase;
int eventBase;
// Open a connection to the X server
g_pDisplay = XOpenDisplay(NULL);
if (g_pDisplay == NULL)
{
fprintf(stderr, "glxsimple: %s\n", "could not open display");
exit(1);
}
// Make sure OpenGL's GLX extension supported
if (!glXQueryExtension(g_pDisplay, &errorBase, &eventBase))
{
fprintf(stderr, "glxsimple: %s\n", "X server has no OpenGL GLX extension");
exit(1);
}
// Find an appropriate visual
int doubleBufferVisual[] =
{
GLX_RGBA, // Needs to support OpenGL
GLX_DEPTH_SIZE, 16, // Needs to support a 16 bit depth buffer
GLX_DOUBLEBUFFER, // Needs to support double-buffering
None // end of list
};
int singleBufferVisual[] =
{
GLX_RGBA, // Needs to support OpenGL
GLX_DEPTH_SIZE, 16, // Needs to support a 16 bit depth buffer
None // end of list
};
// Try for the double-bufferd visual first
visualInfo = glXChooseVisual(g_pDisplay, DefaultScreen(g_pDisplay), doubleBufferVisual);
if (visualInfo == NULL)
{
// If we can't find a double-bufferd visual, try for a single-buffered visual...
visualInfo = glXChooseVisual(g_pDisplay, DefaultScreen(g_pDisplay), singleBufferVisual);
if (visualInfo == NULL)
{
fprintf(stderr, "glxsimple: %s\n", "no RGB visual with depth buffer");
exit(1);
}
g_bDoubleBuffered = false;
}
// Create an OpenGL rendering context
glxContext = glXCreateContext(g_pDisplay,
visualInfo,
NULL, // No sharing of display lists
GL_TRUE); // Direct rendering if possible
if (glxContext == NULL)
{
fprintf(stderr, "glxsimple: %s\n", "could not create rendering context");
exit(1);
}
// Create an X colormap since we're probably not using the default visual
colorMap = XCreateColormap(g_pDisplay,
RootWindow(g_pDisplay, visualInfo->screen),
visualInfo->visual,
AllocNone);
windowAttributes.colormap = colorMap;
windowAttributes.border_pixel = 0;
windowAttributes.event_mask = ExposureMask |
VisibilityChangeMask |
KeyPressMask |
KeyReleaseMask |
ButtonPressMask |
ButtonReleaseMask |
PointerMotionMask |
StructureNotifyMask |
SubstructureNotifyMask |
FocusChangeMask;
// Create an X window with the selected visual
g_window = XCreateWindow(g_pDisplay,
RootWindow(g_pDisplay, visualInfo->screen),
0, 0, // x/y position of top-left outside corner of the window
640, 480, // Width and height of window
0, // Border width
visualInfo->depth,
InputOutput,
visualInfo->visual,
CWBorderPixel | CWColormap | CWEventMask,
&windowAttributes);
XSetStandardProperties(g_pDisplay,
g_window,
"AliHLTTPCCA Online Event Display",
"AliHLTTPCCA Online Event Display",
None,
NULL,
0,
NULL);
// Bind the rendering context to the window
glXMakeCurrent(g_pDisplay, g_window, glxContext);
// Request the X window to be displayed on the screen
XMapWindow(g_pDisplay, g_window);
// Init OpenGL...
init();
//
// Enter the render loop and don't forget to dispatch X events as
// they occur.
//
XMapWindow(g_pDisplay, g_window);
XFlush(g_pDisplay);
int x11_fd = ConnectionNumber(g_pDisplay);
while (1)
{
int num_ready_fds;
struct timeval tv;
fd_set in_fds;
do
{
FD_ZERO(&in_fds);
FD_SET(x11_fd, &in_fds);
tv.tv_usec = 10000;
tv.tv_sec = 0;
num_ready_fds = XPending(g_pDisplay) || select(x11_fd + 1, &in_fds, NULL, NULL, &tv);
if (num_ready_fds < 0)
{
printf("Error\n");
}
else if (num_ready_fds > 0) needUpdate = 0;
if (buttonPressed == 2) break;
} while (!(num_ready_fds || needUpdate));
do
{
//XNextEvent(g_pDisplay, &event);
if (needUpdate)
{
needUpdate = 0;
event.type = Expose;
}
else
{
XNextEvent(g_pDisplay, &event);
}
if (buttonPressed == 2) break;
switch (event.type)
{
case ButtonPress:
{
if (event.xbutton.button == 1)
{
mouseDn = true;
}
if (event.xbutton.button != 1)
{
mouseDnR = true;
}
mouseDnX = event.xmotion.x;
mouseDnY = event.xmotion.y;
}
break;
case ButtonRelease:
{
if (event.xbutton.button == 1)
{
mouseDn = false;
}
if (event.xbutton.button != 1)
{
mouseDnR = false;
}
}
break;
case KeyPress:
{
int wParam = GetKey(event.xkey.keycode);
//fprintf(stderr, "KeyPress event %d --> %d (%c)\n", event.xkey.keycode, wParam, (char) wParam);
keys[wParam] = true;
}
break;
case KeyRelease:
{
int wParam = GetKey(event.xkey.keycode);
fprintf(stderr, "KeyRelease event %d -> %d (%c)\n", event.xkey.keycode, wParam, (char) wParam);
HandleKeyRelease(wParam);
}
break;
case MotionNotify:
{
mouseMvX = event.xmotion.x;
mouseMvY = event.xmotion.y;
}
break;
case Expose:
{
}
break;
case ConfigureNotify:
{
glViewport(0, 0, event.xconfigure.width, event.xconfigure.height);
ReSizeGLScene(event.xconfigure.width, event.xconfigure.height);
}
}
} while (XPending(g_pDisplay)); // Loop to compress events
if (buttonPressed == 2) break;
render();
}
return(NULL);
}
void ShowNextEvent()
{
needUpdate = 1;
}
//-----------------------------------------------------------------------------
// Name: init()
// Desc: Init OpenGL context for rendering
//-----------------------------------------------------------------------------
void init(void)
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glEnable(GL_TEXTURE_2D);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, 640.0f / 480.0f, 0.1f, 100.0f);
ReSizeGLScene(1024, 768);
}
//-----------------------------------------------------------------------------
// Name: getBitmapImageData()
// Desc: Simply image loader for 24 bit BMP files.
//-----------------------------------------------------------------------------
void render(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
DrawGLScene();
if (g_bDoubleBuffered)
glXSwapBuffers(g_pDisplay, g_window); // Buffer swap does implicit glFlush
else
glFlush(); // Explicit flush for single buffered case
}
#endif
some cleanup, add missing options for linux gpu tracker event display
#define SEPERATE_GLOBAL_TRACKS
#include "AliHLTTPCCADef.h"
#ifdef R__WIN32
#include <winbase.h>
#include <windows.h> // Header File For Windows
#include <windowsx.h>
HDC hDC = NULL; // Private GDI Device Context
HGLRC hRC = NULL; // Permanent Rendering Context
HWND hWnd = NULL; // Holds Our Window Handle
HINSTANCE hInstance; // Holds The Instance Of The Application
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // Declaration For WndProc
bool active = TRUE; // Window Active Flag Set To TRUE By Default
bool fullscreen = TRUE; // Fullscreen Flag Set To Fullscreen Mode By Default
HANDLE semLockDisplay = NULL;
POINT mouseCursorPos;
volatile int mouseReset = false;
#else
#include "bitmapfile.h"
#include <GL/glx.h> // This includes the necessary X headers
#include <pthread.h>
Display *g_pDisplay = NULL;
Window g_window;
bool g_bDoubleBuffered = GL_TRUE;
GLuint g_textureID = 0;
float g_fSpinX = 0.0f;
float g_fSpinY = 0.0f;
int g_nLastMousePositX = 0;
int g_nLastMousePositY = 0;
bool g_bMousing = false;
pthread_mutex_t semLockDisplay = PTHREAD_MUTEX_INITIALIZER;
#endif
#include <GL/gl.h> // Header File For The OpenGL32 Library
#include <GL/glu.h> // Header File For The GLu32 Library
#include "AliHLTTPCCASliceData.h"
#include "AliHLTTPCCAStandaloneFramework.h"
#include "AliHLTTPCCATrack.h"
#include "AliHLTTPCCATracker.h"
#include "AliHLTTPCCATrackerFramework.h"
#ifdef HLTCA_STANDALONE_OLD_MERGER
#include "AliHLTTPCCAMergerOutput.h"
#else
#include "AliHLTTPCGMMergedTrack.h"
#endif
#include "include.h"
#define fgkNSlices 36
bool keys[256]; // Array Used For The Keyboard Routine
#ifdef SEPERATE_GLOBAL_TRACKS
#define SEPERATE_GLOBAL_TRACKS_MAXID 5
#else
#define SEPERATE_GLOBAL_TRACKS_MAXID 100
#endif
#define SEPERATE_GLOBAL_TRACKS_DISTINGUISH_TYPES 6
float rotateX = 0, rotateY = 0;
float mouseDnX, mouseDnY;
float mouseMvX, mouseMvY;
bool mouseDn = false;
bool mouseDnR = false;
int mouseWheel = 0;
volatile int buttonPressed = 0;
GLfloat currentMatrice[16];
int drawClusters = true;
int drawLinks = false;
int drawSeeds = false;
int drawInitLinks = false;
int drawTracklets = false;
int drawTracks = false;
int drawGlobalTracks = false;
int drawFinal = false;
int drawSlice = -1;
int drawGrid = 0;
int excludeClusters = 0;
int projectxy = 0;
float Xadd = 0;
float Zadd = 0;
float4 *globalPos = NULL;
int maxClusters = 0;
int currentClusters = 0;
volatile int displayEventNr = 0;
int currentEventNr = -1;
int glDLrecent = 0;
int updateDLList = 0;
float pointSize = 2.0;
float lineWidth = 1.5;
int animate = 0;
volatile int resetScene = 0;
inline void SetColorClusters() { glColor3f(0, 0.7, 1.0); }
inline void SetColorInitLinks() { glColor3f(0.62, 0.1, 0.1); }
inline void SetColorLinks() { glColor3f(0.8, 0.2, 0.2); }
inline void SetColorSeeds() { glColor3f(0.8, 0.1, 0.85); }
inline void SetColorTracklets() { glColor3f(1, 1, 1); }
#ifdef SEPERATE_GLOBAL_TRACKSa
inline void SetColorTracks()
{
glColor3f(1., 1., 0.15);
}
inline void SetColorGlobalTracks() { glColor3f(1., 0.15, 0.15); }
#else
inline void SetColorTracks()
{
glColor3f(0.4, 1, 0);
}
inline void SetColorGlobalTracks() { glColor3f(1.0, 0.4, 0); }
#endif
inline void SetColorFinal()
{
glColor3f(0, 0.7, 0.2);
}
inline void SetColorGrid() { glColor3f(0.7, 0.7, 0.0); }
void ReSizeGLScene(GLsizei width, GLsizei height) // Resize And Initialize The GL Window
{
if (height == 0) // Prevent A Divide By Zero By
{
height = 1; // Making Height Equal One
}
static int init = 1;
GLfloat tmp[16];
glGetFloatv(GL_MODELVIEW_MATRIX, tmp);
glViewport(0, 0, width, height); // Reset The Current Viewport
glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity(); // Reset The Projection Matrix
// Calculate The Aspect Ratio Of The Window
gluPerspective(45.0f, (GLfloat) width / (GLfloat) height, 0.1f, 100.0f);
glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity(); // Reset The Modelview Matrix
if (init)
{
glTranslatef(0, 0, -16);
init = 0;
}
else
{
glLoadMatrixf(tmp);
}
glGetFloatv(GL_MODELVIEW_MATRIX, currentMatrice);
}
int InitGL() // All Setup For OpenGL Goes Here
{
glShadeModel(GL_SMOOTH); // Enable Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
glClearDepth(1.0f); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations
return (true); // Initialization Went OK
}
inline void drawPointLinestrip(int cid, int id, int id_limit = 100)
{
glVertex3f(globalPos[cid].x, globalPos[cid].y, globalPos[cid].z);
if (globalPos[cid].w < id_limit) globalPos[cid].w = id;
}
void DrawClusters(AliHLTTPCCATracker &tracker, int id)
{
glBegin(GL_POINTS);
for (int i = 0; i < tracker.Param().NRows(); i++)
{
const AliHLTTPCCARow &row = tracker.Data().Row(i);
for (int j = 0; j < row.NHits(); j++)
{
const int cid = tracker.ClusterData()->Id(tracker.Data().ClusterDataIndex(row, j));
if (globalPos[cid].w == id)
{
glVertex3f(globalPos[cid].x, globalPos[cid].y, globalPos[cid].z);
}
}
}
glEnd();
}
void DrawLinks(AliHLTTPCCATracker &tracker, int id, bool dodown = false)
{
glBegin(GL_LINES);
for (int i = 0; i < tracker.Param().NRows(); i++)
{
const AliHLTTPCCARow &row = tracker.Data().Row(i);
if (i < tracker.Param().NRows() - 2)
{
const AliHLTTPCCARow &rowUp = tracker.Data().Row(i + 2);
for (int j = 0; j < row.NHits(); j++)
{
if (tracker.Data().HitLinkUpData(row, j) != -1)
{
const int cid1 = tracker.ClusterData()->Id(tracker.Data().ClusterDataIndex(row, j));
const int cid2 = tracker.ClusterData()->Id(tracker.Data().ClusterDataIndex(rowUp, tracker.Data().HitLinkUpData(row, j)));
drawPointLinestrip(cid1, id);
drawPointLinestrip(cid2, id);
}
}
}
if (dodown && i >= 2)
{
const AliHLTTPCCARow &rowDown = tracker.Data().Row(i - 2);
for (int j = 0; j < row.NHits(); j++)
{
if (tracker.Data().HitLinkDownData(row, j) != -1)
{
const int cid1 = tracker.ClusterData()->Id(tracker.Data().ClusterDataIndex(row, j));
const int cid2 = tracker.ClusterData()->Id(tracker.Data().ClusterDataIndex(rowDown, tracker.Data().HitLinkDownData(row, j)));
drawPointLinestrip(cid1, id);
drawPointLinestrip(cid2, id);
}
}
}
}
glEnd();
}
void DrawSeeds(AliHLTTPCCATracker &tracker)
{
for (int i = 0; i < *tracker.NTracklets(); i++)
{
const AliHLTTPCCAHitId &hit = tracker.TrackletStartHit(i);
glBegin(GL_LINE_STRIP);
int ir = hit.RowIndex();
int ih = hit.HitIndex();
do
{
const AliHLTTPCCARow &row = tracker.Data().Row(ir);
const int cid = tracker.ClusterData()->Id(tracker.Data().ClusterDataIndex(row, ih));
drawPointLinestrip(cid, 3);
ir += 2;
ih = tracker.Data().HitLinkUpData(row, ih);
} while (ih != -1);
glEnd();
}
}
void DrawTracklets(AliHLTTPCCATracker &tracker)
{
for (int i = 0; i < *tracker.NTracklets(); i++)
{
const AliHLTTPCCATracklet &tracklet = tracker.Tracklet(i);
if (tracklet.NHits() == 0) continue;
glBegin(GL_LINE_STRIP);
float4 oldpos;
for (int j = tracklet.FirstRow(); j <= tracklet.LastRow(); j++)
{
#ifdef EXTERN_ROW_HITS
const int rowHit = tracker.TrackletRowHits()[j * *tracker.NTracklets() + i];
#else
const int rowHit = tracklet.RowHit(j);
#endif
if (rowHit != -1)
{
const AliHLTTPCCARow &row = tracker.Data().Row(j);
const int cid = tracker.ClusterData()->Id(tracker.Data().ClusterDataIndex(row, rowHit));
/*if (j != tracklet.FirstRow())
{
float dist = (oldpos.x - globalPos[cid].x) * (oldpos.x - globalPos[cid].x) + (oldpos.y - globalPos[cid].y) * (oldpos.y - globalPos[cid].y) + (oldpos.z - globalPos[cid].z) * (oldpos.z - globalPos[cid].z);
}*/
oldpos = globalPos[cid];
drawPointLinestrip(cid, 4);
}
}
glEnd();
}
}
void DrawTracks(AliHLTTPCCATracker &tracker, int global)
{
for (int i = (global ? tracker.CommonMemory()->fNLocalTracks : 0); i < (global ? *tracker.NTracks() : tracker.CommonMemory()->fNLocalTracks); i++)
{
AliHLTTPCCATrack &track = tracker.Tracks()[i];
glBegin(GL_LINE_STRIP);
for (int j = 0; j < track.NHits(); j++)
{
const AliHLTTPCCAHitId &hit = tracker.TrackHits()[track.FirstHitID() + j];
const AliHLTTPCCARow &row = tracker.Data().Row(hit.RowIndex());
const int cid = tracker.ClusterData()->Id(tracker.Data().ClusterDataIndex(row, hit.HitIndex()));
drawPointLinestrip(cid, 5 + global);
}
glEnd();
}
}
void DrawFinal(AliHLTTPCCAStandaloneFramework &hlt)
{
#ifdef HLTCA_STANDALONE_OLD_MERGER
const AliHLTTPCCAMerger &merger = hlt.Merger();
const AliHLTTPCCAMergerOutput &mergerOut = *merger.Output();
for (int i = 0; i < mergerOut.NTracks(); i++)
{
const AliHLTTPCCAMergedTrack &track = mergerOut.Track(i);
glBegin(GL_LINE_STRIP);
for (int j = 0; j < track.NClusters(); j++)
{
int cid = mergerOut.ClusterId(track.FirstClusterRef() + j);
drawPointLinestrip(cid, 7);
}
glEnd();
}
#else
const AliHLTTPCGMMerger &merger = hlt.Merger();
for (int i = 0; i < merger.NOutputTracks(); i++)
{
const AliHLTTPCGMMergedTrack &track = merger.OutputTracks()[i];
if (track.NClusters() == 0) continue;
int *clusterused = new int[track.NClusters()];
for (int j = 0; j < track.NClusters(); j++)
clusterused[j] = 0;
if (!track.OK()) continue;
glBegin(GL_LINE_STRIP);
float smallest = 1e20;
int bestk = 0;
for (int k = 0; k < track.NClusters(); k++)
{
int cid = merger.OutputClusterIds()[track.FirstClusterRef() + k];
float dist = globalPos[cid].x * globalPos[cid].x + globalPos[cid].y * globalPos[cid].y + globalPos[cid].z * globalPos[cid].z;
if (dist < smallest)
{
smallest = dist;
bestk = k;
}
}
int lastcid = merger.OutputClusterIds()[track.FirstClusterRef() + bestk];
clusterused[bestk] = 1;
#ifdef SEPERATE_GLOBAL_TRACKS
bool linestarted = (globalPos[lastcid].w < SEPERATE_GLOBAL_TRACKS_DISTINGUISH_TYPES);
if (linestarted)
#endif
{
drawPointLinestrip(lastcid, 7, SEPERATE_GLOBAL_TRACKS_MAXID);
}
for (int j = 1; j < track.NClusters(); j++)
{
int bestcid = 0;
int bestk = 0;
float bestdist = 1e20;
for (int k = 0; k < track.NClusters(); k++)
{
if (clusterused[k]) continue;
int cid = merger.OutputClusterIds()[track.FirstClusterRef() + k];
float dist = (globalPos[cid].x - globalPos[lastcid].x) * (globalPos[cid].x - globalPos[lastcid].x) +
(globalPos[cid].y - globalPos[lastcid].y) * (globalPos[cid].y - globalPos[lastcid].y) +
(globalPos[cid].z - globalPos[lastcid].z) * (globalPos[cid].z - globalPos[lastcid].z);
if (dist < bestdist)
{
bestdist = dist;
bestcid = cid;
bestk = k;
}
}
#ifdef SEPERATE_GLOBAL_TRACKS
if (!linestarted && globalPos[bestcid].w < SEPERATE_GLOBAL_TRACKS_DISTINGUISH_TYPES)
{
drawPointLinestrip(lastcid, 7, SEPERATE_GLOBAL_TRACKS_MAXID);
linestarted = true;
}
if (linestarted)
#endif
{
drawPointLinestrip(bestcid, 7, SEPERATE_GLOBAL_TRACKS_MAXID);
}
#ifdef SEPERATE_GLOBAL_TRACKS
if (linestarted && !(globalPos[bestcid].w < SEPERATE_GLOBAL_TRACKS_DISTINGUISH_TYPES)) linestarted = false;
#endif
clusterused[bestk] = 1;
lastcid = bestcid;
}
glEnd();
delete[] clusterused;
}
#endif
}
void DrawGrid(AliHLTTPCCATracker &tracker)
{
glBegin(GL_LINES);
for (int i = 0; i < tracker.Param().NRows(); i++)
{
const AliHLTTPCCARow &row = tracker.Data().Row(i);
for (int j = 0; j <= (signed) row.Grid().Ny(); j++)
{
float z1 = row.Grid().ZMin();
float z2 = row.Grid().ZMax();
float x = row.X() + Xadd;
float y = row.Grid().YMin() + (float) j / row.Grid().StepYInv();
float zz1, zz2, yy1, yy2, xx1, xx2;
tracker.Param().Slice2Global(x, y, z1, &xx1, &yy1, &zz1);
tracker.Param().Slice2Global(x, y, z2, &xx2, &yy2, &zz2);
if (zz1 >= 0)
{
zz1 += Zadd;
zz2 += Zadd;
}
else
{
zz1 -= Zadd;
zz2 -= Zadd;
}
glVertex3f(xx1 / 50, yy1 / 50, zz1 / 50);
glVertex3f(xx2 / 50, yy2 / 50, zz2 / 50);
}
for (int j = 0; j <= (signed) row.Grid().Nz(); j++)
{
float y1 = row.Grid().YMin();
float y2 = row.Grid().YMax();
float x = row.X() + Xadd;
float z = row.Grid().ZMin() + (float) j / row.Grid().StepZInv();
float zz1, zz2, yy1, yy2, xx1, xx2;
tracker.Param().Slice2Global(x, y1, z, &xx1, &yy1, &zz1);
tracker.Param().Slice2Global(x, y2, z, &xx2, &yy2, &zz2);
if (zz1 >= 0)
{
zz1 += Zadd;
zz2 += Zadd;
}
else
{
zz1 -= Zadd;
zz2 -= Zadd;
}
glVertex3f(xx1 / 50, yy1 / 50, zz1 / 50);
glVertex3f(xx2 / 50, yy2 / 50, zz2 / 50);
}
}
glEnd();
}
int DrawGLScene(bool doAnimation = false) // Here's Where We Do All The Drawing
{
static float fpsscale = 1;
static int framesDone = 0;
static unsigned long long int startTime, displayFpsTime, timeFreq;
static GLuint glDLlines[fgkNSlices][6];
static GLuint glDLlinesFinal;
static GLuint glDLpoints[fgkNSlices][8];
static GLuint glDLgrid[fgkNSlices];
static int glDLcreated = 0;
AliHLTTPCCAStandaloneFramework &hlt = AliHLTTPCCAStandaloneFramework::Instance();
//Initialize
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
glLoadIdentity(); // Reset The Current Modelview Matrix
int mouseWheelTmp = mouseWheel;
mouseWheel = 0;
//Calculate rotation / translation scaling factors
float scalefactor = keys[16] ? 0.2 : 1.0;
float rotatescalefactor = 1;
float sqrdist = sqrt(sqrt(currentMatrice[12] * currentMatrice[12] + currentMatrice[13] * currentMatrice[13] + currentMatrice[14] * currentMatrice[14]) / 50) * 0.8;
if (sqrdist < 0.2) sqrdist = 0.2;
if (sqrdist > 5) sqrdist = 5;
scalefactor *= sqrdist;
if (drawSlice != -1)
{
scalefactor /= 5;
rotatescalefactor = 3;
}
//Perform new rotation / translation
if (doAnimation)
{
float moveY = scalefactor * -0.14 * 0.25;
float moveX = scalefactor * -0.14;
static int nFrame = 0;
nFrame++;
float moveZ = 0;
if (nFrame > 570)
{
moveZ = scalefactor * 1.;
}
else if (nFrame > 510)
{
moveZ = scalefactor * 1.f * (nFrame - 510) / 60.f;
}
glTranslatef(moveX, moveY, moveZ);
}
else
{
float moveZ = scalefactor * ((float) mouseWheelTmp / 150 + (float) (keys['W'] - keys['S']) * 0.2 * fpsscale);
float moveX = scalefactor * ((float) (keys['A'] - keys['D']) * 0.2 * fpsscale);
glTranslatef(moveX, 0, moveZ);
}
if (doAnimation)
{
glRotatef(scalefactor * rotatescalefactor * -0.5, 0, 1, 0);
glRotatef(scalefactor * rotatescalefactor * 0.5 * 0.25, 1, 0, 0);
glRotatef(scalefactor * 0.2, 0, 0, 1);
}
else if (mouseDnR && mouseDn)
{
glTranslatef(0, 0, -scalefactor * ((float) mouseMvY - (float) mouseDnY) / 4);
glRotatef(scalefactor * ((float) mouseMvX - (float) mouseDnX), 0, 0, 1);
}
else if (mouseDnR)
{
glTranslatef(-scalefactor * 0.5 * ((float) mouseDnX - (float) mouseMvX) / 4, -scalefactor * 0.5 * ((float) mouseMvY - (float) mouseDnY) / 4, 0);
}
else if (mouseDn)
{
glRotatef(scalefactor * rotatescalefactor * ((float) mouseMvX - (float) mouseDnX), 0, 1, 0);
glRotatef(scalefactor * rotatescalefactor * ((float) mouseMvY - (float) mouseDnY), 1, 0, 0);
}
if (keys['E'] ^ keys['F'])
{
glRotatef(scalefactor * fpsscale * 2, 0, 0, keys['E'] - keys['F']);
}
if (mouseDn || mouseDnR)
{
#ifdef R__WIN32a
mouseReset = true;
SetCursorPos(mouseCursorPos.x, mouseCursorPos.y);
#else
mouseDnX = mouseMvX;
mouseDnY = mouseMvY;
#endif
}
//Apply standard translation / rotation
glMultMatrixf(currentMatrice);
//Graphichs Options
pointSize += (float) (keys[107] - keys[109] + keys[187] - keys[189]) * fpsscale * 0.05;
if (pointSize <= 0.01) pointSize = 0.01;
//Reset position
if (resetScene)
{
glLoadIdentity();
glTranslatef(0, 0, -16);
AliHLTTPCCATracker::StandaloneQueryTime(&startTime);
displayFpsTime = startTime;
framesDone = 0;
pointSize = 2.0;
drawSlice = -1;
Xadd = 0;
Zadd = 0;
resetScene = 0;
updateDLList = true;
}
//Store position
glGetFloatv(GL_MODELVIEW_MATRIX, currentMatrice);
//Make sure event gets not overwritten during display
#ifdef R__WIN32
WaitForSingleObject(semLockDisplay, INFINITE);
#else
pthread_mutex_lock(&semLockDisplay);
#endif
//Open GL Default Values
glEnable(GL_POINT_SMOOTH);
glEnable(GL_LINE_SMOOTH);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glPointSize(pointSize);
glLineWidth(lineWidth);
//Extract global cluster information
if (updateDLList || displayEventNr != currentEventNr)
{
currentClusters = 0;
for (int iSlice = 0; iSlice < fgkNSlices; iSlice++)
{
currentClusters += hlt.fTracker.fCPUTrackers[iSlice].NHitsTotal();
}
if (maxClusters < currentClusters)
{
if (globalPos) delete[] globalPos;
maxClusters = currentClusters;
globalPos = new float4[maxClusters];
}
for (int iSlice = 0; iSlice < fgkNSlices; iSlice++)
{
const AliHLTTPCCAClusterData &cdata = hlt.fClusterData[iSlice];
for (int i = 0; i < cdata.NumberOfClusters(); i++)
{
const int cid = cdata.Id(i);
if (cid >= maxClusters)
{
printf("Cluster Buffer Size exceeded (id %d max %d)\n", cid, maxClusters);
exit(1);
}
float4 *ptr = &globalPos[cid];
hlt.fTracker.fCPUTrackers[iSlice].Param().Slice2Global(cdata.X(i) + Xadd, cdata.Y(i), cdata.Z(i), &ptr->x, &ptr->y, &ptr->z);
if (ptr->z >= 0)
{
ptr->z += Zadd;
ptr->z += Zadd;
}
else
{
ptr->z -= Zadd;
ptr->z -= Zadd;
}
ptr->x /= 50;
ptr->y /= 50;
ptr->z /= 50;
ptr->w = 1;
}
}
currentEventNr = displayEventNr;
AliHLTTPCCATracker::StandaloneQueryFreq(&timeFreq);
AliHLTTPCCATracker::StandaloneQueryTime(&startTime);
displayFpsTime = startTime;
framesDone = 0;
glDLrecent = 0;
updateDLList = 0;
}
//Prepare Event
if (!glDLrecent)
{
for (int iSlice = 0; iSlice < fgkNSlices; iSlice++)
{
if (glDLcreated)
{
for (int i = 0; i < 6; i++)
glDeleteLists(glDLlines[iSlice][i], 1);
for (int i = 0; i < 8; i++)
glDeleteLists(glDLpoints[iSlice][i], 1);
glDeleteLists(glDLgrid[iSlice], 1);
}
else
{
for (int i = 0; i < 6; i++)
glDLlines[iSlice][i] = glGenLists(1);
for (int i = 0; i < 8; i++)
glDLpoints[iSlice][i] = glGenLists(1);
glDLgrid[iSlice] = glGenLists(1);
}
}
if (glDLcreated)
{
glDeleteLists(glDLlinesFinal, 1);
}
else
{
glDLlinesFinal = glGenLists(1);
}
for (int i = 0; i < currentClusters; i++)
globalPos[i].w = 0;
for (int iSlice = 0; iSlice < fgkNSlices; iSlice++)
{
AliHLTTPCCATracker &tracker = hlt.fTracker.fCPUTrackers[iSlice];
glNewList(glDLlines[iSlice][0], GL_COMPILE);
if (drawInitLinks)
{
char *tmpMem[fgkNSlices];
for (int i = 0; i < fgkNSlices; i++)
{
AliHLTTPCCATracker &tracker = hlt.fTracker.fCPUTrackers[i];
tmpMem[i] = tracker.Data().Memory();
tracker.SetGPUSliceDataMemory((void *) tracker.LinkTmpMemory(), tracker.Data().Rows());
tracker.SetPointersSliceData(tracker.ClusterData());
}
DrawLinks(tracker, 1, true);
for (int i = 0; i < fgkNSlices; i++)
{
AliHLTTPCCATracker &tracker = hlt.fTracker.fCPUTrackers[i];
tracker.SetGPUSliceDataMemory(tmpMem[i], tracker.Data().Rows());
tracker.SetPointersSliceData(tracker.ClusterData());
}
}
glEndList();
glNewList(glDLlines[iSlice][1], GL_COMPILE);
DrawLinks(tracker, 2);
glEndList();
glNewList(glDLlines[iSlice][2], GL_COMPILE);
DrawSeeds(tracker);
glEndList();
glNewList(glDLlines[iSlice][3], GL_COMPILE);
DrawTracklets(tracker);
glEndList();
glNewList(glDLlines[iSlice][4], GL_COMPILE);
DrawTracks(tracker, 0);
glEndList();
glNewList(glDLlines[iSlice][5], GL_COMPILE);
DrawTracks(tracker, 1);
glEndList();
glNewList(glDLgrid[iSlice], GL_COMPILE);
DrawGrid(tracker);
glEndList();
}
glNewList(glDLlinesFinal, GL_COMPILE);
//#ifndef SEPERATE_GLOBAL_TRACKS
DrawFinal(hlt);
//#endif
glEndList();
for (int iSlice = 0; iSlice < fgkNSlices; iSlice++)
{
AliHLTTPCCATracker &tracker = hlt.fTracker.fCPUTrackers[iSlice];
for (int i = 0; i < 8; i++)
{
glNewList(glDLpoints[iSlice][i], GL_COMPILE);
DrawClusters(tracker, i);
glEndList();
}
}
int errCode;
if ((errCode = glGetError()) != GL_NO_ERROR)
{
printf("Error creating OpenGL display list: %s\n", gluErrorString(errCode));
resetScene = 1;
}
else
{
glDLrecent = 1;
}
}
++framesDone;
unsigned long long int tmpTime;
AliHLTTPCCATracker::StandaloneQueryTime(&tmpTime);
if (tmpTime - displayFpsTime > timeFreq)
{
displayFpsTime = tmpTime;
float fps = (double) framesDone * (double) timeFreq / (double) (tmpTime - startTime);
printf("FPS: %f (%d frames, Slice: %d, 1:Clusters %d, 2:Prelinks %d, 3:Links %d, 4:Seeds %d, 5:Tracklets %d, 6:Tracks %d, 7:GTracks %d, 8:Merger %d)\n", fps, framesDone, drawSlice, drawClusters, drawInitLinks, drawLinks, drawSeeds, drawTracklets, drawTracks, drawGlobalTracks, drawFinal);
fpsscale = 60 / fps;
}
//Draw Event
if (glDLrecent)
{
for (int iSlice = 0; iSlice < fgkNSlices; iSlice++)
{
if (drawSlice != -1 && drawSlice != iSlice) continue;
if (drawGrid)
{
SetColorGrid();
glCallList(glDLgrid[iSlice]);
}
if (drawClusters)
{
SetColorClusters();
glCallList(glDLpoints[iSlice][0]);
if (drawInitLinks)
{
if (excludeClusters) goto skip1;
SetColorInitLinks();
}
glCallList(glDLpoints[iSlice][1]);
if (drawLinks)
{
if (excludeClusters) goto skip1;
SetColorLinks();
}
glCallList(glDLpoints[iSlice][2]);
if (drawSeeds)
{
if (excludeClusters) goto skip1;
SetColorSeeds();
}
glCallList(glDLpoints[iSlice][3]);
skip1:
glColor3f(0, 0.7, 1.0);
if (drawTracklets)
{
if (excludeClusters) goto skip2;
SetColorTracklets();
}
glCallList(glDLpoints[iSlice][4]);
if (drawTracks)
{
if (excludeClusters) goto skip2;
SetColorTracks();
}
glCallList(glDLpoints[iSlice][5]);
skip2:
if (drawGlobalTracks)
{
if (excludeClusters) goto skip3;
SetColorGlobalTracks();
}
glCallList(glDLpoints[iSlice][6]);
if (drawFinal)
{
if (excludeClusters) goto skip3;
SetColorFinal();
}
glCallList(glDLpoints[iSlice][7]);
skip3:;
}
if (!excludeClusters)
{
if (drawInitLinks) {
SetColorInitLinks();
glCallList(glDLlines[iSlice][0]);
}
if (drawLinks) {
SetColorLinks();
glCallList(glDLlines[iSlice][1]);
}
if (drawSeeds) {
SetColorSeeds();
glCallList(glDLlines[iSlice][2]);
}
if (drawTracklets) {
SetColorTracklets();
glCallList(glDLlines[iSlice][3]);
}
if (drawTracks) {
SetColorTracks();
glCallList(glDLlines[iSlice][4]);
}
if (drawGlobalTracks) {
SetColorGlobalTracks();
glCallList(glDLlines[iSlice][5]);
}
}
}
if (!excludeClusters && drawFinal) {
SetColorFinal();
if (!drawClusters)
{
for (int iSlice = 0; iSlice < fgkNSlices; iSlice++)
{
glCallList(glDLpoints[iSlice][7]);
}
}
glCallList(glDLlinesFinal);
}
}
//Free event
#ifdef R__WIN32
ReleaseSemaphore(semLockDisplay, 1, NULL);
#else
pthread_mutex_unlock(&semLockDisplay);
#endif
return true; // Keep Going
}
void DoScreenshot(char *filename, int SCALE_X, unsigned char **mixBuffer = NULL, float mixFactor = 0.)
{
//#define SCALE_X 3
#define SCALE_Y SCALE_X
if (mixFactor < 0.f) mixFactor = 0.f;
if (mixFactor > 1.f) mixFactor = 1.f;
float tmpPointSize = pointSize;
float tmpLineWidth = lineWidth;
//pointSize *= (float) (SCALE_X + SCALE_Y) / 2. * 2.;
//lineWidth *= (float) (SCALE_X + SCALE_Y) / 2. * 2.;
if (animate)
{
}
else
{
pointSize *= 2;
}
GLint view[4], viewold[4];
glGetIntegerv(GL_VIEWPORT, viewold);
glGetIntegerv(GL_VIEWPORT, view);
view[2] *= SCALE_X;
view[3] *= SCALE_Y;
unsigned char *pixels = (unsigned char *) malloc(4 * view[2] * view[3]);
memset(pixels, 0, 4 * view[2] * view[3]);
unsigned char *pixels2 = (unsigned char *) malloc(4 * view[2] * view[3]);
for (int i = 0; i < SCALE_X; i++)
{
for (int j = 0; j < SCALE_Y; j++)
{
glViewport(-i * viewold[2], -j * viewold[3], view[2], view[3]);
DrawGLScene();
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadBuffer(GL_BACK);
glReadPixels(0, 0, view[2], view[3], GL_RGBA, GL_UNSIGNED_BYTE, pixels2);
for (int k = 0; k < viewold[2]; k++)
{
for (int l = 0; l < viewold[3]; l++)
{
pixels[((j * viewold[3] + l) * view[2] + i * viewold[2] + k) * 4] = pixels2[(l * view[2] + k) * 4 + 2];
pixels[((j * viewold[3] + l) * view[2] + i * viewold[2] + k) * 4 + 1] = pixels2[(l * view[2] + k) * 4 + 1];
pixels[((j * viewold[3] + l) * view[2] + i * viewold[2] + k) * 4 + 2] = pixels2[(l * view[2] + k) * 4];
pixels[((j * viewold[3] + l) * view[2] + i * viewold[2] + k) * 4 + 3] = 0;
}
}
}
}
free(pixels2);
if (mixBuffer)
{
if (*mixBuffer == NULL)
{
*mixBuffer = (unsigned char *) malloc(4 * view[2] * view[3]);
memcpy(*mixBuffer, pixels, 4 * view[2] * view[3]);
}
else
{
for (int i = 0; i < 4 * view[2] * view[3]; i++)
{
pixels[i] = (*mixBuffer)[i] = (mixFactor * pixels[i] + (1.f - mixFactor) * (*mixBuffer)[i]);
}
}
}
if (filename)
{
FILE *fp = fopen(filename, "w+b");
BITMAPFILEHEADER bmpFH;
BITMAPINFOHEADER bmpIH;
memset(&bmpFH, 0, sizeof(bmpFH));
memset(&bmpIH, 0, sizeof(bmpIH));
bmpFH.bfType = 19778; //"BM"
bmpFH.bfSize = sizeof(bmpFH) + sizeof(bmpIH) + 3 * view[2] * view[3];
bmpFH.bfOffBits = sizeof(bmpFH) + sizeof(bmpIH);
bmpIH.biSize = sizeof(bmpIH);
bmpIH.biWidth = view[2];
bmpIH.biHeight = view[3];
bmpIH.biPlanes = 1;
bmpIH.biBitCount = 32;
fwrite(&bmpFH, 1, sizeof(bmpFH), fp);
fwrite(&bmpIH, 1, sizeof(bmpIH), fp);
fwrite(pixels, view[2] * view[3], 4, fp);
fclose(fp);
}
free(pixels);
glViewport(0, 0, viewold[2], viewold[3]);
pointSize = tmpPointSize;
lineWidth = tmpLineWidth;
DrawGLScene();
}
void PrintHelp()
{
printf("[N]/[SPACE]\tNext event\n");
printf("[Q]/[ESC]\tQuit\n");
printf("[R]\t\tReset Display Settings\n");
printf("[L]\t\tDraw single slice (next slice)\n");
printf("[K]\t\tDraw single slice (previous slice)\n");
printf("[Z]/[U]\t\tShow splitting of TPC in slices by extruding volume, [U] resets\n");
printf("[Y]\t\tStart Animation\n");
printf("[G]\t\tDraw Grid\n");
printf("[X]\t\tExclude Clusters used in the tracking steps enabled for visualization ([1]-[8])");
printf("[1]\t\tShow Clusters\n");
printf("[2]\t\tShow Links that were removed\n");
printf("[3]\t\tShow Links that remained in Neighbors Cleaner\n");
printf("[4]\t\tShow Seeds (Start Hits)\n");
printf("[5]\t\tShow Tracklets\n");
printf("[6]\t\tShow Tracks (after Tracklet Selector)\n");
printf("[7]\t\tShow Global Track Segments\n");
printf("[8]\t\tShow Final Merged Tracks (after Track Merger)\n");
printf("[T]\t\tTake Screenshot\n");
printf("[O]\t\tSave current camera position\n");
printf("[P]\t\tRestore camera position\n");
printf("[H]\t\tPrint Help\n");
printf("[W]/[S]/[A]/[D]\tZoom / Move Left Right\n");
printf("[E]/[F]\t\tRotate\n");
printf("[+]/[-]\t\tMake points thicker / fainter\n");
printf("[MOUSE1]\tLook around\n");
printf("[MOUSE2]\tShift camera\n");
printf("[MOUSE1+2]\tZoom / Rotate\n");
printf("[SHIFT]\tSlow Zoom / Move / Rotate\n");
}
void HandleKeyRelease(int wParam)
{
keys[wParam] = false;
if (wParam == 13 || wParam == 'N') buttonPressed = 1;
else if (wParam == 'Q') buttonPressed = 2;
else if (wParam == 'R') resetScene = 1;
else if (wParam == 'L')
{
if (drawSlice == fgkNSlices - 1)
drawSlice = -1;
else
drawSlice++;
}
else if (wParam == 'K')
{
if (drawSlice == -1)
drawSlice = fgkNSlices - 1;
else
drawSlice--;
}
else if (wParam == 'I')
{
updateDLList = true;
projectxy ^= 1;
}
else if (wParam == 'Z')
{
updateDLList = true;
Xadd += 60;
Zadd += 60;
}
else if (wParam == 'U')
{
updateDLList = true;
Xadd -= 60;
Zadd -= 60;
if (Zadd < 0 || Xadd < 0) Zadd = Xadd = 0;
}
else if (wParam == 'Y')
{
animate = 1;
printf("Starting Animation\n");
}
else if (wParam == 'G') drawGrid ^= 1;
else if (wParam == 'X') excludeClusters ^= 1;
else if (wParam == '1')
drawClusters ^= 1;
else if (wParam == '2')
drawInitLinks ^= 1;
else if (wParam == '3')
drawLinks ^= 1;
else if (wParam == '4')
drawSeeds ^= 1;
else if (wParam == '5')
drawTracklets ^= 1;
else if (wParam == '6')
drawTracks ^= 1;
else if (wParam == '7')
drawGlobalTracks ^= 1;
else if (wParam == '8')
drawFinal ^= 1;
else if (wParam == 'T')
{
printf("Taking Screenshot\n");
DoScreenshot("screenshot.bmp", 3);
}
else if (wParam == 'O')
{
GLfloat tmp[16];
glGetFloatv(GL_MODELVIEW_MATRIX, tmp);
FILE *ftmp = fopen("glpos.tmp", "w+b");
if (ftmp)
{
int retval = fwrite(&tmp[0], sizeof(GLfloat), 16, ftmp);
if (retval != 16)
printf("Error writing position to file\n");
else
printf("Position stored to file\n");
fclose(ftmp);
}
else
{
printf("Error opening file\n");
}
}
else if (wParam == 'P')
{
GLfloat tmp[16];
FILE *ftmp = fopen("glpos.tmp", "rb");
if (ftmp)
{
int retval = fread(&tmp[0], sizeof(GLfloat), 16, ftmp);
if (retval == 16)
{
glLoadMatrixf(tmp);
glGetFloatv(GL_MODELVIEW_MATRIX, currentMatrice);
printf("Position read from file\n");
}
else
{
printf("Error reading position from file\n");
}
fclose(ftmp);
}
else
{
printf("Error opening file\n");
}
}
else if (wParam == 'H')
{
PrintHelp();
}
}
#ifdef R__WIN32
void KillGLWindow() // Properly Kill The Window
{
if (fullscreen) // Are We In Fullscreen Mode?
{
ChangeDisplaySettings(NULL, 0); // If So Switch Back To The Desktop
ShowCursor(TRUE); // Show Mouse Pointer
}
if (hRC) // Do We Have A Rendering Context?
{
if (!wglMakeCurrent(NULL, NULL)) // Are We Able To Release The DC And RC Contexts?
{
MessageBox(NULL, "Release Of DC And RC Failed.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
}
if (!wglDeleteContext(hRC)) // Are We Able To Delete The RC?
{
MessageBox(NULL, "Release Rendering Context Failed.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
}
hRC = NULL; // Set RC To NULL
}
if (hDC && !ReleaseDC(hWnd, hDC)) // Are We Able To Release The DC
{
MessageBox(NULL, "Release Device Context Failed.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
hDC = NULL; // Set DC To NULL
}
if (hWnd && !DestroyWindow(hWnd)) // Are We Able To Destroy The Window?
{
MessageBox(NULL, "Could Not Release hWnd.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
hWnd = NULL; // Set hWnd To NULL
}
if (!UnregisterClass("OpenGL", hInstance)) // Are We Able To Unregister Class
{
MessageBox(NULL, "Could Not Unregister Class.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
hInstance = NULL; // Set hInstance To NULL
}
}
/* This Code Creates Our OpenGL Window. Parameters Are: *
* title - Title To Appear At The Top Of The Window *
* width - Width Of The GL Window Or Fullscreen Mode *
* height - Height Of The GL Window Or Fullscreen Mode *
* bits - Number Of Bits To Use For Color (8/16/24/32) *
* fullscreenflag - Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE) */
BOOL CreateGLWindow(char *title, int width, int height, int bits, bool fullscreenflag)
{
GLuint PixelFormat; // Holds The Results After Searching For A Match
WNDCLASS wc; // Windows Class Structure
DWORD dwExStyle; // Window Extended Style
DWORD dwStyle; // Window Style
RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values
WindowRect.left = (long) 0; // Set Left Value To 0
WindowRect.right = (long) width; // Set Right Value To Requested Width
WindowRect.top = (long) 0; // Set Top Value To 0
WindowRect.bottom = (long) height; // Set Bottom Value To Requested Height
fullscreen = fullscreenflag; // Set The Global Fullscreen Flag
hInstance = GetModuleHandle(NULL); // Grab An Instance For Our Window
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw On Size, And Own DC For Window.
wc.lpfnWndProc = (WNDPROC) WndProc; // WndProc Handles Messages
wc.cbClsExtra = 0; // No Extra Window Data
wc.cbWndExtra = 0; // No Extra Window Data
wc.hInstance = hInstance; // Set The Instance
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load The Default Icon
wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load The Arrow Pointer
wc.hbrBackground = NULL; // No Background Required For GL
wc.lpszMenuName = NULL; // We Don't Want A Menu
wc.lpszClassName = "OpenGL"; // Set The Class Name
if (!RegisterClass(&wc)) // Attempt To Register The Window Class
{
MessageBox(NULL, "Failed To Register The Window Class.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (fullscreen) // Attempt Fullscreen Mode?
{
DEVMODE dmScreenSettings; // Device Mode
memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared
dmScreenSettings.dmSize = sizeof(dmScreenSettings); // Size Of The Devmode Structure
dmScreenSettings.dmPelsWidth = width; // Selected Screen Width
dmScreenSettings.dmPelsHeight = height; // Selected Screen Height
dmScreenSettings.dmBitsPerPel = bits; // Selected Bits Per Pixel
dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
// Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
{
// If The Mode Fails, Offer Two Options. Quit Or Use Windowed Mode.
if (MessageBox(NULL, "The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?", "NeHe GL", MB_YESNO | MB_ICONEXCLAMATION) == IDYES)
{
fullscreen = FALSE; // Windowed Mode Selected. Fullscreen = FALSE
}
else
{
// Pop Up A Message Box Letting User Know The Program Is Closing.
MessageBox(NULL, "Program Will Now Close.", "ERROR", MB_OK | MB_ICONSTOP);
return FALSE; // Return FALSE
}
}
}
if (fullscreen) // Are We Still In Fullscreen Mode?
{
dwExStyle = WS_EX_APPWINDOW; // Window Extended Style
dwStyle = WS_POPUP; // Windows Style
ShowCursor(FALSE); // Hide Mouse Pointer
}
else
{
dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style
dwStyle = WS_OVERLAPPEDWINDOW; // Windows Style
}
AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size
// Create The Window
if (!(hWnd = CreateWindowEx(dwExStyle, // Extended Style For The Window
"OpenGL", // Class Name
title, // Window Title
dwStyle | // Defined Window Style
WS_CLIPSIBLINGS | // Required Window Style
WS_CLIPCHILDREN, // Required Window Style
0,
0, // Window Position
WindowRect.right - WindowRect.left, // Calculate Window Width
WindowRect.bottom - WindowRect.top, // Calculate Window Height
NULL, // No Parent Window
NULL, // No Menu
hInstance, // Instance
NULL))) // Dont Pass Anything To WM_CREATE
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, "Window Creation Error.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
static PIXELFORMATDESCRIPTOR pfd = // pfd Tells Windows How We Want Things To Be
{
sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
1, // Version Number
PFD_DRAW_TO_WINDOW | // Format Must Support Window
PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
PFD_DOUBLEBUFFER, // Must Support Double Buffering
PFD_TYPE_RGBA, // Request An RGBA Format
(unsigned char) bits, // Select Our Color Depth
0,
0, 0, 0, 0, 0, // Color Bits Ignored
0, // No Alpha Buffer
0, // Shift Bit Ignored
0, // No Accumulation Buffer
0, 0, 0, 0, // Accumulation Bits Ignored
16, // 16Bit Z-Buffer (Depth Buffer)
0, // No Stencil Buffer
0, // No Auxiliary Buffer
PFD_MAIN_PLANE, // Main Drawing Layer
0, // Reserved
0, 0, 0 // Layer Masks Ignored
};
if (!(hDC = GetDC(hWnd))) // Did We Get A Device Context?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, "Can't Create A GL Device Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) // Did Windows Find A Matching Pixel Format?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, "Can't Find A Suitable PixelFormat.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!SetPixelFormat(hDC, PixelFormat, &pfd)) // Are We Able To Set The Pixel Format?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, "Can't Set The PixelFormat.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!(hRC = wglCreateContext(hDC))) // Are We Able To Get A Rendering Context?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, "Can't Create A GL Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!wglMakeCurrent(hDC, hRC)) // Try To Activate The Rendering Context
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, "Can't Activate The GL Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
ShowWindow(hWnd, SW_SHOW); // Show The Window
SetForegroundWindow(hWnd); // Slightly Higher Priority
SetFocus(hWnd); // Sets Keyboard Focus To The Window
ReSizeGLScene(width, height); // Set Up Our Perspective GL Screen
if (!InitGL()) // Initialize Our Newly Created GL Window
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, "Initialization Failed.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
return TRUE; // Success
}
LRESULT CALLBACK WndProc(HWND hWnd, // Handle For This Window
UINT uMsg, // Message For This Window
WPARAM wParam, // Additional Message Information
LPARAM lParam) // Additional Message Information
{
switch (uMsg) // Check For Windows Messages
{
case WM_ACTIVATE: // Watch For Window Activate Message
{
if (!HIWORD(wParam)) // Check Minimization State
{
active = TRUE; // Program Is Active
}
else
{
active = FALSE; // Program Is No Longer Active
}
return 0; // Return To The Message Loop
}
case WM_SYSCOMMAND: // Intercept System Commands
{
switch (wParam) // Check System Calls
{
case SC_SCREENSAVE: // Screensaver Trying To Start?
case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
return 0; // Prevent From Happening
}
break; // Exit
}
case WM_CLOSE: // Did We Receive A Close Message?
{
PostQuitMessage(0); // Send A Quit Message
return 0; // Jump Back
}
case WM_KEYDOWN: // Is A Key Being Held Down?
{
keys[wParam] = TRUE; // If So, Mark It As TRUE
return 0; // Jump Back
}
case WM_KEYUP: // Has A Key Been Released?
{
HandleKeyRelease(wParam);
printf("Key: %d\n", wParam);
return 0; // Jump Back
}
case WM_SIZE: // Resize The OpenGL Window
{
ReSizeGLScene(LOWORD(lParam), HIWORD(lParam)); // LoWord=Width, HiWord=Height
return 0; // Jump Back
}
case WM_LBUTTONDOWN:
{
mouseDnX = GET_X_LPARAM(lParam);
mouseDnY = GET_Y_LPARAM(lParam);
mouseDn = true;
GetCursorPos(&mouseCursorPos);
//ShowCursor(false);
return 0;
}
case WM_LBUTTONUP:
{
mouseDn = false;
//ShowCursor(true);
return 0;
}
case WM_RBUTTONDOWN:
{
mouseDnX = GET_X_LPARAM(lParam);
mouseDnY = GET_Y_LPARAM(lParam);
mouseDnR = true;
GetCursorPos(&mouseCursorPos);
//ShowCursor(false);
return 0;
}
case WM_RBUTTONUP:
{
mouseDnR = false;
//ShowCursor(true);
return 0;
}
case WM_MOUSEMOVE:
{
if (mouseReset)
{
mouseDnX = GET_X_LPARAM(lParam);
mouseDnY = GET_Y_LPARAM(lParam);
mouseReset = 0;
}
mouseMvX = GET_X_LPARAM(lParam);
mouseMvY = GET_Y_LPARAM(lParam);
return 0;
}
case WM_MOUSEWHEEL:
{
mouseWheel += GET_WHEEL_DELTA_WPARAM(wParam);
return 0;
}
}
// Pass All Unhandled Messages To DefWindowProc
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
DWORD WINAPI OpenGLMain(LPVOID tmp)
{
MSG msg; // Windows Message Structure
BOOL done = FALSE; // Bool Variable To Exit Loop
// Ask The User Which Screen Mode They Prefer
fullscreen = FALSE; // Windowed Mode
// Create Our OpenGL Window
if (!CreateGLWindow("Alice HLT TPC CA Event Display", 1280, 1080, 32, fullscreen))
{
return 0; // Quit If Window Was Not Created
}
while (!done) // Loop That Runs While done=FALSE
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) // Is There A Message Waiting?
{
if (msg.message == WM_QUIT) // Have We Received A Quit Message?
{
done = TRUE; // If So done=TRUE
}
else // If Not, Deal With Window Messages
{
TranslateMessage(&msg); // Translate The Message
DispatchMessage(&msg); // Dispatch The Message
}
}
else // If There Are No Messages
{
// Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene()
if (active) // Program Active?
{
if (keys[VK_ESCAPE]) // Was ESC Pressed?
{
done = TRUE; // ESC Signalled A Quit
}
else // Not Time To Quit, Update Screen
{
if (animate)
{
static int nFrame = 0;
DrawGLScene(true);
char filename[16];
sprintf(filename, "video%05d.bmp", nFrame++);
unsigned char *mixBuffer = NULL;
drawClusters = nFrame < 240;
drawSeeds = nFrame >= 90 && nFrame < 210;
drawTracklets = nFrame >= 210 && nFrame < 300;
pointSize = nFrame >= 90 ? 1.0 : 2.0;
drawTracks = nFrame >= 300 && nFrame < 390;
drawFinal = nFrame >= 390;
drawGlobalTracks = nFrame >= 480;
DoScreenshot(NULL, 1, &mixBuffer);
drawClusters = nFrame < 210;
drawSeeds = nFrame > 60 && nFrame < 180;
drawTracklets = nFrame >= 180 && nFrame < 270;
pointSize = nFrame > 60 ? 1.0 : 2.0;
drawTracks = nFrame > 270 && nFrame < 360;
drawFinal = nFrame > 360;
drawGlobalTracks = nFrame > 450;
DoScreenshot(filename, 1, &mixBuffer, (float) (nFrame % 30) / 30.f);
free(mixBuffer);
printf("Wrote video frame %s\n\n", filename);
}
else
{
DrawGLScene(); // Draw The Scene
}
SwapBuffers(hDC); // Swap Buffers (Double Buffering)
}
}
/*if (keys[VK_F1]) // Is F1 Being Pressed?
{
keys[VK_F1]=FALSE; // If So Make Key FALSE
KillGLWindow(); // Kill Our Current Window
fullscreen=!fullscreen; // Toggle Fullscreen / Windowed Mode
// Recreate Our OpenGL Window
if (!CreateGLWindow("NeHe's OpenGL Framework",640,480,16,fullscreen))
{
return 0; // Quit If Window Was Not Created
}
}*/
}
}
// Shutdown
KillGLWindow(); // Kill The Window
return (msg.wParam); // Exit The Program
}
#else
void render(void);
void init(void);
int GetKey(int key)
{
int wParam = 0;
switch (key)
{
case 50:
wParam = 16;
break;
case 10:
wParam = '1';
break;
case 11:
wParam = '2';
break;
case 12:
wParam = '3';
break;
case 13:
wParam = '4';
break;
case 14:
wParam = '5';
break;
case 15:
wParam = '6';
break;
case 16:
wParam = '7';
break;
case 17:
wParam = '8';
break;
case 18:
wParam = '9';
break;
case 57:
wParam = 'N';
break;
case 24:
case 9:
wParam = 'Q';
break;
case 27:
wParam = 'R';
break;
case 65:
wParam = 13;
break;
case 25:
wParam = 'W';
break;
case 38:
wParam = 'A';
break;
case 39:
wParam = 'S';
break;
case 40:
wParam = 'D';
break;
case 26:
wParam = 'E';
break;
case 41:
wParam = 'F';
break;
case 43:
wParam = 'H';
break;
case 33:
wParam = 'P';
break;
case 32:
wParam = 'O';
break;
case 42:
wParam = 'G';
break;
case 29:
wParam = 'Z';
break;
case 28:
wParam = 'T';
break;
case 30:
wParam = 'U';
break;
case 45:
wParam = 'K';
break;
case 46:
wParam = 'L';
break;
case 53:
wParam = 'X';
break;
case 31:
wParam = 'I';
break;
case 52:
wParam = 'Y';
break;
case 35:
case 86:
wParam = 107;
break;
case 61:
case 82:
wParam = 109;
break;
}
return (wParam);
}
volatile static int needUpdate = 0;
void *OpenGLMain(void *ptr)
{
XSetWindowAttributes windowAttributes;
XVisualInfo *visualInfo = NULL;
XEvent event;
Colormap colorMap;
GLXContext glxContext;
int errorBase;
int eventBase;
// Open a connection to the X server
g_pDisplay = XOpenDisplay(NULL);
if (g_pDisplay == NULL)
{
fprintf(stderr, "glxsimple: %s\n", "could not open display");
exit(1);
}
// Make sure OpenGL's GLX extension supported
if (!glXQueryExtension(g_pDisplay, &errorBase, &eventBase))
{
fprintf(stderr, "glxsimple: %s\n", "X server has no OpenGL GLX extension");
exit(1);
}
// Find an appropriate visual
int doubleBufferVisual[] =
{
GLX_RGBA, // Needs to support OpenGL
GLX_DEPTH_SIZE, 16, // Needs to support a 16 bit depth buffer
GLX_DOUBLEBUFFER, // Needs to support double-buffering
None // end of list
};
int singleBufferVisual[] =
{
GLX_RGBA, // Needs to support OpenGL
GLX_DEPTH_SIZE, 16, // Needs to support a 16 bit depth buffer
None // end of list
};
// Try for the double-bufferd visual first
visualInfo = glXChooseVisual(g_pDisplay, DefaultScreen(g_pDisplay), doubleBufferVisual);
if (visualInfo == NULL)
{
// If we can't find a double-bufferd visual, try for a single-buffered visual...
visualInfo = glXChooseVisual(g_pDisplay, DefaultScreen(g_pDisplay), singleBufferVisual);
if (visualInfo == NULL)
{
fprintf(stderr, "glxsimple: %s\n", "no RGB visual with depth buffer");
exit(1);
}
g_bDoubleBuffered = false;
}
// Create an OpenGL rendering context
glxContext = glXCreateContext(g_pDisplay,
visualInfo,
NULL, // No sharing of display lists
GL_TRUE); // Direct rendering if possible
if (glxContext == NULL)
{
fprintf(stderr, "glxsimple: %s\n", "could not create rendering context");
exit(1);
}
// Create an X colormap since we're probably not using the default visual
colorMap = XCreateColormap(g_pDisplay,
RootWindow(g_pDisplay, visualInfo->screen),
visualInfo->visual,
AllocNone);
windowAttributes.colormap = colorMap;
windowAttributes.border_pixel = 0;
windowAttributes.event_mask = ExposureMask |
VisibilityChangeMask |
KeyPressMask |
KeyReleaseMask |
ButtonPressMask |
ButtonReleaseMask |
PointerMotionMask |
StructureNotifyMask |
SubstructureNotifyMask |
FocusChangeMask;
// Create an X window with the selected visual
g_window = XCreateWindow(g_pDisplay,
RootWindow(g_pDisplay, visualInfo->screen),
0, 0, // x/y position of top-left outside corner of the window
640, 480, // Width and height of window
0, // Border width
visualInfo->depth,
InputOutput,
visualInfo->visual,
CWBorderPixel | CWColormap | CWEventMask,
&windowAttributes);
XSetStandardProperties(g_pDisplay,
g_window,
"AliHLTTPCCA Online Event Display",
"AliHLTTPCCA Online Event Display",
None,
NULL,
0,
NULL);
// Bind the rendering context to the window
glXMakeCurrent(g_pDisplay, g_window, glxContext);
// Request the X window to be displayed on the screen
XMapWindow(g_pDisplay, g_window);
// Init OpenGL...
init();
//
// Enter the render loop and don't forget to dispatch X events as
// they occur.
//
XMapWindow(g_pDisplay, g_window);
XFlush(g_pDisplay);
int x11_fd = ConnectionNumber(g_pDisplay);
while (1)
{
int num_ready_fds;
struct timeval tv;
fd_set in_fds;
do
{
FD_ZERO(&in_fds);
FD_SET(x11_fd, &in_fds);
tv.tv_usec = 10000;
tv.tv_sec = 0;
num_ready_fds = XPending(g_pDisplay) || select(x11_fd + 1, &in_fds, NULL, NULL, &tv);
if (num_ready_fds < 0)
{
printf("Error\n");
}
else if (num_ready_fds > 0) needUpdate = 0;
if (buttonPressed == 2) break;
} while (!(num_ready_fds || needUpdate));
do
{
//XNextEvent(g_pDisplay, &event);
if (needUpdate)
{
needUpdate = 0;
event.type = Expose;
}
else
{
XNextEvent(g_pDisplay, &event);
}
if (buttonPressed == 2) break;
switch (event.type)
{
case ButtonPress:
{
if (event.xbutton.button == 1)
{
mouseDn = true;
}
if (event.xbutton.button != 1)
{
mouseDnR = true;
}
mouseDnX = event.xmotion.x;
mouseDnY = event.xmotion.y;
}
break;
case ButtonRelease:
{
if (event.xbutton.button == 1)
{
mouseDn = false;
}
if (event.xbutton.button != 1)
{
mouseDnR = false;
}
}
break;
case KeyPress:
{
int wParam = GetKey(event.xkey.keycode);
//fprintf(stderr, "KeyPress event %d --> %d (%c)\n", event.xkey.keycode, wParam, (char) wParam);
keys[wParam] = true;
}
break;
case KeyRelease:
{
int wParam = GetKey(event.xkey.keycode);
fprintf(stderr, "KeyRelease event %d -> %d (%c)\n", event.xkey.keycode, wParam, (char) wParam);
HandleKeyRelease(wParam);
}
break;
case MotionNotify:
{
mouseMvX = event.xmotion.x;
mouseMvY = event.xmotion.y;
}
break;
case Expose:
{
}
break;
case ConfigureNotify:
{
glViewport(0, 0, event.xconfigure.width, event.xconfigure.height);
ReSizeGLScene(event.xconfigure.width, event.xconfigure.height);
}
}
} while (XPending(g_pDisplay)); // Loop to compress events
if (buttonPressed == 2) break;
render();
}
return(NULL);
}
void ShowNextEvent()
{
needUpdate = 1;
}
//-----------------------------------------------------------------------------
// Name: init()
// Desc: Init OpenGL context for rendering
//-----------------------------------------------------------------------------
void init(void)
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glEnable(GL_TEXTURE_2D);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, 640.0f / 480.0f, 0.1f, 100.0f);
ReSizeGLScene(1024, 768);
}
//-----------------------------------------------------------------------------
// Name: getBitmapImageData()
// Desc: Simply image loader for 24 bit BMP files.
//-----------------------------------------------------------------------------
void render(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
DrawGLScene();
if (g_bDoubleBuffered)
glXSwapBuffers(g_pDisplay, g_window); // Buffer swap does implicit glFlush
else
glFlush(); // Explicit flush for single buffered case
}
#endif
|
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2019 *
* *
* 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 <modules/autonavigation/avoidcollisioncurve.h>
#include <modules/autonavigation/helperfunctions.h>
#include <openspace/engine/globals.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/scene/scene.h>
#include <openspace/query/query.h>
#include <ghoul/logging/logmanager.h>
#include <glm/gtx/projection.hpp>
#include <algorithm>
#include <vector>
namespace {
constexpr const char* _loggerCat = "AvoidCollisionCurve";
const double Epsilon = 1E-7;
// TODO: move this list somewhere else
const std::vector<std::string> RelevantTags{
"planet_solarSystem",
"moon_solarSystem"
// TODO
};
} // namespace
namespace openspace::autonavigation {
AvoidCollisionCurve::AvoidCollisionCurve(const Waypoint& start, const Waypoint& end) {
_points.push_back(start.position());
// Add a point to first go straight out if starting close to planet
double thresholdFactor = 3.0;
glm::dvec3 startNodePos = start.node()->worldPosition();
double startNodeRadius = start.nodeDetails.validBoundingSphere;
glm::dvec3 startNodeToStartPos = start.position() - startNodePos;
glm::dvec3 startViewDir = glm::normalize(start.rotation() * glm::dvec3(0.0, 0.0, -1.0));
if (glm::length(startNodeToStartPos) < thresholdFactor * startNodeRadius) {
double distance = startNodeRadius;
glm::dvec3 newPos = start.position() - distance * startViewDir;
_points.push_back(newPos);
}
// Add point for moving out if the end state is in opposite direction
//TODO: determine if its best to compare to end orientation or position
glm::dvec3 startToEnd = end.position() - start.position();
double cosStartAngle = glm::dot(normalize(-startViewDir), normalize(startToEnd));
if (cosStartAngle > 0.7) {
glm::dquat middleRotation = glm::slerp(start.rotation(), end.rotation(), 0.5); // OBS! Rotation method is not necessarily slerp
glm::dvec3 middleViewDir = glm::normalize(middleRotation * glm::dvec3(0.0, 0.0, -1.0));
double distance = 0.4 * glm::length(startToEnd);
glm::dvec3 newPos = start.position() + 0.2 * startToEnd - distance * middleViewDir;
_points.push_back(newPos);
}
// TODO: Add a point to approach straigt towards a specific pose near planet
// TODO: Calculate nice end pose if not defined
_points.push_back(end.position());
std::vector<SceneGraphNode*> relevantNodes = findRelevantNodes();
// Create extra points to avoid collision
removeCollisions(relevantNodes);
int nrSegments = _points.size() - 1;
// default values for the curve parameter - equally spaced
for (double t = 0.0; t <= 1.0; t += 1.0 / (double)nrSegments) {
_parameterIntervals.push_back(t);
}
_length = arcLength(1.0);
initParameterIntervals();
}
// Interpolate a list of control points and knot times
glm::dvec3 AvoidCollisionCurve::positionAt(double u) {
return interpolatePoints(u);
}
std::vector<SceneGraphNode*> AvoidCollisionCurve::findRelevantNodes() {
// TODO: make more efficient
const std::vector<SceneGraphNode*>& allNodes =
global::renderEngine.scene()->allSceneGraphNodes();
auto isRelevant = [](const SceneGraphNode* node) {
// does the node match any of the relevant tags?
const std::vector<std::string> tags = node->tags();
auto result = std::find_first_of(RelevantTags.begin(), RelevantTags.end(), tags.begin(), tags.end());
// does not match any tags => not interesting
if (result == RelevantTags.end()) {
return false;
}
return node->renderable() && (node->boundingSphere() > 0.0);
};
std::vector<SceneGraphNode*> result{};
std::copy_if(allNodes.begin(), allNodes.end(), std::back_inserter(result), isRelevant);
return result;
}
void AvoidCollisionCurve::removeCollisions(std::vector<SceneGraphNode*>& relevantNodes, int step) {
int nrSegments = _points.size() - 1;
int maxSteps = 10;
// TODO: handle better / present warning if early out
if (step > maxSteps) return;
// go through all segments and check for collisions
for (int i = 0; i < nrSegments; ++i) {
const glm::dvec3 lineStart = _points[i];
const glm::dvec3 lineEnd = _points[i + 1];
for (SceneGraphNode* node : relevantNodes) {
// do collision check in relative coordinates, to avoid huge numbers
const glm::dmat4 modelTransform = node->modelTransform();
glm::dvec3 p1 = glm::inverse(modelTransform) * glm::dvec4(lineStart, 1.0);
glm::dvec3 p2 = glm::inverse(modelTransform) * glm::dvec4(lineEnd, 1.0);
// sphere to check for collision
double bs = node->boundingSphere();
double radius = bs;
// TODO: add a buffer (i.e. sue a little larger sphere), when we have
// behaviour for leaving a target. Don't want to pass too close to objects
glm::dvec3 center = glm::dvec3(0.0, 0.0, 0.0);
glm::dvec3 point;
bool collision = helpers::lineSphereIntersection(p1, p2, center, radius, point);
// convert back to world coordinates
glm::dvec3 pointWorld = modelTransform * glm::dvec4(point, 1.0);
if (collision) {
LINFO(fmt::format("Collision with node: {}!", node->identifier()));
// to avoid collision, take a step in an orhtogonal direction of the
// collision point and add a new point
glm::dvec3 lineDir = glm::normalize(lineEnd - lineStart);
glm::dvec3 nodePos = node->worldPosition();
glm::dvec3 collisionPointToCenter = nodePos - pointWorld;
glm::dvec3 parallell = glm::proj(collisionPointToCenter, lineDir);
glm::dvec3 orthogonal = collisionPointToCenter - parallell;
double distance = 3.0 * radius;
glm::dvec3 extraKnot = pointWorld - distance * glm::normalize(orthogonal);
_points.insert(_points.begin() + i + 1, extraKnot);
// TODO: maybe make this more efficient, and make sure that we have a base case.
removeCollisions(relevantNodes, ++step);
break;
}
}
}
}
// compute curve parameter intervals based on relative arc length
void AvoidCollisionCurve::initParameterIntervals() {
std::vector<double> newIntervals;
int nrSegments = _points.size() - 1;
for (double t = 0.0; t <= 1.0; t += 1.0 / (double)nrSegments) {
newIntervals.push_back(arcLength(t) / _length);
}
_parameterIntervals.swap(newIntervals);
}
// Catmull-Rom inspired interpolation of the curve points
glm::dvec3 AvoidCollisionCurve::interpolatePoints(double u)
{
ghoul_assert(_points.size() == _parameterIntervals.size(),
"Must have equal number of points and times!");
ghoul_assert(_points.size() > 2, "Minimum of two control points needed for interpolation!");
size_t nrSegments = _points.size() - 1;
const glm::dvec3 start = _points.front();
const glm::dvec3 end = _points.back();
if (u <= 0.0) return _points.front();
if (u >= 1.0) return _points.back();
if (nrSegments == 1) {
return roundedSpline(u, start, start, end, end);
}
// compute current segment index
std::vector<double>::const_iterator segmentEndIt =
std::lower_bound(_parameterIntervals.begin(), _parameterIntervals.end(), u);
unsigned int idx = (segmentEndIt - 1) - _parameterIntervals.begin();
double segmentStart = _parameterIntervals[idx];
double segmentDuration = (_parameterIntervals[idx + 1] - _parameterIntervals[idx]);
double tScaled = (u - segmentStart) / segmentDuration;
glm::dvec3 first = (idx == 0) ? start : _points[idx - 1];
glm::dvec3 last = (idx == (nrSegments - 1)) ? end : _points[idx + 2];
return roundedSpline(tScaled, first, _points[idx], _points[idx + 1], last);
}
glm::dvec3 AvoidCollisionCurve::roundedSpline(double t, const glm::dvec3 &a,
const glm::dvec3 &b, const glm::dvec3 &c, const glm::dvec3 &d)
{
ghoul_assert(t >= 0 && t <= 1.0, "Interpolation variable out of range [0, 1]");
if (t <= 0.0) return b;
if (t >= 1.0) return c;
auto isNormalizable = [](const glm::dvec3 v) {
return !(abs(glm::length(v)) < Epsilon);
};
// find velocities at b and c
glm::dvec3 cb = c - b;
glm::dvec3 bc = -cb;
if (!isNormalizable(cb)) {
return b;
}
glm::dvec3 ab = a - b;
// a and b are the same point
if (!isNormalizable(ab)) {
ab = bc;
}
glm::dvec3 bVelocity = glm::normalize(cb) - glm::normalize(ab);
bVelocity = isNormalizable(bVelocity) ?
glm::normalize(bVelocity) : glm::dvec3(0.0, 1.0, 0.0);
glm::dvec3 dc = d - c;
// d and c are the same point
if (!isNormalizable(dc)) {
dc = cb;
}
glm::dvec3 cVelocity = glm::normalize(dc) - glm::normalize(bc);
cVelocity = isNormalizable(cVelocity) ?
glm::normalize(cVelocity) : glm::dvec3(0.0, 1.0, 0.0);
double cbDistance = glm::length(cb);
double tangetLength = cbDistance;
// Distances in space can be extremely large, so we dont want the tangents to always have the full length.
const double tangentlengthThreshold = 1E10; // TODO: What's a good threshold?? ALSO make global
if (tangetLength > tangentlengthThreshold)
tangetLength = tangentlengthThreshold;
// the resulting curve gets much better and more predictable when using a genric
// hermite curve compared to the Catmull Rom implementation
return interpolation::hermite(t, b, c, bVelocity * tangetLength, cVelocity * tangetLength);
//return interpolation::catmullRom(t, b - bVelocity * cbDistance, b, c, c + cVelocity * cbDistance);
}
} // namespace openspace::autonavigation
Use rounded catmull-rom interpolatior instead
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2019 *
* *
* 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 <modules/autonavigation/avoidcollisioncurve.h>
#include <modules/autonavigation/helperfunctions.h>
#include <openspace/engine/globals.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/scene/scene.h>
#include <openspace/query/query.h>
#include <ghoul/logging/logmanager.h>
#include <glm/gtx/projection.hpp>
#include <algorithm>
#include <vector>
namespace {
constexpr const char* _loggerCat = "AvoidCollisionCurve";
const double Epsilon = 1E-7;
// TODO: move this list somewhere else
const std::vector<std::string> RelevantTags{
"planet_solarSystem",
"moon_solarSystem"
// TODO
};
} // namespace
namespace openspace::autonavigation {
AvoidCollisionCurve::AvoidCollisionCurve(const Waypoint& start, const Waypoint& end) {
double thresholdFactor = 3.0;
glm::dvec3 startNodePos = start.node()->worldPosition();
glm::dvec3 endNodePos = end.node()->worldPosition();
double startNodeRadius = start.nodeDetails.validBoundingSphere;
glm::dvec3 startNodeToStartPos = start.position() - startNodePos;
glm::dvec3 startViewDir = glm::normalize(start.rotation() * glm::dvec3(0.0, 0.0, -1.0));
// Add control points for a catmull-rom spline, first and last will no be intersected
// TODO: test other first and last control points, ex positive or negative view dir
_points.push_back(startNodePos);
_points.push_back(start.position());
// Add an extra point to first go backwards if starting close to planet
if (glm::length(startNodeToStartPos) < thresholdFactor * startNodeRadius) {
double distance = startNodeRadius;
glm::dvec3 newPos = start.position() - distance * startViewDir;
_points.push_back(newPos);
}
// Add point for moving out if the end state is in opposite direction
//TODO: determine if its best to compare to end orientation or position
glm::dvec3 startToEnd = end.position() - start.position();
double cosStartAngle = glm::dot(normalize(-startViewDir), normalize(startToEnd));
if (cosStartAngle > 0.7) {
glm::dquat middleRotation = glm::slerp(start.rotation(), end.rotation(), 0.5); // OBS! Rotation method is not necessarily slerp
glm::dvec3 middleViewDir = glm::normalize(middleRotation * glm::dvec3(0.0, 0.0, -1.0));
double distance = 0.4 * glm::length(startToEnd);
glm::dvec3 newPos = start.position() + 0.2 * startToEnd - distance * middleViewDir;
_points.push_back(newPos);
}
// TODO: Add a point to approach straigt towards a specific pose near planet
// TODO: Calculate nice end pose if not defined
_points.push_back(end.position());
_points.push_back(endNodePos);
std::vector<SceneGraphNode*> relevantNodes = findRelevantNodes();
// Create extra points to avoid collision
removeCollisions(relevantNodes);
int nrSegments = _points.size() - 3;
// default values for the curve parameter - equally spaced
for (double t = 0.0; t <= 1.0; t += 1.0 / (double)nrSegments) {
_parameterIntervals.push_back(t);
}
_length = arcLength(1.0);
initParameterIntervals();
}
// Interpolate a list of control points and knot times
glm::dvec3 AvoidCollisionCurve::positionAt(double u) {
if (u < 0.000001)
return _points[1];
if (u > 0.999999)
return *(_points.end() - 2);
//distribute t by segment arc lenghts
// compute current segment, by first finding iterator to the first value that is larger than t
std::vector<double>::iterator segmentEndIt =
std::lower_bound(_parameterIntervals.begin(), _parameterIntervals.end(), u);
unsigned int idx = (segmentEndIt - 1) - _parameterIntervals.begin();
double segmentStart = _parameterIntervals[idx];
double segmentDuration = (_parameterIntervals[idx + 1] - _parameterIntervals[idx]);
double uSegment = (u - segmentStart) / segmentDuration;
return interpolation::catmullRom(uSegment, _points[idx], _points[idx + 1], _points[idx + 2], _points[idx + 3], 1.0);
// return interpolatePoints(u);
}
std::vector<SceneGraphNode*> AvoidCollisionCurve::findRelevantNodes() {
// TODO: make more efficient
const std::vector<SceneGraphNode*>& allNodes =
global::renderEngine.scene()->allSceneGraphNodes();
auto isRelevant = [](const SceneGraphNode* node) {
// does the node match any of the relevant tags?
const std::vector<std::string> tags = node->tags();
auto result = std::find_first_of(RelevantTags.begin(), RelevantTags.end(), tags.begin(), tags.end());
// does not match any tags => not interesting
if (result == RelevantTags.end()) {
return false;
}
return node->renderable() && (node->boundingSphere() > 0.0);
};
std::vector<SceneGraphNode*> result{};
std::copy_if(allNodes.begin(), allNodes.end(), std::back_inserter(result), isRelevant);
return result;
}
void AvoidCollisionCurve::removeCollisions(std::vector<SceneGraphNode*>& relevantNodes, int step) {
int nrSegments = _points.size() - 3;
int maxSteps = 10;
// TODO: handle better / present warning if early out
if (step > maxSteps) return;
// go through all segments and check for collisions
for (int i = 0; i < nrSegments; ++i) {
const glm::dvec3 lineStart = _points[i + 1];
const glm::dvec3 lineEnd = _points[i + 2];
for (SceneGraphNode* node : relevantNodes) {
// do collision check in relative coordinates, to avoid huge numbers
const glm::dmat4 modelTransform = node->modelTransform();
glm::dvec3 p1 = glm::inverse(modelTransform) * glm::dvec4(lineStart, 1.0);
glm::dvec3 p2 = glm::inverse(modelTransform) * glm::dvec4(lineEnd, 1.0);
// sphere to check for collision
double bs = node->boundingSphere();
double radius = bs;
// TODO: add a buffer (i.e. sue a little larger sphere), when we have
// behaviour for leaving a target. Don't want to pass too close to objects
glm::dvec3 center = glm::dvec3(0.0, 0.0, 0.0);
glm::dvec3 point;
bool collision = helpers::lineSphereIntersection(p1, p2, center, radius, point);
// convert back to world coordinates
glm::dvec3 pointWorld = modelTransform * glm::dvec4(point, 1.0);
if (collision) {
LINFO(fmt::format("Collision with node: {}!", node->identifier()));
// to avoid collision, take a step in an orhtogonal direction of the
// collision point and add a new point
glm::dvec3 lineDir = glm::normalize(lineEnd - lineStart);
glm::dvec3 nodePos = node->worldPosition();
glm::dvec3 collisionPointToCenter = nodePos - pointWorld;
glm::dvec3 parallell = glm::proj(collisionPointToCenter, lineDir);
glm::dvec3 orthogonal = collisionPointToCenter - parallell;
double distance = 3.0 * radius;
glm::dvec3 extraKnot = pointWorld - distance * glm::normalize(orthogonal);
_points.insert(_points.begin() + i + 2, extraKnot);
// TODO: maybe make this more efficient, and make sure that we have a base case.
removeCollisions(relevantNodes, ++step);
break;
}
}
}
}
// compute curve parameter intervals based on relative arc length
void AvoidCollisionCurve::initParameterIntervals() {
std::vector<double> newIntervals;
int nrSegments = _points.size() - 3;
for (double t = 0.0; t <= 1.0; t += 1.0 / (double)nrSegments) {
newIntervals.push_back(arcLength(t) / _length);
}
_parameterIntervals.swap(newIntervals);
}
} // namespace openspace::autonavigation
|
/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin-server.
*
* libbitcoin-server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <bitcoin/server/workers/notification_worker.hpp>
#include <algorithm>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <bitcoin/protocol.hpp>
#include <bitcoin/server/messages/message.hpp>
#include <bitcoin/server/messages/route.hpp>
#include <bitcoin/server/server_node.hpp>
#include <bitcoin/server/services/query_service.hpp>
#include <bitcoin/server/settings.hpp>
#include <bitcoin/server/utility/fetch_helpers.hpp>
namespace libbitcoin {
namespace server {
#define NAME "notification_worker"
using namespace std::placeholders;
using namespace bc::chain;
using namespace bc::protocol;
using namespace bc::wallet;
// Purge subscriptions at 10% of the expiration period.
static constexpr int64_t purge_interval_ratio = 10;
// Notifications respond with commands that are distinct from the subscription.
static const std::string address_update("address.update");
static const std::string address_stealth("address.stealth_update");
static const std::string address_update2("address.update2");
static const std::string penetration_update("penetration.update");
notification_worker::notification_worker(zmq::authenticator& authenticator,
server_node& node, bool secure)
: worker(node.thread_pool()),
secure_(secure),
settings_(node.server_settings()),
node_(node),
authenticator_(authenticator),
payment_subscriber_(std::make_shared<payment_subscriber>(
node.thread_pool(), settings_.subscription_limit, NAME "_payment")),
stealth_subscriber_(std::make_shared<stealth_subscriber>(
node.thread_pool(), settings_.subscription_limit, NAME "_stealth")),
address_subscriber_(std::make_shared<address_subscriber>(
node.thread_pool(), settings_.subscription_limit, NAME "_address")),
penetration_subscriber_(std::make_shared<penetration_subscriber>(
node.thread_pool(), settings_.subscription_limit, NAME "_penetration"))
{
}
// There is no unsubscribe so this class shouldn't be restarted.
bool notification_worker::start()
{
// v2/v3 (deprecated)
payment_subscriber_->start();
stealth_subscriber_->start();
// v3
address_subscriber_->start();
penetration_subscriber_->start();
// Subscribe to blockchain reorganizations.
node_.subscribe_blockchain(
std::bind(¬ification_worker::handle_blockchain_reorganization,
this, _1, _2, _3, _4));
// Subscribe to transaction pool acceptances.
node_.subscribe_transaction_pool(
std::bind(¬ification_worker::handle_transaction_pool,
this, _1, _2, _3));
// Subscribe to all inventory messages from all peers.
node_.subscribe<bc::message::inventory>(
std::bind(¬ification_worker::handle_inventory,
this, _1, _2));
return zmq::worker::start();
}
// No unsubscribe so must be kept in scope until subscriber stop complete.
bool notification_worker::stop()
{
static const auto code = error::channel_stopped;
// v2/v3 (deprecated)
payment_subscriber_->stop();
payment_subscriber_->invoke(code, {}, 0, {}, {});
stealth_subscriber_->stop();
stealth_subscriber_->invoke(code, 0, 0, {}, {});
// v3
address_subscriber_->stop();
address_subscriber_->invoke(code, {}, 0, {}, {});
penetration_subscriber_->stop();
penetration_subscriber_->invoke(code, 0, {}, {});
return zmq::worker::stop();
}
// Implement worker as a router to the query service.
// The notification worker receives no messages from the query service.
void notification_worker::work()
{
zmq::socket router(authenticator_, zmq::socket::role::router);
// Connect socket to the service endpoint.
if (!started(connect(router)))
return;
zmq::poller poller;
poller.add(router);
const auto interval = purge_interval_milliseconds();
// We do not send/receive on the poller, we use its timer and context stop.
// Other threads connect and disconnect dynamically to send updates.
while (!poller.terminated() && !stopped())
{
// BUGBUG: this can fail on some platforms if interval is > 1000.
poller.wait(interval);
purge();
}
// Disconnect the socket and exit this thread.
finished(disconnect(router));
}
int32_t notification_worker::purge_interval_milliseconds() const
{
const int64_t minutes = settings_.subscription_expiration_minutes;
const int64_t milliseconds = minutes * 60 * 1000 / purge_interval_ratio;
const auto capped = std::max(milliseconds, static_cast<int64_t>(max_int32));
return static_cast<int32_t>(capped);
}
// Connect/Disconnect.
//-----------------------------------------------------------------------------
bool notification_worker::connect(socket& router)
{
const auto security = secure_ ? "secure" : "public";
const auto& endpoint = secure_ ? query_service::secure_notify :
query_service::public_notify;
const auto ec = router.connect(endpoint);
if (ec)
{
log::error(LOG_SERVER)
<< "Failed to connect " << security << " notification worker to "
<< endpoint << " : " << ec.message();
return false;
}
log::debug(LOG_SERVER)
<< "Connected " << security << " notification worker to " << endpoint;
return true;
}
bool notification_worker::disconnect(socket& router)
{
const auto security = secure_ ? "secure" : "public";
// Don't log stop success.
if (router.stop())
return true;
log::error(LOG_SERVER)
<< "Failed to disconnect " << security << " notification worker.";
return false;
}
// Pruning.
// ----------------------------------------------------------------------------
// Signal expired subscriptions to self-remove.
void notification_worker::purge()
{
static const auto code = error::channel_timeout;
// v2/v3 (deprecated)
payment_subscriber_->purge(code, {}, 0, {}, {});
stealth_subscriber_->purge(code, 0, 0, {}, {});
// v3
address_subscriber_->purge(code, {}, 0, {}, {});
penetration_subscriber_->purge(code, 0, {}, {});
}
// Sending.
// ----------------------------------------------------------------------------
void notification_worker::send(const route& reply_to,
const std::string& command, uint32_t id, const data_chunk& payload)
{
const auto security = secure_ ? "secure" : "public";
const auto& endpoint = secure_ ? query_service::secure_notify :
query_service::public_notify;
zmq::socket notifier(authenticator_, zmq::socket::role::router);
auto ec = notifier.connect(endpoint);
if (ec == error::service_stopped)
return;
if (ec)
{
log::warning(LOG_SERVER)
<< "Failed to connect " << security << " notification worker: "
<< ec.message();
return;
}
// Notifications are formatted as query response messages.
message notification(reply_to, command, id, payload);
ec = notification.send(notifier);
if (ec && ec != error::service_stopped)
log::warning(LOG_SERVER)
<< "Failed to send notification to "
<< notification.route().display() << " " << ec.message();
}
void notification_worker::send_payment(const route& reply_to, uint32_t id,
const wallet::payment_address& address, uint32_t height,
const hash_digest& block_hash, const chain::transaction& tx)
{
// [ address.version:1 ]
// [ address.hash:20 ]
// [ height:4 ]
// [ block_hash:32 ]
// [ tx:... ]
const auto payload = build_chunk(
{
to_array(address.version()),
address.hash(),
to_little_endian(height),
block_hash,
tx.to_data()
});
send(reply_to, address_update, id, payload);
}
void notification_worker::send_stealth(const route& reply_to, uint32_t id,
uint32_t prefix, uint32_t height, const hash_digest& block_hash,
const chain::transaction& tx)
{
// [ prefix:4 ]
// [ height:4 ]
// [ block_hash:32 ]
// [ tx:... ]
const auto payload = build_chunk(
{
to_little_endian(prefix),
to_little_endian(height),
block_hash,
tx.to_data()
});
send(reply_to, address_stealth, id, payload);
}
void notification_worker::send_address(const route& reply_to, uint32_t id,
uint8_t sequence, uint32_t height, const hash_digest& block_hash,
const chain::transaction& tx)
{
// [ code:4 ]
// [ sequence:1 ]
// [ height:4 ]
// [ block_hash:32 ]
// [ tx:... ]
const auto payload = build_chunk(
{
message::to_bytes(error::success),
to_array(sequence),
to_little_endian(height),
block_hash,
tx.to_data()
});
send(reply_to, address_update2, id, payload);
}
// Handlers.
// ----------------------------------------------------------------------------
bool notification_worker::handle_payment(const code& ec,
const payment_address& address, uint32_t height,
const hash_digest& block_hash, const chain::transaction& tx,
const route& reply_to, uint32_t id, const binary& prefix_filter)
{
if (ec)
{
send(reply_to, address_update, id, message::to_bytes(ec));
return false;
}
if (prefix_filter.is_prefix_of(address.hash()))
send_payment(reply_to, id, address, height, block_hash, tx);
return true;
}
bool notification_worker::handle_stealth(const code& ec,
uint32_t prefix, uint32_t height, const hash_digest& block_hash,
const chain::transaction& tx, const route& reply_to, uint32_t id,
const binary& prefix_filter)
{
if (ec)
{
send(reply_to, address_stealth, id, message::to_bytes(ec));
return false;
}
if (prefix_filter.is_prefix_of(prefix))
send_stealth(reply_to, id, prefix, height, block_hash, tx);
return true;
}
bool notification_worker::handle_address(const code& ec,
const binary& field, uint32_t height, const hash_digest& block_hash,
const chain::transaction& tx, const route& reply_to, uint32_t id,
const binary& prefix_filter, sequence_ptr sequence)
{
if (ec)
{
send(reply_to, address_update2, id, message::to_bytes(ec));
return false;
}
if (prefix_filter.is_prefix_of(field))
{
send_address(reply_to, id, *sequence, height, block_hash, tx);
++(*sequence);
}
return true;
}
// Subscribers.
// ----------------------------------------------------------------------------
// Subscribe to address and stealth prefix notifications.
// Each delegate must connect to the appropriate query notification endpoint.
void notification_worker::subscribe_address(const route& reply_to, uint32_t id,
const binary& prefix_filter, subscribe_type type)
{
static const auto error_code = error::channel_stopped;
const auto& duration = settings_.subscription_expiration();
const address_key key(reply_to, prefix_filter);
switch (type)
{
// v2/v3 (deprecated)
case subscribe_type::payment:
{
// This class must be kept in scope until work is terminated.
const auto handler =
std::bind(¬ification_worker::handle_payment,
this, _1, _2, _3, _4, _5, reply_to, id, prefix_filter);
payment_subscriber_->subscribe(handler, key, duration, error_code,
{}, 0, {}, {});
break;
}
// v2/v3 (deprecated)
case subscribe_type::stealth:
{
// This class must be kept in scope until work is terminated.
const auto handler =
std::bind(¬ification_worker::handle_stealth,
this, _1, _2, _3, _4, _5, reply_to, id, prefix_filter);
stealth_subscriber_->subscribe(handler, key, duration, error_code,
0, 0, {}, {});
break;
}
// v3
case subscribe_type::unspecified:
{
// The sequence enables the client to detect dropped messages.
const auto sequence = std::make_shared<uint8_t>(0);
// This class must be kept in scope until work is terminated.
const auto handler =
std::bind(¬ification_worker::handle_address,
this, _1, _2, _3, _4, _5, reply_to, id, prefix_filter,
sequence);
// v3
address_subscriber_->subscribe(handler, key, duration, error_code,
{}, 0, {}, {});
break;
}
// v3
default:
case subscribe_type::unsubscribe:
{
// Just as with an expiration (purge) this will cause the stored
// handler (notification_worker::handle_address) to be invoked but
// with the specified error code (error::channel_stopped) as
// opposed to error::channel_timeout.
// v3
address_subscriber_->unsubscribe(key, error_code, {}, 0, {}, {});
break;
}
}
}
// Subscribe to transaction penetration notifications.
// Each delegate must connect to the appropriate query notification endpoint.
void notification_worker::subscribe_penetration(const route& reply_to,
uint32_t id, const hash_digest& tx_hash)
{
// TODO:
// Height and hash are zeroized if tx is not chained (inv/mempool).
// If chained or penetration is 100 (percent) drop subscription.
// Only send messages at configured thresholds (e.g. 20/40/60/80/100%).
// Thresholding allows the server to mask its peer count.
// Penetration is computed by the relay handler.
// No sequence is required because gaps are okay.
// [ tx_hash:32 ]
// [ penetration:1 ]
// [ height:4 ]
// [ block_hash:32 ]
////penetration_subscriber_->subscribe();
}
// Notification (via blockchain).
// ----------------------------------------------------------------------------
bool notification_worker::handle_blockchain_reorganization(const code& ec,
uint64_t fork_point, const block_list& new_blocks, const block_list&)
{
if (stopped() || ec == error::service_stopped)
return false;
if (ec)
{
log::warning(LOG_SERVER)
<< "Failure handling new block: " << ec.message();
// Don't let a failure here prevent prevent future notifications.
return true;
}
// Blockchain height is 64 bit but obelisk protocol is 32 bit.
BITCOIN_ASSERT(fork_point <= max_uint32);
const auto fork_point32 = static_cast<uint32_t>(fork_point);
notify_blocks(fork_point32, new_blocks);
return true;
}
void notification_worker::notify_blocks(uint32_t fork_point,
const block_list& blocks)
{
if (stopped())
return;
const auto security = secure_ ? "secure" : "public";
const auto& endpoint = secure_ ? block_service::secure_worker :
block_service::public_worker;
// Notifications are off the pub-sub thread so this must connect back.
// This could be optimized by caching the socket as thread static.
zmq::socket publisher(authenticator_, zmq::socket::role::publisher);
const auto ec = publisher.connect(endpoint);
if (ec == error::service_stopped)
return;
if (ec)
{
log::warning(LOG_SERVER)
<< "Failed to connect " << security << " block worker: "
<< ec.message();
return;
}
BITCOIN_ASSERT(blocks.size() <= max_uint32);
BITCOIN_ASSERT(fork_point < max_uint32 - blocks.size());
auto height = fork_point;
for (const auto block: blocks)
notify_block(publisher, height++, block);
}
void notification_worker::notify_block(zmq::socket& publisher, uint32_t height,
const block::ptr block)
{
if (stopped())
return;
const auto block_hash = block->header.hash();
for (const auto& tx: block->transactions)
{
const auto tx_hash = tx.hash();
notify_transaction(height, block_hash, tx);
notify_penetration(height, block_hash, tx_hash);
}
}
// Notification (via transaction inventory).
// ----------------------------------------------------------------------------
// This relies on peers always notifying us of new txs via inv messages.
bool notification_worker::handle_inventory(const code& ec,
const bc::message::inventory::ptr packet)
{
if (stopped() || ec == error::service_stopped)
return false;
if (ec)
{
log::warning(LOG_SERVER)
<< "Failure handling inventory: " << ec.message();
// Don't let a failure here prevent prevent future notifications.
return true;
}
// Loop inventories and extract transaction hashes.
for (const auto& inventory: packet->inventories)
if (inventory.is_transaction_type())
notify_penetration(0, null_hash, inventory.hash);
return true;
}
// Notification (via mempool).
// ----------------------------------------------------------------------------
bool notification_worker::handle_transaction_pool(const code& ec,
const point::indexes&, bc::message::transaction_message::ptr tx)
{
if (stopped() || ec == error::service_stopped)
return false;
if (ec)
{
log::warning(LOG_SERVER)
<< "Failure handling new transaction: " << ec.message();
// Don't let a failure here prevent future notifications.
return true;
}
notify_transaction(0, null_hash, *tx);
return true;
}
// This parsing is duplicated by bc::database::data_base.
void notification_worker::notify_transaction(uint32_t height,
const hash_digest& block_hash, const transaction& tx)
{
uint32_t prefix;
// TODO: move full integer and array constructors into binary.
static constexpr size_t prefix_bits = sizeof(prefix) * byte_bits;
static constexpr size_t address_bits = short_hash_size * byte_bits;
if (stopped() || tx.outputs.empty())
return;
// see data_base::push_inputs
// Loop inputs and extract payment addresses.
for (const auto& input: tx.inputs)
{
const auto address = payment_address::extract(input.script);
if (address)
{
const binary field(address_bits, address.hash());
notify_address(field, height, block_hash, tx);
notify_payment(address, height, block_hash, tx);
}
}
// see data_base::push_outputs
// Loop outputs and extract payment addresses.
for (const auto& output: tx.outputs)
{
const auto address = payment_address::extract(output.script);
if (address)
{
const binary field(address_bits, address.hash());
notify_address(field, height, block_hash, tx);
notify_payment(address, height, block_hash, tx);
}
}
// see data_base::push_stealth
// Loop output pairs and extract stealth payments.
for (size_t index = 0; index < (tx.outputs.size() - 1); ++index)
{
const auto& ephemeral_script = tx.outputs[index].script;
const auto& payment_script = tx.outputs[index + 1].script;
// Try to extract a stealth prefix from the first output.
// Try to extract the payment address from the second output.
if (to_stealth_prefix(prefix, ephemeral_script) &&
payment_address::extract(payment_script))
{
const binary field(prefix_bits, to_little_endian(prefix));
notify_address(field, height, block_hash, tx);
notify_stealth(prefix, height, block_hash, tx);
}
}
}
// v2/v3 (deprecated)
void notification_worker::notify_payment(const payment_address& address,
uint32_t height, const hash_digest& block_hash, const transaction& tx)
{
static const auto code = error::success;
payment_subscriber_->relay(code, address, height, block_hash, tx);
}
// v2/v3 (deprecated)
void notification_worker::notify_stealth(uint32_t prefix, uint32_t height,
const hash_digest& block_hash, const transaction& tx)
{
static const auto code = error::success;
stealth_subscriber_->relay(code, prefix, height, block_hash, tx);
}
// v3
void notification_worker::notify_address(const binary& field, uint32_t height,
const hash_digest& block_hash, const transaction& tx)
{
static const auto code = error::success;
address_subscriber_->relay(code, field, height, block_hash, tx);
}
// v3.x
void notification_worker::notify_penetration(uint32_t height,
const hash_digest& block_hash, const hash_digest& tx_hash)
{
static const auto code = error::success;
penetration_subscriber_->relay(code, height, block_hash, tx_hash);
}
} // namespace server
} // namespace libbitcoin
Fix log text typo in notification_worker.
/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin-server.
*
* libbitcoin-server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <bitcoin/server/workers/notification_worker.hpp>
#include <algorithm>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <bitcoin/protocol.hpp>
#include <bitcoin/server/messages/message.hpp>
#include <bitcoin/server/messages/route.hpp>
#include <bitcoin/server/server_node.hpp>
#include <bitcoin/server/services/query_service.hpp>
#include <bitcoin/server/settings.hpp>
#include <bitcoin/server/utility/fetch_helpers.hpp>
namespace libbitcoin {
namespace server {
#define NAME "notification_worker"
using namespace std::placeholders;
using namespace bc::chain;
using namespace bc::protocol;
using namespace bc::wallet;
// Purge subscriptions at 10% of the expiration period.
static constexpr int64_t purge_interval_ratio = 10;
// Notifications respond with commands that are distinct from the subscription.
static const std::string address_update("address.update");
static const std::string address_stealth("address.stealth_update");
static const std::string address_update2("address.update2");
static const std::string penetration_update("penetration.update");
notification_worker::notification_worker(zmq::authenticator& authenticator,
server_node& node, bool secure)
: worker(node.thread_pool()),
secure_(secure),
settings_(node.server_settings()),
node_(node),
authenticator_(authenticator),
payment_subscriber_(std::make_shared<payment_subscriber>(
node.thread_pool(), settings_.subscription_limit, NAME "_payment")),
stealth_subscriber_(std::make_shared<stealth_subscriber>(
node.thread_pool(), settings_.subscription_limit, NAME "_stealth")),
address_subscriber_(std::make_shared<address_subscriber>(
node.thread_pool(), settings_.subscription_limit, NAME "_address")),
penetration_subscriber_(std::make_shared<penetration_subscriber>(
node.thread_pool(), settings_.subscription_limit, NAME "_penetration"))
{
}
// There is no unsubscribe so this class shouldn't be restarted.
bool notification_worker::start()
{
// v2/v3 (deprecated)
payment_subscriber_->start();
stealth_subscriber_->start();
// v3
address_subscriber_->start();
penetration_subscriber_->start();
// Subscribe to blockchain reorganizations.
node_.subscribe_blockchain(
std::bind(¬ification_worker::handle_blockchain_reorganization,
this, _1, _2, _3, _4));
// Subscribe to transaction pool acceptances.
node_.subscribe_transaction_pool(
std::bind(¬ification_worker::handle_transaction_pool,
this, _1, _2, _3));
// Subscribe to all inventory messages from all peers.
node_.subscribe<bc::message::inventory>(
std::bind(¬ification_worker::handle_inventory,
this, _1, _2));
return zmq::worker::start();
}
// No unsubscribe so must be kept in scope until subscriber stop complete.
bool notification_worker::stop()
{
static const auto code = error::channel_stopped;
// v2/v3 (deprecated)
payment_subscriber_->stop();
payment_subscriber_->invoke(code, {}, 0, {}, {});
stealth_subscriber_->stop();
stealth_subscriber_->invoke(code, 0, 0, {}, {});
// v3
address_subscriber_->stop();
address_subscriber_->invoke(code, {}, 0, {}, {});
penetration_subscriber_->stop();
penetration_subscriber_->invoke(code, 0, {}, {});
return zmq::worker::stop();
}
// Implement worker as a router to the query service.
// The notification worker receives no messages from the query service.
void notification_worker::work()
{
zmq::socket router(authenticator_, zmq::socket::role::router);
// Connect socket to the service endpoint.
if (!started(connect(router)))
return;
zmq::poller poller;
poller.add(router);
const auto interval = purge_interval_milliseconds();
// We do not send/receive on the poller, we use its timer and context stop.
// Other threads connect and disconnect dynamically to send updates.
while (!poller.terminated() && !stopped())
{
// BUGBUG: this can fail on some platforms if interval is > 1000.
poller.wait(interval);
purge();
}
// Disconnect the socket and exit this thread.
finished(disconnect(router));
}
int32_t notification_worker::purge_interval_milliseconds() const
{
const int64_t minutes = settings_.subscription_expiration_minutes;
const int64_t milliseconds = minutes * 60 * 1000 / purge_interval_ratio;
const auto capped = std::max(milliseconds, static_cast<int64_t>(max_int32));
return static_cast<int32_t>(capped);
}
// Connect/Disconnect.
//-----------------------------------------------------------------------------
bool notification_worker::connect(socket& router)
{
const auto security = secure_ ? "secure" : "public";
const auto& endpoint = secure_ ? query_service::secure_notify :
query_service::public_notify;
const auto ec = router.connect(endpoint);
if (ec)
{
log::error(LOG_SERVER)
<< "Failed to connect " << security << " notification worker to "
<< endpoint << " : " << ec.message();
return false;
}
log::debug(LOG_SERVER)
<< "Connected " << security << " notification worker to " << endpoint;
return true;
}
bool notification_worker::disconnect(socket& router)
{
const auto security = secure_ ? "secure" : "public";
// Don't log stop success.
if (router.stop())
return true;
log::error(LOG_SERVER)
<< "Failed to disconnect " << security << " notification worker.";
return false;
}
// Pruning.
// ----------------------------------------------------------------------------
// Signal expired subscriptions to self-remove.
void notification_worker::purge()
{
static const auto code = error::channel_timeout;
// v2/v3 (deprecated)
payment_subscriber_->purge(code, {}, 0, {}, {});
stealth_subscriber_->purge(code, 0, 0, {}, {});
// v3
address_subscriber_->purge(code, {}, 0, {}, {});
penetration_subscriber_->purge(code, 0, {}, {});
}
// Sending.
// ----------------------------------------------------------------------------
void notification_worker::send(const route& reply_to,
const std::string& command, uint32_t id, const data_chunk& payload)
{
const auto security = secure_ ? "secure" : "public";
const auto& endpoint = secure_ ? query_service::secure_notify :
query_service::public_notify;
zmq::socket notifier(authenticator_, zmq::socket::role::router);
auto ec = notifier.connect(endpoint);
if (ec == error::service_stopped)
return;
if (ec)
{
log::warning(LOG_SERVER)
<< "Failed to connect " << security << " notification worker: "
<< ec.message();
return;
}
// Notifications are formatted as query response messages.
message notification(reply_to, command, id, payload);
ec = notification.send(notifier);
if (ec && ec != error::service_stopped)
log::warning(LOG_SERVER)
<< "Failed to send notification to "
<< notification.route().display() << " " << ec.message();
}
void notification_worker::send_payment(const route& reply_to, uint32_t id,
const wallet::payment_address& address, uint32_t height,
const hash_digest& block_hash, const chain::transaction& tx)
{
// [ address.version:1 ]
// [ address.hash:20 ]
// [ height:4 ]
// [ block_hash:32 ]
// [ tx:... ]
const auto payload = build_chunk(
{
to_array(address.version()),
address.hash(),
to_little_endian(height),
block_hash,
tx.to_data()
});
send(reply_to, address_update, id, payload);
}
void notification_worker::send_stealth(const route& reply_to, uint32_t id,
uint32_t prefix, uint32_t height, const hash_digest& block_hash,
const chain::transaction& tx)
{
// [ prefix:4 ]
// [ height:4 ]
// [ block_hash:32 ]
// [ tx:... ]
const auto payload = build_chunk(
{
to_little_endian(prefix),
to_little_endian(height),
block_hash,
tx.to_data()
});
send(reply_to, address_stealth, id, payload);
}
void notification_worker::send_address(const route& reply_to, uint32_t id,
uint8_t sequence, uint32_t height, const hash_digest& block_hash,
const chain::transaction& tx)
{
// [ code:4 ]
// [ sequence:1 ]
// [ height:4 ]
// [ block_hash:32 ]
// [ tx:... ]
const auto payload = build_chunk(
{
message::to_bytes(error::success),
to_array(sequence),
to_little_endian(height),
block_hash,
tx.to_data()
});
send(reply_to, address_update2, id, payload);
}
// Handlers.
// ----------------------------------------------------------------------------
bool notification_worker::handle_payment(const code& ec,
const payment_address& address, uint32_t height,
const hash_digest& block_hash, const chain::transaction& tx,
const route& reply_to, uint32_t id, const binary& prefix_filter)
{
if (ec)
{
send(reply_to, address_update, id, message::to_bytes(ec));
return false;
}
if (prefix_filter.is_prefix_of(address.hash()))
send_payment(reply_to, id, address, height, block_hash, tx);
return true;
}
bool notification_worker::handle_stealth(const code& ec,
uint32_t prefix, uint32_t height, const hash_digest& block_hash,
const chain::transaction& tx, const route& reply_to, uint32_t id,
const binary& prefix_filter)
{
if (ec)
{
send(reply_to, address_stealth, id, message::to_bytes(ec));
return false;
}
if (prefix_filter.is_prefix_of(prefix))
send_stealth(reply_to, id, prefix, height, block_hash, tx);
return true;
}
bool notification_worker::handle_address(const code& ec,
const binary& field, uint32_t height, const hash_digest& block_hash,
const chain::transaction& tx, const route& reply_to, uint32_t id,
const binary& prefix_filter, sequence_ptr sequence)
{
if (ec)
{
send(reply_to, address_update2, id, message::to_bytes(ec));
return false;
}
if (prefix_filter.is_prefix_of(field))
{
send_address(reply_to, id, *sequence, height, block_hash, tx);
++(*sequence);
}
return true;
}
// Subscribers.
// ----------------------------------------------------------------------------
// Subscribe to address and stealth prefix notifications.
// Each delegate must connect to the appropriate query notification endpoint.
void notification_worker::subscribe_address(const route& reply_to, uint32_t id,
const binary& prefix_filter, subscribe_type type)
{
static const auto error_code = error::channel_stopped;
const auto& duration = settings_.subscription_expiration();
const address_key key(reply_to, prefix_filter);
switch (type)
{
// v2/v3 (deprecated)
case subscribe_type::payment:
{
// This class must be kept in scope until work is terminated.
const auto handler =
std::bind(¬ification_worker::handle_payment,
this, _1, _2, _3, _4, _5, reply_to, id, prefix_filter);
payment_subscriber_->subscribe(handler, key, duration, error_code,
{}, 0, {}, {});
break;
}
// v2/v3 (deprecated)
case subscribe_type::stealth:
{
// This class must be kept in scope until work is terminated.
const auto handler =
std::bind(¬ification_worker::handle_stealth,
this, _1, _2, _3, _4, _5, reply_to, id, prefix_filter);
stealth_subscriber_->subscribe(handler, key, duration, error_code,
0, 0, {}, {});
break;
}
// v3
case subscribe_type::unspecified:
{
// The sequence enables the client to detect dropped messages.
const auto sequence = std::make_shared<uint8_t>(0);
// This class must be kept in scope until work is terminated.
const auto handler =
std::bind(¬ification_worker::handle_address,
this, _1, _2, _3, _4, _5, reply_to, id, prefix_filter,
sequence);
// v3
address_subscriber_->subscribe(handler, key, duration, error_code,
{}, 0, {}, {});
break;
}
// v3
default:
case subscribe_type::unsubscribe:
{
// Just as with an expiration (purge) this will cause the stored
// handler (notification_worker::handle_address) to be invoked but
// with the specified error code (error::channel_stopped) as
// opposed to error::channel_timeout.
// v3
address_subscriber_->unsubscribe(key, error_code, {}, 0, {}, {});
break;
}
}
}
// Subscribe to transaction penetration notifications.
// Each delegate must connect to the appropriate query notification endpoint.
void notification_worker::subscribe_penetration(const route& reply_to,
uint32_t id, const hash_digest& tx_hash)
{
// TODO:
// Height and hash are zeroized if tx is not chained (inv/mempool).
// If chained or penetration is 100 (percent) drop subscription.
// Only send messages at configured thresholds (e.g. 20/40/60/80/100%).
// Thresholding allows the server to mask its peer count.
// Penetration is computed by the relay handler.
// No sequence is required because gaps are okay.
// [ tx_hash:32 ]
// [ penetration:1 ]
// [ height:4 ]
// [ block_hash:32 ]
////penetration_subscriber_->subscribe();
}
// Notification (via blockchain).
// ----------------------------------------------------------------------------
bool notification_worker::handle_blockchain_reorganization(const code& ec,
uint64_t fork_point, const block_list& new_blocks, const block_list&)
{
if (stopped() || ec == error::service_stopped)
return false;
if (ec)
{
log::warning(LOG_SERVER)
<< "Failure handling new block: " << ec.message();
// Don't let a failure here prevent prevent future notifications.
return true;
}
// Blockchain height is 64 bit but obelisk protocol is 32 bit.
BITCOIN_ASSERT(fork_point <= max_uint32);
const auto fork_point32 = static_cast<uint32_t>(fork_point);
notify_blocks(fork_point32, new_blocks);
return true;
}
void notification_worker::notify_blocks(uint32_t fork_point,
const block_list& blocks)
{
if (stopped())
return;
const auto security = secure_ ? "secure" : "public";
const auto& endpoint = secure_ ? block_service::secure_worker :
block_service::public_worker;
// Notifications are off the pub-sub thread so this must connect back.
// This could be optimized by caching the socket as thread static.
zmq::socket publisher(authenticator_, zmq::socket::role::publisher);
const auto ec = publisher.connect(endpoint);
if (ec == error::service_stopped)
return;
if (ec)
{
log::warning(LOG_SERVER)
<< "Failed to connect " << security << " notification worker: "
<< ec.message();
return;
}
BITCOIN_ASSERT(blocks.size() <= max_uint32);
BITCOIN_ASSERT(fork_point < max_uint32 - blocks.size());
auto height = fork_point;
for (const auto block: blocks)
notify_block(publisher, height++, block);
}
void notification_worker::notify_block(zmq::socket& publisher, uint32_t height,
const block::ptr block)
{
if (stopped())
return;
const auto block_hash = block->header.hash();
for (const auto& tx: block->transactions)
{
const auto tx_hash = tx.hash();
notify_transaction(height, block_hash, tx);
notify_penetration(height, block_hash, tx_hash);
}
}
// Notification (via transaction inventory).
// ----------------------------------------------------------------------------
// This relies on peers always notifying us of new txs via inv messages.
bool notification_worker::handle_inventory(const code& ec,
const bc::message::inventory::ptr packet)
{
if (stopped() || ec == error::service_stopped)
return false;
if (ec)
{
log::warning(LOG_SERVER)
<< "Failure handling inventory: " << ec.message();
// Don't let a failure here prevent prevent future notifications.
return true;
}
// Loop inventories and extract transaction hashes.
for (const auto& inventory: packet->inventories)
if (inventory.is_transaction_type())
notify_penetration(0, null_hash, inventory.hash);
return true;
}
// Notification (via mempool).
// ----------------------------------------------------------------------------
bool notification_worker::handle_transaction_pool(const code& ec,
const point::indexes&, bc::message::transaction_message::ptr tx)
{
if (stopped() || ec == error::service_stopped)
return false;
if (ec)
{
log::warning(LOG_SERVER)
<< "Failure handling new transaction: " << ec.message();
// Don't let a failure here prevent future notifications.
return true;
}
notify_transaction(0, null_hash, *tx);
return true;
}
// This parsing is duplicated by bc::database::data_base.
void notification_worker::notify_transaction(uint32_t height,
const hash_digest& block_hash, const transaction& tx)
{
uint32_t prefix;
// TODO: move full integer and array constructors into binary.
static constexpr size_t prefix_bits = sizeof(prefix) * byte_bits;
static constexpr size_t address_bits = short_hash_size * byte_bits;
if (stopped() || tx.outputs.empty())
return;
// see data_base::push_inputs
// Loop inputs and extract payment addresses.
for (const auto& input: tx.inputs)
{
const auto address = payment_address::extract(input.script);
if (address)
{
const binary field(address_bits, address.hash());
notify_address(field, height, block_hash, tx);
notify_payment(address, height, block_hash, tx);
}
}
// see data_base::push_outputs
// Loop outputs and extract payment addresses.
for (const auto& output: tx.outputs)
{
const auto address = payment_address::extract(output.script);
if (address)
{
const binary field(address_bits, address.hash());
notify_address(field, height, block_hash, tx);
notify_payment(address, height, block_hash, tx);
}
}
// see data_base::push_stealth
// Loop output pairs and extract stealth payments.
for (size_t index = 0; index < (tx.outputs.size() - 1); ++index)
{
const auto& ephemeral_script = tx.outputs[index].script;
const auto& payment_script = tx.outputs[index + 1].script;
// Try to extract a stealth prefix from the first output.
// Try to extract the payment address from the second output.
if (to_stealth_prefix(prefix, ephemeral_script) &&
payment_address::extract(payment_script))
{
const binary field(prefix_bits, to_little_endian(prefix));
notify_address(field, height, block_hash, tx);
notify_stealth(prefix, height, block_hash, tx);
}
}
}
// v2/v3 (deprecated)
void notification_worker::notify_payment(const payment_address& address,
uint32_t height, const hash_digest& block_hash, const transaction& tx)
{
static const auto code = error::success;
payment_subscriber_->relay(code, address, height, block_hash, tx);
}
// v2/v3 (deprecated)
void notification_worker::notify_stealth(uint32_t prefix, uint32_t height,
const hash_digest& block_hash, const transaction& tx)
{
static const auto code = error::success;
stealth_subscriber_->relay(code, prefix, height, block_hash, tx);
}
// v3
void notification_worker::notify_address(const binary& field, uint32_t height,
const hash_digest& block_hash, const transaction& tx)
{
static const auto code = error::success;
address_subscriber_->relay(code, field, height, block_hash, tx);
}
// v3.x
void notification_worker::notify_penetration(uint32_t height,
const hash_digest& block_hash, const hash_digest& tx_hash)
{
static const auto code = error::success;
penetration_subscriber_->relay(code, height, block_hash, tx_hash);
}
} // namespace server
} // namespace libbitcoin
|
/* A node factory that:
* * Sorts children to increases sharing,
* * Performs constant evaluation,
* * performs simplify boolean simplifications,
* * converts less thans to greater thans.
*
* NOTE: CreateNode doesn't necessary return a node with the same Kind as what it was called
* with. For example: (AND TRUE FALSE) will return FALSE. Which isn't an AND node.
*
* The intention is to never create nodes that will later be simplified by single level
* re-write rules. So we will never create the node (NOT(NOT x)). This is and example of
* a multi-level rule that never increases the global number of nodes.
*
* These rules never increase the total number of nodes. They are complimented by
* multi-level re-write rules that consider the global reference count when simplifying.
*
*/
#include "../../AST/AST.h"
#include <cassert>
#include "SimplifyingNodeFactory.h"
#include "../../simplifier/simplifier.h"
using BEEV::Kind;
static bool debug_simplifyingNodeFactory = false;
ASTNode SimplifyingNodeFactory::CreateNode(Kind kind, const ASTVec & children)
{
assert(kind != BEEV::SYMBOL); // These are created specially.
// If all the parameters are constant, return the constant value.
// The bitblaster calls CreateNode with a boolean vector. We don't try to simplify those.
if (kind != BEEV::UNDEFINED)
{
bool allConstant = true;
for (unsigned i = 0; i < children.size(); i++)
if (!children[i].isConstant())
{
allConstant = false;
break;
}
if (allConstant)
{
const ASTNode& hash = hashing.CreateNode(kind, children);
const ASTNode& c = NonMemberBVConstEvaluator(hash);
assert(c.isConstant());
return c;
}
}
ASTNode result;
switch (kind)
{
case BEEV::BVLT:
assert(children.size() ==2);
result = NodeFactory::CreateNode(BEEV::BVGT, children[1], children[0]);
break;
case BEEV::BVLE:
assert(children.size() ==2);
result = NodeFactory::CreateNode(BEEV::BVGE, children[1], children[0]);
break;
case BEEV::BVSLT:
assert(children.size() ==2);
result = NodeFactory::CreateNode(BEEV::BVSGT, children[1], children[0]);
break;
case BEEV::BVSLE:
assert(children.size() ==2);
result = NodeFactory::CreateNode(BEEV::BVSGE, children[1], children[0]);
break;
case BEEV::BVSGT:
case BEEV::BVGT:
assert(children.size() ==2);
if (children[0] == children[1])
result = ASTFalse;
else
result = hashing.CreateNode(kind, children);
break;
case BEEV::BVSGE:
case BEEV::BVGE:
assert(children.size() ==2);
if (children[0] == children[1])
result = ASTTrue;
else
result = hashing.CreateNode(kind, children);
break;
case BEEV::NOT:
result = CreateSimpleNot(children);
break;
case BEEV::AND:
result = CreateSimpleAndOr(1, children);
break;
case BEEV::OR:
result = CreateSimpleAndOr(0, children);
break;
case BEEV::NAND:
result = CreateSimpleNot(CreateSimpleAndOr(1, children));
break;
case BEEV::NOR:
result = CreateSimpleNot(CreateSimpleAndOr(0, children));
break;
case BEEV::XOR:
result = CreateSimpleXor(children);
break;
case BEEV::ITE:
result = CreateSimpleFormITE(children);
break;
case BEEV::EQ:
result = CreateSimpleEQ(children);
break;
case BEEV::IFF:
{
assert(children.size() ==2);
ASTVec newCh;
newCh.reserve(2);
newCh.push_back(CreateSimpleNot(children[0]));
newCh.push_back(children[1]);
result = CreateSimpleXor(newCh);
break;
}
case BEEV::IMPLIES:
{
assert(children.size() ==2);
ASTVec newCh;
newCh.reserve(2);
newCh.push_back(CreateSimpleNot(children[0]));
newCh.push_back(children[1]);
result = CreateSimpleAndOr(0,newCh);
break;
}
default:
result = hashing.CreateNode(kind, children);
}
return result;
}
ASTNode SimplifyingNodeFactory::CreateSimpleNot(const ASTNode& form)
{
const Kind k = form.GetKind();
switch (k)
{
case BEEV::FALSE:
{
return form.GetSTPMgr()->ASTTrue;
}
case BEEV::TRUE:
{
return form.GetSTPMgr()->ASTFalse;
}
case BEEV::NOT:
{
return form[0];
} // NOT NOT cancellation
default:
{
ASTVec children;
children.push_back(form);
return hashing.CreateNode(BEEV::NOT, children);
}
}
}
ASTNode SimplifyingNodeFactory::CreateSimpleNot(const ASTVec& children)
{
const Kind k = children[0].GetKind();
switch (k)
{
case BEEV::FALSE:
{
return children[0].GetSTPMgr()->ASTTrue;
}
case BEEV::TRUE:
{
return children[0].GetSTPMgr()->ASTFalse;
}
case BEEV::NOT:
{
return children[0][0];
} // NOT NOT cancellation
default:
{
return hashing.CreateNode(BEEV::NOT, children);
}
}
}
ASTNode SimplifyingNodeFactory::CreateSimpleAndOr(bool IsAnd,
const ASTNode& form1, const ASTNode& form2)
{
ASTVec children;
children.push_back(form1);
children.push_back(form2);
return CreateSimpleAndOr(IsAnd, children);
}
ASTNode SimplifyingNodeFactory::CreateSimpleAndOr(bool IsAnd,
const ASTVec &children)
{
const Kind k = IsAnd ? BEEV::AND : BEEV::OR;
const ASTNode& annihilator = (IsAnd ? ASTFalse : ASTTrue);
const ASTNode& identity = (IsAnd ? ASTTrue : ASTFalse);
ASTNode retval;
ASTVec new_children;
new_children.reserve(children.size());
const ASTVec::const_iterator it_end = children.end();
for (ASTVec::const_iterator it = children.begin(); it != it_end; it++)
{
ASTVec::const_iterator next_it;
bool nextexists = (it + 1 < it_end);
if (nextexists)
next_it = it + 1;
else
next_it = it_end;
if (*it == annihilator)
{
return annihilator;
}
else if (*it == identity || (nextexists && (*next_it == *it)))
{
// just drop it
}else
new_children.push_back(*it);
}
// If we get here, we saw no annihilators, and children should
// be only the non-True nodes.
if (0 == new_children.size())
{
retval = identity;
}
else if (1==new_children.size())
{
// there is just one child
retval = new_children[0];
}
else
{
// 2 or more children. Create a new node.
retval = hashing.CreateNode(IsAnd ? BEEV::AND : BEEV::OR, new_children);
}
return retval;
}
//Tries to simplify the input to TRUE/FALSE. if it fails, then
//return the constructed equality
ASTNode SimplifyingNodeFactory::CreateSimpleEQ(const ASTVec& children)
{
const ASTNode& in1 = children[0];
const ASTNode& in2 = children[1];
const Kind k1 = in1.GetKind();
const Kind k2 = in2.GetKind();
if (in1 == in2)
//terms are syntactically the same
return in1.GetSTPMgr()->ASTTrue;
//here the terms are definitely not syntactically equal but may be
//semantically equal.
if (BEEV::BVCONST == k1 && BEEV::BVCONST == k2)
return in1.GetSTPMgr()->ASTFalse;
//last resort is to CreateNode
return hashing.CreateNode(BEEV::EQ, children);
}
// Constant children are accumulated in "accumconst".
ASTNode SimplifyingNodeFactory::CreateSimpleXor(const ASTVec &children)
{
if (debug_simplifyingNodeFactory)
{
cout << "========" << endl << "CreateSimpXor ";
lpvec(children);
cout << endl;
}
ASTVec flat_children; // empty vector
flat_children = children;
// sort so that identical nodes occur in sequential runs, followed by
// their negations.
SortByExprNum(flat_children);
// This is the C Boolean value of all constant args seen. It is initially
// 0. TRUE children cause it to change value.
bool accumconst = 0;
ASTVec new_children;
new_children.reserve(children.size());
const ASTVec::const_iterator it_end = flat_children.end();
ASTVec::iterator next_it;
for (ASTVec::iterator it = flat_children.begin(); it != it_end; it++)
{
next_it = it + 1;
bool nextexists = (next_it < it_end);
if (ASTTrue == *it)
{
accumconst = !accumconst;
}
else if (ASTFalse == *it)
{
// Ignore it
}
else if (nextexists && (*next_it == *it))
{
// x XOR x = FALSE. Skip current, write "false" into next_it
// so that it gets tossed, too.
*next_it = ASTFalse;
}
else if (nextexists && (next_it->GetKind() == BEEV::NOT)
&& ((*next_it)[0] == *it))
{
// x XOR NOT x = TRUE. Skip current, write "true" into next_it
// so that it gets tossed, too.
*next_it = ASTTrue;
}
else if (BEEV::NOT == it->GetKind())
{
// If child is (NOT alpha), we can flip accumconst and use alpha.
// This is ok because (NOT alpha) == TRUE XOR alpha
accumconst = !accumconst;
// CreateSimpNot just takes child of not.
new_children.push_back(CreateSimpleNot(*it));
}
else
{
new_children.push_back(*it);
}
}
ASTNode retval;
// Children should be non-constant.
if (new_children.size() < 2)
{
if (0 == new_children.size())
{
// XOR(TRUE, FALSE) -- accumconst will be 1.
if (accumconst)
{
retval = ASTTrue;
}
else
{
retval = ASTFalse;
}
}
else
{
// there is just one child
// XOR(x, TRUE) -- accumconst will be 1.
if (accumconst)
{
retval = CreateSimpleNot(new_children[0]);
}
else
{
retval = new_children[0];
}
}
}
else
{
// negate first child if accumconst == 1
if (accumconst)
{
new_children[0] = CreateSimpleNot(new_children[0]);
}
retval = hashing.CreateNode(BEEV::XOR, new_children);
}
if (debug_simplifyingNodeFactory)
{
cout << "returns " << retval << endl;
}
return retval;
}
// FIXME: How do I know whether ITE is a formula or not?
ASTNode SimplifyingNodeFactory::CreateSimpleFormITE(const ASTVec& children)
{
const ASTNode& child0 = children[0];
const ASTNode& child1 = children[1];
const ASTNode& child2 = children[2];
ASTNode retval;
if (debug_simplifyingNodeFactory)
{
cout << "========" << endl << "CreateSimpleFormITE " << child0
<< child1 << child2 << endl;
}
if (ASTTrue == child0)
{
retval = child1;
}
else if (ASTFalse == child0)
{
retval = child2;
}
else if (child1 == child2)
{
retval = child1;
}
// ITE(x, TRUE, y ) == x OR y
else if (ASTTrue == child1)
{
retval = CreateSimpleAndOr(0, child0, child2);
}
// ITE(x, FALSE, y ) == (!x AND y)
else if (ASTFalse == child1)
{
retval = CreateSimpleAndOr(1, CreateSimpleNot(child0), child2);
}
// ITE(x, y, TRUE ) == (!x OR y)
else if (ASTTrue == child2)
{
retval = CreateSimpleAndOr(0, CreateSimpleNot(child0), child1);
}
// ITE(x, y, FALSE ) == (x AND y)
else if (ASTFalse == child2)
{
retval = CreateSimpleAndOr(1, child0, child1);
}
else
{
retval = hashing.CreateNode(BEEV::ITE, children);
}
if (debug_simplifyingNodeFactory)
{
cout << "returns " << retval << endl;
}
return retval;
}
// Move reads down through writes until, either we hit a write to an identical (syntactically) index,
// or we hit a write to an index that might be the same. This is intended to simplify things like:
// read(write(write(A,1,2),2,3),4) cheaply.
// The "children" that are passed should be the children of a READ.
ASTNode SimplifyingNodeFactory::chaseRead(const ASTVec& children, unsigned int width)
{
assert(children[0].GetKind() == BEEV::WRITE);
const ASTNode& readIndex = children[1];
ASTNode write = children[0];
const bool read_is_const = (BEEV::BVCONST == readIndex.GetKind());
while (write.GetKind() == BEEV::WRITE)
{
const ASTNode& write_index = write[1];
if (readIndex == write_index)
{
// The are definately the same.
//cerr << "-";
return write[2];
}
else if (read_is_const && BEEV::BVCONST == write_index.GetKind())
{
// They are definately different. Ignore this.
//cerr << "+";
}else
{
// They may be the same. Exit.
//cerr << "#";
break;
}
write = write[0];
}
return hashing.CreateTerm(BEEV::READ, width, write,readIndex);
}
ASTNode SimplifyingNodeFactory::CreateTerm(Kind kind, unsigned int width,
const ASTVec &children)
{
if (!is_Term_kind(kind))
FatalError("CreateTerm: Illegal kind to CreateTerm:", ASTUndefined,
kind);
assert(kind != BEEV::BVCONST); // These are created specially.
assert(kind != BEEV::SYMBOL); // so are these.
// If all the parameters are constant, return the constant value.
bool allConstant = true;
for (unsigned i = 0; i < children.size(); i++)
if (!children[i].isConstant())
{
allConstant = false;
break;
}
assert(bm.hashingNodeFactory == &hashing);
if (allConstant)
{
const ASTNode& hash = hashing.CreateTerm(kind, width, children);
const ASTNode& c = NonMemberBVConstEvaluator(hash);
assert(c.isConstant());
return c;
}
ASTNode result;
switch (kind)
{
case BEEV::ITE:
{
if (children[0]== ASTTrue)
result = children[1];
else if (children[0]== ASTFalse)
result = children[2];
else if (children[1] == children[2])
result = children[1];
break;
}
case BEEV::BVSX:
{
if (width == children[0].GetValueWidth())
result = children[0];
break;
}
case BEEV::BVNEG:
{
switch (children[0].GetKind())
{
case BEEV::BVNEG:
result = children[0][0];
break;
default: // quieten compiler.
break;
}
}
break;
case BEEV::BVMOD:
if (children[1].isConstant())
{
ASTNode one = bm.CreateOneConst(width);
if (children[1] == one)
result = bm.CreateZeroConst(width);
}
break;
case BEEV::READ:
if (children[0].GetKind() == BEEV::WRITE)
{
result = chaseRead(children,width);
}
break;
default: // quieten compiler.
break;
}
if (result.IsNull())
result = hashing.CreateTerm(kind, width, children);
return result;
}
Improvement. More cases for the simplifying node factory.
/* A node factory that:
* * Sorts children to increases sharing,
* * Performs constant evaluation,
* * performs simplify boolean simplifications,
* * converts less thans to greater thans.
*
* NOTE: CreateNode doesn't necessary return a node with the same Kind as what it was called
* with. For example: (AND TRUE FALSE) will return FALSE. Which isn't an AND node.
*
* The intention is to never create nodes that will later be simplified by single level
* re-write rules. So we will never create the node (NOT(NOT x)). This is and example of
* a multi-level rule that never increases the global number of nodes.
*
* These rules never increase the total number of nodes. They are complimented by
* multi-level re-write rules that consider the global reference count when simplifying.
*
*/
#include "../../AST/AST.h"
#include <cassert>
#include "SimplifyingNodeFactory.h"
#include "../../simplifier/simplifier.h"
using BEEV::Kind;
static bool debug_simplifyingNodeFactory = false;
ASTNode SimplifyingNodeFactory::CreateNode(Kind kind, const ASTVec & children)
{
assert(kind != BEEV::SYMBOL); // These are created specially.
// If all the parameters are constant, return the constant value.
// The bitblaster calls CreateNode with a boolean vector. We don't try to simplify those.
if (kind != BEEV::UNDEFINED)
{
bool allConstant = true;
for (unsigned i = 0; i < children.size(); i++)
if (!children[i].isConstant())
{
allConstant = false;
break;
}
if (allConstant)
{
const ASTNode& hash = hashing.CreateNode(kind, children);
const ASTNode& c = NonMemberBVConstEvaluator(hash);
assert(c.isConstant());
return c;
}
}
ASTNode result;
switch (kind)
{
case BEEV::BVLT:
assert(children.size() ==2);
result = NodeFactory::CreateNode(BEEV::BVGT, children[1], children[0]);
break;
case BEEV::BVLE:
assert(children.size() ==2);
result = NodeFactory::CreateNode(BEEV::BVGE, children[1], children[0]);
break;
case BEEV::BVSLT:
assert(children.size() ==2);
result = NodeFactory::CreateNode(BEEV::BVSGT, children[1], children[0]);
break;
case BEEV::BVSLE:
assert(children.size() ==2);
result = NodeFactory::CreateNode(BEEV::BVSGE, children[1], children[0]);
break;
case BEEV::BVSGT:
case BEEV::BVGT:
assert(children.size() ==2);
if (children[0] == children[1])
result = ASTFalse;
else
result = hashing.CreateNode(kind, children);
break;
case BEEV::BVSGE:
case BEEV::BVGE:
assert(children.size() ==2);
if (children[0] == children[1])
result = ASTTrue;
else
result = hashing.CreateNode(kind, children);
break;
case BEEV::NOT:
result = CreateSimpleNot(children);
break;
case BEEV::AND:
result = CreateSimpleAndOr(1, children);
break;
case BEEV::OR:
result = CreateSimpleAndOr(0, children);
break;
case BEEV::NAND:
result = CreateSimpleNot(CreateSimpleAndOr(1, children));
break;
case BEEV::NOR:
result = CreateSimpleNot(CreateSimpleAndOr(0, children));
break;
case BEEV::XOR:
result = CreateSimpleXor(children);
break;
case BEEV::ITE:
result = CreateSimpleFormITE(children);
break;
case BEEV::EQ:
result = CreateSimpleEQ(children);
break;
case BEEV::IFF:
{
assert(children.size() ==2);
ASTVec newCh;
newCh.reserve(2);
newCh.push_back(CreateSimpleNot(children[0]));
newCh.push_back(children[1]);
result = CreateSimpleXor(newCh);
break;
}
case BEEV::IMPLIES:
{
assert(children.size() ==2);
ASTVec newCh;
newCh.reserve(2);
newCh.push_back(CreateSimpleNot(children[0]));
newCh.push_back(children[1]);
result = CreateSimpleAndOr(0,newCh);
break;
}
default:
result = hashing.CreateNode(kind, children);
}
return result;
}
ASTNode SimplifyingNodeFactory::CreateSimpleNot(const ASTNode& form)
{
const Kind k = form.GetKind();
switch (k)
{
case BEEV::FALSE:
{
return form.GetSTPMgr()->ASTTrue;
}
case BEEV::TRUE:
{
return form.GetSTPMgr()->ASTFalse;
}
case BEEV::NOT:
{
return form[0];
} // NOT NOT cancellation
default:
{
ASTVec children;
children.push_back(form);
return hashing.CreateNode(BEEV::NOT, children);
}
}
}
ASTNode SimplifyingNodeFactory::CreateSimpleNot(const ASTVec& children)
{
const Kind k = children[0].GetKind();
switch (k)
{
case BEEV::FALSE:
{
return children[0].GetSTPMgr()->ASTTrue;
}
case BEEV::TRUE:
{
return children[0].GetSTPMgr()->ASTFalse;
}
case BEEV::NOT:
{
return children[0][0];
} // NOT NOT cancellation
default:
{
return hashing.CreateNode(BEEV::NOT, children);
}
}
}
ASTNode SimplifyingNodeFactory::CreateSimpleAndOr(bool IsAnd,
const ASTNode& form1, const ASTNode& form2)
{
ASTVec children;
children.push_back(form1);
children.push_back(form2);
return CreateSimpleAndOr(IsAnd, children);
}
ASTNode SimplifyingNodeFactory::CreateSimpleAndOr(bool IsAnd,
const ASTVec &children)
{
const Kind k = IsAnd ? BEEV::AND : BEEV::OR;
const ASTNode& annihilator = (IsAnd ? ASTFalse : ASTTrue);
const ASTNode& identity = (IsAnd ? ASTTrue : ASTFalse);
ASTNode retval;
ASTVec new_children;
new_children.reserve(children.size());
const ASTVec::const_iterator it_end = children.end();
for (ASTVec::const_iterator it = children.begin(); it != it_end; it++)
{
ASTVec::const_iterator next_it;
bool nextexists = (it + 1 < it_end);
if (nextexists)
next_it = it + 1;
else
next_it = it_end;
if (*it == annihilator)
{
return annihilator;
}
else if (*it == identity || (nextexists && (*next_it == *it)))
{
// just drop it
}else
new_children.push_back(*it);
}
// If we get here, we saw no annihilators, and children should
// be only the non-True nodes.
if (0 == new_children.size())
{
retval = identity;
}
else if (1==new_children.size())
{
// there is just one child
retval = new_children[0];
}
else
{
// 2 or more children. Create a new node.
retval = hashing.CreateNode(IsAnd ? BEEV::AND : BEEV::OR, new_children);
}
return retval;
}
//Tries to simplify the input to TRUE/FALSE. if it fails, then
//return the constructed equality
ASTNode SimplifyingNodeFactory::CreateSimpleEQ(const ASTVec& children)
{
const ASTNode& in1 = children[0];
const ASTNode& in2 = children[1];
const Kind k1 = in1.GetKind();
const Kind k2 = in2.GetKind();
if (in1 == in2)
//terms are syntactically the same
return in1.GetSTPMgr()->ASTTrue;
//here the terms are definitely not syntactically equal but may be
//semantically equal.
if (BEEV::BVCONST == k1 && BEEV::BVCONST == k2)
return in1.GetSTPMgr()->ASTFalse;
//last resort is to CreateNode
return hashing.CreateNode(BEEV::EQ, children);
}
// Constant children are accumulated in "accumconst".
ASTNode SimplifyingNodeFactory::CreateSimpleXor(const ASTVec &children)
{
if (debug_simplifyingNodeFactory)
{
cout << "========" << endl << "CreateSimpXor ";
lpvec(children);
cout << endl;
}
ASTVec flat_children; // empty vector
flat_children = children;
// sort so that identical nodes occur in sequential runs, followed by
// their negations.
SortByExprNum(flat_children);
// This is the C Boolean value of all constant args seen. It is initially
// 0. TRUE children cause it to change value.
bool accumconst = 0;
ASTVec new_children;
new_children.reserve(children.size());
const ASTVec::const_iterator it_end = flat_children.end();
ASTVec::iterator next_it;
for (ASTVec::iterator it = flat_children.begin(); it != it_end; it++)
{
next_it = it + 1;
bool nextexists = (next_it < it_end);
if (ASTTrue == *it)
{
accumconst = !accumconst;
}
else if (ASTFalse == *it)
{
// Ignore it
}
else if (nextexists && (*next_it == *it))
{
// x XOR x = FALSE. Skip current, write "false" into next_it
// so that it gets tossed, too.
*next_it = ASTFalse;
}
else if (nextexists && (next_it->GetKind() == BEEV::NOT)
&& ((*next_it)[0] == *it))
{
// x XOR NOT x = TRUE. Skip current, write "true" into next_it
// so that it gets tossed, too.
*next_it = ASTTrue;
}
else if (BEEV::NOT == it->GetKind())
{
// If child is (NOT alpha), we can flip accumconst and use alpha.
// This is ok because (NOT alpha) == TRUE XOR alpha
accumconst = !accumconst;
// CreateSimpNot just takes child of not.
new_children.push_back(CreateSimpleNot(*it));
}
else
{
new_children.push_back(*it);
}
}
ASTNode retval;
// Children should be non-constant.
if (new_children.size() < 2)
{
if (0 == new_children.size())
{
// XOR(TRUE, FALSE) -- accumconst will be 1.
if (accumconst)
{
retval = ASTTrue;
}
else
{
retval = ASTFalse;
}
}
else
{
// there is just one child
// XOR(x, TRUE) -- accumconst will be 1.
if (accumconst)
{
retval = CreateSimpleNot(new_children[0]);
}
else
{
retval = new_children[0];
}
}
}
else
{
// negate first child if accumconst == 1
if (accumconst)
{
new_children[0] = CreateSimpleNot(new_children[0]);
}
retval = hashing.CreateNode(BEEV::XOR, new_children);
}
if (debug_simplifyingNodeFactory)
{
cout << "returns " << retval << endl;
}
return retval;
}
// FIXME: How do I know whether ITE is a formula or not?
ASTNode SimplifyingNodeFactory::CreateSimpleFormITE(const ASTVec& children)
{
const ASTNode& child0 = children[0];
const ASTNode& child1 = children[1];
const ASTNode& child2 = children[2];
ASTNode retval;
if (debug_simplifyingNodeFactory)
{
cout << "========" << endl << "CreateSimpleFormITE " << child0
<< child1 << child2 << endl;
}
if (ASTTrue == child0)
{
retval = child1;
}
else if (ASTFalse == child0)
{
retval = child2;
}
else if (child1 == child2)
{
retval = child1;
}
// ITE(x, TRUE, y ) == x OR y
else if (ASTTrue == child1)
{
retval = CreateSimpleAndOr(0, child0, child2);
}
// ITE(x, FALSE, y ) == (!x AND y)
else if (ASTFalse == child1)
{
retval = CreateSimpleAndOr(1, CreateSimpleNot(child0), child2);
}
// ITE(x, y, TRUE ) == (!x OR y)
else if (ASTTrue == child2)
{
retval = CreateSimpleAndOr(0, CreateSimpleNot(child0), child1);
}
// ITE(x, y, FALSE ) == (x AND y)
else if (ASTFalse == child2)
{
retval = CreateSimpleAndOr(1, child0, child1);
}
else
{
retval = hashing.CreateNode(BEEV::ITE, children);
}
if (debug_simplifyingNodeFactory)
{
cout << "returns " << retval << endl;
}
return retval;
}
// Move reads down through writes until, either we hit a write to an identical (syntactically) index,
// or we hit a write to an index that might be the same. This is intended to simplify things like:
// read(write(write(A,1,2),2,3),4) cheaply.
// The "children" that are passed should be the children of a READ.
ASTNode SimplifyingNodeFactory::chaseRead(const ASTVec& children, unsigned int width)
{
assert(children[0].GetKind() == BEEV::WRITE);
const ASTNode& readIndex = children[1];
ASTNode write = children[0];
const bool read_is_const = (BEEV::BVCONST == readIndex.GetKind());
while (write.GetKind() == BEEV::WRITE)
{
const ASTNode& write_index = write[1];
if (readIndex == write_index)
{
// The are definately the same.
//cerr << "-";
return write[2];
}
else if (read_is_const && BEEV::BVCONST == write_index.GetKind())
{
// They are definately different. Ignore this.
//cerr << "+";
}else
{
// They may be the same. Exit.
//cerr << "#";
break;
}
write = write[0];
}
return hashing.CreateTerm(BEEV::READ, width, write,readIndex);
}
ASTNode SimplifyingNodeFactory::CreateTerm(Kind kind, unsigned int width,
const ASTVec &children)
{
if (!is_Term_kind(kind))
FatalError("CreateTerm: Illegal kind to CreateTerm:", ASTUndefined,
kind);
assert(kind != BEEV::BVCONST); // These are created specially.
assert(kind != BEEV::SYMBOL); // so are these.
// If all the parameters are constant, return the constant value.
bool allConstant = true;
for (unsigned i = 0; i < children.size(); i++)
if (!children[i].isConstant())
{
allConstant = false;
break;
}
assert(bm.hashingNodeFactory == &hashing);
if (allConstant)
{
const ASTNode& hash = hashing.CreateTerm(kind, width, children);
const ASTNode& c = NonMemberBVConstEvaluator(hash);
assert(c.isConstant());
return c;
}
ASTNode result;
switch (kind)
{
case BEEV::ITE:
{
if (children[0]== ASTTrue)
result = children[1];
else if (children[0]== ASTFalse)
result = children[2];
else if (children[1] == children[2])
result = children[1];
break;
}
case BEEV::BVAND:
{
bool oneFound=false;
bool zeroFound=false;
for (int i = 0; i < children.size(); i++)
{
if (children[i].GetKind() == BEEV::BVCONST)
{
if (CONSTANTBV::BitVector_is_full(children[i].GetBVConst()))
oneFound = true;
else if (CONSTANTBV::BitVector_is_empty(children[i].GetBVConst()))
zeroFound = true;
}
}
if (zeroFound)
return bm.CreateZeroConst(width);
if (oneFound)
{
ASTVec new_children;
for (int i = 0; i < children.size(); i++)
{
if (children[i].GetKind() != BEEV::BVCONST || !CONSTANTBV::BitVector_is_full(children[i].GetBVConst()))
new_children.push_back(children[i]);
}
assert(new_children.size() != 0); // constant. Should have been handled earlier.
if (new_children.size() == 1)
return new_children[0];
else
result = hashing.CreateTerm(kind, width, new_children);
}
}
break;
case BEEV::BVSX:
{
if (width == children[0].GetValueWidth())
result = children[0];
break;
}
case BEEV::BVNEG:
if (children[0].GetKind() == BEEV::BVNEG)
return children[0][0];
break;
case BEEV::BVUMINUS:
if (children[0].GetKind() == BEEV::BVUMINUS)
return children[0][0];
break;
case BEEV::BVMOD:
if (children[1].isConstant())
{
ASTNode one = bm.CreateOneConst(width);
if (children[1] == one)
result = bm.CreateZeroConst(width);
}
break;
case BEEV::READ:
if (children[0].GetKind() == BEEV::WRITE)
{
result = chaseRead(children,width);
}
break;
default: // quieten compiler.
break;
}
if (result.IsNull())
result = hashing.CreateTerm(kind, width, children);
return result;
}
|
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include "qtcontacts.h"
//TESTED_CLASS=
//TESTED_FILES=
class tst_QContact: public QObject
{
Q_OBJECT
public:
tst_QContact();
virtual ~tst_QContact();
private slots:
void details();
void actions();
void preferences();
void relationships();
void displayName();
void type();
void emptiness();
};
tst_QContact::tst_QContact()
{
}
tst_QContact::~tst_QContact()
{
}
void tst_QContact::details()
{
QContact c;
// Test there are no details (apart from display label + type) by default
QVERIFY(c.isEmpty() == true);
QVERIFY(c.details().count() == 2);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 0);
QVERIFY(c.details<QContactPhoneNumber>().count() == 0);
QVERIFY(c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(c.detail<QContactPhoneNumber>().isEmpty());
// Test retrieving the first detail (the display label)
QList<QContactDetail> details = c.details(QString());
QVERIFY(details.at(0).definitionName() == QContactDisplayLabel::DefinitionName);
QVERIFY(details.at(1).definitionName() == QContactType::DefinitionName);
QContactDetail detail = c.detail("nonexistent");
QVERIFY(detail.isEmpty());
QVERIFY(detail.definitionName().isEmpty());
QVERIFY(c.details("nonexistent").count() == 0);
// Add a detail
QContactPhoneNumber p;
p.setNumber("12345678");
QVERIFY(c.saveDetail(&p));
QVERIFY(c.isEmpty() == false);
QVERIFY(c.details().count() == 3);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 1);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName, QContactPhoneNumber::FieldNumber, QString("12345678")).count() == 1);
QVERIFY(c.details<QContactPhoneNumber>().count() == 1);
QVERIFY(!c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(!c.detail<QContactPhoneNumber>().isEmpty());
QCOMPARE(c.detail<QContactPhoneNumber>(), p);
// Remove detail
QVERIFY(c.removeDetail(&p));
QVERIFY(c.details().count() == 2);
QVERIFY(c.isEmpty() == true);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 0);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName, QContactPhoneNumber::FieldNumber, QString("12345678")).count() == 0);
QVERIFY(c.details<QContactPhoneNumber>().count() == 0);
QVERIFY(c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(c.detail<QContactPhoneNumber>().isEmpty());
// Try removing it again
QVERIFY(!c.removeDetail(&p));
// Add again, and remove a different way (retrieved copy)
QVERIFY(c.saveDetail(&p));
QVERIFY(c.isEmpty() == false);
QVERIFY(c.details().count() == 3);
QContactPhoneNumber p2 = c.detail(QContactPhoneNumber::DefinitionName);
QCOMPARE(p, p2);
QVERIFY(c.removeDetail(&p2));
QVERIFY(c.details().count() == 2);
QVERIFY(c.isEmpty() == true);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 0);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName, QContactPhoneNumber::FieldNumber, QString("12345678")).count() == 0);
QVERIFY(c.details<QContactPhoneNumber>().count() == 0);
QVERIFY(c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(c.detail<QContactPhoneNumber>().isEmpty());
QCOMPARE(p, p2);
// Add again again, and remove a different way (base class)
QVERIFY(c.saveDetail(&p));
QVERIFY(c.details().count() == 3);
QContactDetail p3 = c.detail(QContactPhoneNumber::DefinitionName);
QVERIFY(p == p3);
QVERIFY(c.removeDetail(&p3));
QVERIFY(c.details().count() == 2);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 0);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName, QContactPhoneNumber::FieldNumber, QString("12345678")).count() == 0);
QVERIFY(c.details<QContactPhoneNumber>().count() == 0);
QVERIFY(c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(c.detail<QContactPhoneNumber>().isEmpty());
QVERIFY(p == p3);
// now try removing a detail for which we've set a preference
QContactEmailAddress pref;
pref.setEmailAddress("test@test");
c.saveDetail(&pref);
c.setPreferredDetail("SendEmail", pref);
QVERIFY(c.isPreferredDetail(QString(), pref));
QVERIFY(c.removeDetail(&pref));
QVERIFY(!c.isPreferredDetail(QString(), pref));
// Now try adding a detail to multiple contacts
QContact c2;
QVERIFY(c2.isEmpty() == true);
QVERIFY(c.saveDetail(&p));
QVERIFY(c2.saveDetail(&p));
QVERIFY(c2.isEmpty() == false);
QVERIFY(c.details().count() == 3);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 1);
QVERIFY(c.details<QContactPhoneNumber>().count() == 1);
QVERIFY(!c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(!c.detail<QContactPhoneNumber>().isEmpty());
QCOMPARE(c.detail<QContactPhoneNumber>(), p);
QVERIFY(c2.details().count() == 3);
QVERIFY(c2.details(QContactPhoneNumber::DefinitionName).count() == 1);
QVERIFY(c2.details<QContactPhoneNumber>().count() == 1);
QVERIFY(!c2.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(!c2.detail<QContactPhoneNumber>().isEmpty());
QCOMPARE(c2.detail<QContactPhoneNumber>(), p);
// Now try removing it from one
QVERIFY(c.removeDetail(&p));
// Make sure it's gone from the first contact
QVERIFY(c.isEmpty() == true);
QVERIFY(c.details().count() == 2);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 0);
QVERIFY(c.details<QContactPhoneNumber>().count() == 0);
QVERIFY(c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(c.detail<QContactPhoneNumber>().isEmpty());
// but not the second
QVERIFY(c2.isEmpty() == false);
QVERIFY(c2.details().count() == 3);
QVERIFY(c2.details(QContactPhoneNumber::DefinitionName).count() == 1);
QVERIFY(c2.details<QContactPhoneNumber>().count() == 1);
QVERIFY(!c2.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(!c2.detail<QContactPhoneNumber>().isEmpty());
QCOMPARE(c2.detail<QContactPhoneNumber>(), p);
// Now remove it from the second as well
QVERIFY(c2.removeDetail(&p));
// Make sure it's gone from both
QVERIFY(c.details().count() == 2);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 0);
QVERIFY(c.details<QContactPhoneNumber>().count() == 0);
QVERIFY(c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(c.detail<QContactPhoneNumber>().isEmpty());
QVERIFY(c2.details().count() == 2);
QVERIFY(c2.details(QContactPhoneNumber::DefinitionName).count() == 0);
QVERIFY(c2.details<QContactPhoneNumber>().count() == 0);
QVERIFY(c2.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(c2.detail<QContactPhoneNumber>().isEmpty());
// add a, add b, remove a, add a, remove b, remove a
QVERIFY(c.saveDetail(&p));
QVERIFY(c2.saveDetail(&p));
QVERIFY(c.removeDetail(&p));
QVERIFY(c.saveDetail(&p));
QVERIFY(c2.removeDetail(&p));
QVERIFY(c.removeDetail(&p));
// Now add a detail with the same values twice
QContactPhoneNumber one;
QContactPhoneNumber two;
one.setNumber("12345");
two.setNumber("12345");
// add it once
QVERIFY(c.saveDetail(&one));
QVERIFY(c.details().count() == 3);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 1);
QVERIFY(c.details<QContactPhoneNumber>().count() == 1);
QVERIFY(!c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(!c.detail<QContactPhoneNumber>().isEmpty());
QCOMPARE(c.detail<QContactPhoneNumber>(), one);
// add it twice
QVERIFY(c.saveDetail(&two));
QVERIFY(c.details().count() == 4);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 2);
QVERIFY(c.details<QContactPhoneNumber>().count() == 2);
QVERIFY(!c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(!c.detail<QContactPhoneNumber>().isEmpty());
QCOMPARE(c.detail<QContactPhoneNumber>(), one);
QCOMPARE(c.details<QContactPhoneNumber>()[0], one);
QCOMPARE(c.details<QContactPhoneNumber>()[1], two);
// Remove it once
QVERIFY(c.removeDetail(&one));
QVERIFY(c.details().count() == 3);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 1);
QVERIFY(c.details<QContactPhoneNumber>().count() == 1);
QVERIFY(!c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(!c.detail<QContactPhoneNumber>().isEmpty());
QCOMPARE(c.detail<QContactPhoneNumber>(), two);
// Remove it twice
QVERIFY(c.removeDetail(&two));
QVERIFY(c.details().count() == 2);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 0);
QVERIFY(c.details<QContactPhoneNumber>().count() == 0);
QVERIFY(c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(c.detail<QContactPhoneNumber>().isEmpty());
// Null pointer tests
QVERIFY(c.saveDetail(0) == false);
QVERIFY(c.removeDetail(0) == false);
// Reference tests...
QContactDetail& ref = one;
QVERIFY(c.saveDetail(&one));
QVERIFY(ref == one);
one.setNumber("56678");
QVERIFY(c.saveDetail(&one));
QVERIFY(ref == one);
// Retrieve the detail again and modify it
QContactPhoneNumber three = c.detail<QContactPhoneNumber>();
QVERIFY(ref == three);
QVERIFY(one == three);
three.setNumber("542343");
QVERIFY(c.saveDetail(&three));
// Now see if we got any updates to ref/one
QVERIFY(ref == one);
QVERIFY(ref != three);
// test saving of a detail with an empty field.
QContactPhoneNumber four;
four.setNumber("");
c.saveDetail(&four);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 2);
QVERIFY(!four.values().isEmpty()); // an empty qstring is not invalid; make sure it exists in the detail.
// ensure that clearing a contact's details works correctly
c.setDisplayLabel("test");
QVERIFY(!c.displayLabel().isSynthesised());
QCOMPARE(c.displayLabel().label(), QString("test"));
QVERIFY(c.details().size() > 0);
QVERIFY(!c.isEmpty());
QContactId oldId = c.id();
c.clearDetails();
QVERIFY(c.details().size() == 1); // always has a display label.
QCOMPARE(c.displayLabel().label(), QString());
QVERIFY(c.displayLabel().isSynthesised());
QVERIFY(c.isEmpty());
QCOMPARE(c.id(), oldId); // id shouldn't change.
}
void tst_QContact::actions()
{
QContact c; // empty contact.
QContact c2; // contact with email saved.
QContactEmailAddress e;
e.setEmailAddress("test@nokia.com");
c2.saveDetail(&e);
// XXX this is here to make the bulk
// of this test pass. The first set
// of tests expect to not find plugins.
QString path = QApplication::applicationDirPath() + "/dummyplugin/plugins/";
QApplication::addLibraryPath(path);
// Prior to plugin loading:
// first, the empty contact
QStringList availableActions = c.availableActions();
QVERIFY(availableActions.isEmpty());
QContactDetail d = c.detailWithAction("SendEmail");
QVERIFY(d.isEmpty());
QList<QContactDetail> dets = c.detailsWithAction("SendEmail");
QVERIFY(dets.isEmpty());
// then, the email contact
availableActions = c2.availableActions();
QEXPECT_FAIL("", "Plugins are only loaded once", Continue);
QVERIFY(availableActions.isEmpty());
d = c2.detailWithAction("SendEmail");
QEXPECT_FAIL("", "Plugins are only loaded once", Continue);
QVERIFY(d.isEmpty());
dets = c2.detailsWithAction("SendEmail");
QEXPECT_FAIL("", "Plugins are only loaded once", Continue);
QVERIFY(dets.isEmpty());
// set the correct path to look for plugins and load them
// QString path = QApplication::applicationDirPath() + "/dummyplugin/plugins/";
// QApplication::addLibraryPath(path);
// available actions - should be one there now.
// empty contact
availableActions = c.availableActions();
QVERIFY(availableActions.isEmpty());
// contact with email
availableActions = c2.availableActions();
QVERIFY(availableActions.contains("SendEmail"));
// detail with action:
// empty contact
d = c.detailWithAction("SendEmail");
QVERIFY(d.isEmpty());
d = c.detailWithAction("NonexistentAction");
QVERIFY(d.isEmpty());
d = c.detailWithAction(QString());
QVERIFY(d.isEmpty());
// contact with email
d = c2.detailWithAction("SendEmail");
QVERIFY(d == e);
d = c2.detailWithAction("NonexistentAction");
QVERIFY(d.isEmpty());
d = c2.detailWithAction(QString());
QVERIFY(d.isEmpty());
// details with action:
// empty contact
dets = c.detailsWithAction("SendEmail");
QVERIFY(dets.isEmpty());
dets = c.detailsWithAction("NonexistentAction");
QVERIFY(dets.isEmpty());
dets = c.detailsWithAction(QString());
QVERIFY(dets.isEmpty());
// contact with email
dets = c2.detailsWithAction("SendEmail");
QVERIFY(dets.contains(e));
dets = c2.detailsWithAction("NonexistentAction");
QVERIFY(dets.isEmpty());
dets = c2.detailsWithAction(QString());
QVERIFY(dets.isEmpty());
// remove the library path.
QApplication::removeLibraryPath(path);
}
void tst_QContact::preferences()
{
QContact c;
// test first set
QContactDetail det("TestId");
det.setValue("test", QVariant("test1"));
c.saveDetail(&det);
QCOMPARE(c.isPreferredDetail("testAction", det), false);
QCOMPARE(c.setPreferredDetail("testAction", det), true);
QCOMPARE(c.isPreferredDetail("testAction", det), true);
QCOMPARE(c.isPreferredDetail(QString(), det), true);
QCOMPARE(c.preferredDetail("testAction"), det);
// test replacement
QContactDetail det2("TestId");
det2.setValue("test", QVariant("test2"));
c.saveDetail(&det2);
QCOMPARE(c.isPreferredDetail("testAction", det2), false);
QCOMPARE(c.setPreferredDetail("testAction", det2), true);
QCOMPARE(c.isPreferredDetail("testAction", det2), true);
QCOMPARE(c.isPreferredDetail("testAction", det), false);
QCOMPARE(c.preferredDetail("testAction"), det2);
// test for detail that is not part of the contact
QContactDetail det3("TestId");
det3.setValue("test", QVariant("test3"));
QCOMPARE(c.setPreferredDetail("testAction", det3), false);
QCOMPARE(c.preferredDetail("testAction"), det2); // shouldn't have changed.
// test invalid set
QCOMPARE(c.setPreferredDetail(QString(), det3), false);
QCOMPARE(c.setPreferredDetail(QString(), QContactDetail()), false);
QCOMPARE(c.setPreferredDetail("testAction", QContactDetail()), false);
QCOMPARE(c.preferredDetail("testAction"), det2); // shouldn't have changed.
// test invalid query
QContactDetail det4;
det4.setValue("test", QVariant("test4"));
c.saveDetail(&det4);
QCOMPARE(c.isPreferredDetail(QString(), QContactDetail()), false);
QCOMPARE(c.isPreferredDetail(QString(), det4), false); // valid detail, but no pref set.
QCOMPARE(c.isPreferredDetail("testAction", QContactDetail()), false);
// test retrieving preferred details
QContactDetail pd = c.preferredDetail(QString());
QVERIFY(pd.isEmpty());
pd = c.preferredDetail("testAction");
QVERIFY(pd == det2); // shouldn't have changed.
// test for preference for action that hasn't been added
QVERIFY(c.preferredDetail("NonexistentAction").isEmpty());
// Remove a non preferred detail
QContactDetail det2copy("TestId");
det2copy.setValue("test", QVariant("test2"));
QVERIFY(c.saveDetail(&det2copy));
QVERIFY(c.isPreferredDetail("testAction", det2) == true);
QVERIFY(c.isPreferredDetail("testAction", det2copy) == false);
QVERIFY(c.removeDetail(&det2copy));
QVERIFY(c.isPreferredDetail("testAction", det2) == true);
QVERIFY(c.isPreferredDetail("testAction", det2copy) == false);
// Add it again
QVERIFY(c.saveDetail(&det2copy));
QVERIFY(c.isPreferredDetail("testAction", det2) == true);
QVERIFY(c.isPreferredDetail("testAction", det2copy) == false);
// Remove the preferred detail (the copy should not become preferred)
QVERIFY(c.removeDetail(&det2));
QVERIFY(c.isPreferredDetail("testAction", det2) == false);
QVERIFY(c.isPreferredDetail("testAction", det2copy) == false);
}
void tst_QContact::relationships()
{
QContact c;
// boring test, because the default contact has no relationships
// we test this more convincingly in the QContactManager tests.
QList<QContactId> related = c.relatedContacts();
QVERIFY(related.isEmpty());
related = c.relatedContacts(QContactRelationship::HasMember);
QVERIFY(related.isEmpty());
related = c.relatedContacts(QContactRelationship::HasMember, QContactRelationshipFilter::First);
QVERIFY(related.isEmpty());
QList<QContactRelationship> relationshipList = c.relationships();
QVERIFY(relationshipList.isEmpty());
relationshipList = c.relationships(QContactRelationship::HasMember);
QVERIFY(relationshipList.isEmpty());
// now test that we can change the order of relationships regardless of the number of relationships
QList<QContactRelationship> orderedList = c.relationshipOrder();
QVERIFY(orderedList == relationshipList); // should be the same by default
QContactRelationship dummyRel;
QContactId firstId;
firstId.setManagerUri("test-nokia");
firstId.setLocalId(QContactLocalId(5));
QContactId secondId;
secondId.setManagerUri("test-nokia-2");
secondId.setLocalId(QContactLocalId(5));
dummyRel.setFirst(firstId);
dummyRel.setSecond(secondId);
dummyRel.setRelationshipType(QContactRelationship::IsAssistantOf);
QList<QContactRelationship> reorderedList;
reorderedList.append(dummyRel);
c.setRelationshipOrder(reorderedList);
QVERIFY(c.relationshipOrder() == reorderedList);
}
void tst_QContact::displayName()
{
QContact c;
QContactManager cm("memory"); // for formatting names
QContactDisplayLabel label = c.displayLabel();
QVERIFY(label.label().isEmpty());
QVERIFY(c.displayLabel().isSynthesised() == true);
label.setLabel("Wesley Wentworth Worrier");
QVERIFY(label.isEmpty() == false);
QVERIFY(label.label().isEmpty() == false);
QVERIFY(label.isSynthesised() == false);
label.setSynthesised(true);
c.setDisplayLabel(label);
QVERIFY(c.displayLabel().label() == "Wesley Wentworth Worrier");
QVERIFY(c.displayLabel().isSynthesised() == true);
//label.setLabel(QString());
//QVERIFY(label.isSynthesised() == true);
/* Clear the label again */
c.setDisplayLabel(QString());
QVERIFY(c.displayLabel().label().isEmpty());
QVERIFY(c.displayLabel().isSynthesised() == true);
/* Use the string mutator */
c.setDisplayLabel("Wesley Wentworth Worrier");
QVERIFY(c.displayLabel().label() == "Wesley Wentworth Worrier");
QVERIFY(c.displayLabel().isSynthesised() == false);
/* Try to make this a bit more consistent by using a single name */
QContact d;
QContactName name;
name.setFirst("Wesley");
QVERIFY(d.displayLabel().label().isEmpty());
QVERIFY(d.saveDetail(&name));
/*
* The display label is not updated until you save the contact, or
* do it manually.
*/
QString synth = cm.synthesiseDisplayLabel(d);
QVERIFY(d.displayLabel().label().isEmpty());
QVERIFY(d.displayLabel().isSynthesised() == true);
QVERIFY(synth == name.first()); // XXX Perhaps not guaranteed
/* Set something else */
d.setDisplayLabel("The grand old duchess");
QVERIFY(d.displayLabel().label() == "The grand old duchess");
QVERIFY(d.displayLabel().isSynthesised() == false);
/* Remove the detail via removeDetail */
QContactDisplayLabel old = d.displayLabel();
QVERIFY(d.details().count() == 3);
QVERIFY(d.removeDetail(&old));
QVERIFY(d.isEmpty() == false);
QVERIFY(d.details().count() == 3); // it should not be removed, only cleared (!)
/* Make sure we go back to the old synth version */
QVERIFY(d.displayLabel().isSynthesised() == true);
QVERIFY(d.displayLabel().label().isEmpty());
}
void tst_QContact::type()
{
QContact c;
QVERIFY(c.isEmpty() == true);
c.setType(QContactType::TypeContact);
QVERIFY(c.type() == QString(QLatin1String(QContactType::TypeContact)));
QVERIFY(c.isEmpty() == true); // type doesn't affect emptiness
QContactType groupType;
groupType.setType(QString(QLatin1String(QContactType::TypeGroup)));
c.setType(groupType);
QVERIFY(c.type() == QString(QLatin1String(QContactType::TypeGroup)));
}
void tst_QContact::emptiness()
{
QContact c;
QVERIFY(c.isEmpty() == true);
QContactDisplayLabel label = c.displayLabel();
QVERIFY(label.label().isEmpty());
label.setLabel("Wesley Wentworth Worrier");
QVERIFY(label.isEmpty() == false);
QVERIFY(label.label().isEmpty() == false);
c.setDisplayLabel(label);
QVERIFY(c.isEmpty() == false);
QVERIFY(c.displayLabel().label() == "Wesley Wentworth Worrier");
QVERIFY(c.displayLabel().isSynthesised() == false);
c.setDisplayLabel(QString());
QVERIFY(c.isEmpty() == true);
c.setType(QContactType::TypeContact);
QVERIFY(c.type() == QString(QLatin1String(QContactType::TypeContact)));
QVERIFY(c.isEmpty() == true); // type doesn't affect emptiness
}
QTEST_MAIN(tst_QContact)
#include "tst_qcontact.moc"
Add tests for detail retrieval in qcontact
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include "qtcontacts.h"
//TESTED_CLASS=
//TESTED_FILES=
class tst_QContact: public QObject
{
Q_OBJECT
public:
tst_QContact();
virtual ~tst_QContact();
private slots:
void details();
void actions();
void preferences();
void relationships();
void displayName();
void type();
void emptiness();
};
tst_QContact::tst_QContact()
{
}
tst_QContact::~tst_QContact()
{
}
void tst_QContact::details()
{
QContact c;
// Test there are no details (apart from display label + type) by default
QVERIFY(c.isEmpty() == true);
QVERIFY(c.details().count() == 2);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 0);
QVERIFY(c.details<QContactPhoneNumber>().count() == 0);
QVERIFY(c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(c.detail<QContactPhoneNumber>().isEmpty());
// Test retrieving the first detail (the display label)
QList<QContactDetail> details = c.details(QString());
QVERIFY(details.at(0).definitionName() == QContactDisplayLabel::DefinitionName);
QVERIFY(details.at(1).definitionName() == QContactType::DefinitionName);
QContactDetail detail = c.detail("nonexistent");
QVERIFY(detail.isEmpty());
QVERIFY(detail.definitionName().isEmpty());
// retrieve the first detail using the empty definition name accessor.
detail = c.detail(QString());
QVERIFY(detail == details.at(0));
QVERIFY(c.details("nonexistent").count() == 0);
// Add a detail
QContactPhoneNumber p;
p.setNumber("12345678");
QVERIFY(c.saveDetail(&p));
QVERIFY(c.isEmpty() == false);
QVERIFY(c.details().count() == 3);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 1);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName, QContactPhoneNumber::FieldNumber, QString("12345678")).count() == 1);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName, QString(), QString("12345678")).count() == c.details(QContactPhoneNumber::DefinitionName).count());
QVERIFY(c.details<QContactPhoneNumber>().count() == 1);
QVERIFY(!c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(!c.detail<QContactPhoneNumber>().isEmpty());
QCOMPARE(c.detail<QContactPhoneNumber>(), p);
// Remove detail
QVERIFY(c.removeDetail(&p));
QVERIFY(c.details().count() == 2);
QVERIFY(c.isEmpty() == true);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 0);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName, QContactPhoneNumber::FieldNumber, QString("12345678")).count() == 0);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName, QString(), QString("12345678")).count() == c.details(QContactPhoneNumber::DefinitionName).count());
QVERIFY(c.details<QContactPhoneNumber>().count() == 0);
QVERIFY(c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(c.detail<QContactPhoneNumber>().isEmpty());
// Try removing it again
QVERIFY(!c.removeDetail(&p));
// Add again, and remove a different way (retrieved copy)
QVERIFY(c.saveDetail(&p));
QVERIFY(c.isEmpty() == false);
QVERIFY(c.details().count() == 3);
QContactPhoneNumber p2 = c.detail(QContactPhoneNumber::DefinitionName);
QCOMPARE(p, p2);
QVERIFY(c.removeDetail(&p2));
QVERIFY(c.details().count() == 2);
QVERIFY(c.isEmpty() == true);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 0);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName, QContactPhoneNumber::FieldNumber, QString("12345678")).count() == 0);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName, QString(), QString("12345678")).count() == c.details(QContactPhoneNumber::DefinitionName).count());
QVERIFY(c.details<QContactPhoneNumber>().count() == 0);
QVERIFY(c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(c.detail<QContactPhoneNumber>().isEmpty());
QCOMPARE(p, p2);
// Add again again, and remove a different way (base class)
QVERIFY(c.saveDetail(&p));
QVERIFY(c.details().count() == 3);
QContactDetail p3 = c.detail(QContactPhoneNumber::DefinitionName);
QVERIFY(p == p3);
QVERIFY(c.removeDetail(&p3));
QVERIFY(c.details().count() == 2);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 0);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName, QContactPhoneNumber::FieldNumber, QString("12345678")).count() == 0);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName, QString(), QString("12345678")).count() == c.details(QContactPhoneNumber::DefinitionName).count());
QVERIFY(c.details<QContactPhoneNumber>().count() == 0);
QVERIFY(c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(c.detail<QContactPhoneNumber>().isEmpty());
QVERIFY(p == p3);
// now we want to add multiple details of the same type, and test that retrieval works correctly.
p2.setNumber("22222");
p2.setValue("nonexistent-field", QVariant("22222-2"));
c.saveDetail(&p);
c.saveDetail(&p2);
QVERIFY(c.details().count() == 4);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 2);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName, QContactPhoneNumber::FieldNumber, QString("12345678")).count() == 1);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName, QString(), QString("12345678")).count() == c.details(QContactPhoneNumber::DefinitionName).count());
QVERIFY(c.details<QContactPhoneNumber>().count() == 2);
QVERIFY(!c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(!c.detail<QContactPhoneNumber>().isEmpty());
QCOMPARE(c.detail<QContactPhoneNumber>(), p);
QVERIFY(c.removeDetail(&p2));
// now try removing a detail for which we've set a preference
QContactEmailAddress pref;
pref.setEmailAddress("test@test");
c.saveDetail(&pref);
c.setPreferredDetail("SendEmail", pref);
QVERIFY(c.isPreferredDetail(QString(), pref));
QVERIFY(c.removeDetail(&pref));
QVERIFY(!c.isPreferredDetail(QString(), pref));
// Now try adding a detail to multiple contacts
QContact c2;
QVERIFY(c2.isEmpty() == true);
QVERIFY(c.saveDetail(&p));
QVERIFY(c2.saveDetail(&p));
QVERIFY(c2.isEmpty() == false);
QVERIFY(c.details().count() == 3);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 1);
QVERIFY(c.details<QContactPhoneNumber>().count() == 1);
QVERIFY(!c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(!c.detail<QContactPhoneNumber>().isEmpty());
QCOMPARE(c.detail<QContactPhoneNumber>(), p);
QVERIFY(c2.details().count() == 3);
QVERIFY(c2.details(QContactPhoneNumber::DefinitionName).count() == 1);
QVERIFY(c2.details<QContactPhoneNumber>().count() == 1);
QVERIFY(!c2.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(!c2.detail<QContactPhoneNumber>().isEmpty());
QCOMPARE(c2.detail<QContactPhoneNumber>(), p);
// Now try removing it from one
QVERIFY(c.removeDetail(&p));
// Make sure it's gone from the first contact
QVERIFY(c.isEmpty() == true);
QVERIFY(c.details().count() == 2);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 0);
QVERIFY(c.details<QContactPhoneNumber>().count() == 0);
QVERIFY(c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(c.detail<QContactPhoneNumber>().isEmpty());
// but not the second
QVERIFY(c2.isEmpty() == false);
QVERIFY(c2.details().count() == 3);
QVERIFY(c2.details(QContactPhoneNumber::DefinitionName).count() == 1);
QVERIFY(c2.details<QContactPhoneNumber>().count() == 1);
QVERIFY(!c2.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(!c2.detail<QContactPhoneNumber>().isEmpty());
QCOMPARE(c2.detail<QContactPhoneNumber>(), p);
// Now remove it from the second as well
QVERIFY(c2.removeDetail(&p));
// Make sure it's gone from both
QVERIFY(c.details().count() == 2);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 0);
QVERIFY(c.details<QContactPhoneNumber>().count() == 0);
QVERIFY(c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(c.detail<QContactPhoneNumber>().isEmpty());
QVERIFY(c2.details().count() == 2);
QVERIFY(c2.details(QContactPhoneNumber::DefinitionName).count() == 0);
QVERIFY(c2.details<QContactPhoneNumber>().count() == 0);
QVERIFY(c2.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(c2.detail<QContactPhoneNumber>().isEmpty());
// add a, add b, remove a, add a, remove b, remove a
QVERIFY(c.saveDetail(&p));
QVERIFY(c2.saveDetail(&p));
QVERIFY(c.removeDetail(&p));
QVERIFY(c.saveDetail(&p));
QVERIFY(c2.removeDetail(&p));
QVERIFY(c.removeDetail(&p));
// Now add a detail with the same values twice
QContactPhoneNumber one;
QContactPhoneNumber two;
one.setNumber("12345");
two.setNumber("12345");
// add it once
QVERIFY(c.saveDetail(&one));
QVERIFY(c.details().count() == 3);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 1);
QVERIFY(c.details<QContactPhoneNumber>().count() == 1);
QVERIFY(!c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(!c.detail<QContactPhoneNumber>().isEmpty());
QCOMPARE(c.detail<QContactPhoneNumber>(), one);
// add it twice
QVERIFY(c.saveDetail(&two));
QVERIFY(c.details().count() == 4);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 2);
QVERIFY(c.details<QContactPhoneNumber>().count() == 2);
QVERIFY(!c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(!c.detail<QContactPhoneNumber>().isEmpty());
QCOMPARE(c.detail<QContactPhoneNumber>(), one);
QCOMPARE(c.details<QContactPhoneNumber>()[0], one);
QCOMPARE(c.details<QContactPhoneNumber>()[1], two);
// Remove it once
QVERIFY(c.removeDetail(&one));
QVERIFY(c.details().count() == 3);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 1);
QVERIFY(c.details<QContactPhoneNumber>().count() == 1);
QVERIFY(!c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(!c.detail<QContactPhoneNumber>().isEmpty());
QCOMPARE(c.detail<QContactPhoneNumber>(), two);
// Remove it twice
QVERIFY(c.removeDetail(&two));
QVERIFY(c.details().count() == 2);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 0);
QVERIFY(c.details<QContactPhoneNumber>().count() == 0);
QVERIFY(c.detail(QContactPhoneNumber::DefinitionName).isEmpty());
QVERIFY(c.detail<QContactPhoneNumber>().isEmpty());
// Null pointer tests
QVERIFY(c.saveDetail(0) == false);
QVERIFY(c.removeDetail(0) == false);
// Reference tests...
QContactDetail& ref = one;
QVERIFY(c.saveDetail(&one));
QVERIFY(ref == one);
one.setNumber("56678");
QVERIFY(c.saveDetail(&one));
QVERIFY(ref == one);
// Retrieve the detail again and modify it
QContactPhoneNumber three = c.detail<QContactPhoneNumber>();
QVERIFY(ref == three);
QVERIFY(one == three);
three.setNumber("542343");
QVERIFY(c.saveDetail(&three));
// Now see if we got any updates to ref/one
QVERIFY(ref == one);
QVERIFY(ref != three);
// test saving of a detail with an empty field.
QContactPhoneNumber four;
four.setNumber("");
c.saveDetail(&four);
QVERIFY(c.details(QContactPhoneNumber::DefinitionName).count() == 2);
QVERIFY(!four.values().isEmpty()); // an empty qstring is not invalid; make sure it exists in the detail.
// ensure that clearing a contact's details works correctly
c.setDisplayLabel("test");
QVERIFY(!c.displayLabel().isSynthesised());
QCOMPARE(c.displayLabel().label(), QString("test"));
QVERIFY(c.details().size() > 0);
QVERIFY(!c.isEmpty());
QContactId oldId = c.id();
c.clearDetails();
QVERIFY(c.details().size() == 1); // always has a display label.
QCOMPARE(c.displayLabel().label(), QString());
QVERIFY(c.displayLabel().isSynthesised());
QVERIFY(c.isEmpty());
QCOMPARE(c.id(), oldId); // id shouldn't change.
}
void tst_QContact::actions()
{
QContact c; // empty contact.
QContact c2; // contact with email saved.
QContactEmailAddress e;
e.setEmailAddress("test@nokia.com");
c2.saveDetail(&e);
// XXX this is here to make the bulk
// of this test pass. The first set
// of tests expect to not find plugins.
QString path = QApplication::applicationDirPath() + "/dummyplugin/plugins/";
QApplication::addLibraryPath(path);
// Prior to plugin loading:
// first, the empty contact
QStringList availableActions = c.availableActions();
QVERIFY(availableActions.isEmpty());
QContactDetail d = c.detailWithAction("SendEmail");
QVERIFY(d.isEmpty());
QList<QContactDetail> dets = c.detailsWithAction("SendEmail");
QVERIFY(dets.isEmpty());
// then, the email contact
availableActions = c2.availableActions();
QEXPECT_FAIL("", "Plugins are only loaded once", Continue);
QVERIFY(availableActions.isEmpty());
d = c2.detailWithAction("SendEmail");
QEXPECT_FAIL("", "Plugins are only loaded once", Continue);
QVERIFY(d.isEmpty());
dets = c2.detailsWithAction("SendEmail");
QEXPECT_FAIL("", "Plugins are only loaded once", Continue);
QVERIFY(dets.isEmpty());
// set the correct path to look for plugins and load them
// QString path = QApplication::applicationDirPath() + "/dummyplugin/plugins/";
// QApplication::addLibraryPath(path);
// available actions - should be one there now.
// empty contact
availableActions = c.availableActions();
QVERIFY(availableActions.isEmpty());
// contact with email
availableActions = c2.availableActions();
QVERIFY(availableActions.contains("SendEmail"));
// detail with action:
// empty contact
d = c.detailWithAction("SendEmail");
QVERIFY(d.isEmpty());
d = c.detailWithAction("NonexistentAction");
QVERIFY(d.isEmpty());
d = c.detailWithAction(QString());
QVERIFY(d.isEmpty());
// contact with email
d = c2.detailWithAction("SendEmail");
QVERIFY(d == e);
d = c2.detailWithAction("NonexistentAction");
QVERIFY(d.isEmpty());
d = c2.detailWithAction(QString());
QVERIFY(d.isEmpty());
// details with action:
// empty contact
dets = c.detailsWithAction("SendEmail");
QVERIFY(dets.isEmpty());
dets = c.detailsWithAction("NonexistentAction");
QVERIFY(dets.isEmpty());
dets = c.detailsWithAction(QString());
QVERIFY(dets.isEmpty());
// contact with email
dets = c2.detailsWithAction("SendEmail");
QVERIFY(dets.contains(e));
dets = c2.detailsWithAction("NonexistentAction");
QVERIFY(dets.isEmpty());
dets = c2.detailsWithAction(QString());
QVERIFY(dets.isEmpty());
// remove the library path.
QApplication::removeLibraryPath(path);
}
void tst_QContact::preferences()
{
QContact c;
// test first set
QContactDetail det("TestId");
det.setValue("test", QVariant("test1"));
c.saveDetail(&det);
QCOMPARE(c.isPreferredDetail("testAction", det), false);
QCOMPARE(c.setPreferredDetail("testAction", det), true);
QCOMPARE(c.isPreferredDetail("testAction", det), true);
QCOMPARE(c.isPreferredDetail(QString(), det), true);
QCOMPARE(c.preferredDetail("testAction"), det);
// test replacement
QContactDetail det2("TestId");
det2.setValue("test", QVariant("test2"));
c.saveDetail(&det2);
QCOMPARE(c.isPreferredDetail("testAction", det2), false);
QCOMPARE(c.setPreferredDetail("testAction", det2), true);
QCOMPARE(c.isPreferredDetail("testAction", det2), true);
QCOMPARE(c.isPreferredDetail("testAction", det), false);
QCOMPARE(c.preferredDetail("testAction"), det2);
// test for detail that is not part of the contact
QContactDetail det3("TestId");
det3.setValue("test", QVariant("test3"));
QCOMPARE(c.setPreferredDetail("testAction", det3), false);
QCOMPARE(c.preferredDetail("testAction"), det2); // shouldn't have changed.
// test invalid set
QCOMPARE(c.setPreferredDetail(QString(), det3), false);
QCOMPARE(c.setPreferredDetail(QString(), QContactDetail()), false);
QCOMPARE(c.setPreferredDetail("testAction", QContactDetail()), false);
QCOMPARE(c.preferredDetail("testAction"), det2); // shouldn't have changed.
// test invalid query
QContactDetail det4;
det4.setValue("test", QVariant("test4"));
c.saveDetail(&det4);
QCOMPARE(c.isPreferredDetail(QString(), QContactDetail()), false);
QCOMPARE(c.isPreferredDetail(QString(), det4), false); // valid detail, but no pref set.
QCOMPARE(c.isPreferredDetail("testAction", QContactDetail()), false);
// test retrieving preferred details
QContactDetail pd = c.preferredDetail(QString());
QVERIFY(pd.isEmpty());
pd = c.preferredDetail("testAction");
QVERIFY(pd == det2); // shouldn't have changed.
// test for preference for action that hasn't been added
QVERIFY(c.preferredDetail("NonexistentAction").isEmpty());
// Remove a non preferred detail
QContactDetail det2copy("TestId");
det2copy.setValue("test", QVariant("test2"));
QVERIFY(c.saveDetail(&det2copy));
QVERIFY(c.isPreferredDetail("testAction", det2) == true);
QVERIFY(c.isPreferredDetail("testAction", det2copy) == false);
QVERIFY(c.removeDetail(&det2copy));
QVERIFY(c.isPreferredDetail("testAction", det2) == true);
QVERIFY(c.isPreferredDetail("testAction", det2copy) == false);
// Add it again
QVERIFY(c.saveDetail(&det2copy));
QVERIFY(c.isPreferredDetail("testAction", det2) == true);
QVERIFY(c.isPreferredDetail("testAction", det2copy) == false);
// Remove the preferred detail (the copy should not become preferred)
QVERIFY(c.removeDetail(&det2));
QVERIFY(c.isPreferredDetail("testAction", det2) == false);
QVERIFY(c.isPreferredDetail("testAction", det2copy) == false);
}
void tst_QContact::relationships()
{
QContact c;
// boring test, because the default contact has no relationships
// we test this more convincingly in the QContactManager tests.
QList<QContactId> related = c.relatedContacts();
QVERIFY(related.isEmpty());
related = c.relatedContacts(QContactRelationship::HasMember);
QVERIFY(related.isEmpty());
related = c.relatedContacts(QContactRelationship::HasMember, QContactRelationshipFilter::First);
QVERIFY(related.isEmpty());
QList<QContactRelationship> relationshipList = c.relationships();
QVERIFY(relationshipList.isEmpty());
relationshipList = c.relationships(QContactRelationship::HasMember);
QVERIFY(relationshipList.isEmpty());
// now test that we can change the order of relationships regardless of the number of relationships
QList<QContactRelationship> orderedList = c.relationshipOrder();
QVERIFY(orderedList == relationshipList); // should be the same by default
QContactRelationship dummyRel;
QContactId firstId;
firstId.setManagerUri("test-nokia");
firstId.setLocalId(QContactLocalId(5));
QContactId secondId;
secondId.setManagerUri("test-nokia-2");
secondId.setLocalId(QContactLocalId(5));
dummyRel.setFirst(firstId);
dummyRel.setSecond(secondId);
dummyRel.setRelationshipType(QContactRelationship::IsAssistantOf);
QList<QContactRelationship> reorderedList;
reorderedList.append(dummyRel);
c.setRelationshipOrder(reorderedList);
QVERIFY(c.relationshipOrder() == reorderedList);
}
void tst_QContact::displayName()
{
QContact c;
QContactManager cm("memory"); // for formatting names
QContactDisplayLabel label = c.displayLabel();
QVERIFY(label.label().isEmpty());
QVERIFY(c.displayLabel().isSynthesised() == true);
label.setLabel("Wesley Wentworth Worrier");
QVERIFY(label.isEmpty() == false);
QVERIFY(label.label().isEmpty() == false);
QVERIFY(label.isSynthesised() == false);
label.setSynthesised(true);
c.setDisplayLabel(label);
QVERIFY(c.displayLabel().label() == "Wesley Wentworth Worrier");
QVERIFY(c.displayLabel().isSynthesised() == true);
//label.setLabel(QString());
//QVERIFY(label.isSynthesised() == true);
/* Clear the label again */
c.setDisplayLabel(QString());
QVERIFY(c.displayLabel().label().isEmpty());
QVERIFY(c.displayLabel().isSynthesised() == true);
/* Use the string mutator */
c.setDisplayLabel("Wesley Wentworth Worrier");
QVERIFY(c.displayLabel().label() == "Wesley Wentworth Worrier");
QVERIFY(c.displayLabel().isSynthesised() == false);
/* Try to make this a bit more consistent by using a single name */
QContact d;
QContactName name;
name.setFirst("Wesley");
QVERIFY(d.displayLabel().label().isEmpty());
QVERIFY(d.saveDetail(&name));
/*
* The display label is not updated until you save the contact, or
* do it manually.
*/
QString synth = cm.synthesiseDisplayLabel(d);
QVERIFY(d.displayLabel().label().isEmpty());
QVERIFY(d.displayLabel().isSynthesised() == true);
QVERIFY(synth == name.first()); // XXX Perhaps not guaranteed
/* Set something else */
d.setDisplayLabel("The grand old duchess");
QVERIFY(d.displayLabel().label() == "The grand old duchess");
QVERIFY(d.displayLabel().isSynthesised() == false);
/* Remove the detail via removeDetail */
QContactDisplayLabel old = d.displayLabel();
QVERIFY(d.details().count() == 3);
QVERIFY(d.removeDetail(&old));
QVERIFY(d.isEmpty() == false);
QVERIFY(d.details().count() == 3); // it should not be removed, only cleared (!)
/* Make sure we go back to the old synth version */
QVERIFY(d.displayLabel().isSynthesised() == true);
QVERIFY(d.displayLabel().label().isEmpty());
}
void tst_QContact::type()
{
QContact c;
QVERIFY(c.isEmpty() == true);
// ensure that the default type is the QContactType::TypeContact type
QVERIFY(c.type() == QString(QLatin1String(QContactType::TypeContact)));
// now set it to be a group via the type mutator, and test that it works
QContactType groupType;
groupType.setType(QString(QLatin1String(QContactType::TypeGroup)));
c.setType(groupType);
QVERIFY(c.type() == QString(QLatin1String(QContactType::TypeGroup)));
// set it back to a contact, via the string mutator
c.setType(QContactType::TypeContact);
QVERIFY(c.type() == QString(QLatin1String(QContactType::TypeContact)));
QVERIFY(c.isEmpty() == true); // type doesn't affect emptiness
}
void tst_QContact::emptiness()
{
QContact c;
QVERIFY(c.isEmpty() == true);
QContactDisplayLabel label = c.displayLabel();
QVERIFY(label.label().isEmpty());
label.setLabel("Wesley Wentworth Worrier");
QVERIFY(label.isEmpty() == false);
QVERIFY(label.label().isEmpty() == false);
c.setDisplayLabel(label);
QVERIFY(c.isEmpty() == false);
QVERIFY(c.displayLabel().label() == "Wesley Wentworth Worrier");
QVERIFY(c.displayLabel().isSynthesised() == false);
c.setDisplayLabel(QString());
QVERIFY(c.isEmpty() == true);
c.setType(QContactType::TypeContact);
QVERIFY(c.type() == QString(QLatin1String(QContactType::TypeContact)));
QVERIFY(c.isEmpty() == true); // type doesn't affect emptiness
}
QTEST_MAIN(tst_QContact)
#include "tst_qcontact.moc"
|
// @(#)root/proofplayer:$Id$
// Author: Maarten Ballintijn 07/01/02
// Modified: Long Tran-Thanh 04/09/07 (Addition of TEventIterUnit)
/*************************************************************************
* Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TEventIter //
// //
// Special iterator class used in TProofPlayer to iterate over events //
// or objects in the packets. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TEnv.h"
#include "TEventIter.h"
#include "TCollection.h"
#include "TDSet.h"
#include "TFile.h"
#include "TKey.h"
#include "TProofDebug.h"
#include "TSelector.h"
#include "TTimeStamp.h"
#include "TTree.h"
#include "TTreeCache.h"
#include "TVirtualPerfStats.h"
#include "TEventList.h"
#include "TEntryList.h"
#include "TList.h"
#include "TMap.h"
#include "TObjString.h"
#include "TRegexp.h"
#include "TError.h"
ClassImp(TEventIter)
//______________________________________________________________________________
TEventIter::TEventIter()
{
// Default constructor
fDSet = 0;
fElem = 0;
fFile = 0;
fDir = 0;
fSel = 0;
fFirst = 0;
fCur = -1;
fNum = 0;
fStop = kFALSE;
fOldBytesRead = 0;
fEventList = 0;
fEntryList = 0;
}
//______________________________________________________________________________
TEventIter::TEventIter(TDSet *dset, TSelector *sel, Long64_t first, Long64_t num)
: fDSet(dset), fSel(sel)
{
// Constructor
fElem = 0;
fFile = 0;
fDir = 0;
fFirst = first;
fCur = -1;
fNum = num;
fStop = kFALSE;
fEventList = 0;
fEventListPos = 0;
fEntryList = 0;
fOldBytesRead = 0;
}
//______________________________________________________________________________
TEventIter::~TEventIter()
{
// Destructor
delete fFile;
}
//______________________________________________________________________________
void TEventIter::StopProcess(Bool_t /*abort*/)
{
// Set flag to stop the process
fStop = kTRUE;
}
//______________________________________________________________________________
TEventIter *TEventIter::Create(TDSet *dset, TSelector *sel, Long64_t first, Long64_t num)
{
// Create and instance of the appropriate iterator
if (dset->TestBit(TDSet::kEmpty)) {
return new TEventIterUnit(dset, sel, num);
} else if (dset->IsTree()) {
return new TEventIterTree(dset, sel, first, num);
} else {
return new TEventIterObj(dset, sel, first, num);
}
}
//______________________________________________________________________________
Int_t TEventIter::LoadDir()
{
// Load directory
Int_t ret = 0;
// Check Filename
if ( fFile == 0 || fFilename != fElem->GetFileName() ) {
fDir = 0;
delete fFile; fFile = 0;
fFilename = fElem->GetFileName();
TDirectory *dirsave = gDirectory;
Double_t start = 0;
if (gPerfStats != 0) start = TTimeStamp();
// Take into acoount possible prefixes
TFile::EFileType typ = TFile::kDefault;
TString fname = gEnv->GetValue("Path.Localroot","");
if (!fname.IsNull())
typ = TFile::GetType(fFilename, "", &fname);
if (typ != TFile::kLocal)
fname = fFilename;
fFile = TFile::Open(fname);
if (gPerfStats != 0) {
gPerfStats->FileOpenEvent(fFile, fFilename, double(TTimeStamp())-start);
fOldBytesRead = 0;
}
if (dirsave) dirsave->cd();
if (!fFile || fFile->IsZombie() ) {
if (fFile)
Error("Process","Cannot open file: %s (%s)",
fFilename.Data(), strerror(fFile->GetErrno()) );
else
Error("Process","Cannot open file: %s (errno unavailable)",
fFilename.Data());
// cleanup ?
return -1;
}
PDB(kLoop,2) Info("LoadDir","Opening file: %s", fFilename.Data() );
ret = 1;
}
// Check Directory
if ( fDir == 0 || fPath != fElem->GetDirectory() ) {
TDirectory *dirsave = gDirectory;
fPath = fElem->GetDirectory();
if ( !fFile->cd(fPath) ) {
Error("Process","Cannot cd to: %s",
fPath.Data() );
return -1;
}
PDB(kLoop,2) Info("Process","Cd to: %s", fPath.Data() );
fDir = gDirectory;
if (dirsave) dirsave->cd();
ret = 1;
}
return ret;
}
//------------------------------------------------------------------------
ClassImp(TEventIterUnit)
//______________________________________________________________________________
TEventIterUnit::TEventIterUnit()
{
// Default constructor
fDSet = 0;
fElem = 0;
fSel = 0;
fNum = 0;
fCurrent = 0;
fStop = kFALSE;
}
//______________________________________________________________________________
TEventIterUnit::TEventIterUnit(TDSet* dset, TSelector *sel, Long64_t num)
{
// Main constructor
fDSet = dset;
fElem = 0;
fSel = sel;
fNum = num;
fCurrent = 0;
fStop = kFALSE;
}
//______________________________________________________________________________
Long64_t TEventIterUnit::GetNextEvent()
{
// Get next event
if (fStop || fNum == 0)
return -1;
while (fElem == 0 || fCurrent == 0) {
fElem = fDSet->Next();
if (!fElem->TestBit(TDSetElement::kEmpty)) {
Error("GetNextEvent", "data element must be set to kEmtpy");
return -1;
}
fNum = fElem->GetNum();
if (!(fCurrent = fNum)) {
fNum = 0;
return -1;
}
}
--fCurrent;
return fCurrent;
}
//------------------------------------------------------------------------
ClassImp(TEventIterObj)
//______________________________________________________________________________
TEventIterObj::TEventIterObj()
{
// Default ctor.
fKeys = 0;
fNextKey = 0;
fObj = 0;
}
//______________________________________________________________________________
TEventIterObj::TEventIterObj(TDSet *dset, TSelector *sel, Long64_t first, Long64_t num)
: TEventIter(dset,sel,first,num)
{
// Constructor
fClassName = dset->GetType();
fKeys = 0;
fNextKey = 0;
fObj = 0;
}
//______________________________________________________________________________
TEventIterObj::~TEventIterObj()
{
// Destructor
// delete fKeys ?
delete fNextKey;
delete fObj;
}
//______________________________________________________________________________
Long64_t TEventIterObj::GetNextEvent()
{
// Get next event
if (fStop || fNum == 0) return -1;
while ( fElem == 0 || fElemNum == 0 || fCur < fFirst-1 ) {
if (gPerfStats != 0 && fFile != 0) {
Long64_t bytesRead = fFile->GetBytesRead();
gPerfStats->SetBytesRead(bytesRead - fOldBytesRead);
fOldBytesRead = bytesRead;
}
fElem = fDSet->Next(fKeys->GetSize());
if (fElem->GetEntryList()) {
Error("GetNextEvent", "Entry- or event-list not available");
return -1;
}
if ( fElem == 0 ) {
fNum = 0;
return -1;
}
Int_t r = LoadDir();
if ( r == -1 ) {
// Error has been reported
fNum = 0;
return -1;
} else if ( r == 1 ) {
// New file and/or directory
fKeys = fDir->GetListOfKeys();
fNextKey = new TIter(fKeys);
}
// Validate values for this element
fElemFirst = fElem->GetFirst();
fElemNum = fElem->GetNum();
fEntryList = dynamic_cast<TEntryList *>(fElem->GetEntryList());
fEventList = (fEntryList) ? (TEventList *)0
: dynamic_cast<TEventList *>(fElem->GetEntryList());
fEventListPos = 0;
if (fEventList)
fElemNum = fEventList->GetN();
Long64_t num = fKeys->GetSize();
if ( fElemFirst > num ) {
Error("GetNextEvent","First (%d) higher then number of keys (%d) in %d",
fElemFirst, num, fElem->GetName() );
fNum = 0;
return -1;
}
if ( fElemNum == -1 ) {
fElemNum = num - fElemFirst;
} else if ( fElemFirst+fElemNum > num ) {
Error("GetNextEvent","Num (%d) + First (%d) larger then number of keys (%d) in %s",
fElemNum, fElemFirst, num, fElem->GetDirectory() );
fElemNum = num - fElemFirst;
}
// Skip this element completely?
if ( fCur + fElemNum < fFirst ) {
fCur += fElemNum;
continue;
}
// Position within this element. TODO: more efficient?
fNextKey->Reset();
for(fElemCur = -1; fElemCur < fElemFirst-1 ; fElemCur++, fNextKey->Next()) { }
}
--fElemNum;
++fElemCur;
--fNum;
++fCur;
TKey *key = (TKey*) fNextKey->Next();
TDirectory *dirsave = gDirectory;
fDir->cd();
fObj = key->ReadObj();
if (dirsave) dirsave->cd();
fSel->SetObject( fObj );
return fElemCur;
}
//------------------------------------------------------------------------
//______________________________________________________________________________
TEventIterTree::TFileTree::TFileTree(const char *name, TFile *f)
: TNamed(name, ""), fUsed(kFALSE), fFile(f)
{
// Default ctor.
fTrees = new TList;
fTrees->SetOwner();
}
//______________________________________________________________________________
TEventIterTree::TFileTree::~TFileTree()
{
// Default cdtor.
// Avoid destroying the cache; must be placed before deleting the trees
fFile->SetCacheRead(0);
SafeDelete(fTrees);
SafeDelete(fFile);
}
ClassImp(TEventIterTree)
//______________________________________________________________________________
TEventIterTree::TEventIterTree()
{
// Default ctor.
fTree = 0;
fTreeCache = 0;
}
//______________________________________________________________________________
TEventIterTree::TEventIterTree(TDSet *dset, TSelector *sel, Long64_t first, Long64_t num)
: TEventIter(dset,sel,first,num)
{
// Constructor
fTreeName = dset->GetObjName();
fTree = 0;
fTreeCache = 0;
fFileTrees = new TList;
fFileTrees->SetOwner();
fUseTreeCache = gEnv->GetValue("ProofPlayer.UseTreeCache", 1);
}
//______________________________________________________________________________
TEventIterTree::~TEventIterTree()
{
// Destructor
// The cache is deleted in here
SafeDelete(fFileTrees);
SafeDelete(fTreeCache);
}
//______________________________________________________________________________
TTree* TEventIterTree::GetTrees(TDSetElement *elem)
{
// Create a Tree for the main TDSetElement and for all the friends.
// Returns the main tree or 0 in case of an error.
// Reset used flags
TIter nxft(fFileTrees);
TFileTree *ft = 0;
while ((ft = (TFileTree *)nxft()))
ft->fUsed = kFALSE;
TTree* main = Load(elem);
if (main && main != fTree) {
// Set the file cache
if (fUseTreeCache) {
TFile *curfile = main->GetCurrentFile();
if (!fTreeCache) {
main->SetCacheSize();
fTreeCache = (TTreeCache *)curfile->GetCacheRead();
} else {
curfile->SetCacheRead(fTreeCache);
fTreeCache->UpdateBranches(main, kTRUE);
}
}
// Also the friends
TList *friends = elem->GetListOfFriends();
if (friends) {
TIter nxf(friends);
TPair *p = 0;
while ((p = (TPair *) nxf())) {
TDSetElement *dse = (TDSetElement *) p->Key();
TObjString *str = (TObjString *) p->Value();
TTree* friendTree = Load(dse);
if (friendTree) {
main->AddFriend(friendTree, str->GetName());
} else {
return 0;
}
}
}
}
// Remove instances not used
nxft.Reset();
while ((ft = (TFileTree *)nxft())) {
if (!(ft->fUsed)) {
fFileTrees->Remove(ft);
delete ft;
}
}
// Done, successfully or not
return main;
}
//______________________________________________________________________________
TTree* TEventIterTree::Load(TDSetElement *e)
{
// Load a tree from s TDSetElement
if (!e) {
Error("Load","undefined element", e->GetFileName());
return (TTree *)0;
}
const char *fn = e->GetFileName();
const char *dn = e->GetDirectory();
const char *tn = e->GetObjName();
TFile *f = 0;
// Check if the file is already open
TString names(fn);
TString name;
Ssiz_t from = 0;
TFileTree *ft = 0;
while (names.Tokenize(name,from,"|")) {
TString key(TUrl(name).GetFileAndOptions());
if ((ft = (TFileTree *) fFileTrees->FindObject(key.Data()))) {
f = ft->fFile;
break;
}
}
// Open the file, if needed
if (!f) {
TFile::EFileType typ = TFile::kDefault;
TString fname = gEnv->GetValue("Path.Localroot","");
if (!fname.IsNull())
typ = TFile::GetType(fn, "", &fname);
if (typ != TFile::kLocal)
fname = fn;
// Open the file
f = TFile::Open(fname);
if (!f) {
Error("GetTrees","file '%s' ('%s') could not be open", fn, fname.Data());
return (TTree *)0;
}
// Create TFileTree instance in the list
ft = new TFileTree(TUrl(f->GetName()).GetFileAndOptions(), f);
fFileTrees->Add(ft);
}
// Check if the tree is already loaded
if (ft && ft->fTrees->GetSize() > 0) {
TTree *t = 0;
if (!strcmp(tn, "*"))
t = (TTree *) ft->fTrees->First();
else
t = (TTree *) ft->fTrees->FindObject(tn);
if (t) {
ft->fUsed = kTRUE;
return t;
}
}
TDirectory *dd = f;
// Change dir, if required
if (dn && !(dd = f->GetDirectory(dn))) {
Error("Load","Cannot get to: %s", dn);
return (TTree *)0;
}
PDB(kLoop,2)
Info("Load","got directory: %s", dn);
// If a wild card we will use the first object of the type
// requested compatible with the reg expression we got
TString on(tn);
TString sreg(tn);
if (sreg.Length() <= 0 || sreg == "" || sreg.Contains("*")) {
if (sreg.Contains("*"))
sreg.ReplaceAll("*", ".*");
else
sreg = ".*";
TRegexp re(sreg);
if (dd->GetListOfKeys()) {
TIter nxk(dd->GetListOfKeys());
TKey *k = 0;
while ((k = (TKey *) nxk())) {
if (!strcmp(k->GetClassName(), "TTree")) {
TString kn(k->GetName());
if (kn.Index(re) != kNPOS) {
on = kn;
break;
}
}
}
}
}
// Point to the key
TKey *key = dd->GetKey(on);
if (key == 0) {
Error("Load", "Cannot find tree \"%s\" in %s", tn, fn);
return (TTree*)0;
}
PDB(kLoop,2)
Info("Load", "Reading: %s", tn);
TTree *tree = dynamic_cast<TTree*> (key->ReadObj());
dd->cd();
if (tree == 0) {
Error("Load", "Cannot <dynamic_cast> obj to tree \"%s\"", tn);
return (TTree*)0;
}
// Add track in the cache
ft->fTrees->Add(tree);
ft->fUsed = kTRUE;
// Done
return tree;
}
//______________________________________________________________________________
Long64_t TEventIterTree::GetNextEvent()
{
// Get next event
if (fStop || fNum == 0) return -1;
Bool_t attach = kFALSE;
while ( fElem == 0 || fElemNum == 0 || fCur < fFirst-1 ) {
if (gPerfStats != 0 && fTree != 0) {
Long64_t totBytesRead = fTree->GetCurrentFile()->GetBytesRead();
Long64_t bytesRead = totBytesRead - fOldBytesRead;
gPerfStats->SetBytesRead(bytesRead);
fOldBytesRead = totBytesRead;
}
SafeDelete(fElem);
while (!fElem) {
if (fTree) {
fElem = fDSet->Next(fTree->GetEntries());
} else {
fElem = fDSet->Next();
}
if (!fElem) {
// End of processing
fNum = 0;
return -1;
}
TTree *newTree = GetTrees(fElem);
if (newTree) {
if (newTree != fTree) {
// The old tree is wonwd by TFileTree and will be deleted there
fTree = newTree;
attach = kTRUE;
fOldBytesRead = fTree->GetCurrentFile()->GetBytesRead();
}
} else {
// Could not open this element: ask for another one
SafeDelete(fElem);
// The current tree, if any, is not valid anymore
fTree = 0;
}
}
// Validate values for this element
fElemFirst = fElem->GetFirst();
fElemNum = fElem->GetNum();
fEntryList = dynamic_cast<TEntryList *>(fElem->GetEntryList());
fEventList = (fEntryList) ? (TEventList *)0
: dynamic_cast<TEventList *>(fElem->GetEntryList());
fEntryListPos = fElemFirst;
fEventListPos = 0;
if (fEntryList)
fElemNum = fEntryList->GetEntriesToProcess();
else if (fEventList)
fElemNum = fEventList->GetN();
Long64_t num = (Long64_t) fTree->GetEntries();
if (!fEntryList && !fEventList) {
if ( fElemFirst > num ) {
Error("GetNextEvent","First (%d) higher then number of entries (%d) in %s",
fElemFirst, num, fElem->GetObjName() );
fNum = 0;
return -1;
}
if ( fElemNum == -1 ) {
fElemNum = num - fElemFirst;
} else if ( fElemFirst+fElemNum > num ) {
Error("GetNextEvent","Num (%d) + First (%d) larger then number of entries (%d) in %s",
fElemNum, fElemFirst, num, fElem->GetName() );
fElemNum = num - fElemFirst;
}
// Skip this element completely?
if ( fCur + fElemNum < fFirst ) {
fCur += fElemNum;
continue;
}
// Position within this element. TODO: more efficient?
fElemCur = fElemFirst-1;
}
}
if ( attach ) {
PDB(kLoop,1) Info("GetNextEvent","Call Init(%p) and Notify()",fTree);
fSel->Init(fTree);
fSel->Notify();
TIter next(fSel->GetOutputList());
TEntryList *elist=0;
while ((elist=(TEntryList*)next())){
if (elist->InheritsFrom(TEntryList::Class()))
elist->SetTree(fTree->GetName(), fElem->GetFileName());
}
if (fSel->GetAbort() == TSelector::kAbortProcess) {
// the error has been reported
return -1;
}
attach = kFALSE;
}
Long64_t rv;
if (fEntryList){
--fElemNum;
rv = fEntryList->GetEntry(fEntryListPos);
fEntryListPos++;
} else if (fEventList) {
--fElemNum;
rv = fEventList->GetEntry(fEventListPos);
fEventListPos++;
} else {
--fElemNum;
++fElemCur;
--fNum;
++fCur;
rv = fElemCur;
}
// For prefetching
fTree->LoadTree(rv);
return rv;
}
Add missing protection
git-svn-id: ecbadac9c76e8cf640a0bca86f6bd796c98521e3@23750 27541ba8-7e3a-0410-8455-c3a389f83636
// @(#)root/proofplayer:$Id$
// Author: Maarten Ballintijn 07/01/02
// Modified: Long Tran-Thanh 04/09/07 (Addition of TEventIterUnit)
/*************************************************************************
* Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TEventIter //
// //
// Special iterator class used in TProofPlayer to iterate over events //
// or objects in the packets. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TEnv.h"
#include "TEventIter.h"
#include "TCollection.h"
#include "TDSet.h"
#include "TFile.h"
#include "TKey.h"
#include "TProofDebug.h"
#include "TSelector.h"
#include "TTimeStamp.h"
#include "TTree.h"
#include "TTreeCache.h"
#include "TVirtualPerfStats.h"
#include "TEventList.h"
#include "TEntryList.h"
#include "TList.h"
#include "TMap.h"
#include "TObjString.h"
#include "TRegexp.h"
#include "TError.h"
ClassImp(TEventIter)
//______________________________________________________________________________
TEventIter::TEventIter()
{
// Default constructor
fDSet = 0;
fElem = 0;
fFile = 0;
fDir = 0;
fSel = 0;
fFirst = 0;
fCur = -1;
fNum = 0;
fStop = kFALSE;
fOldBytesRead = 0;
fEventList = 0;
fEntryList = 0;
}
//______________________________________________________________________________
TEventIter::TEventIter(TDSet *dset, TSelector *sel, Long64_t first, Long64_t num)
: fDSet(dset), fSel(sel)
{
// Constructor
fElem = 0;
fFile = 0;
fDir = 0;
fFirst = first;
fCur = -1;
fNum = num;
fStop = kFALSE;
fEventList = 0;
fEventListPos = 0;
fEntryList = 0;
fOldBytesRead = 0;
}
//______________________________________________________________________________
TEventIter::~TEventIter()
{
// Destructor
delete fFile;
}
//______________________________________________________________________________
void TEventIter::StopProcess(Bool_t /*abort*/)
{
// Set flag to stop the process
fStop = kTRUE;
}
//______________________________________________________________________________
TEventIter *TEventIter::Create(TDSet *dset, TSelector *sel, Long64_t first, Long64_t num)
{
// Create and instance of the appropriate iterator
if (dset->TestBit(TDSet::kEmpty)) {
return new TEventIterUnit(dset, sel, num);
} else if (dset->IsTree()) {
return new TEventIterTree(dset, sel, first, num);
} else {
return new TEventIterObj(dset, sel, first, num);
}
}
//______________________________________________________________________________
Int_t TEventIter::LoadDir()
{
// Load directory
Int_t ret = 0;
// Check Filename
if ( fFile == 0 || fFilename != fElem->GetFileName() ) {
fDir = 0;
delete fFile; fFile = 0;
fFilename = fElem->GetFileName();
TDirectory *dirsave = gDirectory;
Double_t start = 0;
if (gPerfStats != 0) start = TTimeStamp();
// Take into acoount possible prefixes
TFile::EFileType typ = TFile::kDefault;
TString fname = gEnv->GetValue("Path.Localroot","");
if (!fname.IsNull())
typ = TFile::GetType(fFilename, "", &fname);
if (typ != TFile::kLocal)
fname = fFilename;
fFile = TFile::Open(fname);
if (gPerfStats != 0) {
gPerfStats->FileOpenEvent(fFile, fFilename, double(TTimeStamp())-start);
fOldBytesRead = 0;
}
if (dirsave) dirsave->cd();
if (!fFile || fFile->IsZombie() ) {
if (fFile)
Error("Process","Cannot open file: %s (%s)",
fFilename.Data(), strerror(fFile->GetErrno()) );
else
Error("Process","Cannot open file: %s (errno unavailable)",
fFilename.Data());
// cleanup ?
return -1;
}
PDB(kLoop,2) Info("LoadDir","Opening file: %s", fFilename.Data() );
ret = 1;
}
// Check Directory
if ( fDir == 0 || fPath != fElem->GetDirectory() ) {
TDirectory *dirsave = gDirectory;
fPath = fElem->GetDirectory();
if ( !fFile->cd(fPath) ) {
Error("Process","Cannot cd to: %s",
fPath.Data() );
return -1;
}
PDB(kLoop,2) Info("Process","Cd to: %s", fPath.Data() );
fDir = gDirectory;
if (dirsave) dirsave->cd();
ret = 1;
}
return ret;
}
//------------------------------------------------------------------------
ClassImp(TEventIterUnit)
//______________________________________________________________________________
TEventIterUnit::TEventIterUnit()
{
// Default constructor
fDSet = 0;
fElem = 0;
fSel = 0;
fNum = 0;
fCurrent = 0;
fStop = kFALSE;
}
//______________________________________________________________________________
TEventIterUnit::TEventIterUnit(TDSet* dset, TSelector *sel, Long64_t num)
{
// Main constructor
fDSet = dset;
fElem = 0;
fSel = sel;
fNum = num;
fCurrent = 0;
fStop = kFALSE;
}
//______________________________________________________________________________
Long64_t TEventIterUnit::GetNextEvent()
{
// Get next event
if (fStop || fNum == 0)
return -1;
while (fElem == 0 || fCurrent == 0) {
if (!(fElem = fDSet->Next()))
return -1;
if (!fElem->TestBit(TDSetElement::kEmpty)) {
Error("GetNextEvent", "data element must be set to kEmtpy");
return -1;
}
fNum = fElem->GetNum();
if (!(fCurrent = fNum)) {
fNum = 0;
return -1;
}
}
--fCurrent;
return fCurrent;
}
//------------------------------------------------------------------------
ClassImp(TEventIterObj)
//______________________________________________________________________________
TEventIterObj::TEventIterObj()
{
// Default ctor.
fKeys = 0;
fNextKey = 0;
fObj = 0;
}
//______________________________________________________________________________
TEventIterObj::TEventIterObj(TDSet *dset, TSelector *sel, Long64_t first, Long64_t num)
: TEventIter(dset,sel,first,num)
{
// Constructor
fClassName = dset->GetType();
fKeys = 0;
fNextKey = 0;
fObj = 0;
}
//______________________________________________________________________________
TEventIterObj::~TEventIterObj()
{
// Destructor
// delete fKeys ?
delete fNextKey;
delete fObj;
}
//______________________________________________________________________________
Long64_t TEventIterObj::GetNextEvent()
{
// Get next event
if (fStop || fNum == 0) return -1;
while ( fElem == 0 || fElemNum == 0 || fCur < fFirst-1 ) {
if (gPerfStats != 0 && fFile != 0) {
Long64_t bytesRead = fFile->GetBytesRead();
gPerfStats->SetBytesRead(bytesRead - fOldBytesRead);
fOldBytesRead = bytesRead;
}
fElem = fDSet->Next(fKeys->GetSize());
if (fElem->GetEntryList()) {
Error("GetNextEvent", "Entry- or event-list not available");
return -1;
}
if ( fElem == 0 ) {
fNum = 0;
return -1;
}
Int_t r = LoadDir();
if ( r == -1 ) {
// Error has been reported
fNum = 0;
return -1;
} else if ( r == 1 ) {
// New file and/or directory
fKeys = fDir->GetListOfKeys();
fNextKey = new TIter(fKeys);
}
// Validate values for this element
fElemFirst = fElem->GetFirst();
fElemNum = fElem->GetNum();
fEntryList = dynamic_cast<TEntryList *>(fElem->GetEntryList());
fEventList = (fEntryList) ? (TEventList *)0
: dynamic_cast<TEventList *>(fElem->GetEntryList());
fEventListPos = 0;
if (fEventList)
fElemNum = fEventList->GetN();
Long64_t num = fKeys->GetSize();
if ( fElemFirst > num ) {
Error("GetNextEvent","First (%d) higher then number of keys (%d) in %d",
fElemFirst, num, fElem->GetName() );
fNum = 0;
return -1;
}
if ( fElemNum == -1 ) {
fElemNum = num - fElemFirst;
} else if ( fElemFirst+fElemNum > num ) {
Error("GetNextEvent","Num (%d) + First (%d) larger then number of keys (%d) in %s",
fElemNum, fElemFirst, num, fElem->GetDirectory() );
fElemNum = num - fElemFirst;
}
// Skip this element completely?
if ( fCur + fElemNum < fFirst ) {
fCur += fElemNum;
continue;
}
// Position within this element. TODO: more efficient?
fNextKey->Reset();
for(fElemCur = -1; fElemCur < fElemFirst-1 ; fElemCur++, fNextKey->Next()) { }
}
--fElemNum;
++fElemCur;
--fNum;
++fCur;
TKey *key = (TKey*) fNextKey->Next();
TDirectory *dirsave = gDirectory;
fDir->cd();
fObj = key->ReadObj();
if (dirsave) dirsave->cd();
fSel->SetObject( fObj );
return fElemCur;
}
//------------------------------------------------------------------------
//______________________________________________________________________________
TEventIterTree::TFileTree::TFileTree(const char *name, TFile *f)
: TNamed(name, ""), fUsed(kFALSE), fFile(f)
{
// Default ctor.
fTrees = new TList;
fTrees->SetOwner();
}
//______________________________________________________________________________
TEventIterTree::TFileTree::~TFileTree()
{
// Default cdtor.
// Avoid destroying the cache; must be placed before deleting the trees
fFile->SetCacheRead(0);
SafeDelete(fTrees);
SafeDelete(fFile);
}
ClassImp(TEventIterTree)
//______________________________________________________________________________
TEventIterTree::TEventIterTree()
{
// Default ctor.
fTree = 0;
fTreeCache = 0;
}
//______________________________________________________________________________
TEventIterTree::TEventIterTree(TDSet *dset, TSelector *sel, Long64_t first, Long64_t num)
: TEventIter(dset,sel,first,num)
{
// Constructor
fTreeName = dset->GetObjName();
fTree = 0;
fTreeCache = 0;
fFileTrees = new TList;
fFileTrees->SetOwner();
fUseTreeCache = gEnv->GetValue("ProofPlayer.UseTreeCache", 1);
}
//______________________________________________________________________________
TEventIterTree::~TEventIterTree()
{
// Destructor
// The cache is deleted in here
SafeDelete(fFileTrees);
SafeDelete(fTreeCache);
}
//______________________________________________________________________________
TTree* TEventIterTree::GetTrees(TDSetElement *elem)
{
// Create a Tree for the main TDSetElement and for all the friends.
// Returns the main tree or 0 in case of an error.
// Reset used flags
TIter nxft(fFileTrees);
TFileTree *ft = 0;
while ((ft = (TFileTree *)nxft()))
ft->fUsed = kFALSE;
TTree* main = Load(elem);
if (main && main != fTree) {
// Set the file cache
if (fUseTreeCache) {
TFile *curfile = main->GetCurrentFile();
if (!fTreeCache) {
main->SetCacheSize();
fTreeCache = (TTreeCache *)curfile->GetCacheRead();
} else {
curfile->SetCacheRead(fTreeCache);
fTreeCache->UpdateBranches(main, kTRUE);
}
}
// Also the friends
TList *friends = elem->GetListOfFriends();
if (friends) {
TIter nxf(friends);
TPair *p = 0;
while ((p = (TPair *) nxf())) {
TDSetElement *dse = (TDSetElement *) p->Key();
TObjString *str = (TObjString *) p->Value();
TTree* friendTree = Load(dse);
if (friendTree) {
main->AddFriend(friendTree, str->GetName());
} else {
return 0;
}
}
}
}
// Remove instances not used
nxft.Reset();
while ((ft = (TFileTree *)nxft())) {
if (!(ft->fUsed)) {
fFileTrees->Remove(ft);
delete ft;
}
}
// Done, successfully or not
return main;
}
//______________________________________________________________________________
TTree* TEventIterTree::Load(TDSetElement *e)
{
// Load a tree from s TDSetElement
if (!e) {
Error("Load","undefined element", e->GetFileName());
return (TTree *)0;
}
const char *fn = e->GetFileName();
const char *dn = e->GetDirectory();
const char *tn = e->GetObjName();
TFile *f = 0;
// Check if the file is already open
TString names(fn);
TString name;
Ssiz_t from = 0;
TFileTree *ft = 0;
while (names.Tokenize(name,from,"|")) {
TString key(TUrl(name).GetFileAndOptions());
if ((ft = (TFileTree *) fFileTrees->FindObject(key.Data()))) {
f = ft->fFile;
break;
}
}
// Open the file, if needed
if (!f) {
TFile::EFileType typ = TFile::kDefault;
TString fname = gEnv->GetValue("Path.Localroot","");
if (!fname.IsNull())
typ = TFile::GetType(fn, "", &fname);
if (typ != TFile::kLocal)
fname = fn;
// Open the file
f = TFile::Open(fname);
if (!f) {
Error("GetTrees","file '%s' ('%s') could not be open", fn, fname.Data());
return (TTree *)0;
}
// Create TFileTree instance in the list
ft = new TFileTree(TUrl(f->GetName()).GetFileAndOptions(), f);
fFileTrees->Add(ft);
}
// Check if the tree is already loaded
if (ft && ft->fTrees->GetSize() > 0) {
TTree *t = 0;
if (!strcmp(tn, "*"))
t = (TTree *) ft->fTrees->First();
else
t = (TTree *) ft->fTrees->FindObject(tn);
if (t) {
ft->fUsed = kTRUE;
return t;
}
}
TDirectory *dd = f;
// Change dir, if required
if (dn && !(dd = f->GetDirectory(dn))) {
Error("Load","Cannot get to: %s", dn);
return (TTree *)0;
}
PDB(kLoop,2)
Info("Load","got directory: %s", dn);
// If a wild card we will use the first object of the type
// requested compatible with the reg expression we got
TString on(tn);
TString sreg(tn);
if (sreg.Length() <= 0 || sreg == "" || sreg.Contains("*")) {
if (sreg.Contains("*"))
sreg.ReplaceAll("*", ".*");
else
sreg = ".*";
TRegexp re(sreg);
if (dd->GetListOfKeys()) {
TIter nxk(dd->GetListOfKeys());
TKey *k = 0;
while ((k = (TKey *) nxk())) {
if (!strcmp(k->GetClassName(), "TTree")) {
TString kn(k->GetName());
if (kn.Index(re) != kNPOS) {
on = kn;
break;
}
}
}
}
}
// Point to the key
TKey *key = dd->GetKey(on);
if (key == 0) {
Error("Load", "Cannot find tree \"%s\" in %s", tn, fn);
return (TTree*)0;
}
PDB(kLoop,2)
Info("Load", "Reading: %s", tn);
TTree *tree = dynamic_cast<TTree*> (key->ReadObj());
dd->cd();
if (tree == 0) {
Error("Load", "Cannot <dynamic_cast> obj to tree \"%s\"", tn);
return (TTree*)0;
}
// Add track in the cache
ft->fTrees->Add(tree);
ft->fUsed = kTRUE;
// Done
return tree;
}
//______________________________________________________________________________
Long64_t TEventIterTree::GetNextEvent()
{
// Get next event
if (fStop || fNum == 0) return -1;
Bool_t attach = kFALSE;
while ( fElem == 0 || fElemNum == 0 || fCur < fFirst-1 ) {
if (gPerfStats != 0 && fTree != 0) {
Long64_t totBytesRead = fTree->GetCurrentFile()->GetBytesRead();
Long64_t bytesRead = totBytesRead - fOldBytesRead;
gPerfStats->SetBytesRead(bytesRead);
fOldBytesRead = totBytesRead;
}
SafeDelete(fElem);
while (!fElem) {
if (fTree) {
fElem = fDSet->Next(fTree->GetEntries());
} else {
fElem = fDSet->Next();
}
if (!fElem) {
// End of processing
fNum = 0;
return -1;
}
TTree *newTree = GetTrees(fElem);
if (newTree) {
if (newTree != fTree) {
// The old tree is wonwd by TFileTree and will be deleted there
fTree = newTree;
attach = kTRUE;
fOldBytesRead = fTree->GetCurrentFile()->GetBytesRead();
}
} else {
// Could not open this element: ask for another one
SafeDelete(fElem);
// The current tree, if any, is not valid anymore
fTree = 0;
}
}
// Validate values for this element
fElemFirst = fElem->GetFirst();
fElemNum = fElem->GetNum();
fEntryList = dynamic_cast<TEntryList *>(fElem->GetEntryList());
fEventList = (fEntryList) ? (TEventList *)0
: dynamic_cast<TEventList *>(fElem->GetEntryList());
fEntryListPos = fElemFirst;
fEventListPos = 0;
if (fEntryList)
fElemNum = fEntryList->GetEntriesToProcess();
else if (fEventList)
fElemNum = fEventList->GetN();
Long64_t num = (Long64_t) fTree->GetEntries();
if (!fEntryList && !fEventList) {
if ( fElemFirst > num ) {
Error("GetNextEvent","First (%d) higher then number of entries (%d) in %s",
fElemFirst, num, fElem->GetObjName() );
fNum = 0;
return -1;
}
if ( fElemNum == -1 ) {
fElemNum = num - fElemFirst;
} else if ( fElemFirst+fElemNum > num ) {
Error("GetNextEvent","Num (%d) + First (%d) larger then number of entries (%d) in %s",
fElemNum, fElemFirst, num, fElem->GetName() );
fElemNum = num - fElemFirst;
}
// Skip this element completely?
if ( fCur + fElemNum < fFirst ) {
fCur += fElemNum;
continue;
}
// Position within this element. TODO: more efficient?
fElemCur = fElemFirst-1;
}
}
if ( attach ) {
PDB(kLoop,1) Info("GetNextEvent","Call Init(%p) and Notify()",fTree);
fSel->Init(fTree);
fSel->Notify();
TIter next(fSel->GetOutputList());
TEntryList *elist=0;
while ((elist=(TEntryList*)next())){
if (elist->InheritsFrom(TEntryList::Class()))
elist->SetTree(fTree->GetName(), fElem->GetFileName());
}
if (fSel->GetAbort() == TSelector::kAbortProcess) {
// the error has been reported
return -1;
}
attach = kFALSE;
}
Long64_t rv;
if (fEntryList){
--fElemNum;
rv = fEntryList->GetEntry(fEntryListPos);
fEntryListPos++;
} else if (fEventList) {
--fElemNum;
rv = fEventList->GetEntry(fEventListPos);
fEventListPos++;
} else {
--fElemNum;
++fElemCur;
--fNum;
++fCur;
rv = fElemCur;
}
// For prefetching
fTree->LoadTree(rv);
return rv;
}
|
/**
* @file MessageBuffers.hpp
* @ingroup bliss::io
* @author tpan
* @brief MessageBuffers base class and SendMessageBuffers subclass for buffering data for MPI send/receive
* @details SendMessageBuffers is a collection of in-memory Buffers that containing data that
* 1. will be sent to remote destinations, such as a MPI process
* 2. was received from remote destinations, such as a MPI process
*
* In contrast to BufferPool, whose purpose is to prevent local process from blocking waiting for a buffer to clear,
* MessageBuffer's purpose is to batch the data to be transmitted, using BufferPool to prevent local process from blocking.
*
* As there may be several different patterns of interactions between MessageBuffers and other MessageBuffers, MessageBuffers and
* local thread/process, there is a base class MessageBuffers that acts as proxy to the underlying BufferPool (memory management).
* Two subclasses are planned: SendMessageBuffers and RecvMessageBuffers, but only SendMessageBuffers has been implemented.
*
* Envisioned patterns of interaction:
* Send: MessageBuffers -> mpi send
* Recv: mpi recv -> MessageBuffers
* Forward: mpi recv -> mpi send
* Local: MessageBuffers -> MessageBuffers
*
* The SendMessageBuffers accumulates data in its internal buffer, and notifies the caller when a buffer is full.
*
* The (unimplemented) RecvMessageBuffers requires an event notification mechanism that works with callbacks to handle the received messages.
* This is currently implemented in CommunicationLayer.
*
*
* Copyright (c) 2014 Georgia Institute of Technology. All Rights Reserved.
*
* TODO add License
*/
#ifndef MESSAGEBUFFERS_HPP_
#define MESSAGEBUFFERS_HPP_
#include <vector>
#include <type_traits>
#include <typeinfo>
#include <iostream>
#include <sstream>
#include <mutex>
#include <condition_variable>
#include <xmmintrin.h>
#include "config.hpp"
#include "concurrent/buffer.hpp"
#include "concurrent/object_pool.hpp"
#include <atomic>
#include <iterator> // for ostream_iterator
namespace bliss
{
namespace io
{
/**
* @class MessageBuffers
* @brief a data structure to buffering/batching messages for communication
* @details Templated base class for a collection of buffers that are used for communication.
*
*
* The class contains a BufferPool, which contains an array of reusable Buffer objects for in-memory storage.
*
* @tparam LockType Indicates whether the class should be thread safe or not.
*/
template<bliss::concurrent::LockType PoolLT, bliss::concurrent::LockType BufferLT = PoolLT, int64_t BufferCapacity = 8192>
class MessageBuffers
{
// TODO: move consturctor and assignment operator to copy between thread safety levels.
public:
typedef Buffer<BufferLT, BufferCapacity> BufferType;
protected:
/// Internal BufferPool Type. typedefed only to shorten the usage.
typedef typename bliss::io::ObjectPool<PoolLT, BufferType> BufferPoolType;
public:
/// IdType of a Buffer, aliased from BufferPool
typedef typename BufferPoolType::ObjectPtrType BufferPtrType;
protected:
/// a pool of in-memory Buffers for storage.
BufferPoolType pool;
/**
* Gets the capacity of the Buffer instances.
* @return capacity of each buffer.
*/
const size_t getBufferCapacity() const {
return BufferCapacity;
}
/**
* @brief Constructor. creates a buffer given a specified per-buffer capacity, and the BufferPool capacity.
* @note Protected so base class function is not called directly.
*
* limit BufferPool to have unlimited capacity, so as to ensure that we don't get nullptrs and thus don't need to
* check in code.
*
*
* @param buffer_capacity the Buffer's maximum capacity. default to 8192.
* @param pool_capacity the BufferPool's capacity. default to unlimited.
*/
explicit MessageBuffers() : pool() {}; // unlimited size pool
/**
* @brief default copy constructor. deleted. since internal BufferPool does not allow copy construction/assignment.
* @note Protected so base class function is not called directly.
*
* @param other source MessageBuffers to copy from
*/
explicit MessageBuffers(const MessageBuffers<PoolLT, BufferLT, BufferCapacity>& other) = delete;
/**
* @brief default copy assignment operator. deleted. since internal BufferPool does not allow copy construction/assignment.
* @note Protected so base class function is not called directly.
*
* @param other source MessageBuffers to copy from
* @return self.
*/
MessageBuffers<PoolLT, BufferLT, BufferCapacity>& operator=(const MessageBuffers<PoolLT, BufferLT, BufferCapacity>& other) = delete;
/**
* @brief default move constructor.
* @note Protected so base class function is not called directly.
*
* @param other source MessageBuffers to move from
*/
explicit MessageBuffers(MessageBuffers<PoolLT, BufferLT, BufferCapacity>&& other) : pool(std::move(other.pool)) {};
/**
* @brief default move assignment operator.
* @note Protected so base class function is not called directly.
*
* @param other source MessageBuffers to move from
* @return self.
*/
MessageBuffers<PoolLT, BufferLT, BufferCapacity>& operator=(MessageBuffers<PoolLT, BufferLT, BufferCapacity>&& other) {
pool = std::move(other.pool);
return *this;
}
public:
/**
* @brief default destructor
*/
virtual ~MessageBuffers() {};
/**
* @brief Releases a Buffer by it's BufferPool id, after the buffer is no longer needed.
* @note this should be called on a buffer that is not being used by MessageBuffers, i.e. flush does not satisfy this.
*
* @note This to be called after the communication logic is done with the Send or Recv buffer.
*
* @param id Buffer's id (assigned from BufferPool)
*/
virtual void releaseBuffer(BufferPtrType ptr) {
pool.releaseObject(ptr);
}
protected:
/**
* @brief Convenience method to release and clear all current Buffers in the pool.
*/
virtual void reset() {
pool.reset();
}
};
/**
* @class SendMessageBuffers
* @brief SendMessageBuffers is a subclass of MessageBuffers designed to manage the actual buffering of data for a set of messaging targets.
* @details
*
* The class is designed with the following requirements in mind:
* 1. data is destined for some remote process identifiable by a process id (e.g. rank)
* 2. data is appended to buffer incrementally and with minimal blocking
* 3. calling thread has a mechanism to process a full buffer. e.g. send it
* 4. all data in a SendMessageBuffers are homogeneously typed.
*
* The class is implemented to support the requirement:
* 1. SendMessageBuffers is not aware of its data's type or metadata specifying its type.
* 2. SendMessageBuffers uses the base MessageBuffers class' internal BufferPool to reuse memory
* 3. SendMessageBuffers stores a vector of Buffer Ids (as assigned from BufferPool), thus mapping from process Rank to BufferId.
* 4. SendMessageBuffers provides an Append function to incrementally add data to the Buffer object for the targt process rank.
* 5. When a particular buffer is full, return the Buffer Id to the calling thread for it to process (send), and swap in an empty
* Buffer from BufferPool.
*
* An internal vector is used to map from target process rank to Buffer pointer. For multithreading flavors of message buffers,
* atomic<BufferType*> is used.
*
* @note
* pool size is unlimited so we would not get nullptr, and therefore do not need to check it.
*
* @note
* For Buffers that are full, the calling thread will need to track the full buffers' Ids as this class evicts a full Buffer's id from it's
* vector of Buffer Ids. The Calling Thread can do t his via a queue, as in the case of CommunicationLayer.
* Note that a Buffer is "in use" from the first call to the Buffer's append function to the completion of the send (e.g. via MPI Isend)
*
* @tparam LockType determines if this class should be thread safe
*/
template<bliss::concurrent::LockType PoolLT, bliss::concurrent::LockType BufferLT = PoolLT, int64_t BufferCapacity = 8192>
class SendMessageBuffers : public MessageBuffers<PoolLT, BufferLT, BufferCapacity>
{
public:
/// Id type of the Buffers
using BufferType = typename MessageBuffers<PoolLT, BufferLT, BufferCapacity>::BufferType;
using BufferPtrType = typename MessageBuffers<PoolLT, BufferLT, BufferCapacity>::BufferPtrType;
/// the BufferPoolType from parent class
using BufferPoolType = typename MessageBuffers<PoolLT, BufferLT, BufferCapacity>::BufferPoolType;
protected:
/// Vector of pointers (atomic). Provides a mapping from process id (0 to vector size), to bufferPtr (from BufferPool)
/// using vector of atomic pointers allows atomic swap of each pointer, without array of mutex or atomic_flags.
typedef typename std::conditional<PoolLT == bliss::concurrent::LockType::NONE, BufferType*, std::atomic<BufferType*> >::type BufferPtrTypeInternal;
std::vector< BufferPtrTypeInternal > buffers;
/// for synchronizing access to buffers (and pool).
mutable std::mutex mutex;
mutable std::atomic_flag spinlock;
private:
// private copy contructor
SendMessageBuffers(SendMessageBuffers&& other, const std::lock_guard<std::mutex>&) :
MessageBuffers<PoolLT, BufferLT, BufferCapacity>(std::move(other)), buffers(std::move(other.buffers))
{};
/**
* @brief default copy constructor. deleted.
* @param other source SendMessageBuffers to copy from.
*/
explicit SendMessageBuffers(const SendMessageBuffers<PoolLT, BufferLT, BufferCapacity> &other) = delete;
/**
* @brief default copy assignment operator, deleted.
* @param other source SendMessageBuffers to copy from.
* @return self
*/
SendMessageBuffers<PoolLT, BufferLT, BufferCapacity>& operator=(const SendMessageBuffers<PoolLT, BufferLT, BufferCapacity> &other) = delete;
/**
* @brief Default constructor, deleted
*/
SendMessageBuffers() = delete;
public:
/**
* @brief Constructor.
* @param numDests The number of messaging targets/destinations
* @param bufferCapacity The capacity of the individual buffers. default 8192.
* @param poolCapacity The capacity of the pool. default unbounded.
*/
explicit SendMessageBuffers(const int & numDests) :
MessageBuffers<PoolLT, BufferLT, BufferCapacity>(), buffers(numDests)
{
this->reset();
};
/**
* default move constructor. calls superclass move constructor first.
* @param other source SendMessageBuffers to move from.
*/
explicit SendMessageBuffers(SendMessageBuffers<PoolLT, BufferLT, BufferCapacity> && other) :
SendMessageBuffers(std::forward<SendMessageBuffers<PoolLT, BufferLT, BufferCapacity> >(other), std::lock_guard<std::mutex>(other.mutex)) {};
/**
* @brief default move assignment operator.
* @param other source SendMessageBuffers to move from.
* @return self
*/
SendMessageBuffers<PoolLT, BufferLT, BufferCapacity>& operator=(SendMessageBuffers<PoolLT, BufferLT, BufferCapacity> && other) {
std::unique_lock<std::mutex> mine(mutex, std::defer_lock),
hers(other.mutex, std::defer_lock);
std::lock(mine, hers);
this->pool = std::move(other.pool);
buffers.clear(); std::swap(buffers, other.buffers);
return *this;
}
/**
* @brief default destructor
*/
virtual ~SendMessageBuffers() {
buffers.clear();
};
/**
* @brief get the number of buffers. should be same as number of targets for messages
* @return number of buffers
*/
const size_t getSize() const {
return buffers.size();
}
/**
* @brief get a raw pointer to the the BufferId that a messaging target maps to.
* @details for simplicity, not distinguishing between thread safe and unsafe versions
*
* @param targetRank the target id for the messages.
* @return reference to the unique_ptr. when swapping, the content of the unique ptrs are swapped.
*/
// template<bliss::concurrent::LockType LT = PoolLT>
// const typename std::enable_if<LT != bliss::concurrent::LockType::NONE, BufferType*>::type at(const int targetRank) const {
// return buffers.at(targetRank).load(); // can use reference since we made pool unlimited, so never get nullptr
// }
BufferType* at(const int targetRank) const {
return (BufferType*)(buffers.at(targetRank)); // if atomic pointer, then will do load()
}
BufferType* operator[](const int targetRank) const {
return at(targetRank);
}
/**
* @brief Reset the current MessageBuffers instance by first clearing its list of Buffer Ids, then repopulate it from the pool.
* @note One thread only should call this.
*/
virtual void reset() {
std::lock_guard<std::mutex> lock(mutex);
int count = buffers.size();
// release all buffers back to pool
for (int i = 0; i < count; ++i) {
if (this->at(i)) {
this->at(i)->block_and_flush();
this->pool.releaseObject(this->at(i));
buffers.at(i) = nullptr;
}
}
// reset the pool. local vector should contain a bunch of nullptrs.
this->pool.reset();
// buffers.clear();
// buffers.resize(count);
// populate the buffers from the pool
for (int i = 0; i < count; ++i) {
printf("initializing buffer %p \n", this->at(i));
swapInEmptyBuffer<PoolLT>(i);
printf("initialized buffer %p blocked? %s, empty? %s\n", this->at(i), this->at(i)->is_read_only()? "y" : "n", this->at(i)->isEmpty() ? "y" : "n");
}
}
/** thread safety:
* called by commlayer's send/recv thread, so single threaded there
* called by sendMessageBuffer's swapInEmptyBuffer
* if threadsafe version of sendMessageBuffer, then the pointer to buffer to be released will be unique.
* if not threadsafe version, then the sendMessageBuffer should be used by a single threaded program, so buffer to release should be unique.
*
* overall, do not need to worry about multiple threads releasing the same buffer.
*/
virtual void releaseBuffer(BufferPtrType ptr) {
if (ptr) {
ptr->block_and_flush(); // if already blocked and flushed, no op.
MessageBuffers<PoolLT, BufferLT, BufferCapacity>::releaseBuffer(ptr);
}
}
/**
* @brief Appends data to the target message buffer.
* @details internally will try to swap in a new buffer when full, and notify the caller of the full buffer's id.
* need to return 2 things:
* 1. success/failure of current insert
* 2. indicator that there is a full buffer (the full buffer's id).
*
* Notes:
* on left side -
* targetBufferId is obtained outside of CAS, so when CAS is called to update bufferIdForProcId[dest], it may be different already (on left side)
* on right side -
* fullBufferId and bufferId[dest] are set atomically, but newTargetBufferId is obtained outside of CAS, so the id of the TargetBufferId
* may be more up to date than the CAS function results, which is okay. Note that a fullBuffer will be marked as blocked to prevent further append.
*
* Table of values and compare exchange behavior (called when a buffer if full and an empty buffer is swapped in.)
* targetBufferId, bufferIdForProcId[dest], newBufferId (from pool) -> fullBufferId, bufferId[dest], newTargetBufferId
* x x y x y y
* x x -1 x -1 -1
* x z y -1 z z
* x z -1 -1 z z
* x -1 y -1 -1 -1
* x -1 -1 -1 -1 -1
* -1 -1 y -1 y y
* -1 -1 -1 -1 -1 -1
* -1 z y -1 -1 -1
* -1 z -1 -1 -1 -1
*
* @note if failure, data to be inserted would need to be handled by the caller.
*
* @param[in] data data to be inserted, as byteArray
* @param[in] count number of bytes to be inserted in the the Buffer
* @param[in] dest messaging target for the data, decides which buffer to append into.
* @return std::pair containing the status of the append (boolean success/fail), and the id of a full buffer if there is one.
*/
std::pair<bool, BufferType*> append(const void* data, const size_t count, const int targetProc) {
//== if data being set is null, throw error
if (data == nullptr || count <= 0) {
throw (std::invalid_argument("ERROR: calling MessageBuffer append with nullptr"));
}
//== if there is not enough room for the new data in even a new buffer, LOGIC ERROR IN CODE: throw exception
if (count > this->getBufferCapacity()) {
throw (std::invalid_argument("ERROR: messageBuffer append with count exceeding Buffer capacity"));
}
//== if targetProc is outside the valid range, throw an error
if (targetProc < 0 || targetProc > getSize()) {
throw (std::invalid_argument("ERROR: messageBuffer append with invalid targetProc"));
}
// NOTE: BufferPool is unlimited in size, so don't need to check for nullptr, can just append directly. is append really atomic?
// question is what happens in unique_ptr when dereferencing the internal pointer - if the dereference happens before a unique_ptr swap
// from swapInEmptyBuffer, then append would use the old object. however, it was probably swapped because it's full,
// or flushing, so lock_read() would have been set for the full case. now it depends on what happens in append.
// if flush, then block is set just before swap, so it's more likely this thread enters append without a block.
unsigned int appendResult = this->at(targetProc)->append(data, count);
// printf("buffer blocked? %s, empty? %s\n", this->at(targetProc)->is_read_only()? "y" : "n", this->at(targetProc)->isEmpty() ? "y" : "n");
// now if appendResult is false, then we return false, but also swap in a new buffer.
// conditions are either full buffer, or blocked buffer.
// this call will mark the fullBuffer as blocked to prevent multiple write attempts while flushing the buffer
// ideally, we want it to be a reference that gets updated for all threads.
if (appendResult & 0x2) { // only 1 thread gets 0x2 result for a buffer. all other threads either writes successfully or fails.
return std::move(std::make_pair(appendResult & 0x1, swapInEmptyBuffer<PoolLT>(targetProc) ) );
} else {
//if (preswap != postswap) printf("ERROR: NOSWAP: preswap %p and postswap %p are not the same.\n", preswap, postswap);
return std::move(std::make_pair(appendResult & 0x1, nullptr));
}
}
/**
* flushes the buffer at rank targetProc.
*
* @note only 1 thread should call this per proc.
* multiple calls to this may be needed to get all data that are written to the new empty buffer.
*
* @param targetProc
* @return
*/
BufferType* flushBufferForRank(const int targetProc) {
//== if targetProc is outside the valid range, throw an error
if (targetProc < 0 || targetProc > getSize()) {
throw (std::invalid_argument("ERROR: messageBuffer append with invalid targetProc"));
}
// // block the old buffer (when append full, will block as well). each proc has a unique buffer.
// this->at(targetProc)->block_and_flush(); // this part can be concurrent.
//
// passing in getBufferIdForRank result to ensure atomicity.
// may return ABSENT if there is no available buffer to use.
auto old = swapInEmptyBuffer<PoolLT>(targetProc);
if (old) old->block_and_flush();
return old;
}
protected:
/**
* @brief Swap in an empty Buffer from BufferPool at the dest location in MessageBuffers. The old buffer is returned.
* @details The new buffer may be BufferPoolType::ABSENT (invalid buffer, when there is no available Buffer from pool)
*
* Effect: bufferIdForProcId[dest] gets a new Buffer Id, full Buffer is set to "blocked" to prevent further append.
*
* This is the THREAD SAFE version. Uses std::compare_exchange_strong to ensure that another thread hasn't swapped in a new Empty one already.
*
* @note we make the caller get the new bufferIdForProcId[dest] directly instead of returning by reference in the method parameter variable
* because this way there is less of a chance of race condition if a shared "old" variable was accidentally used.
* and the caller will likely prefer the most up to date bufferIdForProcId[dest] anyway.
*
* @note below is now relevant any more now that message buffer hold buffer ptrs and pool is unlimited.. we only have line 5 here.
* old is old assignment action
* ABSENT available not a valid case
* ABSENT at dest swap, return ABS
* ABSENT not at dest dest is already swapped. no op, return ABS
* not ABS available not used. block old, no swap. return ABS
* not ABS at dest swap, block old. return old
* not ABS not at dest being used. no op. return ABS
*
*
* @note: exchanges buffer at dest atomically.
* @note: because only thread that just fills a buffer will do exchange, only 1 thread does exchange at a time. can rely on pool's Lock to get one new buffer
* can be assured that each acquired new buffer will be used, and can ascertain that no 2 threads will replace the same full buffer.
*
* @tparam used to choose thread safe vs not verfsion of the method.
* @param dest position in bufferIdForProcId array to swap out
* @return the BufferId that was swapped out.
*/
template<bliss::concurrent::LockType LT = PoolLT>
typename std::enable_if<LT != bliss::concurrent::LockType::NONE, BufferType*>::type swapInEmptyBuffer(const int dest) {
auto ptr = this->pool.tryAcquireObject();
ptr->clear_and_unblock_writes();
auto oldbuf = buffers.at(dest).exchange(ptr);
if (oldbuf && oldbuf->isEmpty()) {
// printf("oldbuf %p, blocked? %s\n", oldbuf, oldbuf->is_read_only() ? "y" : "n");
releaseBuffer(oldbuf);
return nullptr;
}
else return oldbuf;
}
/**
* @brief Swap in an empty Buffer from BufferPool at the dest location in MessageBuffers. The old buffer is returned.
* @details The new buffer may be BufferPoolType::ABSENT (invalid buffer, when there is no available Buffer from pool)
*
* effect: bufferIdForProcId[dest] gets a new Buffer Id, full Buffer is set to "blocked" to prevent further append.
*
* this is the THREAD UNSAFE version
* @note we make the caller get the new bufferIdForProcId[dest] directly instead of returning by reference in the method parameter variable
* because this way there is less of a chance of race condition if a shared "old" variable was accidentally used.
* and the caller will likely prefer the most up to date bufferIdForProcId[dest] anyway.
*
* @note
* ABSENT available not a valid case
* ABSENT at dest swap, return ABS
* ABSENT not at dest dest is already swapped. no op, return ABS
* not ABS available not used. block old, no swap. return ABS
* not ABS at dest swap, block old. return old
* not ABS not at dest being used. no op. return ABS
*
* @note: requires that the queue at dest to be blocked.
*
*
* @tparam LT used to choose thread safe vs not verfsion of the method.
* @param dest position in bufferIdForProcId array to swap out
* @return the BufferId that was swapped out.
*/
template<bliss::concurrent::LockType LT = PoolLT>
typename std::enable_if<LT == bliss::concurrent::LockType::NONE, BufferType*>::type swapInEmptyBuffer(const int dest) {
auto oldbuf = this->at(dest);
buffers.at(dest) = this->pool.tryAcquireObject();
buffers.at(dest)->clear_and_unblock_writes();
if (oldbuf && oldbuf->isEmpty()) {
// printf("oldbuf %p, empty? %s\n", oldbuf, oldbuf->isEmpty() ? "y" : "n");
releaseBuffer(oldbuf);
return nullptr;
}
else return oldbuf; // swap the pointer to Buffer object, not Buffer's internal "data" pointer
}
};
} /* namespace io */
} /* namespace bliss */
#endif /* MESSAGEBUFFERS_HPP_ */
DEL: no need for thread_local_message_buffers class
|
/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/base/logging.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/util/shim_utils.h"
#include "xenia/kernel/xam/xam_private.h"
#include "xenia/kernel/xenumerator.h"
#include "xenia/xbox.h"
namespace xe {
namespace kernel {
namespace xam {
struct DeviceInfo {
uint32_t device_id;
uint32_t device_type;
uint64_t total_bytes;
uint64_t free_bytes;
wchar_t name[28];
};
static const DeviceInfo dummy_device_info_ = {
0xF00D0000,
1,
120ull * 1024ull * 1024ull * 1024ull, // 120GB
100ull * 1024ull * 1024ull * 1024ull, // 100GB, so it looks a little used.
L"Dummy HDD",
};
dword_result_t XamContentGetLicenseMask(lpdword_t mask_ptr,
lpunknown_t overlapped_ptr) {
// Each bit in the mask represents a granted license. Available licenses
// seems to vary from game to game, but most appear to use bit 0 to indicate
// if the game is purchased or not.
*mask_ptr = 0;
if (overlapped_ptr) {
kernel_state()->CompleteOverlappedImmediate(overlapped_ptr,
X_ERROR_SUCCESS);
return X_ERROR_IO_PENDING;
} else {
return X_ERROR_SUCCESS;
}
}
DECLARE_XAM_EXPORT2(XamContentGetLicenseMask, kContent, kStub, kHighFrequency);
dword_result_t XamContentGetDeviceName(dword_t device_id,
lpwstring_t name_buffer,
dword_t name_capacity) {
if ((device_id & 0xFFFF0000) != dummy_device_info_.device_id) {
return X_ERROR_DEVICE_NOT_CONNECTED;
}
if (name_capacity < wcslen(dummy_device_info_.name) + 1) {
return X_ERROR_INSUFFICIENT_BUFFER;
}
xe::store_and_swap<std::wstring>(name_buffer, dummy_device_info_.name);
return X_ERROR_SUCCESS;
}
DECLARE_XAM_EXPORT1(XamContentGetDeviceName, kContent, kImplemented);
dword_result_t XamContentGetDeviceState(dword_t device_id,
lpunknown_t overlapped_ptr) {
if ((device_id & 0xFFFF0000) != dummy_device_info_.device_id) {
if (overlapped_ptr) {
kernel_state()->CompleteOverlappedImmediateEx(
overlapped_ptr, X_ERROR_FUNCTION_FAILED, X_ERROR_DEVICE_NOT_CONNECTED,
0);
return X_ERROR_IO_PENDING;
} else {
return X_ERROR_DEVICE_NOT_CONNECTED;
}
}
if (overlapped_ptr) {
kernel_state()->CompleteOverlappedImmediate(overlapped_ptr,
X_ERROR_SUCCESS);
return X_ERROR_IO_PENDING;
} else {
return X_ERROR_SUCCESS;
}
}
DECLARE_XAM_EXPORT1(XamContentGetDeviceState, kContent, kStub);
typedef struct {
xe::be<uint32_t> device_id;
xe::be<uint32_t> unknown;
xe::be<uint64_t> total_bytes;
xe::be<uint64_t> free_bytes;
xe::be<uint16_t> name[28];
} X_CONTENT_DEVICE_DATA;
dword_result_t XamContentGetDeviceData(
dword_t device_id, pointer_t<X_CONTENT_DEVICE_DATA> device_data) {
if ((device_id & 0xFFFF0000) != dummy_device_info_.device_id) {
// TODO(benvanik): memset 0 the data?
return X_ERROR_DEVICE_NOT_CONNECTED;
}
device_data.Zero();
const auto& device_info = dummy_device_info_;
device_data->device_id = device_info.device_id;
device_data->unknown = device_id & 0xFFFF; // Fake it.
device_data->total_bytes = device_info.total_bytes;
device_data->free_bytes = device_info.free_bytes;
xe::store_and_swap<std::wstring>(&device_data->name[0], device_info.name);
return X_ERROR_SUCCESS;
}
DECLARE_XAM_EXPORT1(XamContentGetDeviceData, kContent, kImplemented);
dword_result_t XamContentResolve(dword_t user_index, lpvoid_t content_data_ptr,
lpunknown_t buffer_ptr, dword_t buffer_size,
dword_t unk1, dword_t unk2, dword_t unk3) {
auto content_data = XCONTENT_DATA((uint8_t*)content_data_ptr);
// Result of buffer_ptr is sent to RtlInitAnsiString.
// buffer_size is usually 260 (max path).
// Games expect zero if resolve was successful.
assert_always();
XELOGW("XamContentResolve unimplemented!");
return X_ERROR_NOT_FOUND;
}
DECLARE_XAM_EXPORT1(XamContentResolve, kContent, kStub);
// https://github.com/MrColdbird/gameservice/blob/master/ContentManager.cpp
// https://github.com/LestaD/SourceEngine2007/blob/master/se2007/engine/xboxsystem.cpp#L499
dword_result_t XamContentCreateEnumerator(dword_t user_index, dword_t device_id,
dword_t content_type,
dword_t content_flags,
dword_t items_per_enumerate,
lpdword_t buffer_size_ptr,
lpdword_t handle_out) {
assert_not_null(handle_out);
if ((device_id && (device_id & 0xFFFF0000) != dummy_device_info_.device_id) ||
!handle_out) {
if (buffer_size_ptr) {
*buffer_size_ptr = 0;
}
// TODO(benvanik): memset 0 the data?
return X_E_INVALIDARG;
}
if (buffer_size_ptr) {
*buffer_size_ptr = (uint32_t)XCONTENT_DATA::kSize * items_per_enumerate;
}
auto e = new XStaticEnumerator(kernel_state(), items_per_enumerate,
XCONTENT_DATA::kSize);
e->Initialize();
// Get all content data.
auto content_datas = kernel_state()->content_manager()->ListContent(
device_id ? static_cast<uint32_t>(device_id)
: dummy_device_info_.device_id,
content_type);
for (auto& content_data : content_datas) {
auto ptr = e->AppendItem();
assert_not_null(ptr);
content_data.Write(ptr);
}
XELOGD("XamContentCreateEnumerator: added %d items to enumerator",
e->item_count());
*handle_out = e->handle();
return X_ERROR_SUCCESS;
}
DECLARE_XAM_EXPORT1(XamContentCreateEnumerator, kContent, kImplemented);
dword_result_t XamContentCreateDeviceEnumerator(dword_t content_type,
dword_t content_flags,
dword_t max_count,
lpdword_t buffer_size_ptr,
lpdword_t handle_out) {
assert_not_null(handle_out);
if (buffer_size_ptr) {
*buffer_size_ptr = sizeof(DeviceInfo) * max_count;
}
auto e = new XStaticEnumerator(kernel_state(), max_count, sizeof(DeviceInfo));
e->Initialize();
// Copy our dummy device into the enumerator
DeviceInfo* dev = (DeviceInfo*)e->AppendItem();
if (dev) {
xe::store_and_swap(&dev->device_id, dummy_device_info_.device_id);
xe::store_and_swap(&dev->device_type, dummy_device_info_.device_type);
xe::store_and_swap(&dev->total_bytes, dummy_device_info_.total_bytes);
xe::store_and_swap(&dev->free_bytes, dummy_device_info_.free_bytes);
xe::copy_and_swap(dev->name, dummy_device_info_.name, 28);
}
*handle_out = e->handle();
return X_ERROR_SUCCESS;
}
DECLARE_XAM_EXPORT1(XamContentCreateDeviceEnumerator, kNone, kImplemented);
dword_result_t XamContentCreateEx(dword_t user_index, lpstring_t root_name,
lpvoid_t content_data_ptr, dword_t flags,
lpdword_t disposition_ptr,
lpdword_t license_mask_ptr,
dword_t cache_size, qword_t content_size,
lpvoid_t overlapped_ptr) {
X_RESULT result = X_ERROR_INVALID_PARAMETER;
auto content_data = XCONTENT_DATA((uint8_t*)content_data_ptr);
auto content_manager = kernel_state()->content_manager();
bool create = false;
bool open = false;
switch (flags & 0xF) {
case 1: // CREATE_NEW
// Fail if exists.
if (content_manager->ContentExists(content_data)) {
result = X_ERROR_ALREADY_EXISTS;
} else {
create = true;
}
break;
case 2: // CREATE_ALWAYS
// Overwrite existing, if any.
if (content_manager->ContentExists(content_data)) {
content_manager->DeleteContent(content_data);
create = true;
} else {
create = true;
}
break;
case 3: // OPEN_EXISTING
// Open only if exists.
if (!content_manager->ContentExists(content_data)) {
result = X_ERROR_PATH_NOT_FOUND;
} else {
open = true;
}
break;
case 4: // OPEN_ALWAYS
// Create if needed.
if (!content_manager->ContentExists(content_data)) {
create = true;
} else {
open = true;
}
break;
case 5: // TRUNCATE_EXISTING
// Fail if doesn't exist, if does exist delete and recreate.
if (!content_manager->ContentExists(content_data)) {
result = X_ERROR_PATH_NOT_FOUND;
} else {
content_manager->DeleteContent(content_data);
create = true;
}
break;
default:
assert_unhandled_case(flags & 0xF);
break;
}
// creation result
// 0 = ?
// 1 = created
// 2 = opened
uint32_t disposition = create ? 1 : 2;
if (disposition_ptr) {
if (overlapped_ptr) {
// If async always set to zero, but don't set to a real value.
*disposition_ptr = 0;
} else {
*disposition_ptr = disposition;
}
}
if (create) {
result = content_manager->CreateContent(root_name.value(), content_data);
} else if (open) {
result = content_manager->OpenContent(root_name.value(), content_data);
}
if (license_mask_ptr && XSUCCEEDED(result)) {
*license_mask_ptr = 0; // Stub!
}
if (overlapped_ptr) {
kernel_state()->CompleteOverlappedImmediateEx(overlapped_ptr, result, 0,
disposition);
return X_ERROR_IO_PENDING;
} else {
return result;
}
}
DECLARE_XAM_EXPORT1(XamContentCreateEx, kContent, kImplemented);
dword_result_t XamContentCreate(dword_t user_index, lpstring_t root_name,
lpvoid_t content_data_ptr, dword_t flags,
lpdword_t disposition_ptr,
lpdword_t license_mask_ptr,
lpvoid_t overlapped_ptr) {
return XamContentCreateEx(user_index, root_name, content_data_ptr, flags,
disposition_ptr, license_mask_ptr, 0, 0,
overlapped_ptr);
}
DECLARE_XAM_EXPORT1(XamContentCreate, kContent, kImplemented);
dword_result_t XamContentOpenFile(dword_t user_index, lpstring_t root_name,
lpstring_t path, dword_t flags,
lpdword_t disposition_ptr,
lpdword_t license_mask_ptr,
lpvoid_t overlapped_ptr) {
// TODO(gibbed): arguments assumed based on XamContentCreate.
return X_ERROR_FILE_NOT_FOUND;
}
DECLARE_XAM_EXPORT1(XamContentOpenFile, kContent, kStub);
dword_result_t XamContentFlush(lpstring_t root_name,
lpunknown_t overlapped_ptr) {
X_RESULT result = X_ERROR_SUCCESS;
if (overlapped_ptr) {
kernel_state()->CompleteOverlappedImmediate(overlapped_ptr, result);
return X_ERROR_IO_PENDING;
} else {
return result;
}
}
DECLARE_XAM_EXPORT1(XamContentFlush, kContent, kStub);
dword_result_t XamContentClose(lpstring_t root_name,
lpunknown_t overlapped_ptr) {
// Closes a previously opened root from XamContentCreate*.
auto result =
kernel_state()->content_manager()->CloseContent(root_name.value());
if (overlapped_ptr) {
kernel_state()->CompleteOverlappedImmediate(overlapped_ptr, result);
return X_ERROR_IO_PENDING;
} else {
return result;
}
}
DECLARE_XAM_EXPORT1(XamContentClose, kContent, kImplemented);
dword_result_t XamContentGetCreator(dword_t user_index,
lpvoid_t content_data_ptr,
lpdword_t is_creator_ptr,
lpqword_t creator_xuid_ptr,
lpunknown_t overlapped_ptr) {
auto result = X_ERROR_SUCCESS;
auto content_data = XCONTENT_DATA((uint8_t*)content_data_ptr);
if (content_data.content_type == 1) {
// User always creates saves.
*is_creator_ptr = 1;
if (creator_xuid_ptr) {
*creator_xuid_ptr = kernel_state()->user_profile()->xuid();
}
} else {
*is_creator_ptr = 0;
if (creator_xuid_ptr) {
*creator_xuid_ptr = 0;
}
}
if (overlapped_ptr) {
kernel_state()->CompleteOverlappedImmediate(overlapped_ptr, result);
return X_ERROR_IO_PENDING;
} else {
return result;
}
}
DECLARE_XAM_EXPORT1(XamContentGetCreator, kContent, kImplemented);
dword_result_t XamContentGetThumbnail(dword_t user_index,
lpvoid_t content_data_ptr,
lpvoid_t buffer_ptr,
lpdword_t buffer_size_ptr,
lpunknown_t overlapped_ptr) {
assert_not_null(buffer_size_ptr);
uint32_t buffer_size = *buffer_size_ptr;
auto content_data = XCONTENT_DATA((uint8_t*)content_data_ptr);
// Get thumbnail (if it exists).
std::vector<uint8_t> buffer;
auto result = kernel_state()->content_manager()->GetContentThumbnail(
content_data, &buffer);
*buffer_size_ptr = uint32_t(buffer.size());
if (XSUCCEEDED(result)) {
// Write data, if we were given a pointer.
// This may have just been a size query.
if (buffer_ptr) {
if (buffer_size < buffer.size()) {
// Dest buffer too small.
result = X_ERROR_INSUFFICIENT_BUFFER;
} else {
// Copy data.
std::memcpy((uint8_t*)buffer_ptr, buffer.data(), buffer.size());
}
}
}
if (overlapped_ptr) {
kernel_state()->CompleteOverlappedImmediate(overlapped_ptr, result);
return X_ERROR_IO_PENDING;
} else {
return result;
}
}
DECLARE_XAM_EXPORT1(XamContentGetThumbnail, kContent, kImplemented);
dword_result_t XamContentSetThumbnail(dword_t user_index,
lpvoid_t content_data_ptr,
lpvoid_t buffer_ptr, dword_t buffer_size,
lpunknown_t overlapped_ptr) {
auto content_data = XCONTENT_DATA((uint8_t*)content_data_ptr);
// Buffer is PNG data.
auto buffer = std::vector<uint8_t>((uint8_t*)buffer_ptr,
(uint8_t*)buffer_ptr + buffer_size);
auto result = kernel_state()->content_manager()->SetContentThumbnail(
content_data, std::move(buffer));
if (overlapped_ptr) {
kernel_state()->CompleteOverlappedImmediate(overlapped_ptr, result);
return X_ERROR_IO_PENDING;
} else {
return result;
}
}
DECLARE_XAM_EXPORT1(XamContentSetThumbnail, kContent, kImplemented);
dword_result_t XamContentDelete(dword_t user_index, lpvoid_t content_data_ptr,
lpunknown_t overlapped_ptr) {
auto content_data = XCONTENT_DATA((uint8_t*)content_data_ptr);
auto result = kernel_state()->content_manager()->DeleteContent(content_data);
if (overlapped_ptr) {
kernel_state()->CompleteOverlappedImmediate(overlapped_ptr, result);
return X_ERROR_IO_PENDING;
} else {
return result;
}
}
DECLARE_XAM_EXPORT1(XamContentDelete, kContent, kImplemented);
void RegisterContentExports(xe::cpu::ExportResolver* export_resolver,
KernelState* kernel_state) {}
} // namespace xam
} // namespace kernel
} // namespace xe
[Kernel] Static size assert for X_CONTENT_DEVICE_DATA.
/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/base/logging.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/util/shim_utils.h"
#include "xenia/kernel/xam/xam_private.h"
#include "xenia/kernel/xenumerator.h"
#include "xenia/xbox.h"
namespace xe {
namespace kernel {
namespace xam {
struct DeviceInfo {
uint32_t device_id;
uint32_t device_type;
uint64_t total_bytes;
uint64_t free_bytes;
wchar_t name[28];
};
static const DeviceInfo dummy_device_info_ = {
0xF00D0000,
1,
120ull * 1024ull * 1024ull * 1024ull, // 120GB
100ull * 1024ull * 1024ull * 1024ull, // 100GB, so it looks a little used.
L"Dummy HDD",
};
dword_result_t XamContentGetLicenseMask(lpdword_t mask_ptr,
lpunknown_t overlapped_ptr) {
// Each bit in the mask represents a granted license. Available licenses
// seems to vary from game to game, but most appear to use bit 0 to indicate
// if the game is purchased or not.
*mask_ptr = 0;
if (overlapped_ptr) {
kernel_state()->CompleteOverlappedImmediate(overlapped_ptr,
X_ERROR_SUCCESS);
return X_ERROR_IO_PENDING;
} else {
return X_ERROR_SUCCESS;
}
}
DECLARE_XAM_EXPORT2(XamContentGetLicenseMask, kContent, kStub, kHighFrequency);
dword_result_t XamContentGetDeviceName(dword_t device_id,
lpwstring_t name_buffer,
dword_t name_capacity) {
if ((device_id & 0xFFFF0000) != dummy_device_info_.device_id) {
return X_ERROR_DEVICE_NOT_CONNECTED;
}
if (name_capacity < wcslen(dummy_device_info_.name) + 1) {
return X_ERROR_INSUFFICIENT_BUFFER;
}
xe::store_and_swap<std::wstring>(name_buffer, dummy_device_info_.name);
return X_ERROR_SUCCESS;
}
DECLARE_XAM_EXPORT1(XamContentGetDeviceName, kContent, kImplemented);
dword_result_t XamContentGetDeviceState(dword_t device_id,
lpunknown_t overlapped_ptr) {
if ((device_id & 0xFFFF0000) != dummy_device_info_.device_id) {
if (overlapped_ptr) {
kernel_state()->CompleteOverlappedImmediateEx(
overlapped_ptr, X_ERROR_FUNCTION_FAILED, X_ERROR_DEVICE_NOT_CONNECTED,
0);
return X_ERROR_IO_PENDING;
} else {
return X_ERROR_DEVICE_NOT_CONNECTED;
}
}
if (overlapped_ptr) {
kernel_state()->CompleteOverlappedImmediate(overlapped_ptr,
X_ERROR_SUCCESS);
return X_ERROR_IO_PENDING;
} else {
return X_ERROR_SUCCESS;
}
}
DECLARE_XAM_EXPORT1(XamContentGetDeviceState, kContent, kStub);
typedef struct {
xe::be<uint32_t> device_id;
xe::be<uint32_t> unknown;
xe::be<uint64_t> total_bytes;
xe::be<uint64_t> free_bytes;
xe::be<uint16_t> name[28];
} X_CONTENT_DEVICE_DATA;
static_assert_size(X_CONTENT_DEVICE_DATA, 0x50);
dword_result_t XamContentGetDeviceData(
dword_t device_id, pointer_t<X_CONTENT_DEVICE_DATA> device_data) {
if ((device_id & 0xFFFF0000) != dummy_device_info_.device_id) {
// TODO(benvanik): memset 0 the data?
return X_ERROR_DEVICE_NOT_CONNECTED;
}
device_data.Zero();
const auto& device_info = dummy_device_info_;
device_data->device_id = device_info.device_id;
device_data->unknown = device_id & 0xFFFF; // Fake it.
device_data->total_bytes = device_info.total_bytes;
device_data->free_bytes = device_info.free_bytes;
xe::store_and_swap<std::wstring>(&device_data->name[0], device_info.name);
return X_ERROR_SUCCESS;
}
DECLARE_XAM_EXPORT1(XamContentGetDeviceData, kContent, kImplemented);
dword_result_t XamContentResolve(dword_t user_index, lpvoid_t content_data_ptr,
lpunknown_t buffer_ptr, dword_t buffer_size,
dword_t unk1, dword_t unk2, dword_t unk3) {
auto content_data = XCONTENT_DATA((uint8_t*)content_data_ptr);
// Result of buffer_ptr is sent to RtlInitAnsiString.
// buffer_size is usually 260 (max path).
// Games expect zero if resolve was successful.
assert_always();
XELOGW("XamContentResolve unimplemented!");
return X_ERROR_NOT_FOUND;
}
DECLARE_XAM_EXPORT1(XamContentResolve, kContent, kStub);
// https://github.com/MrColdbird/gameservice/blob/master/ContentManager.cpp
// https://github.com/LestaD/SourceEngine2007/blob/master/se2007/engine/xboxsystem.cpp#L499
dword_result_t XamContentCreateEnumerator(dword_t user_index, dword_t device_id,
dword_t content_type,
dword_t content_flags,
dword_t items_per_enumerate,
lpdword_t buffer_size_ptr,
lpdword_t handle_out) {
assert_not_null(handle_out);
if ((device_id && (device_id & 0xFFFF0000) != dummy_device_info_.device_id) ||
!handle_out) {
if (buffer_size_ptr) {
*buffer_size_ptr = 0;
}
// TODO(benvanik): memset 0 the data?
return X_E_INVALIDARG;
}
if (buffer_size_ptr) {
*buffer_size_ptr = (uint32_t)XCONTENT_DATA::kSize * items_per_enumerate;
}
auto e = new XStaticEnumerator(kernel_state(), items_per_enumerate,
XCONTENT_DATA::kSize);
e->Initialize();
// Get all content data.
auto content_datas = kernel_state()->content_manager()->ListContent(
device_id ? static_cast<uint32_t>(device_id)
: dummy_device_info_.device_id,
content_type);
for (auto& content_data : content_datas) {
auto ptr = e->AppendItem();
assert_not_null(ptr);
content_data.Write(ptr);
}
XELOGD("XamContentCreateEnumerator: added %d items to enumerator",
e->item_count());
*handle_out = e->handle();
return X_ERROR_SUCCESS;
}
DECLARE_XAM_EXPORT1(XamContentCreateEnumerator, kContent, kImplemented);
dword_result_t XamContentCreateDeviceEnumerator(dword_t content_type,
dword_t content_flags,
dword_t max_count,
lpdword_t buffer_size_ptr,
lpdword_t handle_out) {
assert_not_null(handle_out);
if (buffer_size_ptr) {
*buffer_size_ptr = sizeof(DeviceInfo) * max_count;
}
auto e = new XStaticEnumerator(kernel_state(), max_count, sizeof(DeviceInfo));
e->Initialize();
// Copy our dummy device into the enumerator
DeviceInfo* dev = (DeviceInfo*)e->AppendItem();
if (dev) {
xe::store_and_swap(&dev->device_id, dummy_device_info_.device_id);
xe::store_and_swap(&dev->device_type, dummy_device_info_.device_type);
xe::store_and_swap(&dev->total_bytes, dummy_device_info_.total_bytes);
xe::store_and_swap(&dev->free_bytes, dummy_device_info_.free_bytes);
xe::copy_and_swap(dev->name, dummy_device_info_.name, 28);
}
*handle_out = e->handle();
return X_ERROR_SUCCESS;
}
DECLARE_XAM_EXPORT1(XamContentCreateDeviceEnumerator, kNone, kImplemented);
dword_result_t XamContentCreateEx(dword_t user_index, lpstring_t root_name,
lpvoid_t content_data_ptr, dword_t flags,
lpdword_t disposition_ptr,
lpdword_t license_mask_ptr,
dword_t cache_size, qword_t content_size,
lpvoid_t overlapped_ptr) {
X_RESULT result = X_ERROR_INVALID_PARAMETER;
auto content_data = XCONTENT_DATA((uint8_t*)content_data_ptr);
auto content_manager = kernel_state()->content_manager();
bool create = false;
bool open = false;
switch (flags & 0xF) {
case 1: // CREATE_NEW
// Fail if exists.
if (content_manager->ContentExists(content_data)) {
result = X_ERROR_ALREADY_EXISTS;
} else {
create = true;
}
break;
case 2: // CREATE_ALWAYS
// Overwrite existing, if any.
if (content_manager->ContentExists(content_data)) {
content_manager->DeleteContent(content_data);
create = true;
} else {
create = true;
}
break;
case 3: // OPEN_EXISTING
// Open only if exists.
if (!content_manager->ContentExists(content_data)) {
result = X_ERROR_PATH_NOT_FOUND;
} else {
open = true;
}
break;
case 4: // OPEN_ALWAYS
// Create if needed.
if (!content_manager->ContentExists(content_data)) {
create = true;
} else {
open = true;
}
break;
case 5: // TRUNCATE_EXISTING
// Fail if doesn't exist, if does exist delete and recreate.
if (!content_manager->ContentExists(content_data)) {
result = X_ERROR_PATH_NOT_FOUND;
} else {
content_manager->DeleteContent(content_data);
create = true;
}
break;
default:
assert_unhandled_case(flags & 0xF);
break;
}
// creation result
// 0 = ?
// 1 = created
// 2 = opened
uint32_t disposition = create ? 1 : 2;
if (disposition_ptr) {
if (overlapped_ptr) {
// If async always set to zero, but don't set to a real value.
*disposition_ptr = 0;
} else {
*disposition_ptr = disposition;
}
}
if (create) {
result = content_manager->CreateContent(root_name.value(), content_data);
} else if (open) {
result = content_manager->OpenContent(root_name.value(), content_data);
}
if (license_mask_ptr && XSUCCEEDED(result)) {
*license_mask_ptr = 0; // Stub!
}
if (overlapped_ptr) {
kernel_state()->CompleteOverlappedImmediateEx(overlapped_ptr, result, 0,
disposition);
return X_ERROR_IO_PENDING;
} else {
return result;
}
}
DECLARE_XAM_EXPORT1(XamContentCreateEx, kContent, kImplemented);
dword_result_t XamContentCreate(dword_t user_index, lpstring_t root_name,
lpvoid_t content_data_ptr, dword_t flags,
lpdword_t disposition_ptr,
lpdword_t license_mask_ptr,
lpvoid_t overlapped_ptr) {
return XamContentCreateEx(user_index, root_name, content_data_ptr, flags,
disposition_ptr, license_mask_ptr, 0, 0,
overlapped_ptr);
}
DECLARE_XAM_EXPORT1(XamContentCreate, kContent, kImplemented);
dword_result_t XamContentOpenFile(dword_t user_index, lpstring_t root_name,
lpstring_t path, dword_t flags,
lpdword_t disposition_ptr,
lpdword_t license_mask_ptr,
lpvoid_t overlapped_ptr) {
// TODO(gibbed): arguments assumed based on XamContentCreate.
return X_ERROR_FILE_NOT_FOUND;
}
DECLARE_XAM_EXPORT1(XamContentOpenFile, kContent, kStub);
dword_result_t XamContentFlush(lpstring_t root_name,
lpunknown_t overlapped_ptr) {
X_RESULT result = X_ERROR_SUCCESS;
if (overlapped_ptr) {
kernel_state()->CompleteOverlappedImmediate(overlapped_ptr, result);
return X_ERROR_IO_PENDING;
} else {
return result;
}
}
DECLARE_XAM_EXPORT1(XamContentFlush, kContent, kStub);
dword_result_t XamContentClose(lpstring_t root_name,
lpunknown_t overlapped_ptr) {
// Closes a previously opened root from XamContentCreate*.
auto result =
kernel_state()->content_manager()->CloseContent(root_name.value());
if (overlapped_ptr) {
kernel_state()->CompleteOverlappedImmediate(overlapped_ptr, result);
return X_ERROR_IO_PENDING;
} else {
return result;
}
}
DECLARE_XAM_EXPORT1(XamContentClose, kContent, kImplemented);
dword_result_t XamContentGetCreator(dword_t user_index,
lpvoid_t content_data_ptr,
lpdword_t is_creator_ptr,
lpqword_t creator_xuid_ptr,
lpunknown_t overlapped_ptr) {
auto result = X_ERROR_SUCCESS;
auto content_data = XCONTENT_DATA((uint8_t*)content_data_ptr);
if (content_data.content_type == 1) {
// User always creates saves.
*is_creator_ptr = 1;
if (creator_xuid_ptr) {
*creator_xuid_ptr = kernel_state()->user_profile()->xuid();
}
} else {
*is_creator_ptr = 0;
if (creator_xuid_ptr) {
*creator_xuid_ptr = 0;
}
}
if (overlapped_ptr) {
kernel_state()->CompleteOverlappedImmediate(overlapped_ptr, result);
return X_ERROR_IO_PENDING;
} else {
return result;
}
}
DECLARE_XAM_EXPORT1(XamContentGetCreator, kContent, kImplemented);
dword_result_t XamContentGetThumbnail(dword_t user_index,
lpvoid_t content_data_ptr,
lpvoid_t buffer_ptr,
lpdword_t buffer_size_ptr,
lpunknown_t overlapped_ptr) {
assert_not_null(buffer_size_ptr);
uint32_t buffer_size = *buffer_size_ptr;
auto content_data = XCONTENT_DATA((uint8_t*)content_data_ptr);
// Get thumbnail (if it exists).
std::vector<uint8_t> buffer;
auto result = kernel_state()->content_manager()->GetContentThumbnail(
content_data, &buffer);
*buffer_size_ptr = uint32_t(buffer.size());
if (XSUCCEEDED(result)) {
// Write data, if we were given a pointer.
// This may have just been a size query.
if (buffer_ptr) {
if (buffer_size < buffer.size()) {
// Dest buffer too small.
result = X_ERROR_INSUFFICIENT_BUFFER;
} else {
// Copy data.
std::memcpy((uint8_t*)buffer_ptr, buffer.data(), buffer.size());
}
}
}
if (overlapped_ptr) {
kernel_state()->CompleteOverlappedImmediate(overlapped_ptr, result);
return X_ERROR_IO_PENDING;
} else {
return result;
}
}
DECLARE_XAM_EXPORT1(XamContentGetThumbnail, kContent, kImplemented);
dword_result_t XamContentSetThumbnail(dword_t user_index,
lpvoid_t content_data_ptr,
lpvoid_t buffer_ptr, dword_t buffer_size,
lpunknown_t overlapped_ptr) {
auto content_data = XCONTENT_DATA((uint8_t*)content_data_ptr);
// Buffer is PNG data.
auto buffer = std::vector<uint8_t>((uint8_t*)buffer_ptr,
(uint8_t*)buffer_ptr + buffer_size);
auto result = kernel_state()->content_manager()->SetContentThumbnail(
content_data, std::move(buffer));
if (overlapped_ptr) {
kernel_state()->CompleteOverlappedImmediate(overlapped_ptr, result);
return X_ERROR_IO_PENDING;
} else {
return result;
}
}
DECLARE_XAM_EXPORT1(XamContentSetThumbnail, kContent, kImplemented);
dword_result_t XamContentDelete(dword_t user_index, lpvoid_t content_data_ptr,
lpunknown_t overlapped_ptr) {
auto content_data = XCONTENT_DATA((uint8_t*)content_data_ptr);
auto result = kernel_state()->content_manager()->DeleteContent(content_data);
if (overlapped_ptr) {
kernel_state()->CompleteOverlappedImmediate(overlapped_ptr, result);
return X_ERROR_IO_PENDING;
} else {
return result;
}
}
DECLARE_XAM_EXPORT1(XamContentDelete, kContent, kImplemented);
void RegisterContentExports(xe::cpu::ExportResolver* export_resolver,
KernelState* kernel_state) {}
} // namespace xam
} // namespace kernel
} // namespace xe
|
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2001 The Apache Software Foundation. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/Janitor.hpp>
#include <xercesc/util/Mutexes.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/RefVectorOf.hpp>
#include <xercesc/util/RuntimeException.hpp>
#include <xercesc/util/UnexpectedEOFException.hpp>
#include <xercesc/util/XMLMsgLoader.hpp>
#include <xercesc/util/XMLRegisterCleanup.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/XMLUni.hpp>
#include <xercesc/util/XMLURL.hpp>
#include <xercesc/sax/InputSource.hpp>
#include <xercesc/sax/SAXException.hpp>
#include <xercesc/framework/LocalFileInputSource.hpp>
#include <xercesc/framework/URLInputSource.hpp>
#include <xercesc/framework/XMLDocumentHandler.hpp>
#include <xercesc/framework/XMLErrorReporter.hpp>
#include <xercesc/framework/XMLEntityHandler.hpp>
#include <xercesc/framework/XMLPScanToken.hpp>
#include <xercesc/framework/XMLValidator.hpp>
#include <xercesc/framework/XMLValidityCodes.hpp>
#include <xercesc/internal/XMLScanner.hpp>
#include <xercesc/internal/EndOfEntityException.hpp>
#include <xercesc/validators/DTD/DocTypeHandler.hpp>
#include <xercesc/validators/DTD/DTDScanner.hpp>
#include <xercesc/validators/schema/SchemaSymbols.hpp>
#include <xercesc/validators/schema/identity/FieldActivator.hpp>
#include <xercesc/validators/schema/identity/XPathMatcherStack.hpp>
#include <xercesc/validators/schema/identity/ValueStoreCache.hpp>
#include <xercesc/validators/schema/identity/IC_Selector.hpp>
#include <xercesc/validators/schema/identity/ValueStore.hpp>
// ---------------------------------------------------------------------------
// Local static data
// ---------------------------------------------------------------------------
static XMLUInt32 gScannerId;
static bool sRegistered = false;
static XMLMutex* sScannerMutex = 0;
static XMLRegisterCleanup scannerMutexCleanup;
static XMLMsgLoader* gMsgLoader = 0;
static XMLRegisterCleanup cleanupMsgLoader;
// ---------------------------------------------------------------------------
// Local const data
//
// These are the text for the require char refs that must always be present.
// We init these into the entity pool upon construction.
// ---------------------------------------------------------------------------
static const XMLCh gAmp[] = { chLatin_a, chLatin_m, chLatin_p, chNull };
static const XMLCh gLT[] = { chLatin_l, chLatin_t, chNull };
static const XMLCh gGT[] = { chLatin_g, chLatin_t, chNull };
static const XMLCh gQuot[] = { chLatin_q, chLatin_u, chLatin_o, chLatin_t, chNull };
static const XMLCh gApos[] = { chLatin_a, chLatin_p, chLatin_o, chLatin_s, chNull };
// ---------------------------------------------------------------------------
// Local, static functions
// ---------------------------------------------------------------------------
// -----------------------------------------------------------------------
// Cleanup for the message loader
// -----------------------------------------------------------------------
void XMLScanner::reinitMsgLoader()
{
delete gMsgLoader;
gMsgLoader = 0;
}
// -----------------------------------------------------------------------
// Cleanup for the scanner mutex
// -----------------------------------------------------------------------
void XMLScanner::reinitScannerMutex()
{
delete sScannerMutex;
sScannerMutex = 0;
sRegistered = false;
}
//
// We need to fault in this mutex. But, since its used for synchronization
// itself, we have to do this the low level way using a compare and swap.
//
static XMLMutex& gScannerMutex()
{
if (!sScannerMutex)
{
XMLMutex* tmpMutex = new XMLMutex;
if (XMLPlatformUtils::compareAndSwap((void**)&sScannerMutex, tmpMutex, 0))
{
// Someone beat us to it, so let's clean up ours
delete tmpMutex;
}
// Now lock it and try to register it
XMLMutexLock lock(sScannerMutex);
// If we got here first, then register it and set the registered flag
if (!sRegistered)
{
scannerMutexCleanup.registerCleanup(XMLScanner::reinitScannerMutex);
sRegistered = true;
}
}
return *sScannerMutex;
}
// ---------------------------------------------------------------------------
// XMLScanner: Constructors and Destructor
// ---------------------------------------------------------------------------
XMLScanner::XMLScanner(XMLValidator* const valToAdopt) :
fDoNamespaces(false)
, fExitOnFirstFatal(true)
, fValidationConstraintFatal(false)
, fInException(false)
, fReuseGrammar(false)
, fStandalone(false)
, fHasNoDTD(true)
, fValidate(false)
, fValidatorFromUser(false)
, fDoSchema(false)
, fSchemaFullChecking(false)
, fSeeXsi(false)
, fErrorCount(0)
, fEmptyNamespaceId(0)
, fUnknownNamespaceId(0)
, fXMLNamespaceId(0)
, fXMLNSNamespaceId(0)
, fSchemaNamespaceId(0)
, fElemStateSize(16)
, fScannerId(0)
, fSequenceId(0)
, fElemState(0)
, fAttrList(0)
, fDocHandler(0)
, fDocTypeHandler(0)
, fEntityHandler(0)
, fErrorReporter(0)
, fErrorHandler(0)
, fIDRefList(0)
, fRawAttrList(0)
, fValidator(valToAdopt)
, fDTDValidator(0)
, fSchemaValidator(0)
, fValScheme(Val_Never)
, fGrammarResolver(0)
, fGrammar(0)
, fEntityDeclPool(0)
, fURIStringPool(0)
, fMatcherStack(0)
, fValueStoreCache(0)
, fFieldActivator(0)
, fRootElemName(0)
, fExternalSchemaLocation(0)
, fExternalNoNamespaceSchemaLocation(0)
, fLoadExternalDTD(true)
, fNormalizeData(true)
{
commonInit();
if (fValidator) {
fValidatorFromUser = true;
initValidator(fValidator);
}
else {
//use fDTDValidator as the default validator
fValidator = fDTDValidator;
}
}
XMLScanner::XMLScanner( XMLDocumentHandler* const docHandler
, DocTypeHandler* const docTypeHandler
, XMLEntityHandler* const entityHandler
, XMLErrorReporter* const errHandler
, XMLValidator* const valToAdopt) :
fDoNamespaces(false)
, fExitOnFirstFatal(true)
, fValidationConstraintFatal(false)
, fInException(false)
, fReuseGrammar(false)
, fStandalone(false)
, fHasNoDTD(true)
, fValidate(false)
, fValidatorFromUser(false)
, fDoSchema(false)
, fSchemaFullChecking(false)
, fSeeXsi(false)
, fErrorCount(0)
, fEmptyNamespaceId(0)
, fUnknownNamespaceId(0)
, fXMLNamespaceId(0)
, fXMLNSNamespaceId(0)
, fSchemaNamespaceId(0)
, fElemStateSize(16)
, fScannerId(0)
, fSequenceId(0)
, fElemState(0)
, fAttrList(0)
, fDocHandler(docHandler)
, fDocTypeHandler(docTypeHandler)
, fEntityHandler(entityHandler)
, fErrorReporter(errHandler)
, fErrorHandler(0)
, fIDRefList(0)
, fRawAttrList(0)
, fValidator(valToAdopt)
, fDTDValidator(0)
, fSchemaValidator(0)
, fValScheme(Val_Never)
, fGrammarResolver(0)
, fGrammar(0)
, fEntityDeclPool(0)
, fURIStringPool(0)
, fMatcherStack(0)
, fValueStoreCache(0)
, fFieldActivator(0)
, fRootElemName(0)
, fExternalSchemaLocation(0)
, fExternalNoNamespaceSchemaLocation(0)
, fLoadExternalDTD(true)
, fNormalizeData(true)
{
commonInit();
if (valToAdopt){
fValidatorFromUser = true;
initValidator(fValidator);
}
else {
//use fDTDValidator as the default validator
fValidator = fDTDValidator;
}
}
XMLScanner::~XMLScanner()
{
delete [] fElemState;
delete fAttrList;
delete fIDRefList;
delete fRawAttrList;
if (fValidatorFromUser)
delete fValidator;
delete fDTDValidator;
delete fSchemaValidator;
delete fEntityDeclPool;
//fGrammarResolver will delete the fGrammar as well
delete fGrammarResolver;
delete fURIStringPool;
delete fFieldActivator;
delete fMatcherStack;
delete fValueStoreCache;
delete [] fRootElemName;
delete [] fExternalSchemaLocation;
delete [] fExternalNoNamespaceSchemaLocation;
}
// ---------------------------------------------------------------------------
// XMLScanner: Main entry point to scan a document
// ---------------------------------------------------------------------------
void XMLScanner::scanDocument( const XMLCh* const systemId
, const bool reuseGrammar)
{
//
// First we try to parse it as a URL. If that fails, we assume its
// a file and try it that way.
//
InputSource* srcToUse = 0;
try
{
//
// Create a temporary URL. Since this is the primary document,
// it has to be fully qualified. If not, then assume we are just
// mistaking a file for a URL.
//
XMLURL tmpURL(systemId);
if (tmpURL.isRelative()) {
srcToUse = new LocalFileInputSource(systemId);
}
else
{
srcToUse = new URLInputSource(tmpURL);
}
}
catch(const MalformedURLException&)
{
srcToUse = new LocalFileInputSource(systemId);
}
catch(...)
{
// Just rethrow this, since its not our problem
throw;
}
Janitor<InputSource> janSrc(srcToUse);
scanDocument(*srcToUse, reuseGrammar);
}
void XMLScanner::scanDocument( const char* const systemId
, const bool reuseGrammar)
{
// We just delegate this to the XMLCh version after transcoding
XMLCh* tmpBuf = XMLString::transcode(systemId);
ArrayJanitor<XMLCh> janBuf(tmpBuf);
scanDocument(tmpBuf, reuseGrammar);
}
void XMLScanner::scanDocument(const InputSource& src, const bool reuseGrammar)
{
//
// Bump up the sequence id for this parser instance. This will invalidate
// any previous progressive scan tokens.
//
fSequenceId++;
// Store the reuse validator flag
fReuseGrammar = reuseGrammar;
try
{
//
// Reset the scanner and its plugged in stuff for a new run. This
// resets all the data structures, creates the initial reader and
// pushes it on the stack, and sets up the base document path.
//
scanReset(src);
// If we have a document handler, then call the start document
if (fDocHandler)
fDocHandler->startDocument();
fValueStoreCache->startDocument();
//
// Scan the prolog part, which is everything before the root element
// including the DTD subsets.
//
scanProlog();
//
// If we got to the end of input, then its not a valid XML file.
// Else, go on to scan the content.
//
if (fReaderMgr.atEOF())
{
emitError(XMLErrs::EmptyMainEntity);
}
else
{
// Scan content, and tell it its not an external entity
if (scanContent(false))
{
// Do post-parse validation if required
if (fValidate)
{
//
// We handle ID reference semantics at this level since
// its required by XML 1.0.
//
checkIDRefs();
// Then allow the validator to do any extra stuff it wants
fValidator->postParseValidation();
}
// That went ok, so scan for any miscellaneous stuff
if (!fReaderMgr.atEOF())
scanMiscellaneous();
}
}
if (fValidate)
fValueStoreCache->endDocument();
// If we have a document handler, then call the end document
if (fDocHandler)
fDocHandler->endDocument();
// Reset the reader manager to close all files, sockets, etc...
fReaderMgr.reset();
}
//
// NOTE:
//
// In all of the error processing below, the emitError() call MUST come
// before the flush of the reader mgr, or it will fail because it tries
// to find out the position in the XML source of the error.
//
catch(const XMLErrs::Codes)
{
// This is a 'first fatal error' type exit, so reset and fall through
fReaderMgr.reset();
}
catch(const XMLValid::Codes)
{
// This is a 'first fatal error' type exit, so reset and fall through
fReaderMgr.reset();
}
catch(const XMLException& excToCatch)
{
//
// Emit the error and catch any user exception thrown from here. Make
// sure in all cases we flush the reader manager.
//
fInException = true;
try
{
if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning)
emitError
(
XMLErrs::XMLException_Warning
, excToCatch.getType()
, excToCatch.getMessage()
);
else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal)
emitError
(
XMLErrs::XMLException_Fatal
, excToCatch.getType()
, excToCatch.getMessage()
);
else
emitError
(
XMLErrs::XMLException_Error
, excToCatch.getType()
, excToCatch.getMessage()
);
}
catch(...)
{
// Flush the reader manager and rethrow user's error
fReaderMgr.reset();
throw;
}
// If it returned, then reset the reader manager and fall through
fReaderMgr.reset();
}
catch(...)
{
// Reset and rethrow
fReaderMgr.reset();
throw;
}
}
//
// This method begins a progressive parse. It scans through the prolog and
// returns a token to be used on subsequent scanNext() calls. If the return
// value is true, then the token is legal and ready for further use. If it
// returns false, then the scan of the prolog failed and the token is not
// going to work on subsequent scanNext() calls.
//
bool XMLScanner::scanFirst( const XMLCh* const systemId
, XMLPScanToken& toFill
, const bool reuseGrammar)
{
//
// First we try to parse it as a URL. If that fails, we assume its
// a file and try it that way.
//
InputSource* srcToUse = 0;
try
{
//
// Create a temporary URL. Since this is the primary document,
// it has to be fully qualified. If not, then assume we are just
// mistaking a file for a URL.
//
XMLURL tmpURL(systemId);
if (tmpURL.isRelative())
ThrowXML(MalformedURLException, XMLExcepts::URL_NoProtocolPresent);
srcToUse = new URLInputSource(tmpURL);
}
catch(const MalformedURLException&)
{
srcToUse = new LocalFileInputSource(systemId);
}
catch(...)
{
// Just rethrow this, since its not our problem
throw;
}
Janitor<InputSource> janSrc(srcToUse);
return scanFirst(*srcToUse, toFill, reuseGrammar);
}
bool XMLScanner::scanFirst( const char* const systemId
, XMLPScanToken& toFill
, const bool reuseGrammar)
{
// We just delegate this to the XMLCh version after transcoding
XMLCh* tmpBuf = XMLString::transcode(systemId);
ArrayJanitor<XMLCh> janBuf(tmpBuf);
return scanFirst(tmpBuf, toFill, reuseGrammar);
}
bool XMLScanner::scanFirst( const InputSource& src
, XMLPScanToken& toFill
, const bool reuseGrammar)
{
// Store the reuse validator flag
fReuseGrammar = reuseGrammar;
//
// Bump up the sequence id for this new scan cycle. This will invalidate
// any previous tokens we've returned.
//
fSequenceId++;
//
// Reset the scanner and its plugged in stuff for a new run. This
// resets all the data structures, creates the initial reader and
// pushes it on the stack, and sets up the base document path
//
scanReset(src);
// If we have a document handler, then call the start document
if (fDocHandler)
fDocHandler->startDocument();
fValueStoreCache->startDocument();
try
{
//
// Scan the prolog part, which is everything before the root element
// including the DTD subsets. This is all that is done on the scan
// first.
//
scanProlog();
//
// If we got to the end of input, then its not a valid XML file.
// Else, go on to scan the content.
//
if (fReaderMgr.atEOF())
{
emitError(XMLErrs::EmptyMainEntity);
}
}
//
// NOTE:
//
// In all of the error processing below, the emitError() call MUST come
// before the flush of the reader mgr, or it will fail because it tries
// to find out the position in the XML source of the error.
//
catch(const XMLErrs::Codes)
{
// This is a 'first failure' exception so reset and return a failure
fReaderMgr.reset();
return false;
}
catch(const XMLValid::Codes)
{
// This is a 'first fatal error' type exit, so reset and reuturn failure
fReaderMgr.reset();
return false;
}
catch(const XMLException& excToCatch)
{
//
// Emit the error and catch any user exception thrown from here. Make
// sure in all cases we flush the reader manager.
//
fInException = true;
try
{
if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning)
emitError
(
XMLErrs::XMLException_Warning
, excToCatch.getType()
, excToCatch.getMessage()
);
else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal)
emitError
(
XMLErrs::XMLException_Fatal
, excToCatch.getType()
, excToCatch.getMessage()
);
else
emitError
(
XMLErrs::XMLException_Error
, excToCatch.getType()
, excToCatch.getMessage()
);
}
catch(...)
{
// Reset and rethrow the user error
fReaderMgr.reset();
throw;
}
// Reset and return a failure
fReaderMgr.reset();
return false;
}
catch(...)
{
// Reset and rethrow original error
fReaderMgr.reset();
throw;
}
// Fill in the caller's token to make it legal and return success
toFill.set(fScannerId, fSequenceId);
return true;
}
bool XMLScanner::scanNext(XMLPScanToken& token)
{
// Make sure this token is still legal
if (!isLegalToken(token))
ThrowXML(RuntimeException, XMLExcepts::Scan_BadPScanToken);
// Find the next token and remember the reader id
unsigned int orgReader;
XMLTokens curToken;
bool retVal = true;
try
{
while (true)
{
//
// We have to handle any end of entity exceptions that happen here.
// We could be at the end of X nested entities, each of which will
// generate an end of entity exception as we try to move forward.
//
try
{
curToken = senseNextToken(orgReader);
break;
}
catch(const EndOfEntityException& toCatch)
{
// Send an end of entity reference event
if (fDocHandler)
fDocHandler->endEntityReference(toCatch.getEntity());
}
}
if (curToken == Token_CharData)
{
scanCharData(fCDataBuf);
}
else if (curToken == Token_EOF)
{
if (!fElemStack.isEmpty())
{
const ElemStack::StackElem* topElem = fElemStack.popTop();
emitError
(
XMLErrs::EndedWithTagsOnStack
, topElem->fThisElement->getFullName()
);
}
retVal = false;
}
else
{
// Its some sort of markup
bool gotData = true;
switch(curToken)
{
case Token_CData :
// Make sure we are within content
if (fElemStack.isEmpty())
emitError(XMLErrs::CDATAOutsideOfContent);
scanCDSection();
break;
case Token_Comment :
scanComment();
break;
case Token_EndTag :
scanEndTag(gotData);
break;
case Token_PI :
scanPI();
break;
case Token_StartTag :
if (fDoNamespaces)
scanStartTagNS(gotData);
else
scanStartTag(gotData);
break;
default :
fReaderMgr.skipToChar(chOpenAngle);
break;
}
if (orgReader != fReaderMgr.getCurrentReaderNum())
emitError(XMLErrs::PartialMarkupInEntity);
// If we hit the end, then do the miscellaneous part
if (!gotData)
{
// Do post-parse validation if required
if (fValidate)
{
//
// We handle ID reference semantics at this level since
// its required by XML 1.0.
//
checkIDRefs();
// Then allow the validator to do any extra stuff it wants
fValidator->postParseValidation();
}
// That went ok, so scan for any miscellaneous stuff
scanMiscellaneous();
if (fValidate)
fValueStoreCache->endDocument();
if (fDocHandler)
fDocHandler->endDocument();
}
}
}
//
// NOTE:
//
// In all of the error processing below, the emitError() call MUST come
// before the flush of the reader mgr, or it will fail because it tries
// to find out the position in the XML source of the error.
//
catch(const XMLErrs::Codes)
{
// This is a 'first failure' exception, so reset and return failure
fReaderMgr.reset();
return false;
}
catch(const XMLValid::Codes)
{
// This is a 'first fatal error' type exit, so reset and reuturn failure
fReaderMgr.reset();
return false;
}
// We have to propogate SAX exceptions
catch(const SAXException&)
{
// Just reset our reader manager and rethrow SAX exception
fReaderMgr.reset();
throw;
}
catch(const XMLException& excToCatch)
{
//
// Emit the error and catch any user exception thrown from here. Make
// sure in all cases we flush the reader manager.
//
fInException = true;
try
{
if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning)
emitError
(
XMLErrs::XMLException_Warning
, excToCatch.getType()
, excToCatch.getMessage()
);
else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal)
emitError
(
XMLErrs::XMLException_Fatal
, excToCatch.getType()
, excToCatch.getMessage()
);
else
emitError
(
XMLErrs::XMLException_Error
, excToCatch.getType()
, excToCatch.getMessage()
);
}
catch(...)
{
// Reset and rethrow user error
fReaderMgr.reset();
throw;
}
// Reset and return failure
fReaderMgr.reset();
return false;
}
catch(...)
{
// Reset and rethrow original error
fReaderMgr.reset();
throw;
}
// If we hit the end, then flush the reader manager
if (!retVal)
fReaderMgr.reset();
return retVal;
}
void XMLScanner::scanReset(XMLPScanToken& token)
{
// Make sure this token is still legal
if (!isLegalToken(token))
ThrowXML(RuntimeException, XMLExcepts::Scan_BadPScanToken);
// Reset the reader manager
fReaderMgr.reset();
// And invalidate any tokens by bumping our sequence number
fSequenceId++;
// Reset our error count
fErrorCount = 0;
}
// ---------------------------------------------------------------------------
// XMLScanner: Private helper methods. Most of these are implemented in
// XMLScanner2.Cpp.
// ---------------------------------------------------------------------------
//
// This method handles the common initialization, to avoid having to do
// it redundantly in multiple constructors.
//
void XMLScanner::commonInit()
{
//
// We have to do a little init that involves statics, so we have to
// use the mutex to protect it.
//
{
XMLMutexLock lockInit(&gScannerMutex());
// If we haven't loaded our message yet, then do that
if (!gMsgLoader)
{
gMsgLoader = XMLPlatformUtils::loadMsgSet(XMLUni::fgXMLErrDomain);
if (!gMsgLoader)
XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);
// Register this object to be cleaned up at termination
cleanupMsgLoader.registerCleanup(reinitMsgLoader);
}
// And assign ourselves the next available scanner id
fScannerId = ++gScannerId;
}
//
// Create the element state array
//
fElemState = new unsigned int[fElemStateSize];
//
// Create the attribute list, which is used to store attribute values
// during start tag processing. Give it a reasonable initial size that
// will serve for most folks, though it will grow as required.
//
fAttrList = new RefVectorOf<XMLAttr>(32);
//
// And we need one for the raw attribute scan. This just stores key/
// value string pairs (prior to any processing.)
//
fRawAttrList = new RefVectorOf<KVStringPair>(32);
//
// Create the id ref list. This is used to enforce XML 1.0 ID ref
// semantics, i.e. all id refs must refer to elements that exist
//
fIDRefList = new RefHashTableOf<XMLRefInfo>(109);
// Create the EntityDeclPool
fEntityDeclPool = new NameIdPool<DTDEntityDecl>(109);
// Create the GrammarResolver
fGrammarResolver = new GrammarResolver();
resetEntityDeclPool();
// Create the Validator and init them
fDTDValidator = new DTDValidator();
initValidator(fDTDValidator);
fSchemaValidator = new SchemaValidator();
initValidator(fSchemaValidator);
// Create IdentityConstraint info
fMatcherStack = new XPathMatcherStack();
fValueStoreCache = new ValueStoreCache();
fFieldActivator = new FieldActivator(fValueStoreCache, fMatcherStack);
fValueStoreCache->setScanner(this);
}
void XMLScanner::initValidator(XMLValidator* theValidator) {
//
// Tell the validator about the stuff it needs to know in order to
// do its work.
//
theValidator->setScannerInfo(this, &fReaderMgr, &fBufMgr);
theValidator->setErrorReporter(fErrorReporter);
if (theValidator->handlesSchema()) {
((SchemaValidator*) theValidator)->setGrammarResolver(fGrammarResolver);
((SchemaValidator*) theValidator)->setExitOnFirstFatal(fExitOnFirstFatal);
}
}
void XMLScanner::resetEntityDeclPool() {
fEntityDeclPool->removeAll();
//
// Add the default entity entries for the character refs that must always
// be present. We indicate that they are from the internal subset. They
// aren't really, but they have to look that way so that they are still
// valid for use within a standalone document.
//
// We also mark them as special char entities, which allows them to be
// used in places whether other non-numeric general entities cannot.
//
fEntityDeclPool->put(new DTDEntityDecl(gAmp, chAmpersand, true, true));
fEntityDeclPool->put(new DTDEntityDecl(gLT, chOpenAngle, true, true));
fEntityDeclPool->put(new DTDEntityDecl(gGT, chCloseAngle, true, true));
fEntityDeclPool->put(new DTDEntityDecl(gQuot, chDoubleQuote, true, true));
fEntityDeclPool->put(new DTDEntityDecl(gApos, chSingleQuote, true, true));
}
void XMLScanner::resetURIStringPool() {
fURIStringPool->flushAll();
fEmptyNamespaceId = fURIStringPool->addOrFind(XMLUni::fgZeroLenString);
fUnknownNamespaceId = fURIStringPool->addOrFind(XMLUni::fgUnknownURIName);
fXMLNamespaceId = fURIStringPool->addOrFind(XMLUni::fgXMLURIName);
fXMLNSNamespaceId = fURIStringPool->addOrFind(XMLUni::fgXMLNSURIName);
fSchemaNamespaceId = fURIStringPool->addOrFind(SchemaSymbols::fgURI_XSI);
}
// ---------------------------------------------------------------------------
// XMLScanner: Error emitting methods
// ---------------------------------------------------------------------------
//
// These methods are called whenever the scanner wants to emit an error.
// It handles getting the message loaded, doing token replacement, etc...
// and then calling the error handler, if its installed.
//
void XMLScanner::emitError(const XMLErrs::Codes toEmit)
{
// Bump the error count if it is not a warning
if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)
incrementErrorCount();
if (fErrorReporter)
{
// Load the message into a local for display
const unsigned int msgSize = 1023;
XMLCh errText[msgSize + 1];
// Lock the mutex and load the text
{
XMLMutexLock lockInit(&gScannerMutex());
if (!gMsgLoader->loadMsg(toEmit, errText, msgSize))
{
// <TBD> Probably should load a default msg here
}
}
//
// Create a LastExtEntityInfo structure and get the reader manager
// to fill it in for us. This will give us the information about
// the last reader on the stack that was an external entity of some
// sort (i.e. it will ignore internal entities.
//
ReaderMgr::LastExtEntityInfo lastInfo;
fReaderMgr.getLastExtEntityInfo(lastInfo);
fErrorReporter->error
(
toEmit
, XMLUni::fgXMLErrDomain
, XMLErrs::errorType(toEmit)
, errText
, lastInfo.systemId
, lastInfo.publicId
, lastInfo.lineNumber
, lastInfo.colNumber
);
}
// Bail out if its fatal an we are to give up on the first fatal error
if (XMLErrs::isFatal(toEmit) && fExitOnFirstFatal && !fInException)
throw toEmit;
}
void XMLScanner::emitError( const XMLErrs::Codes toEmit
, const XMLCh* const text1
, const XMLCh* const text2
, const XMLCh* const text3
, const XMLCh* const text4)
{
// Bump the error count if it is not a warning
if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)
incrementErrorCount();
if (fErrorReporter)
{
//
// Load the message into alocal and replace any tokens found in
// the text.
//
const unsigned int maxChars = 2047;
XMLCh errText[maxChars + 1];
// Lock the mutex and load the text
{
XMLMutexLock lockInit(&gScannerMutex());
if (!gMsgLoader->loadMsg(toEmit, errText, maxChars, text1, text2, text3, text4))
{
// <TBD> Should probably load a default message here
}
}
//
// Create a LastExtEntityInfo structure and get the reader manager
// to fill it in for us. This will give us the information about
// the last reader on the stack that was an external entity of some
// sort (i.e. it will ignore internal entities.
//
ReaderMgr::LastExtEntityInfo lastInfo;
fReaderMgr.getLastExtEntityInfo(lastInfo);
fErrorReporter->error
(
toEmit
, XMLUni::fgXMLErrDomain
, XMLErrs::errorType(toEmit)
, errText
, lastInfo.systemId
, lastInfo.publicId
, lastInfo.lineNumber
, lastInfo.colNumber
);
}
// Bail out if its fatal an we are to give up on the first fatal error
if (XMLErrs::isFatal(toEmit) && fExitOnFirstFatal && !fInException)
throw toEmit;
}
void XMLScanner::emitError( const XMLErrs::Codes toEmit
, const char* const text1
, const char* const text2
, const char* const text3
, const char* const text4)
{
// Bump the error count if it is not a warning
if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)
incrementErrorCount();
if (fErrorReporter)
{
//
// Load the message into alocal and replace any tokens found in
// the text.
//
const unsigned int maxChars = 2047;
XMLCh errText[maxChars + 1];
// Lock the mutex and load the text
{
XMLMutexLock lockInit(&gScannerMutex());
if (!gMsgLoader->loadMsg(toEmit, errText, maxChars, text1, text2, text3, text4))
{
// <TBD> Should probably load a default message here
}
}
//
// Create a LastExtEntityInfo structure and get the reader manager
// to fill it in for us. This will give us the information about
// the last reader on the stack that was an external entity of some
// sort (i.e. it will ignore internal entities.
//
ReaderMgr::LastExtEntityInfo lastInfo;
fReaderMgr.getLastExtEntityInfo(lastInfo);
fErrorReporter->error
(
toEmit
, XMLUni::fgXMLErrDomain
, XMLErrs::errorType(toEmit)
, errText
, lastInfo.systemId
, lastInfo.publicId
, lastInfo.lineNumber
, lastInfo.colNumber
);
}
// Bail out if its fatal an we are to give up on the first fatal error
if (XMLErrs::isFatal(toEmit) && fExitOnFirstFatal && !fInException)
throw toEmit;
}
// ---------------------------------------------------------------------------
// XMLScanner: Getter methods
// ---------------------------------------------------------------------------
//
// This method allows the caller to query the current location of the scanner.
// It will return the sys/public ids of the current entity, and the line/col
// position within it.
//
// NOTE: This API returns the location with the last external file. So if its
// currently scanning an entity, the position returned will be the end of
// the entity reference in the file that had the reference.
//
bool
XMLScanner::getLastExtLocation( XMLCh* const sysIdToFill
, const unsigned int maxSysIdChars
, XMLCh* const pubIdToFill
, const unsigned int maxPubIdChars
, XMLSSize_t& lineToFill
, XMLSSize_t& colToFill)
{
// Create a local info object and get it filled in by the reader manager
ReaderMgr::LastExtEntityInfo lastInfo;
fReaderMgr.getLastExtEntityInfo(lastInfo);
// Fill in the line and column number
lineToFill = lastInfo.lineNumber;
colToFill = lastInfo.colNumber;
// And copy over as much of the ids as will fit
sysIdToFill[0] = 0;
if (lastInfo.systemId)
{
if (XMLString::stringLen(lastInfo.systemId) > maxSysIdChars)
return false;
XMLString::copyString(sysIdToFill, lastInfo.systemId);
}
pubIdToFill[0] = 0;
if (lastInfo.publicId)
{
if (XMLString::stringLen(lastInfo.publicId) > maxPubIdChars)
return false;
XMLString::copyString(pubIdToFill, lastInfo.publicId);
}
return true;
}
// ---------------------------------------------------------------------------
// XMLScanner: Private scanning methods
// ---------------------------------------------------------------------------
//
// This method is called from scanStartTag() to handle the very raw initial
// scan of the attributes. It just fills in the passed collection with
// key/value pairs for each attribute. No processing is done on them at all.
//
unsigned int
XMLScanner::rawAttrScan(const XMLCh* const elemName
, RefVectorOf<KVStringPair>& toFill
, bool& isEmpty)
{
//
// Keep up with how many attributes we've seen so far, and how many
// elements are available in the vector. This way we can reuse old
// elements until we run out and then expand it.
//
unsigned int attCount = 0;
unsigned int curVecSize = toFill.size();
// Assume it is not empty
isEmpty = false;
//
// We loop until we either see a /> or >, handling key/value pairs util
// we get there. We place them in the passed vector, which we will expand
// as required to hold them.
//
while (true)
{
// Get the next character, which should be non-space
XMLCh nextCh = fReaderMgr.peekNextChar();
//
// If the next character is not a slash or closed angle bracket,
// then it must be whitespace, since whitespace is required
// between the end of the last attribute and the name of the next
// one.
//
if (attCount)
{
if ((nextCh != chForwardSlash) && (nextCh != chCloseAngle))
{
if (XMLReader::isWhitespace(nextCh))
{
// Ok, skip by them and get another char
fReaderMgr.getNextChar();
fReaderMgr.skipPastSpaces();
nextCh = fReaderMgr.peekNextChar();
}
else
{
// Emit the error but keep on going
emitError(XMLErrs::ExpectedWhitespace);
}
}
}
//
// Ok, here we first check for any of the special case characters.
// If its not one, then we do the normal case processing, which
// assumes that we've hit an attribute value, Otherwise, we do all
// the special case checks.
//
if (!XMLReader::isSpecialStartTagChar(nextCh))
{
//
// Assume its going to be an attribute, so get a name from
// the input.
//
if (!fReaderMgr.getName(fAttNameBuf))
{
emitError(XMLErrs::ExpectedAttrName);
fReaderMgr.skipPastChar(chCloseAngle);
return attCount;
}
// And next must be an equal sign
if (!scanEq())
{
static const XMLCh tmpList[] =
{
chSingleQuote, chDoubleQuote, chCloseAngle
, chOpenAngle, chForwardSlash, chNull
};
emitError(XMLErrs::ExpectedEqSign);
//
// Try to sync back up by skipping forward until we either
// hit something meaningful.
//
const XMLCh chFound = fReaderMgr.skipUntilInOrWS(tmpList);
if ((chFound == chCloseAngle) || (chFound == chForwardSlash))
{
// Jump back to top for normal processing of these
continue;
}
else if ((chFound == chSingleQuote)
|| (chFound == chDoubleQuote)
|| XMLReader::isWhitespace(chFound))
{
// Just fall through assuming that the value is to follow
}
else if (chFound == chOpenAngle)
{
// Assume a malformed tag and that new one is starting
emitError(XMLErrs::UnterminatedStartTag, elemName);
return attCount;
}
else
{
// Something went really wrong
return attCount;
}
}
//
// Next should be the quoted attribute value. We just do a simple
// and stupid scan of this value. The only thing we do here
// is to expand entity references.
//
if (!basicAttrValueScan(fAttNameBuf.getRawBuffer(), fAttValueBuf))
{
static const XMLCh tmpList[] =
{
chCloseAngle, chOpenAngle, chForwardSlash, chNull
};
emitError(XMLErrs::ExpectedAttrValue);
//
// It failed, so lets try to get synced back up. We skip
// forward until we find some whitespace or one of the
// chars in our list.
//
const XMLCh chFound = fReaderMgr.skipUntilInOrWS(tmpList);
if ((chFound == chCloseAngle)
|| (chFound == chForwardSlash)
|| XMLReader::isWhitespace(chFound))
{
//
// Just fall through and process this attribute, though
// the value will be "".
//
}
else if (chFound == chOpenAngle)
{
// Assume a malformed tag and that new one is starting
emitError(XMLErrs::UnterminatedStartTag, elemName);
return attCount;
}
else
{
// Something went really wrong
return attCount;
}
}
//
// Make sure that the name is basically well formed for namespace
// enabled rules. It either has no colons, or it has one which
// is neither the first or last char.
//
const int colonFirst = XMLString::indexOf(fAttNameBuf.getRawBuffer(), chColon);
if (colonFirst != -1)
{
const int colonLast = XMLString::lastIndexOf(fAttNameBuf.getRawBuffer(), chColon);
if (colonFirst != colonLast)
{
emitError(XMLErrs::TooManyColonsInName);
continue;
}
else if ((colonFirst == 0)
|| (colonLast == (int)fAttNameBuf.getLen() - 1))
{
emitError(XMLErrs::InvalidColonPos);
continue;
}
}
//
// And now lets add it to the passed collection. If we have not
// filled it up yet, then we use the next element. Else we add
// a new one.
//
KVStringPair* curPair = 0;
if (attCount >= curVecSize)
{
curPair = new KVStringPair
(
fAttNameBuf.getRawBuffer()
, fAttValueBuf.getRawBuffer()
);
toFill.addElement(curPair);
}
else
{
curPair = toFill.elementAt(attCount);
curPair->set(fAttNameBuf.getRawBuffer(), fAttValueBuf.getRawBuffer());
}
// And bump the count of attributes we've gotten
attCount++;
// And go to the top again for another attribute
continue;
}
//
// It was some special case character so do all of the checks and
// deal with it.
//
if (!nextCh)
ThrowXML(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF);
if (nextCh == chForwardSlash)
{
fReaderMgr.getNextChar();
isEmpty = true;
if (!fReaderMgr.skippedChar(chCloseAngle))
emitError(XMLErrs::UnterminatedStartTag, elemName);
break;
}
else if (nextCh == chCloseAngle)
{
fReaderMgr.getNextChar();
break;
}
else if (nextCh == chOpenAngle)
{
//
// Check for this one specially, since its going to be common
// and it is kind of auto-recovering since we've already hit the
// next open bracket, which is what we would have seeked to (and
// skipped this whole tag.)
//
emitError(XMLErrs::UnterminatedStartTag, elemName);
break;
}
else if ((nextCh == chSingleQuote) || (nextCh == chDoubleQuote))
{
//
// Check for this one specially, which is probably a missing
// attribute name, e.g. ="value". Just issue expected name
// error and eat the quoted string, then jump back to the
// top again.
//
emitError(XMLErrs::ExpectedAttrName);
fReaderMgr.getNextChar();
fReaderMgr.skipQuotedString(nextCh);
fReaderMgr.skipPastSpaces();
continue;
}
}
return attCount;
}
//
// This method will kick off the scanning of the primary content of the
// document, i.e. the elements.
//
bool XMLScanner::scanContent(const bool extEntity)
{
//
// Go into a loop until we hit the end of the root element, or we fall
// out because there is no root element.
//
// We have to do kind of a deeply nested double loop here in order to
// avoid doing the setup/teardown of the exception handler on each
// round. Doing it this way we only do it when an exception actually
// occurs.
//
bool gotData = true;
bool inMarkup = false;
while (gotData)
{
try
{
while (gotData)
{
// Sense what the next top level token is. According to what
// this tells us, we will call something to handle that kind
// of thing.
//
unsigned int orgReader;
const XMLTokens curToken = senseNextToken(orgReader);
//
// Handle character data and end of file specially. Char data
// is not markup so we don't want to handle it in the loop
// below.
//
if (curToken == Token_CharData)
{
//
// Scan the character data and call appropriate events. Let
// him use our local character data buffer for efficiency.
//
scanCharData(fCDataBuf);
continue;
}
else if (curToken == Token_EOF)
{
//
// The element stack better be empty at this point or we
// ended prematurely before all elements were closed.
//
if (!fElemStack.isEmpty())
{
const ElemStack::StackElem* topElem = fElemStack.popTop();
emitError
(
XMLErrs::EndedWithTagsOnStack
, topElem->fThisElement->getFullName()
);
}
// Its the end of file, so clear the got data flag
gotData = false;
continue;
}
// We are in some sort of markup now
inMarkup = true;
//
// According to the token we got, call the appropriate
// scanning method.
//
switch(curToken)
{
case Token_CData :
// Make sure we are within content
if (fElemStack.isEmpty())
emitError(XMLErrs::CDATAOutsideOfContent);
scanCDSection();
break;
case Token_Comment :
scanComment();
break;
case Token_EndTag :
scanEndTag(gotData);
break;
case Token_PI :
scanPI();
break;
case Token_StartTag :
if (fDoNamespaces)
scanStartTagNS(gotData);
else
scanStartTag(gotData);
break;
default :
fReaderMgr.skipToChar(chOpenAngle);
break;
}
if (orgReader != fReaderMgr.getCurrentReaderNum())
emitError(XMLErrs::PartialMarkupInEntity);
// And we are back out of markup again
inMarkup = false;
}
}
catch(const EndOfEntityException& toCatch)
{
//
// If we were in some markup when this happened, then its a
// partial markup error.
//
if (inMarkup)
emitError(XMLErrs::PartialMarkupInEntity);
// Send an end of entity reference event
if (fDocHandler)
fDocHandler->endEntityReference(toCatch.getEntity());
inMarkup = false;
}
}
// It went ok, so return success
return true;
}
void XMLScanner::scanEndTag(bool& gotData)
{
//
// Assume we will still have data until proven otherwise. It will only
// ever be false if this is the end of the root element.
//
gotData = true;
//
// Check if the element stack is empty. If so, then this is an unbalanced
// element (i.e. more ends than starts, perhaps because of bad text
// causing one to be skipped.)
//
if (fElemStack.isEmpty())
{
emitError(XMLErrs::MoreEndThanStartTags);
fReaderMgr.skipPastChar(chCloseAngle);
ThrowXML(RuntimeException, XMLExcepts::Scan_UnbalancedStartEnd);
}
// After the </ is the element QName, so get a name from the input
XMLBufBid bbQName(&fBufMgr);
XMLBuffer& qnameBuf = bbQName.getBuffer();
if (!fReaderMgr.getName(qnameBuf))
{
// It failed so we can't really do anything with it
emitError(XMLErrs::ExpectedElementName);
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
unsigned int uriId = fEmptyNamespaceId;
XMLBufBid bbName(&fBufMgr);
XMLBufBid bbPrefix(&fBufMgr);
if (fDoNamespaces)
{
uriId = resolveQName
(
qnameBuf.getRawBuffer()
, bbName.getBuffer()
, bbPrefix.getBuffer()
, ElemStack::Mode_Element
);
}
//
// Pop the stack of the element we are supposed to be ending. Remember
// that we don't own this. The stack just keeps them and reuses them.
//
// NOTE: We CANNOT do this until we've resolved the element name because
// the element stack top contains the prefix to URI mappings for this
// element.
//
unsigned int topUri = fElemStack.getCurrentURI();
const ElemStack::StackElem* topElem = fElemStack.popTop();
// See if it was the root element, to avoid multiple calls below
const bool isRoot = fElemStack.isEmpty();
// Make sure that its the end of the element that we expect
XMLElementDecl* tempElement = topElem->fThisElement;
if (fDoNamespaces && fGrammarType == Grammar::SchemaGrammarType) {
if ((topUri != uriId) || (XMLString::compareString(tempElement->getBaseName(), bbName.getRawBuffer())))
{
emitError
(
XMLErrs::ExpectedEndOfTagX
, topElem->fThisElement->getFullName()
);
}
}
else {
if (XMLString::compareString(tempElement->getFullName(), qnameBuf.getRawBuffer()))
{
emitError
(
XMLErrs::ExpectedEndOfTagX
, topElem->fThisElement->getFullName()
);
}
}
// Make sure we are back on the same reader as where we started
if (topElem->fReaderNum != fReaderMgr.getCurrentReaderNum())
emitError(XMLErrs::PartialTagMarkupError);
// Skip optional whitespace
fReaderMgr.skipPastSpaces();
// Make sure we find the closing bracket
if (!fReaderMgr.skippedChar(chCloseAngle))
{
emitError
(
XMLErrs::UnterminatedEndTag
, topElem->fThisElement->getFullName()
);
}
//
// If validation is enabled, then lets pass him the list of children and
// this element and let him validate it.
//
if (fValidate)
{
int res = fValidator->checkContent
(
topElem->fThisElement
, topElem->fChildren
, topElem->fChildCount
);
if (res >= 0)
{
//
// One of the elements is not valid for the content. NOTE that
// if no children were provided but the content model requires
// them, it comes back with a zero value. But we cannot use that
// to index the child array in this case, and have to put out a
// special message.
//
if (!topElem->fChildCount)
{
fValidator->emitError
(
XMLValid::EmptyNotValidForContent
, topElem->fThisElement->getFormattedContentModel()
);
}
else if ((unsigned int)res >= topElem->fChildCount)
{
fValidator->emitError
(
XMLValid::NotEnoughElemsForCM
, topElem->fThisElement->getFormattedContentModel()
);
}
else
{
fValidator->emitError
(
XMLValid::ElementNotValidForContent
, topElem->fChildren[res]->getRawName()
, topElem->fThisElement->getFormattedContentModel()
);
}
}
// reset xsi:type ComplexTypeInfo
if (fGrammarType == Grammar::SchemaGrammarType) {
((SchemaElementDecl*)topElem->fThisElement)->setXsiComplexTypeInfo(0);
// call matchers and de-activate context
int oldCount = fMatcherStack->getMatcherCount();
if (oldCount ||
((SchemaElementDecl*)topElem->fThisElement)->getIdentityConstraintCount()) {
for (int i = oldCount - 1; i >= 0; i--) {
XPathMatcher* matcher = fMatcherStack->getMatcherAt(i);
matcher->endElement(*(topElem->fThisElement));
}
if (fMatcherStack->size() > 0) {
fMatcherStack->popContext();
}
// handle everything *but* keyref's.
int newCount = fMatcherStack->getMatcherCount();
for (int j = oldCount - 1; j >= newCount; j--) {
XPathMatcher* matcher = fMatcherStack->getMatcherAt(j);
IdentityConstraint* ic = matcher->getIdentityConstraint();
if (ic && (ic->getType() != IdentityConstraint::KEYREF)) {
matcher->endDocumentFragment();
fValueStoreCache->transplant(ic);
}
else if (!ic) {
matcher->endDocumentFragment();
}
}
// now handle keyref's...
for (int k = oldCount - 1; k >= newCount; k--) {
XPathMatcher* matcher = fMatcherStack->getMatcherAt(k);
IdentityConstraint* ic = matcher->getIdentityConstraint();
if (ic && (ic->getType() == IdentityConstraint::KEYREF)) {
ValueStore* values = fValueStoreCache->getValueStoreFor(ic);
if (values) { // nothing to do if nothing matched!
values->endDcocumentFragment(fValueStoreCache);
}
matcher->endDocumentFragment();
}
}
fValueStoreCache->endElement();
}
}
}
// If we have a doc handler, tell it about the end tag
if (fDocHandler)
{
fDocHandler->endElement
(
*topElem->fThisElement
, uriId
, isRoot
, bbPrefix.getRawBuffer()
);
}
// If this was the root, then done with content
gotData = !isRoot;
if (gotData) {
if (fDoNamespaces) {
// Restore the grammar
fGrammar = fElemStack.getCurrentGrammar();
fGrammarType = fGrammar->getGrammarType();
if (fGrammarType == Grammar::SchemaGrammarType && !fValidator->handlesSchema()) {
if (fValidatorFromUser)
ThrowXML(RuntimeException, XMLExcepts::Gen_NoSchemaValidator);
else {
fValidator = fSchemaValidator;
}
}
else if (fGrammarType == Grammar::DTDGrammarType && !fValidator->handlesDTD()) {
if (fValidatorFromUser)
ThrowXML(RuntimeException, XMLExcepts::Gen_NoDTDValidator);
else {
fValidator = fDTDValidator;
}
}
fValidator->setGrammar(fGrammar);
}
// Restore the validation flag
fValidate = fElemStack.getValidationFlag();
}
}
//
// This method is called after the end of the root element, to handle
// any miscellaneous stuff hanging around.
//
void XMLScanner::scanMiscellaneous()
{
// Get a buffer for this work
XMLBufBid bbCData(&fBufMgr);
while (true)
{
try
{
const XMLCh nextCh = fReaderMgr.peekNextChar();
// Watch for end of file and break out
if (!nextCh)
break;
if (nextCh == chOpenAngle)
{
if (checkXMLDecl(true))
{
// Can't have an XML decl here
emitError(XMLErrs::NotValidAfterContent);
fReaderMgr.skipPastChar(chCloseAngle);
}
else if (fReaderMgr.skippedString(XMLUni::fgPIString))
{
scanPI();
}
else if (fReaderMgr.skippedString(XMLUni::fgCommentString))
{
scanComment();
}
else
{
// This can't be possible, so just give up
emitError(XMLErrs::ExpectedCommentOrPI);
fReaderMgr.skipPastChar(chCloseAngle);
}
}
else if (XMLReader::isWhitespace(nextCh))
{
//
// If we have a doc handler, then gather up the spaces and
// call back. Otherwise, just skip over whitespace.
//
if (fDocHandler)
{
fReaderMgr.getSpaces(bbCData.getBuffer());
fDocHandler->ignorableWhitespace
(
bbCData.getRawBuffer()
, bbCData.getLen()
, false
);
}
else
{
fReaderMgr.skipPastSpaces();
}
}
else
{
emitError(XMLErrs::ExpectedCommentOrPI);
fReaderMgr.skipPastChar(chCloseAngle);
}
}
catch(const EndOfEntityException&)
{
//
// Some entity leaked out of the content part of the document. Issue
// a warning and keep going.
//
emitError(XMLErrs::EntityPropogated);
}
}
}
//
// Scans a PI and calls the appropriate callbacks. At entry we have just
// scanned the <? part, and need to now start on the PI target name.
//
void XMLScanner::scanPI()
{
const XMLCh* namePtr = 0;
const XMLCh* targetPtr = 0;
//
// If there are any spaces here, then warn about it. If we aren't in
// 'first error' mode, then we'll come back and can easily pick up
// again by just skipping them.
//
if (fReaderMgr.lookingAtSpace())
{
emitError(XMLErrs::PINameExpected);
fReaderMgr.skipPastSpaces();
}
// Get a buffer for the PI name and scan it in
XMLBufBid bbName(&fBufMgr);
if (!fReaderMgr.getName(bbName.getBuffer()))
{
emitError(XMLErrs::PINameExpected);
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
// Point the name pointer at the raw data
namePtr = bbName.getRawBuffer();
// See if it is some form of 'xml' and emit a warning
if (!XMLString::compareIString(namePtr, XMLUni::fgXMLString))
emitError(XMLErrs::NoPIStartsWithXML);
// If namespaces are enabled, then no colons allowed
if (fDoNamespaces)
{
if (XMLString::indexOf(namePtr, chColon) != -1)
emitError(XMLErrs::ColonNotLegalWithNS);
}
//
// If we don't hit a space next, then the PI has no target. If we do
// then get out the target. Get a buffer for it as well
//
XMLBufBid bbTarget(&fBufMgr);
if (fReaderMgr.skippedSpace())
{
// Skip any leading spaces
fReaderMgr.skipPastSpaces();
bool gotLeadingSurrogate = false;
// It does have a target, so lets move on to deal with that.
while (1)
{
const XMLCh nextCh = fReaderMgr.getNextChar();
// Watch for an end of file, which is always bad here
if (!nextCh)
{
emitError(XMLErrs::UnterminatedPI);
ThrowXML(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF);
}
// Watch for potential terminating character
if (nextCh == chQuestion)
{
// It must be followed by '>' to be a termination of the target
if (fReaderMgr.skippedChar(chCloseAngle))
break;
}
// Check for correct surrogate pairs
if ((nextCh >= 0xD800) && (nextCh <= 0xDBFF))
{
if (gotLeadingSurrogate)
emitError(XMLErrs::Expected2ndSurrogateChar);
else
gotLeadingSurrogate = true;
}
else
{
if (gotLeadingSurrogate)
{
if ((nextCh < 0xDC00) || (nextCh > 0xDFFF))
emitError(XMLErrs::Expected2ndSurrogateChar);
}
// Its got to at least be a valid XML character
else if (!XMLReader::isXMLChar(nextCh)) {
XMLCh tmpBuf[9];
XMLString::binToText
(
nextCh
, tmpBuf
, 8
, 16
);
emitError(XMLErrs::InvalidCharacter, tmpBuf);
}
gotLeadingSurrogate = false;
}
bbTarget.append(nextCh);
}
}
else
{
// No target, but make sure its terminated ok
if (!fReaderMgr.skippedChar(chQuestion))
{
emitError(XMLErrs::UnterminatedPI);
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
if (!fReaderMgr.skippedChar(chCloseAngle))
{
emitError(XMLErrs::UnterminatedPI);
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
}
// Point the target pointer at the raw data
targetPtr = bbTarget.getRawBuffer();
// If we have a handler, then call it
if (fDocHandler)
{
fDocHandler->docPI
(
namePtr
, targetPtr
);
}
}
//
// Scans all the input from the start of the file to the root element.
// There does not have to be anything in the prolog necessarily, but usually
// there is at least an XMLDecl.
//
// On exit from here we are either at the end of the file or about to read
// the opening < of the root element.
//
void XMLScanner::scanProlog()
{
// Get a buffer for whitespace processing
XMLBufBid bbCData(&fBufMgr);
//
// Loop through the prolog. If there is no content, this could go all
// the way to the end of the file.
//
// Note that we use a double loop here to avoid the overhead of the
// setup/teardown of the exception handler on each loop.
//
while (true)
{
try
{
while (true)
{
const XMLCh nextCh = fReaderMgr.peekNextChar();
if (nextCh == chOpenAngle)
{
//
// Ok, it could be the xml decl, a comment, the doc type line,
// or the start of the root element.
//
if (checkXMLDecl(true))
{
// There shall be at lease --ONE-- space in between
// the tag '<?xml' and the VersionInfo.
//
//
// If we are not at line 1, col 6, then the decl was not
// the first text, so its invalid.
//
const XMLReader* curReader = fReaderMgr.getCurrentReader();
if ((curReader->getLineNumber() != 1)
|| (curReader->getColumnNumber() != 7))
{
emitError(XMLErrs::XMLDeclMustBeFirst);
}
scanXMLDecl(Decl_XML);
}
else if (fReaderMgr.skippedString(XMLUni::fgPIString))
{
scanPI();
}
else if (fReaderMgr.skippedString(XMLUni::fgCommentString))
{
scanComment();
}
else if (fReaderMgr.skippedString(XMLUni::fgDocTypeString))
{
scanDocTypeDecl();
// if reusing grammar, this has been validated already in first scan
// skip for performance
if (!fReuseGrammar && fValidate) {
// validate the DTD scan so far
fValidator->preContentValidation(fReuseGrammar);
}
}
else
{
// Assume its the start of the root element
return;
}
}
else if (XMLReader::isWhitespace(nextCh))
{
//
// If we have a document handler then gather up the
// whitespace and call back. Otherwise just skip over spaces.
//
if (fDocHandler)
{
fReaderMgr.getSpaces(bbCData.getBuffer());
fDocHandler->ignorableWhitespace
(
bbCData.getRawBuffer()
, bbCData.getLen()
, false
);
}
else
{
fReaderMgr.skipPastSpaces();
}
}
else
{
emitError(XMLErrs::InvalidDocumentStructure);
fReaderMgr.skipPastChar(chCloseAngle);
}
}
}
catch(const EndOfEntityException&)
{
//
// We should never get an end of entity here. They should only
// occur within the doc type scanning method, and not leak out to
// here.
//
emitError
(
XMLErrs::UnexpectedEOE
, "in prolog"
);
}
}
}
//
// This method handles the high level logic of scanning the DOCType
// declaration. This calls the DTDScanner and kicks off both the scanning of
// the internal subset and the scanning of the external subset, if any.
//
// When we get here the '<!DOCTYPE' part has already been scanned, which is
// what told us that we had a doc type decl to parse.
//
void XMLScanner::scanDocTypeDecl()
{
if (!fReuseGrammar && fValidatorFromUser && !fValidator->handlesDTD())
{
ThrowXML(RuntimeException, XMLExcepts::Gen_NoDTDValidator);
}
//
// We have a doc type. So, create a DTDScanner and
// switch the Grammar to the emptyNamespace one.
//
if (!switchGrammar(XMLUni::fgZeroLenString) && fValidate)
{
fValidator->emitError
(
XMLValid::GrammarNotFound
, XMLUni::fgZeroLenString
);
}
DTDScanner dtdScanner((DTDGrammar*)fGrammar, fEntityDeclPool, fDocTypeHandler);
dtdScanner.setScannerInfo(this, &fReaderMgr, &fBufMgr);
if (fDocTypeHandler)
fDocTypeHandler->resetDocType();
// There must be some space after DOCTYPE
if (!fReaderMgr.skipPastSpaces())
{
emitError(XMLErrs::ExpectedWhitespace);
// Just skip the Doctype declaration and return
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
// Get a buffer for the root element
XMLBufBid bbRootName(&fBufMgr);
//
// Get a name from the input, which should be the name of the root
// element of the upcoming content.
//
fReaderMgr.getName(bbRootName.getBuffer());
if (bbRootName.isEmpty())
{
emitError(XMLErrs::NoRootElemInDOCTYPE);
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
//
// Store the root element name for later check
//
setRootElemName(bbRootName.getRawBuffer());
//
// This element obviously is not going to exist in the element decl
// pool yet, but we need to call docTypeDecl. So force it into
// the element decl pool, marked as being there because it was in
// the DOCTYPE. Later, when its declared, the status will be updated.
//
// Only do this if we are not reusing the validator! If we are reusing,
// then look it up instead. It has to exist!
//
DTDElementDecl* rootDecl;
Janitor<DTDElementDecl> janSrc(0);
if (fReuseGrammar)
{
if (fGrammar->getGrammarType() == Grammar::DTDGrammarType) {
rootDecl = (DTDElementDecl*) fGrammar->getElemDecl(fEmptyNamespaceId, 0, bbRootName.getRawBuffer(), Grammar::TOP_LEVEL_SCOPE);
if (rootDecl)
((DTDGrammar*)fGrammar)->setRootElemId(rootDecl->getId());
else {
rootDecl = new DTDElementDecl(bbRootName.getRawBuffer(), fEmptyNamespaceId);
rootDecl->setCreateReason(DTDElementDecl::AsRootElem);
rootDecl->setExternalElemDeclaration(true);
((DTDGrammar*)fGrammar)->setRootElemId(fGrammar->putElemDecl(rootDecl));
}
}
else {
rootDecl = new DTDElementDecl(bbRootName.getRawBuffer(), fEmptyNamespaceId);
rootDecl->setCreateReason(DTDElementDecl::AsRootElem);
rootDecl->setExternalElemDeclaration(true);
janSrc.reset(rootDecl);
}
}
else
{
rootDecl = new DTDElementDecl(bbRootName.getRawBuffer(), fEmptyNamespaceId);
rootDecl->setCreateReason(DTDElementDecl::AsRootElem);
rootDecl->setExternalElemDeclaration(true);
((DTDGrammar*)fGrammar)->setRootElemId(fGrammar->putElemDecl(rootDecl));
}
// Skip any spaces after the name
fReaderMgr.skipPastSpaces();
//
// And now if we are looking at a >, then we are done. It is not
// required to have an internal or external subset, though why you
// would not escapes me.
//
if (fReaderMgr.skippedChar(chCloseAngle)) {
//
// If we have a doc type handler and advanced callbacks are enabled,
// call the doctype event.
//
if (fDocTypeHandler)
fDocTypeHandler->doctypeDecl(*rootDecl, 0, 0, false);
return;
}
// either internal/external subset
if(!fReuseGrammar) {
if (fValScheme == Val_Auto && !fValidate)
fValidate = true;
}
bool hasIntSubset = false;
bool hasExtSubset = false;
XMLCh* sysId = 0;
XMLCh* pubId = 0;
//
// If the next character is '[' then we have no external subset cause
// there is no system id, just the opening character of the internal
// subset. Else, has to be an id.
//
// Just look at the next char, don't eat it.
if (fReaderMgr.peekNextChar() == chOpenSquare)
{
hasIntSubset = true;
}
else
{
// Indicate we have an external subset
hasExtSubset = true;
fHasNoDTD = false;
// Get buffers for the ids
XMLBufBid bbPubId(&fBufMgr);
XMLBufBid bbSysId(&fBufMgr);
// Get the external subset id
if (!dtdScanner.scanId(bbPubId.getBuffer(), bbSysId.getBuffer(), DTDScanner::IDType_External))
{
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
// Get copies of the ids we got
pubId = XMLString::replicate(bbPubId.getRawBuffer());
sysId = XMLString::replicate(bbSysId.getRawBuffer());
// Skip spaces and check again for the opening of an internal subset
fReaderMgr.skipPastSpaces();
// Just look at the next char, don't eat it.
if (fReaderMgr.peekNextChar() == chOpenSquare) {
hasIntSubset = true;
}
}
// Insure that the ids get cleaned up, if they got allocated
ArrayJanitor<XMLCh> janSysId(sysId);
ArrayJanitor<XMLCh> janPubId(pubId);
//
// If we have a doc type handler and advanced callbacks are enabled,
// call the doctype event.
//
if (fDocTypeHandler)
fDocTypeHandler->doctypeDecl(*rootDecl, pubId, sysId, hasIntSubset);
//
// Ok, if we had an internal subset, we are just past the [ character
// and need to parse that first.
//
if (hasIntSubset)
{
// Eat the opening square bracket
fReaderMgr.getNextChar();
// We can't have any internal subset if we are reusing the validator
if (fReuseGrammar)
ThrowXML(RuntimeException, XMLExcepts::Val_CantHaveIntSS);
//
// And try to scan the internal subset. If we fail, try to recover
// by skipping forward tot he close angle and returning.
//
if (!dtdScanner.scanInternalSubset())
{
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
//
// Do a sanity check that some expanded PE did not propogate out of
// the doctype. This could happen if it was terminated early by bad
// syntax.
//
if (fReaderMgr.getReaderDepth() > 1)
{
emitError(XMLErrs::PEPropogated);
// Ask the reader manager to pop back down to the main level
fReaderMgr.cleanStackBackTo(1);
}
fReaderMgr.skipPastSpaces();
}
// And that should leave us at the closing > of the DOCTYPE line
if (!fReaderMgr.skippedChar(chCloseAngle))
{
//
// Do a special check for the common scenario of an extra ] char at
// the end. This is easy to recover from.
//
if (fReaderMgr.skippedChar(chCloseSquare)
&& fReaderMgr.skippedChar(chCloseAngle))
{
emitError(XMLErrs::ExtraCloseSquare);
}
else
{
emitError(XMLErrs::UnterminatedDOCTYPE);
fReaderMgr.skipPastChar(chCloseAngle);
}
}
//
// If we had an external subset, then we need to deal with that one
// next. If we are reusing the validator, then don't scan it.
//
if (hasExtSubset && !fReuseGrammar && (fLoadExternalDTD || fValidate))
{
// And now create a reader to read this entity
InputSource* srcUsed;
XMLReader* reader = fReaderMgr.createReader
(
sysId
, pubId
, false
, XMLReader::RefFrom_NonLiteral
, XMLReader::Type_General
, XMLReader::Source_External
, srcUsed
);
// Put a janitor on the input source
Janitor<InputSource> janSrc(srcUsed);
//
// If it failed then throw an exception
//
if (!reader)
ThrowXML1(RuntimeException, XMLExcepts::Gen_CouldNotOpenDTD, srcUsed->getSystemId());
//
// In order to make the processing work consistently, we have to
// make this look like an external entity. So create an entity
// decl and fill it in and push it with the reader, as happens
// with an external entity. Put a janitor on it to insure it gets
// cleaned up. The reader manager does not adopt them.
//
const XMLCh gDTDStr[] = { chLatin_D, chLatin_T, chLatin_D , chNull };
DTDEntityDecl* declDTD = new DTDEntityDecl(gDTDStr);
declDTD->setSystemId(sysId);
Janitor<DTDEntityDecl> janDecl(declDTD);
// Mark this one as a throw at end
reader->setThrowAtEnd(true);
// And push it onto the stack, with its pseudo name
fReaderMgr.pushReader(reader, declDTD);
// Tell it its not in an include section
dtdScanner.scanExtSubsetDecl(false);
}
}
bool XMLScanner::scanStartTag(bool& gotData)
{
//
// Assume we will still have data until proven otherwise. It will only
// ever be false if this is the root and its empty.
//
gotData = true;
//
// Get the QName. In this case, we are not doing namespaces, so we just
// use it as is and don't have to break it into parts.
//
if (!fReaderMgr.getName(fQNameBuf))
{
emitError(XMLErrs::ExpectedElementName);
fReaderMgr.skipToChar(chOpenAngle);
return false;
}
// Assume it won't be an empty tag
bool isEmpty = false;
//
// Lets try to look up the element in the validator's element decl pool
// We can pass bogus values for the URI id and the base name. We know that
// this can only be called if we are doing a DTD style validator and that
// he will only look at the QName.
//
// We tell him to fault in a decl if he does not find one.
//
bool wasAdded = false;
XMLElementDecl* elemDecl = fGrammar->findOrAddElemDecl
(
fEmptyNamespaceId
, 0
, 0
, fQNameBuf.getRawBuffer()
, Grammar::TOP_LEVEL_SCOPE
, wasAdded
);
//
// We do something different here according to whether we found the
// element or not.
//
if (wasAdded)
{
// If validating then emit an error
if (fValidate)
{
// This is to tell the reuse Validator that this element was
// faulted-in, was not an element in the validator pool originally
elemDecl->setCreateReason(XMLElementDecl::JustFaultIn);
fValidator->emitError
(
XMLValid::ElementNotDefined
, elemDecl->getFullName()
);
}
}
else
{
// If its not marked declared and validating, then emit an error
if (fValidate && !elemDecl->isDeclared())
{
fValidator->emitError
(
XMLValid::ElementNotDefined
, elemDecl->getFullName()
);
}
}
// See if its the root element
const bool isRoot = fElemStack.isEmpty();
// Expand the element stack and add the new element
fElemStack.addLevel(elemDecl, fReaderMgr.getCurrentReaderNum());
fElemStack.setValidationFlag(fValidate);
// Validate the element
if (fValidate)
fValidator->validateElement(elemDecl);
//
// If this is the first element and we are validating, check the root
// element.
//
if (isRoot)
{
if (fValidate)
{
// If a DocType exists, then check if it matches the root name there.
if (fRootElemName && XMLString::compareString(fQNameBuf.getRawBuffer(), fRootElemName))
fValidator->emitError(XMLValid::RootElemNotLikeDocType);
// Some validators may also want to check the root, call the
// XMLValidator::checkRootElement
if (fValidatorFromUser && !fValidator->checkRootElement(elemDecl->getId()))
fValidator->emitError(XMLValid::RootElemNotLikeDocType);
}
}
else
{
//
// If the element stack is not empty, then add this element as a
// child of the previous top element. If its empty, this is the root
// elem and is not the child of anything.
//
fElemStack.addChild(elemDecl->getElementName(), true);
}
//
// Ask the element decl to clear out the 'provided' flag on all of its
// att defs.
//
elemDecl->resetDefs();
// Skip any whitespace after the name
fReaderMgr.skipPastSpaces();
//
// We loop until we either see a /> or >, handling attribute/value
// pairs until we get there.
//
unsigned int attCount = 0;
unsigned int curAttListSize = fAttrList->size();
while (true)
{
// And get the next non-space character
XMLCh nextCh = fReaderMgr.peekNextChar();
//
// If the next character is not a slash or closed angle bracket,
// then it must be whitespace, since whitespace is required
// between the end of the last attribute and the name of the next
// one.
//
if (attCount)
{
if ((nextCh != chForwardSlash) && (nextCh != chCloseAngle))
{
if (XMLReader::isWhitespace(nextCh))
{
// Ok, skip by them and peek another char
fReaderMgr.skipPastSpaces();
nextCh = fReaderMgr.peekNextChar();
}
else
{
// Emit the error but keep on going
emitError(XMLErrs::ExpectedWhitespace);
}
}
}
//
// Ok, here we first check for any of the special case characters.
// If its not one, then we do the normal case processing, which
// assumes that we've hit an attribute value, Otherwise, we do all
// the special case checks.
//
if (!XMLReader::isSpecialStartTagChar(nextCh))
{
//
// Assume its going to be an attribute, so get a name from
// the input.
//
if (!fReaderMgr.getName(fAttNameBuf))
{
emitError(XMLErrs::ExpectedAttrName);
fReaderMgr.skipPastChar(chCloseAngle);
return false;
}
// And next must be an equal sign
if (!scanEq())
{
static const XMLCh tmpList[] =
{
chSingleQuote, chDoubleQuote, chCloseAngle
, chOpenAngle, chForwardSlash, chNull
};
emitError(XMLErrs::ExpectedEqSign);
//
// Try to sync back up by skipping forward until we either
// hit something meaningful.
//
const XMLCh chFound = fReaderMgr.skipUntilInOrWS(tmpList);
if ((chFound == chCloseAngle) || (chFound == chForwardSlash))
{
// Jump back to top for normal processing of these
continue;
}
else if ((chFound == chSingleQuote)
|| (chFound == chDoubleQuote)
|| XMLReader::isWhitespace(chFound))
{
// Just fall through assuming that the value is to follow
}
else if (chFound == chOpenAngle)
{
// Assume a malformed tag and that new one is starting
emitError(XMLErrs::UnterminatedStartTag, elemDecl->getFullName());
return false;
}
else
{
// Something went really wrong
return false;
}
}
//
// See if this attribute is declared for this element. If we are
// not validating of course it will not be at first, but we will
// fault it into the pool (to avoid lots of redundant errors.)
//
wasAdded = false;
XMLAttDef* attDef = elemDecl->findAttr
(
fAttNameBuf.getRawBuffer()
, 0
, 0
, 0
, XMLElementDecl::AddIfNotFound
, wasAdded
);
if (wasAdded)
{
//
// If there is a validation handler, then we are validating
// so emit an error.
//
if (fValidate)
{
// This is to tell the Validator that this attribute was
// faulted-in, was not an attribute in the attdef originally
attDef->setCreateReason(XMLAttDef::JustFaultIn);
fValidator->emitError
(
XMLValid::AttNotDefinedForElement
, fAttNameBuf.getRawBuffer()
, elemDecl->getFullName()
);
}
}
else
{
// If this attribute was faulted-in and first occurence,
// then emit an error
if (fValidate && attDef->getCreateReason() == XMLAttDef::JustFaultIn
&& !attDef->getProvided())
{
fValidator->emitError
(
XMLValid::AttNotDefinedForElement
, fAttNameBuf.getRawBuffer()
, elemDecl->getFullName()
);
}
}
//
// If its already provided, then there are more than one of
// this attribute in this start tag, so emit an error.
//
if (attDef->getProvided())
{
emitError
(
XMLErrs::AttrAlreadyUsedInSTag
, attDef->getFullName()
, elemDecl->getFullName()
);
}
else
{
// Mark this one as already seen
attDef->setProvided(true);
}
//
// Skip any whitespace before the value and then scan the att
// value. This will come back normalized with entity refs and
// char refs expanded.
//
fReaderMgr.skipPastSpaces();
if (!scanAttValue(attDef, fAttValueBuf))
{
static const XMLCh tmpList[] =
{
chCloseAngle, chOpenAngle, chForwardSlash, chNull
};
emitError(XMLErrs::ExpectedAttrValue);
//
// It failed, so lets try to get synced back up. We skip
// forward until we find some whitespace or one of the
// chars in our list.
//
const XMLCh chFound = fReaderMgr.skipUntilInOrWS(tmpList);
if ((chFound == chCloseAngle)
|| (chFound == chForwardSlash)
|| XMLReader::isWhitespace(chFound))
{
//
// Just fall through and process this attribute, though
// the value will be "".
//
}
else if (chFound == chOpenAngle)
{
// Assume a malformed tag and that new one is starting
emitError(XMLErrs::UnterminatedStartTag, elemDecl->getFullName());
return false;
}
else
{
// Something went really wrong
return false;
}
}
//
// Now that its all stretched out, lets look at its type and
// determine if it has a valid value. It will output any needed
// errors, but we just keep going. We only need to do this if
// we are validating.
//
if (!wasAdded && attDef->getCreateReason() != XMLAttDef::JustFaultIn)
{
// Let the validator pass judgement on the attribute value
if (fValidate)
{
fValidator->validateAttrValue
(
attDef
, fAttValueBuf.getRawBuffer()
);
}
}
//
// Add this attribute to the attribute list that we use to
// pass them to the handler. We reuse its existing elements
// but expand it as required.
//
XMLAttr* curAtt;
if (attCount >= curAttListSize)
{
curAtt = new XMLAttr
(
-1
, fAttNameBuf.getRawBuffer()
, XMLUni::fgZeroLenString
, fAttValueBuf.getRawBuffer()
, attDef->getType()
, true
);
fAttrList->addElement(curAtt);
}
else
{
curAtt = fAttrList->elementAt(attCount);
curAtt->set
(
-1
, fAttNameBuf.getRawBuffer()
, XMLUni::fgZeroLenString
, fAttValueBuf.getRawBuffer()
, attDef->getType()
);
curAtt->setSpecified(true);
}
attCount++;
// And jump back to the top of the loop
continue;
}
//
// It was some special case character so do all of the checks and
// deal with it.
//
if (!nextCh)
ThrowXML(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF);
if (nextCh == chForwardSlash)
{
fReaderMgr.getNextChar();
isEmpty = true;
if (!fReaderMgr.skippedChar(chCloseAngle))
emitError(XMLErrs::UnterminatedStartTag, elemDecl->getFullName());
break;
}
else if (nextCh == chCloseAngle)
{
fReaderMgr.getNextChar();
break;
}
else if (nextCh == chOpenAngle)
{
//
// Check for this one specially, since its going to be common
// and it is kind of auto-recovering since we've already hit the
// next open bracket, which is what we would have seeked to (and
// skipped this whole tag.)
//
emitError(XMLErrs::UnterminatedStartTag, elemDecl->getFullName());
break;
}
else if ((nextCh == chSingleQuote) || (nextCh == chDoubleQuote))
{
//
// Check for this one specially, which is probably a missing
// attribute name, e.g. ="value". Just issue expected name
// error and eat the quoted string, then jump back to the
// top again.
//
emitError(XMLErrs::ExpectedAttrName);
fReaderMgr.getNextChar();
fReaderMgr.skipQuotedString(nextCh);
fReaderMgr.skipPastSpaces();
continue;
}
}
//
// Ok, so lets get an enumerator for the attributes of this element
// and run through them for well formedness and validity checks. But
// make sure that we had any attributes before we do it, since the list
// would have have gotten faulted in anyway.
//
if (elemDecl->hasAttDefs())
{
XMLAttDefList& attDefList = elemDecl->getAttDefList();
while (attDefList.hasMoreElements())
{
// Get the current att def, for convenience and its def type
const XMLAttDef& curDef = attDefList.nextElement();
const XMLAttDef::DefAttTypes defType = curDef.getDefaultType();
if (!curDef.getProvided())
{
if (fValidate)
{
// If we are validating and its required, then an error
if (defType == XMLAttDef::Required)
{
fValidator->emitError
(
XMLValid::RequiredAttrNotProvided
, curDef.getFullName()
);
}
else if ((defType == XMLAttDef::Default) ||
(defType == XMLAttDef::Fixed) )
{
if (fStandalone && curDef.isExternal())
{
//
// XML 1.0 Section 2.9
// Document is standalone, so attributes must not be defaulted.
//
fValidator->emitError(XMLValid::NoDefAttForStandalone, curDef.getFullName(), elemDecl->getFullName());
}
}
}
// Fault in the value if needed, and bump the att count
if ((defType == XMLAttDef::Default)
|| (defType == XMLAttDef::Fixed))
{
XMLAttr* curAtt;
if (attCount >= curAttListSize)
{
curAtt = new XMLAttr
(
-1
, curDef.getFullName()
, XMLUni::fgZeroLenString
, curDef.getValue()
, curDef.getType()
, false
);
fAttrList->addElement(curAtt);
curAttListSize++;
}
else
{
curAtt = fAttrList->elementAt(attCount);
curAtt->set
(
-1
, curDef.getFullName()
, XMLUni::fgZeroLenString
, curDef.getValue()
, curDef.getType()
);
curAtt->setSpecified(false);
}
attCount++;
}
}
}
}
//
// If empty, validate content right now if we are validating and then
// pop the element stack top. Else, we have to update the current stack
// top's namespace mapping elements.
//
if (isEmpty)
{
// If validating, then insure that its legal to have no content
if (fValidate)
{
const int res = fValidator->checkContent(elemDecl, 0, 0);
if (res >= 0)
{
fValidator->emitError
(
XMLValid::ElementNotValidForContent
, elemDecl->getFullName()
, elemDecl->getFormattedContentModel()
);
}
}
// Pop the element stack back off since it'll never be used now
fElemStack.popTop();
// If the elem stack is empty, then it was an empty root
if (isRoot)
gotData = false;
else {
// Restore the validation flag
fValidate = fElemStack.getValidationFlag();
}
}
//
// If we have a document handler, then tell it about this start tag. We
// don't have any URI id to send along, so send fEmptyNamespaceId. We also do not send
// any prefix since its just one big name if we are not doing namespaces.
//
if (fDocHandler)
{
fDocHandler->startElement
(
*elemDecl
, fEmptyNamespaceId
, 0
, *fAttrList
, attCount
, isEmpty
, isRoot
);
}
return true;
}
//
//
// This method is called to scan a start tag when we are processing
// namespaces. There are two different versions of this method, one for
// namespace aware processing an done for non-namespace aware processing.
//
// This method is called after we've scanned the < of a start tag. So we
// have to get the element name, then scan the attributes, after which
// we are either going to see >, />, or attributes followed by one of those
// sequences.
//
bool XMLScanner::scanStartTagNS(bool& gotData)
{
//
// Assume we will still have data until proven otherwise. It will only
// ever be false if this is the root and its empty.
//
gotData = true;
//
// The current position is after the open bracket, so we need to read in
// in the element name.
//
if (!fReaderMgr.getName(fQNameBuf))
{
emitError(XMLErrs::ExpectedElementName);
fReaderMgr.skipToChar(chOpenAngle);
return false;
}
//
// Do a little sanity check here. One common problem is that
// badly encoded files cause getName() to exit above on a
// non-name char (an invalid XML char), then the scan start
// tag below fails. This is misleading, so check here that
// we are looking at a valid XML char.
//
if (!XMLReader::isXMLChar(fReaderMgr.peekNextChar()))
{
XMLCh tmpBuf[9];
XMLString::binToText
(
fReaderMgr.getNextChar()
, tmpBuf
, 8
, 16
);
emitError(XMLErrs::InvalidCharacter, tmpBuf);
}
// See if its the root element
const bool isRoot = fElemStack.isEmpty();
// Skip any whitespace after the name
fReaderMgr.skipPastSpaces();
//
// First we have to do the rawest attribute scan. We don't do any
// normalization of them at all, since we don't know yet what type they
// might be (since we need the element decl in order to do that.)
//
bool isEmpty;
unsigned int attCount = rawAttrScan
(
fQNameBuf.getRawBuffer()
, *fRawAttrList
, isEmpty
);
const bool gotAttrs = (attCount != 0);
// save the contentleafname and currentscope before addlevel, for later use
ContentLeafNameTypeVector* cv = 0;
XMLContentModel* cm = 0;
int currentScope = Grammar::TOP_LEVEL_SCOPE;
if (!isRoot && fGrammarType == Grammar::SchemaGrammarType) {
SchemaElementDecl* tempElement = (SchemaElementDecl*) fElemStack.topElement()->fThisElement;
SchemaElementDecl::ModelTypes modelType = tempElement->getModelType();
if ((modelType == SchemaElementDecl::Mixed_Simple)
|| (modelType == SchemaElementDecl::Mixed_Complex)
|| (modelType == SchemaElementDecl::Children))
{
cm = tempElement->getContentModel();
cv = cm->getContentLeafNameTypeVector();
currentScope = fElemStack.getCurrentScope();
}
}
//
// Now, since we might have to update the namespace map for this element,
// but we don't have the element decl yet, we just tell the element stack
// to expand up to get ready.
//
unsigned int elemDepth = fElemStack.addLevel();
fElemStack.setValidationFlag(fValidate);
// Check if there is any external schema location specified, and if we are at root,
// go through them first before scanning those specified in the instance document
if (isRoot
&& fDoSchema
&& !fReuseGrammar
&& (fExternalSchemaLocation || fExternalNoNamespaceSchemaLocation)) {
if (fExternalSchemaLocation)
parseSchemaLocation(fExternalSchemaLocation);
if (fExternalNoNamespaceSchemaLocation)
resolveSchemaGrammar(fExternalNoNamespaceSchemaLocation, XMLUni::fgZeroLenString);
}
//
// Make an initial pass through the list and find any xmlns attributes or
// schema attributes.
//
if (attCount)
scanRawAttrListforNameSpaces(fRawAttrList, attCount);
//
// Also find any default or fixed xmlns attributes in DTD defined for
// this element.
//
if (fGrammarType == Grammar::DTDGrammarType) {
XMLElementDecl* elemDecl = fGrammar->getElemDecl
(
fEmptyNamespaceId
, 0
, fQNameBuf.getRawBuffer()
, Grammar::TOP_LEVEL_SCOPE
);
if (elemDecl) {
if (elemDecl->hasAttDefs()) {
XMLAttDefList& attDefList = elemDecl->getAttDefList();
while (attDefList.hasMoreElements())
{
// Get the current att def, for convenience and its def type
const XMLAttDef& curDef = attDefList.nextElement();
const XMLAttDef::DefAttTypes defType = curDef.getDefaultType();
// update the NSMap if there are any default/fixed xmlns attributes
if ((defType == XMLAttDef::Default)
|| (defType == XMLAttDef::Fixed))
{
const XMLCh* rawPtr = curDef.getFullName();
if (!XMLString::compareNString(rawPtr, XMLUni::fgXMLNSColonString, 6)
|| !XMLString::compareString(rawPtr, XMLUni::fgXMLNSString))
updateNSMap(rawPtr, curDef.getValue());
}
}
}
}
}
//
// Resolve the qualified name to a URI and name so that we can look up
// the element decl for this element. We have now update the prefix to
// namespace map so we should get the correct element now.
//
unsigned int uriId = resolveQName
(
fQNameBuf.getRawBuffer()
, fNameBuf
, fPrefixBuf
, ElemStack::Mode_Element
);
//if schema, check if we should lax or skip the validation of this element
bool laxThisOne = false;
if (cv) {
QName element(fPrefixBuf.getRawBuffer(), fNameBuf.getRawBuffer(), uriId);
// elementDepth will be > 0, as cv is only constructed if element is not
// root.
laxThisOne = laxElementValidation(&element, cv, cm, elemDepth - 1);
}
//
// Look up the element now in the grammar. This will get us back a
// generic element decl object. We tell him to fault one in if he does
// not find it.
//
bool wasAdded = false;
XMLElementDecl* elemDecl;
const XMLCh* nameRawBuf = fNameBuf.getRawBuffer();
const XMLCh* qnameRawBuf = fQNameBuf.getRawBuffer();
if (uriId != fEmptyNamespaceId) {
// Check in current grammar before switching if necessary
elemDecl = fGrammar->getElemDecl
(
uriId
, nameRawBuf
, qnameRawBuf
, currentScope
);
if (!elemDecl && (fURIStringPool->getId(fGrammar->getTargetNamespace()) != uriId)) {
// not found, switch to the specified grammar
const XMLCh* uriStr = getURIText(uriId);
if (!switchGrammar(uriStr) && fValidate && !laxThisOne)
{
fValidator->emitError
(
XMLValid::GrammarNotFound
,uriStr
);
}
elemDecl = fGrammar->getElemDecl
(
uriId
, nameRawBuf
, qnameRawBuf
, currentScope
);
}
if (!elemDecl && currentScope != Grammar::TOP_LEVEL_SCOPE) {
// if not found, then it may be a reference, try TOP_LEVEL_SCOPE
elemDecl = fGrammar->getElemDecl
(
uriId
, nameRawBuf
, qnameRawBuf
, Grammar::TOP_LEVEL_SCOPE
);
if(!elemDecl) {
// still not found in specified uri
// try emptyNamesapce see if element should be un-qualified.
elemDecl = fGrammar->getElemDecl
(
fEmptyNamespaceId
, nameRawBuf
, qnameRawBuf
, currentScope
);
if (elemDecl && elemDecl->getCreateReason() != XMLElementDecl::JustFaultIn && fValidate) {
fValidator->emitError
(
XMLValid::ElementNotUnQualified
, elemDecl->getFullName()
);
}
}
}
if (!elemDecl) {
// still not found, fault this in and issue error later
elemDecl = fGrammar->putElemDecl(uriId
, nameRawBuf
, fPrefixBuf.getRawBuffer()
, qnameRawBuf
, currentScope);
wasAdded = true;
}
}
else
{
//the element has no prefix,
//thus it is either a non-qualified element defined in current targetNS
//or an element that is defined in the globalNS
//try unqualifed first
elemDecl = fGrammar->getElemDecl
(
uriId
, nameRawBuf
, qnameRawBuf
, currentScope
);
unsigned orgGrammarUri = fURIStringPool->getId(fGrammar->getTargetNamespace());
if (!elemDecl && orgGrammarUri != fEmptyNamespaceId) {
//not found, switch grammar and try globalNS
if (!switchGrammar(XMLUni::fgZeroLenString) && fValidate && !laxThisOne)
{
fValidator->emitError
(
XMLValid::GrammarNotFound
, XMLUni::fgZeroLenString
);
}
elemDecl = fGrammar->getElemDecl
(
uriId
, nameRawBuf
, qnameRawBuf
, currentScope
);
}
if (!elemDecl && currentScope != Grammar::TOP_LEVEL_SCOPE) {
// if not found, then it may be a reference, try TOP_LEVEL_SCOPE
elemDecl = fGrammar->getElemDecl
(
uriId
, nameRawBuf
, qnameRawBuf
, Grammar::TOP_LEVEL_SCOPE
);
if (!elemDecl && orgGrammarUri != fEmptyNamespaceId) {
// still Not found in specified uri
// go to original Grammar again to see if element needs to be fully qualified.
const XMLCh* uriStr = getURIText(orgGrammarUri);
if (!switchGrammar(uriStr) && fValidate && !laxThisOne)
{
fValidator->emitError
(
XMLValid::GrammarNotFound
,uriStr
);
}
elemDecl = fGrammar->getElemDecl
(
orgGrammarUri
, nameRawBuf
, qnameRawBuf
, currentScope
);
if (elemDecl && elemDecl->getCreateReason() != XMLElementDecl::JustFaultIn && fValidate) {
fValidator->emitError
(
XMLValid::ElementNotQualified
, elemDecl->getFullName()
);
}
}
}
if (!elemDecl) {
// still not found, fault this in and issue error later
elemDecl = fGrammar->putElemDecl(uriId
, nameRawBuf
, fPrefixBuf.getRawBuffer()
, qnameRawBuf
, currentScope);
wasAdded = true;
}
}
//
// We do something different here according to whether we found the
// element or not.
//
if (wasAdded)
{
if (laxThisOne) {
fValidate = false;
fElemStack.setValidationFlag(fValidate);
}
// If validating then emit an error
if (fValidate)
{
// This is to tell the reuse Validator that this element was
// faulted-in, was not an element in the grammar pool originally
elemDecl->setCreateReason(XMLElementDecl::JustFaultIn);
fValidator->emitError
(
XMLValid::ElementNotDefined
, elemDecl->getFullName()
);
}
}
else
{
// If its not marked declared and validating, then emit an error
if (!elemDecl->isDeclared()) {
if (laxThisOne) {
fValidate = false;
fElemStack.setValidationFlag(fValidate);
}
if (fValidate)
{
fValidator->emitError
(
XMLValid::ElementNotDefined
, elemDecl->getFullName()
);
}
}
if (fGrammarType == Grammar::SchemaGrammarType)
((SchemaElementDecl*)elemDecl)->setXsiComplexTypeInfo(0);
}
//
// Now we can update the element stack to set the current element
// decl. We expanded the stack above, but couldn't store the element
// decl because we didn't know it yet.
//
fElemStack.setElement(elemDecl, fReaderMgr.getCurrentReaderNum());
fElemStack.setCurrentURI(uriId);
// Validate the element
if (fValidate)
fValidator->validateElement(elemDecl);
if (fGrammarType == Grammar::SchemaGrammarType) {
ComplexTypeInfo* typeinfo = ((SchemaElementDecl*)elemDecl)->getComplexTypeInfo();
if (typeinfo) {
currentScope = typeinfo->getScopeDefined();
// switch grammar if the typeinfo has a different grammar (happens when there is xsi:type)
XMLCh* typeName = typeinfo->getTypeName();
const XMLCh poundStr[] = {chPound, chNull};
if (!XMLString::startsWith(typeName, poundStr)) {
const int comma = XMLString::indexOf(typeName, chComma);
if (comma != -1) {
XMLBuffer prefixBuf(comma+1);
prefixBuf.append(typeName, comma);
const XMLCh* uriStr = prefixBuf.getRawBuffer();
if (!switchGrammar(uriStr) && fValidate && !laxThisOne)
{
fValidator->emitError
(
XMLValid::GrammarNotFound
, prefixBuf.getRawBuffer()
);
}
}
}
}
fElemStack.setCurrentScope(currentScope);
// Set element next state
if (elemDepth >= fElemStateSize) {
resizeElemState();
}
fElemState[elemDepth] = 0;
}
fElemStack.setCurrentGrammar(fGrammar);
//
// If this is the first element and we are validating, check the root
// element.
//
if (isRoot)
{
if (fValidate)
{
// If a DocType exists, then check if it matches the root name there.
if (fRootElemName && XMLString::compareString(qnameRawBuf, fRootElemName))
fValidator->emitError(XMLValid::RootElemNotLikeDocType);
// Some validators may also want to check the root, call the
// XMLValidator::checkRootElement
if (fValidatorFromUser && !fValidator->checkRootElement(elemDecl->getId()))
fValidator->emitError(XMLValid::RootElemNotLikeDocType);
}
}
else
{
//
// If the element stack is not empty, then add this element as a
// child of the previous top element. If its empty, this is the root
// elem and is not the child of anything.
//
fElemStack.addChild(elemDecl->getElementName(), true);
}
//
// Now lets get the fAttrList filled in. This involves faulting in any
// defaulted and fixed attributes and normalizing the values of any that
// we got explicitly.
//
// We update the attCount value with the total number of attributes, but
// it goes in with the number of values we got during the raw scan of
// explictly provided attrs above.
//
attCount = buildAttList(*fRawAttrList, attCount, elemDecl, *fAttrList);
//
// activate identity constraints
//
if (fValidate && fGrammar && fGrammarType == Grammar::SchemaGrammarType) {
unsigned int count = ((SchemaElementDecl*) elemDecl)->getIdentityConstraintCount();
if (count || fMatcherStack->getMatcherCount()) {
fValueStoreCache->startElement();
fMatcherStack->pushContext();
fValueStoreCache->initValueStoresFor((SchemaElementDecl*) elemDecl);
for (unsigned int i = 0; i < count; i++) {
activateSelectorFor(((SchemaElementDecl*) elemDecl)->getIdentityConstraintAt(i));
}
// call all active identity constraints
count = fMatcherStack->getMatcherCount();
for (unsigned int j = 0; j < count; j++) {
XPathMatcher* matcher = fMatcherStack->getMatcherAt(j);
matcher->startElement(*elemDecl, uriId, fPrefixBuf.getRawBuffer(), *fAttrList, attCount);
}
}
}
// Since the element may have default values, call start tag now regardless if it is empty or not
// If we have a document handler, then tell it about this start tag
if (fDocHandler)
{
fDocHandler->startElement
(
*elemDecl
, uriId
, fPrefixBuf.getRawBuffer()
, *fAttrList
, attCount
, false
, isRoot
);
}
//
// If empty, validate content right now if we are validating and then
// pop the element stack top. Else, we have to update the current stack
// top's namespace mapping elements.
//
if (isEmpty)
{
// Pop the element stack back off since it'll never be used now
fElemStack.popTop();
// If validating, then insure that its legal to have no content
if (fValidate)
{
const int res = fValidator->checkContent(elemDecl, 0, 0);
if (res >= 0)
{
fValidator->emitError
(
XMLValid::ElementNotValidForContent
, elemDecl->getFullName()
, elemDecl->getFormattedContentModel()
);
}
if (fGrammarType == Grammar::SchemaGrammarType) {
// reset xsi:type ComplexTypeInfo
((SchemaElementDecl*)elemDecl)->setXsiComplexTypeInfo(0);
// call matchers and de-activate context
int oldCount = fMatcherStack->getMatcherCount();
if (oldCount || ((SchemaElementDecl*) elemDecl)->getIdentityConstraintCount()) {
for (int i = oldCount - 1; i >= 0; i--) {
XPathMatcher* matcher = fMatcherStack->getMatcherAt(i);
matcher->endElement(*elemDecl);
}
if (fMatcherStack->size() > 0) {
fMatcherStack->popContext();
}
// handle everything *but* keyref's.
int newCount = fMatcherStack->getMatcherCount();
for (int j = oldCount - 1; j >= newCount; j--) {
XPathMatcher* matcher = fMatcherStack->getMatcherAt(j);
IdentityConstraint* ic = matcher->getIdentityConstraint();
if (ic && (ic->getType() != IdentityConstraint::KEYREF)) {
matcher->endDocumentFragment();
fValueStoreCache->transplant(ic);
}
else if (!ic) {
matcher->endDocumentFragment();
}
}
// now handle keyref's...
for (int k = oldCount - 1; k >= newCount; k--) {
XPathMatcher* matcher = fMatcherStack->getMatcherAt(k);
IdentityConstraint* ic = matcher->getIdentityConstraint();
if (ic && (ic->getType() == IdentityConstraint::KEYREF)) {
ValueStore* values = fValueStoreCache->getValueStoreFor(ic);
if (values) { // nothing to do if nothing matched!
values->endDcocumentFragment(fValueStoreCache);
}
matcher->endDocumentFragment();
}
}
fValueStoreCache->endElement();
}
}
}
// If we have a doc handler, tell it about the end tag
if (fDocHandler)
{
fDocHandler->endElement
(
*elemDecl
, uriId
, isRoot
, fPrefixBuf.getRawBuffer()
);
}
// If the elem stack is empty, then it was an empty root
if (isRoot)
gotData = false;
else
{
// Restore the grammar
fGrammar = fElemStack.getCurrentGrammar();
fGrammarType = fGrammar->getGrammarType();
if (fGrammarType == Grammar::SchemaGrammarType && !fValidator->handlesSchema()) {
if (fValidatorFromUser)
ThrowXML(RuntimeException, XMLExcepts::Gen_NoSchemaValidator);
else {
fValidator = fSchemaValidator;
}
}
else if (fGrammarType == Grammar::DTDGrammarType && !fValidator->handlesDTD()) {
if (fValidatorFromUser)
ThrowXML(RuntimeException, XMLExcepts::Gen_NoDTDValidator);
else {
fValidator = fDTDValidator;
}
}
fValidator->setGrammar(fGrammar);
// Restore the validation flag
fValidate = fElemStack.getValidationFlag();
}
}
return true;
}
//
// Scans the <?xml .... ?> line. This stuff is all sequential so we don't
// do any state machine loop here. We just bull straight through it. It ends
// past the closing bracket. If there is a document handler, then its called
// on the XMLDecl callback.
//
// On entry, the <?xml has been scanned, and we pick it up from there.
//
// NOTE: In order to provide good recovery from bad XML here, we try to be
// very flexible. No matter what order the stuff is in, we'll keep going
// though we'll issue errors.
//
// The parameter tells us which type of decl we should expect, Text or XML.
// [23] XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
// [77] TextDecl::= '<?xml' VersionInfo? EncodingDecl S? '?>'
//
void XMLScanner::scanXMLDecl(const DeclTypes type)
{
// Get us some buffers to use
XMLBufBid bbVersion(&fBufMgr);
XMLBufBid bbEncoding(&fBufMgr);
XMLBufBid bbStand(&fBufMgr);
XMLBufBid bbDummy(&fBufMgr);
XMLBufBid bbName(&fBufMgr);
//
// We use this little enum and array to keep up with what we found
// and what order we found them in. This lets us get them free form
// without too much overhead, but still know that they were in the
// wrong order.
//
enum Strings
{
VersionString
, EncodingString
, StandaloneString
, UnknownString
, StringCount
};
int flags[StringCount] = { -1, -1, -1, -1 };
//
// Also set up a list of buffers in the right order so that we know
// where to put stuff.
//
XMLBuffer* buffers[StringCount] ;
buffers[0] = &bbVersion.getBuffer();
buffers[1] = &bbEncoding.getBuffer();
buffers[2] = &bbStand.getBuffer();
buffers[3] = &bbDummy.getBuffer();
int curCount = 0;
Strings curString;
XMLBuffer& nameBuf = bbName.getBuffer();
while (true)
{
// Skip any spaces
const unsigned int spaceCount = fReaderMgr.skipPastSpaces();
// If we are looking at a question mark, then break out
if (fReaderMgr.lookingAtChar(chQuestion))
break;
// If this is not the first string, then we require the spaces
if (!spaceCount && curCount)
emitError(XMLErrs::ExpectedWhitespace);
//
// Get characters up to the next whitespace or equal's sign.
//
if (!scanUpToWSOr(nameBuf, chEqual))
emitError(XMLErrs::ExpectedDeclString);
// See if it matches any of our expected strings
if (!XMLString::compareString(nameBuf.getRawBuffer(), XMLUni::fgVersionString))
curString = VersionString;
else if (!XMLString::compareString(nameBuf.getRawBuffer(), XMLUni::fgEncodingString))
curString = EncodingString;
else if (!XMLString::compareString(nameBuf.getRawBuffer(), XMLUni::fgStandaloneString))
curString = StandaloneString;
else
curString = UnknownString;
//
// If its an unknown string, then give that error. Else check to
// see if this one has been done already and give that error.
//
if (curString == UnknownString)
emitError(XMLErrs::ExpectedDeclString, nameBuf.getRawBuffer());
else if (flags[curString] != -1)
emitError(XMLErrs::DeclStringRep, nameBuf.getRawBuffer());
else if (flags[curString] == -1)
flags[curString] = ++curCount;
//
// Scan for an equal's sign. If we don't find it, issue an error
// but keep trying to go on.
//
if (!scanEq())
emitError(XMLErrs::ExpectedEqSign);
//
// Get a quote string into the buffer for the string that we are
// currently working on.
//
if (!getQuotedString(*buffers[curString]))
{
emitError(XMLErrs::ExpectedQuotedString);
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
// And validate the value according which one it was
const XMLCh* rawValue = buffers[curString]->getRawBuffer();
if (curString == VersionString)
{
if (XMLString::compareString(rawValue, XMLUni::fgSupportedVersion))
emitError(XMLErrs::UnsupportedXMLVersion, rawValue);
}
else if (curString == EncodingString)
{
if (!XMLString::isValidEncName(rawValue))
emitError(XMLErrs::BadXMLEncoding, rawValue);
}
else if (curString == StandaloneString)
{
if (!XMLString::compareString(rawValue, XMLUni::fgYesString))
fStandalone = true;
else if (!XMLString::compareString(rawValue, XMLUni::fgNoString))
fStandalone = false;
else
{
emitError(XMLErrs::BadStandalone);
if (!XMLString::compareIString(rawValue, XMLUni::fgYesString))
fStandalone = true;
else if (!XMLString::compareIString(rawValue, XMLUni::fgNoString))
fStandalone = false;
}
}
}
//
// Make sure that the strings present are in order. We don't care about
// which ones are present at this point, just that any there are in the
// right order.
//
int curTop = 0;
for (int index = VersionString; index < StandaloneString; index++)
{
if (flags[index] != -1)
{
if (flags[index] != curTop + 1)
{
emitError(XMLErrs::DeclStringsInWrongOrder);
break;
}
curTop = flags[index];
}
}
//
// If its an XML decl, the version must be present.
// If its a Text decl, then encoding must be present AND standalone must not be present.
//
if ((type == Decl_XML) && (flags[VersionString] == -1))
emitError(XMLErrs::XMLVersionRequired);
else if (type == Decl_Text) {
if (flags[StandaloneString] != -1)
emitError(XMLErrs::StandaloneNotLegal);
if (flags[EncodingString] == -1)
emitError(XMLErrs::EncodingRequired);
}
if (!fReaderMgr.skippedChar(chQuestion))
{
emitError(XMLErrs::UnterminatedXMLDecl);
fReaderMgr.skipPastChar(chCloseAngle);
}
else if (!fReaderMgr.skippedChar(chCloseAngle))
{
emitError(XMLErrs::UnterminatedXMLDecl);
fReaderMgr.skipPastChar(chCloseAngle);
}
//
// If we have a document handler then call the XML Decl callback.
//
// !NOTE! Do this before we possibly update the reader with the
// actual encoding string. Otherwise, we will pass the wrong thing
// for the last parameter!
//
if (fDocHandler)
{
fDocHandler->XMLDecl
(
bbVersion.getRawBuffer()
, bbEncoding.getRawBuffer()
, bbStand.getRawBuffer()
, fReaderMgr.getCurrentEncodingStr()
);
}
//
// Ok, we've now seen the real encoding string, if there was one, so
// lets call back on the current reader and tell it what the real
// encoding string was. If it fails, that's because it represents some
// sort of contradiction with the autosensed format, and it keeps the
// original encoding.
//
// NOTE: This can fail for a number of reasons, such as a bogus encoding
// name or because its in flagrant contradiction of the auto-sensed
// format.
//
if (flags[EncodingString] != -1)
{
if (!fReaderMgr.getCurrentReader()->setEncoding(bbEncoding.getRawBuffer()))
emitError(XMLErrs::ContradictoryEncoding, bbEncoding.getRawBuffer());
}
}
const XMLCh* XMLScanner::getURIText(const unsigned int uriId) const
{
if (fURIStringPool->exists(uriId)) {
// Look up the URI in the string pool and return its id
const XMLCh* value = fURIStringPool->getValueForId(uriId);
if (!value)
return XMLUni::fgZeroLenString;
return value;
}
else
return XMLUni::fgZeroLenString;
}
bool XMLScanner::getURIText( const unsigned int uriId
, XMLBuffer& uriBufToFill) const
{
if (fURIStringPool->exists(uriId)) {
// Look up the URI in the string pool and return its id
const XMLCh* value = fURIStringPool->getValueForId(uriId);
if (!value)
return false;
uriBufToFill.set(value);
return true;
}
else
return false;
}
unsigned int
XMLScanner::resolveQName( const XMLCh* const qName
, XMLBuffer& nameBuf
, XMLBuffer& prefixBuf
, const ElemStack::MapModes mode)
{
// Reset both target buffers in case we don't get anything for either
nameBuf.reset();
prefixBuf.reset();
//
// Lets split out the qName into a URI and name buffer first. The URI
// can be empty.
//
const int colonPos = XMLString::indexOf(qName, chColon);
unsigned int uriId = 0;
if (colonPos == -1)
{
//
// Its all name with no prefix, so put the whole thing into the name
// buffer. Then map the empty string to a URI, since the empty string
// represents the default namespace. This will either return some
// explicit URI which the default namespace is mapped to, or the
// the default global namespace.
//
nameBuf.append(qName);
bool unknown;
uriId = fElemStack.mapPrefixToURI(prefixBuf.getRawBuffer(), mode, unknown);
#if defined(XERCES_DEBUG)
if (unknown)
{
// <TBD> This one should never be unknown
}
#endif
}
else
{
//
// Copy the chars up to but not including the colon into the prefix
// buffer.
//
prefixBuf.append(qName, colonPos);
// And copy over the rest of the chars to the name buffer
nameBuf.append(&qName[colonPos+1]);
//
// Watch for the special namespace prefixes. We always map these to
// special URIs. 'xml' gets mapped to the official URI that its defined
// to map to by the NS spec. xmlns gets mapped to a special place holder
// URI that we define (so that it maps to something checkable.)
//
if (!XMLString::compareString(prefixBuf.getRawBuffer(), XMLUni::fgXMLNSString))
uriId = fXMLNSNamespaceId;
else if (!XMLString::compareString(prefixBuf.getRawBuffer(), XMLUni::fgXMLString))
uriId = fXMLNamespaceId;
else
{
bool unknown;
uriId = fElemStack.mapPrefixToURI(prefixBuf.getRawBuffer(), mode, unknown);
if (unknown)
emitError(XMLErrs::UnknownPrefix, prefixBuf.getRawBuffer());
}
}
return uriId;
}
bool XMLScanner::checkXMLDecl(bool startWithAngle) {
//
// [23] XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
// [24] VersionInfo ::= S 'version' Eq ("'" VersionNum "'" | '"' VersionNum '"')
//
// [3] S ::= (#x20 | #x9 | #xD | #xA)+
//
if (startWithAngle) {
if (fReaderMgr.peekString(XMLUni::fgXMLDeclString)) {
if (fReaderMgr.skippedString(XMLUni::fgXMLDeclStringSpace)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringHTab)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringLF)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringCR))
{
return true;
}
else if (fReaderMgr.skippedString(XMLUni::fgXMLDeclStringSpaceU)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringHTabU)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringLFU)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringCRU))
{
//
// Just in case, check for upper case. If found, issue
// an error, but keep going.
//
emitError(XMLErrs::XMLDeclMustBeLowerCase);
return true;
}
}
}
else {
if (fReaderMgr.peekString(XMLUni::fgXMLString)) {
if (fReaderMgr.skippedString(XMLUni::fgXMLStringSpace)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringHTab)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringLF)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringCR))
{
return true;
}
else if (fReaderMgr.skippedString(XMLUni::fgXMLStringSpaceU)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringHTabU)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringLFU)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringCRU))
{
//
// Just in case, check for upper case. If found, issue
// an error, but keep going.
//
emitError(XMLErrs::XMLDeclMustBeLowerCase);
return true;
}
}
}
return false;
}
// ---------------------------------------------------------------------------
// XMLScanner: Helper methos
// ---------------------------------------------------------------------------
void XMLScanner::resizeElemState() {
unsigned int newSize = fElemStateSize * 2;
unsigned int* newElemState = new unsigned int[newSize];
// Copy the existing values
unsigned int index = 0;
for (; index < fElemStateSize; index++)
newElemState[index] = fElemState[index];
for (; index < newSize; index++)
newElemState[index] = 0;
// Delete the old array and udpate our members
delete [] fElemState;
fElemState = newElemState;
fElemStateSize = newSize;
}
// ---------------------------------------------------------------------------
// XMLScanner: IC activation methos
// ---------------------------------------------------------------------------
void XMLScanner::activateSelectorFor(IdentityConstraint* const ic) {
IC_Selector* selector = ic->getSelector();
if (!selector)
return;
XPathMatcher* matcher = selector->createMatcher(fFieldActivator);
fMatcherStack->addMatcher(matcher);
matcher->startDocumentFragment();
}
[Bug 10105] Exception in parse() despite setErrorHandler().
git-svn-id: 3ec853389310512053d525963cab269c063bb453@173954 13f79535-47bb-0310-9956-ffa450edef68
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2001 The Apache Software Foundation. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/Janitor.hpp>
#include <xercesc/util/Mutexes.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/RefVectorOf.hpp>
#include <xercesc/util/RuntimeException.hpp>
#include <xercesc/util/UnexpectedEOFException.hpp>
#include <xercesc/util/XMLMsgLoader.hpp>
#include <xercesc/util/XMLRegisterCleanup.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/XMLUni.hpp>
#include <xercesc/util/XMLURL.hpp>
#include <xercesc/sax/InputSource.hpp>
#include <xercesc/sax/SAXException.hpp>
#include <xercesc/framework/LocalFileInputSource.hpp>
#include <xercesc/framework/URLInputSource.hpp>
#include <xercesc/framework/XMLDocumentHandler.hpp>
#include <xercesc/framework/XMLErrorReporter.hpp>
#include <xercesc/framework/XMLEntityHandler.hpp>
#include <xercesc/framework/XMLPScanToken.hpp>
#include <xercesc/framework/XMLValidator.hpp>
#include <xercesc/framework/XMLValidityCodes.hpp>
#include <xercesc/internal/XMLScanner.hpp>
#include <xercesc/internal/EndOfEntityException.hpp>
#include <xercesc/validators/DTD/DocTypeHandler.hpp>
#include <xercesc/validators/DTD/DTDScanner.hpp>
#include <xercesc/validators/schema/SchemaSymbols.hpp>
#include <xercesc/validators/schema/identity/FieldActivator.hpp>
#include <xercesc/validators/schema/identity/XPathMatcherStack.hpp>
#include <xercesc/validators/schema/identity/ValueStoreCache.hpp>
#include <xercesc/validators/schema/identity/IC_Selector.hpp>
#include <xercesc/validators/schema/identity/ValueStore.hpp>
// ---------------------------------------------------------------------------
// Local static data
// ---------------------------------------------------------------------------
static XMLUInt32 gScannerId;
static bool sRegistered = false;
static XMLMutex* sScannerMutex = 0;
static XMLRegisterCleanup scannerMutexCleanup;
static XMLMsgLoader* gMsgLoader = 0;
static XMLRegisterCleanup cleanupMsgLoader;
// ---------------------------------------------------------------------------
// Local const data
//
// These are the text for the require char refs that must always be present.
// We init these into the entity pool upon construction.
// ---------------------------------------------------------------------------
static const XMLCh gAmp[] = { chLatin_a, chLatin_m, chLatin_p, chNull };
static const XMLCh gLT[] = { chLatin_l, chLatin_t, chNull };
static const XMLCh gGT[] = { chLatin_g, chLatin_t, chNull };
static const XMLCh gQuot[] = { chLatin_q, chLatin_u, chLatin_o, chLatin_t, chNull };
static const XMLCh gApos[] = { chLatin_a, chLatin_p, chLatin_o, chLatin_s, chNull };
// ---------------------------------------------------------------------------
// Local, static functions
// ---------------------------------------------------------------------------
// -----------------------------------------------------------------------
// Cleanup for the message loader
// -----------------------------------------------------------------------
void XMLScanner::reinitMsgLoader()
{
delete gMsgLoader;
gMsgLoader = 0;
}
// -----------------------------------------------------------------------
// Cleanup for the scanner mutex
// -----------------------------------------------------------------------
void XMLScanner::reinitScannerMutex()
{
delete sScannerMutex;
sScannerMutex = 0;
sRegistered = false;
}
//
// We need to fault in this mutex. But, since its used for synchronization
// itself, we have to do this the low level way using a compare and swap.
//
static XMLMutex& gScannerMutex()
{
if (!sScannerMutex)
{
XMLMutex* tmpMutex = new XMLMutex;
if (XMLPlatformUtils::compareAndSwap((void**)&sScannerMutex, tmpMutex, 0))
{
// Someone beat us to it, so let's clean up ours
delete tmpMutex;
}
// Now lock it and try to register it
XMLMutexLock lock(sScannerMutex);
// If we got here first, then register it and set the registered flag
if (!sRegistered)
{
scannerMutexCleanup.registerCleanup(XMLScanner::reinitScannerMutex);
sRegistered = true;
}
}
return *sScannerMutex;
}
// ---------------------------------------------------------------------------
// XMLScanner: Constructors and Destructor
// ---------------------------------------------------------------------------
XMLScanner::XMLScanner(XMLValidator* const valToAdopt) :
fDoNamespaces(false)
, fExitOnFirstFatal(true)
, fValidationConstraintFatal(false)
, fInException(false)
, fReuseGrammar(false)
, fStandalone(false)
, fHasNoDTD(true)
, fValidate(false)
, fValidatorFromUser(false)
, fDoSchema(false)
, fSchemaFullChecking(false)
, fSeeXsi(false)
, fErrorCount(0)
, fEmptyNamespaceId(0)
, fUnknownNamespaceId(0)
, fXMLNamespaceId(0)
, fXMLNSNamespaceId(0)
, fSchemaNamespaceId(0)
, fElemStateSize(16)
, fScannerId(0)
, fSequenceId(0)
, fElemState(0)
, fAttrList(0)
, fDocHandler(0)
, fDocTypeHandler(0)
, fEntityHandler(0)
, fErrorReporter(0)
, fErrorHandler(0)
, fIDRefList(0)
, fRawAttrList(0)
, fValidator(valToAdopt)
, fDTDValidator(0)
, fSchemaValidator(0)
, fValScheme(Val_Never)
, fGrammarResolver(0)
, fGrammar(0)
, fEntityDeclPool(0)
, fURIStringPool(0)
, fMatcherStack(0)
, fValueStoreCache(0)
, fFieldActivator(0)
, fRootElemName(0)
, fExternalSchemaLocation(0)
, fExternalNoNamespaceSchemaLocation(0)
, fLoadExternalDTD(true)
, fNormalizeData(true)
{
commonInit();
if (fValidator) {
fValidatorFromUser = true;
initValidator(fValidator);
}
else {
//use fDTDValidator as the default validator
fValidator = fDTDValidator;
}
}
XMLScanner::XMLScanner( XMLDocumentHandler* const docHandler
, DocTypeHandler* const docTypeHandler
, XMLEntityHandler* const entityHandler
, XMLErrorReporter* const errHandler
, XMLValidator* const valToAdopt) :
fDoNamespaces(false)
, fExitOnFirstFatal(true)
, fValidationConstraintFatal(false)
, fInException(false)
, fReuseGrammar(false)
, fStandalone(false)
, fHasNoDTD(true)
, fValidate(false)
, fValidatorFromUser(false)
, fDoSchema(false)
, fSchemaFullChecking(false)
, fSeeXsi(false)
, fErrorCount(0)
, fEmptyNamespaceId(0)
, fUnknownNamespaceId(0)
, fXMLNamespaceId(0)
, fXMLNSNamespaceId(0)
, fSchemaNamespaceId(0)
, fElemStateSize(16)
, fScannerId(0)
, fSequenceId(0)
, fElemState(0)
, fAttrList(0)
, fDocHandler(docHandler)
, fDocTypeHandler(docTypeHandler)
, fEntityHandler(entityHandler)
, fErrorReporter(errHandler)
, fErrorHandler(0)
, fIDRefList(0)
, fRawAttrList(0)
, fValidator(valToAdopt)
, fDTDValidator(0)
, fSchemaValidator(0)
, fValScheme(Val_Never)
, fGrammarResolver(0)
, fGrammar(0)
, fEntityDeclPool(0)
, fURIStringPool(0)
, fMatcherStack(0)
, fValueStoreCache(0)
, fFieldActivator(0)
, fRootElemName(0)
, fExternalSchemaLocation(0)
, fExternalNoNamespaceSchemaLocation(0)
, fLoadExternalDTD(true)
, fNormalizeData(true)
{
commonInit();
if (valToAdopt){
fValidatorFromUser = true;
initValidator(fValidator);
}
else {
//use fDTDValidator as the default validator
fValidator = fDTDValidator;
}
}
XMLScanner::~XMLScanner()
{
delete [] fElemState;
delete fAttrList;
delete fIDRefList;
delete fRawAttrList;
if (fValidatorFromUser)
delete fValidator;
delete fDTDValidator;
delete fSchemaValidator;
delete fEntityDeclPool;
//fGrammarResolver will delete the fGrammar as well
delete fGrammarResolver;
delete fURIStringPool;
delete fFieldActivator;
delete fMatcherStack;
delete fValueStoreCache;
delete [] fRootElemName;
delete [] fExternalSchemaLocation;
delete [] fExternalNoNamespaceSchemaLocation;
}
// ---------------------------------------------------------------------------
// XMLScanner: Main entry point to scan a document
// ---------------------------------------------------------------------------
void XMLScanner::scanDocument( const XMLCh* const systemId
, const bool reuseGrammar)
{
//
// First we try to parse it as a URL. If that fails, we assume its
// a file and try it that way.
//
InputSource* srcToUse = 0;
try
{
//
// Create a temporary URL. Since this is the primary document,
// it has to be fully qualified. If not, then assume we are just
// mistaking a file for a URL.
//
XMLURL tmpURL(systemId);
if (tmpURL.isRelative()) {
srcToUse = new LocalFileInputSource(systemId);
}
else
{
srcToUse = new URLInputSource(tmpURL);
}
}
catch(const MalformedURLException&)
{
srcToUse = new LocalFileInputSource(systemId);
}
catch(const XMLException& excToCatch)
{
//
// For any other XMLException,
// emit the error and catch any user exception thrown from here.
//
fInException = true;
if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning)
emitError
(
XMLErrs::XMLException_Warning
, excToCatch.getType()
, excToCatch.getMessage()
);
else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal)
emitError
(
XMLErrs::XMLException_Fatal
, excToCatch.getType()
, excToCatch.getMessage()
);
else
emitError
(
XMLErrs::XMLException_Error
, excToCatch.getType()
, excToCatch.getMessage()
);
return;
}
catch(...)
{
// Just rethrow this, since its not our problem
throw;
}
Janitor<InputSource> janSrc(srcToUse);
scanDocument(*srcToUse, reuseGrammar);
}
void XMLScanner::scanDocument( const char* const systemId
, const bool reuseGrammar)
{
// We just delegate this to the XMLCh version after transcoding
XMLCh* tmpBuf = XMLString::transcode(systemId);
ArrayJanitor<XMLCh> janBuf(tmpBuf);
scanDocument(tmpBuf, reuseGrammar);
}
void XMLScanner::scanDocument(const InputSource& src, const bool reuseGrammar)
{
//
// Bump up the sequence id for this parser instance. This will invalidate
// any previous progressive scan tokens.
//
fSequenceId++;
// Store the reuse validator flag
fReuseGrammar = reuseGrammar;
try
{
//
// Reset the scanner and its plugged in stuff for a new run. This
// resets all the data structures, creates the initial reader and
// pushes it on the stack, and sets up the base document path.
//
scanReset(src);
// If we have a document handler, then call the start document
if (fDocHandler)
fDocHandler->startDocument();
fValueStoreCache->startDocument();
//
// Scan the prolog part, which is everything before the root element
// including the DTD subsets.
//
scanProlog();
//
// If we got to the end of input, then its not a valid XML file.
// Else, go on to scan the content.
//
if (fReaderMgr.atEOF())
{
emitError(XMLErrs::EmptyMainEntity);
}
else
{
// Scan content, and tell it its not an external entity
if (scanContent(false))
{
// Do post-parse validation if required
if (fValidate)
{
//
// We handle ID reference semantics at this level since
// its required by XML 1.0.
//
checkIDRefs();
// Then allow the validator to do any extra stuff it wants
fValidator->postParseValidation();
}
// That went ok, so scan for any miscellaneous stuff
if (!fReaderMgr.atEOF())
scanMiscellaneous();
}
}
if (fValidate)
fValueStoreCache->endDocument();
// If we have a document handler, then call the end document
if (fDocHandler)
fDocHandler->endDocument();
// Reset the reader manager to close all files, sockets, etc...
fReaderMgr.reset();
}
//
// NOTE:
//
// In all of the error processing below, the emitError() call MUST come
// before the flush of the reader mgr, or it will fail because it tries
// to find out the position in the XML source of the error.
//
catch(const XMLErrs::Codes)
{
// This is a 'first fatal error' type exit, so reset and fall through
fReaderMgr.reset();
}
catch(const XMLValid::Codes)
{
// This is a 'first fatal error' type exit, so reset and fall through
fReaderMgr.reset();
}
catch(const XMLException& excToCatch)
{
//
// Emit the error and catch any user exception thrown from here. Make
// sure in all cases we flush the reader manager.
//
fInException = true;
try
{
if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning)
emitError
(
XMLErrs::XMLException_Warning
, excToCatch.getType()
, excToCatch.getMessage()
);
else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal)
emitError
(
XMLErrs::XMLException_Fatal
, excToCatch.getType()
, excToCatch.getMessage()
);
else
emitError
(
XMLErrs::XMLException_Error
, excToCatch.getType()
, excToCatch.getMessage()
);
}
catch(...)
{
// Flush the reader manager and rethrow user's error
fReaderMgr.reset();
throw;
}
// If it returned, then reset the reader manager and fall through
fReaderMgr.reset();
}
catch(...)
{
// Reset and rethrow
fReaderMgr.reset();
throw;
}
}
//
// This method begins a progressive parse. It scans through the prolog and
// returns a token to be used on subsequent scanNext() calls. If the return
// value is true, then the token is legal and ready for further use. If it
// returns false, then the scan of the prolog failed and the token is not
// going to work on subsequent scanNext() calls.
//
bool XMLScanner::scanFirst( const XMLCh* const systemId
, XMLPScanToken& toFill
, const bool reuseGrammar)
{
//
// First we try to parse it as a URL. If that fails, we assume its
// a file and try it that way.
//
InputSource* srcToUse = 0;
try
{
//
// Create a temporary URL. Since this is the primary document,
// it has to be fully qualified. If not, then assume we are just
// mistaking a file for a URL.
//
XMLURL tmpURL(systemId);
if (tmpURL.isRelative()) {
srcToUse = new LocalFileInputSource(systemId);
}
else
{
srcToUse = new URLInputSource(tmpURL);
}
}
catch(const MalformedURLException&)
{
srcToUse = new LocalFileInputSource(systemId);
}
catch(const XMLException& excToCatch)
{
//
// For any other XMLException,
// emit the error and catch any user exception thrown from here.
//
fInException = true;
if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning)
emitError
(
XMLErrs::XMLException_Warning
, excToCatch.getType()
, excToCatch.getMessage()
);
else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal)
emitError
(
XMLErrs::XMLException_Fatal
, excToCatch.getType()
, excToCatch.getMessage()
);
else
emitError
(
XMLErrs::XMLException_Error
, excToCatch.getType()
, excToCatch.getMessage()
);
return false;
}
catch(...)
{
// Just rethrow this, since its not our problem
throw;
}
Janitor<InputSource> janSrc(srcToUse);
return scanFirst(*srcToUse, toFill, reuseGrammar);
}
bool XMLScanner::scanFirst( const char* const systemId
, XMLPScanToken& toFill
, const bool reuseGrammar)
{
// We just delegate this to the XMLCh version after transcoding
XMLCh* tmpBuf = XMLString::transcode(systemId);
ArrayJanitor<XMLCh> janBuf(tmpBuf);
return scanFirst(tmpBuf, toFill, reuseGrammar);
}
bool XMLScanner::scanFirst( const InputSource& src
, XMLPScanToken& toFill
, const bool reuseGrammar)
{
// Store the reuse validator flag
fReuseGrammar = reuseGrammar;
//
// Bump up the sequence id for this new scan cycle. This will invalidate
// any previous tokens we've returned.
//
fSequenceId++;
//
// Reset the scanner and its plugged in stuff for a new run. This
// resets all the data structures, creates the initial reader and
// pushes it on the stack, and sets up the base document path
//
scanReset(src);
// If we have a document handler, then call the start document
if (fDocHandler)
fDocHandler->startDocument();
fValueStoreCache->startDocument();
try
{
//
// Scan the prolog part, which is everything before the root element
// including the DTD subsets. This is all that is done on the scan
// first.
//
scanProlog();
//
// If we got to the end of input, then its not a valid XML file.
// Else, go on to scan the content.
//
if (fReaderMgr.atEOF())
{
emitError(XMLErrs::EmptyMainEntity);
}
}
//
// NOTE:
//
// In all of the error processing below, the emitError() call MUST come
// before the flush of the reader mgr, or it will fail because it tries
// to find out the position in the XML source of the error.
//
catch(const XMLErrs::Codes)
{
// This is a 'first failure' exception so reset and return a failure
fReaderMgr.reset();
return false;
}
catch(const XMLValid::Codes)
{
// This is a 'first fatal error' type exit, so reset and reuturn failure
fReaderMgr.reset();
return false;
}
catch(const XMLException& excToCatch)
{
//
// Emit the error and catch any user exception thrown from here. Make
// sure in all cases we flush the reader manager.
//
fInException = true;
try
{
if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning)
emitError
(
XMLErrs::XMLException_Warning
, excToCatch.getType()
, excToCatch.getMessage()
);
else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal)
emitError
(
XMLErrs::XMLException_Fatal
, excToCatch.getType()
, excToCatch.getMessage()
);
else
emitError
(
XMLErrs::XMLException_Error
, excToCatch.getType()
, excToCatch.getMessage()
);
}
catch(...)
{
// Reset and rethrow the user error
fReaderMgr.reset();
throw;
}
// Reset and return a failure
fReaderMgr.reset();
return false;
}
catch(...)
{
// Reset and rethrow original error
fReaderMgr.reset();
throw;
}
// Fill in the caller's token to make it legal and return success
toFill.set(fScannerId, fSequenceId);
return true;
}
bool XMLScanner::scanNext(XMLPScanToken& token)
{
// Make sure this token is still legal
if (!isLegalToken(token))
ThrowXML(RuntimeException, XMLExcepts::Scan_BadPScanToken);
// Find the next token and remember the reader id
unsigned int orgReader;
XMLTokens curToken;
bool retVal = true;
try
{
while (true)
{
//
// We have to handle any end of entity exceptions that happen here.
// We could be at the end of X nested entities, each of which will
// generate an end of entity exception as we try to move forward.
//
try
{
curToken = senseNextToken(orgReader);
break;
}
catch(const EndOfEntityException& toCatch)
{
// Send an end of entity reference event
if (fDocHandler)
fDocHandler->endEntityReference(toCatch.getEntity());
}
}
if (curToken == Token_CharData)
{
scanCharData(fCDataBuf);
}
else if (curToken == Token_EOF)
{
if (!fElemStack.isEmpty())
{
const ElemStack::StackElem* topElem = fElemStack.popTop();
emitError
(
XMLErrs::EndedWithTagsOnStack
, topElem->fThisElement->getFullName()
);
}
retVal = false;
}
else
{
// Its some sort of markup
bool gotData = true;
switch(curToken)
{
case Token_CData :
// Make sure we are within content
if (fElemStack.isEmpty())
emitError(XMLErrs::CDATAOutsideOfContent);
scanCDSection();
break;
case Token_Comment :
scanComment();
break;
case Token_EndTag :
scanEndTag(gotData);
break;
case Token_PI :
scanPI();
break;
case Token_StartTag :
if (fDoNamespaces)
scanStartTagNS(gotData);
else
scanStartTag(gotData);
break;
default :
fReaderMgr.skipToChar(chOpenAngle);
break;
}
if (orgReader != fReaderMgr.getCurrentReaderNum())
emitError(XMLErrs::PartialMarkupInEntity);
// If we hit the end, then do the miscellaneous part
if (!gotData)
{
// Do post-parse validation if required
if (fValidate)
{
//
// We handle ID reference semantics at this level since
// its required by XML 1.0.
//
checkIDRefs();
// Then allow the validator to do any extra stuff it wants
fValidator->postParseValidation();
}
// That went ok, so scan for any miscellaneous stuff
scanMiscellaneous();
if (fValidate)
fValueStoreCache->endDocument();
if (fDocHandler)
fDocHandler->endDocument();
}
}
}
//
// NOTE:
//
// In all of the error processing below, the emitError() call MUST come
// before the flush of the reader mgr, or it will fail because it tries
// to find out the position in the XML source of the error.
//
catch(const XMLErrs::Codes)
{
// This is a 'first failure' exception, so reset and return failure
fReaderMgr.reset();
return false;
}
catch(const XMLValid::Codes)
{
// This is a 'first fatal error' type exit, so reset and reuturn failure
fReaderMgr.reset();
return false;
}
// We have to propogate SAX exceptions
catch(const SAXException&)
{
// Just reset our reader manager and rethrow SAX exception
fReaderMgr.reset();
throw;
}
catch(const XMLException& excToCatch)
{
//
// Emit the error and catch any user exception thrown from here. Make
// sure in all cases we flush the reader manager.
//
fInException = true;
try
{
if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning)
emitError
(
XMLErrs::XMLException_Warning
, excToCatch.getType()
, excToCatch.getMessage()
);
else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal)
emitError
(
XMLErrs::XMLException_Fatal
, excToCatch.getType()
, excToCatch.getMessage()
);
else
emitError
(
XMLErrs::XMLException_Error
, excToCatch.getType()
, excToCatch.getMessage()
);
}
catch(...)
{
// Reset and rethrow user error
fReaderMgr.reset();
throw;
}
// Reset and return failure
fReaderMgr.reset();
return false;
}
catch(...)
{
// Reset and rethrow original error
fReaderMgr.reset();
throw;
}
// If we hit the end, then flush the reader manager
if (!retVal)
fReaderMgr.reset();
return retVal;
}
void XMLScanner::scanReset(XMLPScanToken& token)
{
// Make sure this token is still legal
if (!isLegalToken(token))
ThrowXML(RuntimeException, XMLExcepts::Scan_BadPScanToken);
// Reset the reader manager
fReaderMgr.reset();
// And invalidate any tokens by bumping our sequence number
fSequenceId++;
// Reset our error count
fErrorCount = 0;
}
// ---------------------------------------------------------------------------
// XMLScanner: Private helper methods. Most of these are implemented in
// XMLScanner2.Cpp.
// ---------------------------------------------------------------------------
//
// This method handles the common initialization, to avoid having to do
// it redundantly in multiple constructors.
//
void XMLScanner::commonInit()
{
//
// We have to do a little init that involves statics, so we have to
// use the mutex to protect it.
//
{
XMLMutexLock lockInit(&gScannerMutex());
// If we haven't loaded our message yet, then do that
if (!gMsgLoader)
{
gMsgLoader = XMLPlatformUtils::loadMsgSet(XMLUni::fgXMLErrDomain);
if (!gMsgLoader)
XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);
// Register this object to be cleaned up at termination
cleanupMsgLoader.registerCleanup(reinitMsgLoader);
}
// And assign ourselves the next available scanner id
fScannerId = ++gScannerId;
}
//
// Create the element state array
//
fElemState = new unsigned int[fElemStateSize];
//
// Create the attribute list, which is used to store attribute values
// during start tag processing. Give it a reasonable initial size that
// will serve for most folks, though it will grow as required.
//
fAttrList = new RefVectorOf<XMLAttr>(32);
//
// And we need one for the raw attribute scan. This just stores key/
// value string pairs (prior to any processing.)
//
fRawAttrList = new RefVectorOf<KVStringPair>(32);
//
// Create the id ref list. This is used to enforce XML 1.0 ID ref
// semantics, i.e. all id refs must refer to elements that exist
//
fIDRefList = new RefHashTableOf<XMLRefInfo>(109);
// Create the EntityDeclPool
fEntityDeclPool = new NameIdPool<DTDEntityDecl>(109);
// Create the GrammarResolver
fGrammarResolver = new GrammarResolver();
resetEntityDeclPool();
// Create the Validator and init them
fDTDValidator = new DTDValidator();
initValidator(fDTDValidator);
fSchemaValidator = new SchemaValidator();
initValidator(fSchemaValidator);
// Create IdentityConstraint info
fMatcherStack = new XPathMatcherStack();
fValueStoreCache = new ValueStoreCache();
fFieldActivator = new FieldActivator(fValueStoreCache, fMatcherStack);
fValueStoreCache->setScanner(this);
}
void XMLScanner::initValidator(XMLValidator* theValidator) {
//
// Tell the validator about the stuff it needs to know in order to
// do its work.
//
theValidator->setScannerInfo(this, &fReaderMgr, &fBufMgr);
theValidator->setErrorReporter(fErrorReporter);
if (theValidator->handlesSchema()) {
((SchemaValidator*) theValidator)->setGrammarResolver(fGrammarResolver);
((SchemaValidator*) theValidator)->setExitOnFirstFatal(fExitOnFirstFatal);
}
}
void XMLScanner::resetEntityDeclPool() {
fEntityDeclPool->removeAll();
//
// Add the default entity entries for the character refs that must always
// be present. We indicate that they are from the internal subset. They
// aren't really, but they have to look that way so that they are still
// valid for use within a standalone document.
//
// We also mark them as special char entities, which allows them to be
// used in places whether other non-numeric general entities cannot.
//
fEntityDeclPool->put(new DTDEntityDecl(gAmp, chAmpersand, true, true));
fEntityDeclPool->put(new DTDEntityDecl(gLT, chOpenAngle, true, true));
fEntityDeclPool->put(new DTDEntityDecl(gGT, chCloseAngle, true, true));
fEntityDeclPool->put(new DTDEntityDecl(gQuot, chDoubleQuote, true, true));
fEntityDeclPool->put(new DTDEntityDecl(gApos, chSingleQuote, true, true));
}
void XMLScanner::resetURIStringPool() {
fURIStringPool->flushAll();
fEmptyNamespaceId = fURIStringPool->addOrFind(XMLUni::fgZeroLenString);
fUnknownNamespaceId = fURIStringPool->addOrFind(XMLUni::fgUnknownURIName);
fXMLNamespaceId = fURIStringPool->addOrFind(XMLUni::fgXMLURIName);
fXMLNSNamespaceId = fURIStringPool->addOrFind(XMLUni::fgXMLNSURIName);
fSchemaNamespaceId = fURIStringPool->addOrFind(SchemaSymbols::fgURI_XSI);
}
// ---------------------------------------------------------------------------
// XMLScanner: Error emitting methods
// ---------------------------------------------------------------------------
//
// These methods are called whenever the scanner wants to emit an error.
// It handles getting the message loaded, doing token replacement, etc...
// and then calling the error handler, if its installed.
//
void XMLScanner::emitError(const XMLErrs::Codes toEmit)
{
// Bump the error count if it is not a warning
if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)
incrementErrorCount();
if (fErrorReporter)
{
// Load the message into a local for display
const unsigned int msgSize = 1023;
XMLCh errText[msgSize + 1];
// Lock the mutex and load the text
{
XMLMutexLock lockInit(&gScannerMutex());
if (!gMsgLoader->loadMsg(toEmit, errText, msgSize))
{
// <TBD> Probably should load a default msg here
}
}
//
// Create a LastExtEntityInfo structure and get the reader manager
// to fill it in for us. This will give us the information about
// the last reader on the stack that was an external entity of some
// sort (i.e. it will ignore internal entities.
//
ReaderMgr::LastExtEntityInfo lastInfo;
fReaderMgr.getLastExtEntityInfo(lastInfo);
fErrorReporter->error
(
toEmit
, XMLUni::fgXMLErrDomain
, XMLErrs::errorType(toEmit)
, errText
, lastInfo.systemId
, lastInfo.publicId
, lastInfo.lineNumber
, lastInfo.colNumber
);
}
// Bail out if its fatal an we are to give up on the first fatal error
if (XMLErrs::isFatal(toEmit) && fExitOnFirstFatal && !fInException)
throw toEmit;
}
void XMLScanner::emitError( const XMLErrs::Codes toEmit
, const XMLCh* const text1
, const XMLCh* const text2
, const XMLCh* const text3
, const XMLCh* const text4)
{
// Bump the error count if it is not a warning
if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)
incrementErrorCount();
if (fErrorReporter)
{
//
// Load the message into alocal and replace any tokens found in
// the text.
//
const unsigned int maxChars = 2047;
XMLCh errText[maxChars + 1];
// Lock the mutex and load the text
{
XMLMutexLock lockInit(&gScannerMutex());
if (!gMsgLoader->loadMsg(toEmit, errText, maxChars, text1, text2, text3, text4))
{
// <TBD> Should probably load a default message here
}
}
//
// Create a LastExtEntityInfo structure and get the reader manager
// to fill it in for us. This will give us the information about
// the last reader on the stack that was an external entity of some
// sort (i.e. it will ignore internal entities.
//
ReaderMgr::LastExtEntityInfo lastInfo;
fReaderMgr.getLastExtEntityInfo(lastInfo);
fErrorReporter->error
(
toEmit
, XMLUni::fgXMLErrDomain
, XMLErrs::errorType(toEmit)
, errText
, lastInfo.systemId
, lastInfo.publicId
, lastInfo.lineNumber
, lastInfo.colNumber
);
}
// Bail out if its fatal an we are to give up on the first fatal error
if (XMLErrs::isFatal(toEmit) && fExitOnFirstFatal && !fInException)
throw toEmit;
}
void XMLScanner::emitError( const XMLErrs::Codes toEmit
, const char* const text1
, const char* const text2
, const char* const text3
, const char* const text4)
{
// Bump the error count if it is not a warning
if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)
incrementErrorCount();
if (fErrorReporter)
{
//
// Load the message into alocal and replace any tokens found in
// the text.
//
const unsigned int maxChars = 2047;
XMLCh errText[maxChars + 1];
// Lock the mutex and load the text
{
XMLMutexLock lockInit(&gScannerMutex());
if (!gMsgLoader->loadMsg(toEmit, errText, maxChars, text1, text2, text3, text4))
{
// <TBD> Should probably load a default message here
}
}
//
// Create a LastExtEntityInfo structure and get the reader manager
// to fill it in for us. This will give us the information about
// the last reader on the stack that was an external entity of some
// sort (i.e. it will ignore internal entities.
//
ReaderMgr::LastExtEntityInfo lastInfo;
fReaderMgr.getLastExtEntityInfo(lastInfo);
fErrorReporter->error
(
toEmit
, XMLUni::fgXMLErrDomain
, XMLErrs::errorType(toEmit)
, errText
, lastInfo.systemId
, lastInfo.publicId
, lastInfo.lineNumber
, lastInfo.colNumber
);
}
// Bail out if its fatal an we are to give up on the first fatal error
if (XMLErrs::isFatal(toEmit) && fExitOnFirstFatal && !fInException)
throw toEmit;
}
// ---------------------------------------------------------------------------
// XMLScanner: Getter methods
// ---------------------------------------------------------------------------
//
// This method allows the caller to query the current location of the scanner.
// It will return the sys/public ids of the current entity, and the line/col
// position within it.
//
// NOTE: This API returns the location with the last external file. So if its
// currently scanning an entity, the position returned will be the end of
// the entity reference in the file that had the reference.
//
bool
XMLScanner::getLastExtLocation( XMLCh* const sysIdToFill
, const unsigned int maxSysIdChars
, XMLCh* const pubIdToFill
, const unsigned int maxPubIdChars
, XMLSSize_t& lineToFill
, XMLSSize_t& colToFill)
{
// Create a local info object and get it filled in by the reader manager
ReaderMgr::LastExtEntityInfo lastInfo;
fReaderMgr.getLastExtEntityInfo(lastInfo);
// Fill in the line and column number
lineToFill = lastInfo.lineNumber;
colToFill = lastInfo.colNumber;
// And copy over as much of the ids as will fit
sysIdToFill[0] = 0;
if (lastInfo.systemId)
{
if (XMLString::stringLen(lastInfo.systemId) > maxSysIdChars)
return false;
XMLString::copyString(sysIdToFill, lastInfo.systemId);
}
pubIdToFill[0] = 0;
if (lastInfo.publicId)
{
if (XMLString::stringLen(lastInfo.publicId) > maxPubIdChars)
return false;
XMLString::copyString(pubIdToFill, lastInfo.publicId);
}
return true;
}
// ---------------------------------------------------------------------------
// XMLScanner: Private scanning methods
// ---------------------------------------------------------------------------
//
// This method is called from scanStartTag() to handle the very raw initial
// scan of the attributes. It just fills in the passed collection with
// key/value pairs for each attribute. No processing is done on them at all.
//
unsigned int
XMLScanner::rawAttrScan(const XMLCh* const elemName
, RefVectorOf<KVStringPair>& toFill
, bool& isEmpty)
{
//
// Keep up with how many attributes we've seen so far, and how many
// elements are available in the vector. This way we can reuse old
// elements until we run out and then expand it.
//
unsigned int attCount = 0;
unsigned int curVecSize = toFill.size();
// Assume it is not empty
isEmpty = false;
//
// We loop until we either see a /> or >, handling key/value pairs util
// we get there. We place them in the passed vector, which we will expand
// as required to hold them.
//
while (true)
{
// Get the next character, which should be non-space
XMLCh nextCh = fReaderMgr.peekNextChar();
//
// If the next character is not a slash or closed angle bracket,
// then it must be whitespace, since whitespace is required
// between the end of the last attribute and the name of the next
// one.
//
if (attCount)
{
if ((nextCh != chForwardSlash) && (nextCh != chCloseAngle))
{
if (XMLReader::isWhitespace(nextCh))
{
// Ok, skip by them and get another char
fReaderMgr.getNextChar();
fReaderMgr.skipPastSpaces();
nextCh = fReaderMgr.peekNextChar();
}
else
{
// Emit the error but keep on going
emitError(XMLErrs::ExpectedWhitespace);
}
}
}
//
// Ok, here we first check for any of the special case characters.
// If its not one, then we do the normal case processing, which
// assumes that we've hit an attribute value, Otherwise, we do all
// the special case checks.
//
if (!XMLReader::isSpecialStartTagChar(nextCh))
{
//
// Assume its going to be an attribute, so get a name from
// the input.
//
if (!fReaderMgr.getName(fAttNameBuf))
{
emitError(XMLErrs::ExpectedAttrName);
fReaderMgr.skipPastChar(chCloseAngle);
return attCount;
}
// And next must be an equal sign
if (!scanEq())
{
static const XMLCh tmpList[] =
{
chSingleQuote, chDoubleQuote, chCloseAngle
, chOpenAngle, chForwardSlash, chNull
};
emitError(XMLErrs::ExpectedEqSign);
//
// Try to sync back up by skipping forward until we either
// hit something meaningful.
//
const XMLCh chFound = fReaderMgr.skipUntilInOrWS(tmpList);
if ((chFound == chCloseAngle) || (chFound == chForwardSlash))
{
// Jump back to top for normal processing of these
continue;
}
else if ((chFound == chSingleQuote)
|| (chFound == chDoubleQuote)
|| XMLReader::isWhitespace(chFound))
{
// Just fall through assuming that the value is to follow
}
else if (chFound == chOpenAngle)
{
// Assume a malformed tag and that new one is starting
emitError(XMLErrs::UnterminatedStartTag, elemName);
return attCount;
}
else
{
// Something went really wrong
return attCount;
}
}
//
// Next should be the quoted attribute value. We just do a simple
// and stupid scan of this value. The only thing we do here
// is to expand entity references.
//
if (!basicAttrValueScan(fAttNameBuf.getRawBuffer(), fAttValueBuf))
{
static const XMLCh tmpList[] =
{
chCloseAngle, chOpenAngle, chForwardSlash, chNull
};
emitError(XMLErrs::ExpectedAttrValue);
//
// It failed, so lets try to get synced back up. We skip
// forward until we find some whitespace or one of the
// chars in our list.
//
const XMLCh chFound = fReaderMgr.skipUntilInOrWS(tmpList);
if ((chFound == chCloseAngle)
|| (chFound == chForwardSlash)
|| XMLReader::isWhitespace(chFound))
{
//
// Just fall through and process this attribute, though
// the value will be "".
//
}
else if (chFound == chOpenAngle)
{
// Assume a malformed tag and that new one is starting
emitError(XMLErrs::UnterminatedStartTag, elemName);
return attCount;
}
else
{
// Something went really wrong
return attCount;
}
}
//
// Make sure that the name is basically well formed for namespace
// enabled rules. It either has no colons, or it has one which
// is neither the first or last char.
//
const int colonFirst = XMLString::indexOf(fAttNameBuf.getRawBuffer(), chColon);
if (colonFirst != -1)
{
const int colonLast = XMLString::lastIndexOf(fAttNameBuf.getRawBuffer(), chColon);
if (colonFirst != colonLast)
{
emitError(XMLErrs::TooManyColonsInName);
continue;
}
else if ((colonFirst == 0)
|| (colonLast == (int)fAttNameBuf.getLen() - 1))
{
emitError(XMLErrs::InvalidColonPos);
continue;
}
}
//
// And now lets add it to the passed collection. If we have not
// filled it up yet, then we use the next element. Else we add
// a new one.
//
KVStringPair* curPair = 0;
if (attCount >= curVecSize)
{
curPair = new KVStringPair
(
fAttNameBuf.getRawBuffer()
, fAttValueBuf.getRawBuffer()
);
toFill.addElement(curPair);
}
else
{
curPair = toFill.elementAt(attCount);
curPair->set(fAttNameBuf.getRawBuffer(), fAttValueBuf.getRawBuffer());
}
// And bump the count of attributes we've gotten
attCount++;
// And go to the top again for another attribute
continue;
}
//
// It was some special case character so do all of the checks and
// deal with it.
//
if (!nextCh)
ThrowXML(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF);
if (nextCh == chForwardSlash)
{
fReaderMgr.getNextChar();
isEmpty = true;
if (!fReaderMgr.skippedChar(chCloseAngle))
emitError(XMLErrs::UnterminatedStartTag, elemName);
break;
}
else if (nextCh == chCloseAngle)
{
fReaderMgr.getNextChar();
break;
}
else if (nextCh == chOpenAngle)
{
//
// Check for this one specially, since its going to be common
// and it is kind of auto-recovering since we've already hit the
// next open bracket, which is what we would have seeked to (and
// skipped this whole tag.)
//
emitError(XMLErrs::UnterminatedStartTag, elemName);
break;
}
else if ((nextCh == chSingleQuote) || (nextCh == chDoubleQuote))
{
//
// Check for this one specially, which is probably a missing
// attribute name, e.g. ="value". Just issue expected name
// error and eat the quoted string, then jump back to the
// top again.
//
emitError(XMLErrs::ExpectedAttrName);
fReaderMgr.getNextChar();
fReaderMgr.skipQuotedString(nextCh);
fReaderMgr.skipPastSpaces();
continue;
}
}
return attCount;
}
//
// This method will kick off the scanning of the primary content of the
// document, i.e. the elements.
//
bool XMLScanner::scanContent(const bool extEntity)
{
//
// Go into a loop until we hit the end of the root element, or we fall
// out because there is no root element.
//
// We have to do kind of a deeply nested double loop here in order to
// avoid doing the setup/teardown of the exception handler on each
// round. Doing it this way we only do it when an exception actually
// occurs.
//
bool gotData = true;
bool inMarkup = false;
while (gotData)
{
try
{
while (gotData)
{
// Sense what the next top level token is. According to what
// this tells us, we will call something to handle that kind
// of thing.
//
unsigned int orgReader;
const XMLTokens curToken = senseNextToken(orgReader);
//
// Handle character data and end of file specially. Char data
// is not markup so we don't want to handle it in the loop
// below.
//
if (curToken == Token_CharData)
{
//
// Scan the character data and call appropriate events. Let
// him use our local character data buffer for efficiency.
//
scanCharData(fCDataBuf);
continue;
}
else if (curToken == Token_EOF)
{
//
// The element stack better be empty at this point or we
// ended prematurely before all elements were closed.
//
if (!fElemStack.isEmpty())
{
const ElemStack::StackElem* topElem = fElemStack.popTop();
emitError
(
XMLErrs::EndedWithTagsOnStack
, topElem->fThisElement->getFullName()
);
}
// Its the end of file, so clear the got data flag
gotData = false;
continue;
}
// We are in some sort of markup now
inMarkup = true;
//
// According to the token we got, call the appropriate
// scanning method.
//
switch(curToken)
{
case Token_CData :
// Make sure we are within content
if (fElemStack.isEmpty())
emitError(XMLErrs::CDATAOutsideOfContent);
scanCDSection();
break;
case Token_Comment :
scanComment();
break;
case Token_EndTag :
scanEndTag(gotData);
break;
case Token_PI :
scanPI();
break;
case Token_StartTag :
if (fDoNamespaces)
scanStartTagNS(gotData);
else
scanStartTag(gotData);
break;
default :
fReaderMgr.skipToChar(chOpenAngle);
break;
}
if (orgReader != fReaderMgr.getCurrentReaderNum())
emitError(XMLErrs::PartialMarkupInEntity);
// And we are back out of markup again
inMarkup = false;
}
}
catch(const EndOfEntityException& toCatch)
{
//
// If we were in some markup when this happened, then its a
// partial markup error.
//
if (inMarkup)
emitError(XMLErrs::PartialMarkupInEntity);
// Send an end of entity reference event
if (fDocHandler)
fDocHandler->endEntityReference(toCatch.getEntity());
inMarkup = false;
}
}
// It went ok, so return success
return true;
}
void XMLScanner::scanEndTag(bool& gotData)
{
//
// Assume we will still have data until proven otherwise. It will only
// ever be false if this is the end of the root element.
//
gotData = true;
//
// Check if the element stack is empty. If so, then this is an unbalanced
// element (i.e. more ends than starts, perhaps because of bad text
// causing one to be skipped.)
//
if (fElemStack.isEmpty())
{
emitError(XMLErrs::MoreEndThanStartTags);
fReaderMgr.skipPastChar(chCloseAngle);
ThrowXML(RuntimeException, XMLExcepts::Scan_UnbalancedStartEnd);
}
// After the </ is the element QName, so get a name from the input
XMLBufBid bbQName(&fBufMgr);
XMLBuffer& qnameBuf = bbQName.getBuffer();
if (!fReaderMgr.getName(qnameBuf))
{
// It failed so we can't really do anything with it
emitError(XMLErrs::ExpectedElementName);
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
unsigned int uriId = fEmptyNamespaceId;
XMLBufBid bbName(&fBufMgr);
XMLBufBid bbPrefix(&fBufMgr);
if (fDoNamespaces)
{
uriId = resolveQName
(
qnameBuf.getRawBuffer()
, bbName.getBuffer()
, bbPrefix.getBuffer()
, ElemStack::Mode_Element
);
}
//
// Pop the stack of the element we are supposed to be ending. Remember
// that we don't own this. The stack just keeps them and reuses them.
//
// NOTE: We CANNOT do this until we've resolved the element name because
// the element stack top contains the prefix to URI mappings for this
// element.
//
unsigned int topUri = fElemStack.getCurrentURI();
const ElemStack::StackElem* topElem = fElemStack.popTop();
// See if it was the root element, to avoid multiple calls below
const bool isRoot = fElemStack.isEmpty();
// Make sure that its the end of the element that we expect
XMLElementDecl* tempElement = topElem->fThisElement;
if (fDoNamespaces && fGrammarType == Grammar::SchemaGrammarType) {
if ((topUri != uriId) || (XMLString::compareString(tempElement->getBaseName(), bbName.getRawBuffer())))
{
emitError
(
XMLErrs::ExpectedEndOfTagX
, topElem->fThisElement->getFullName()
);
}
}
else {
if (XMLString::compareString(tempElement->getFullName(), qnameBuf.getRawBuffer()))
{
emitError
(
XMLErrs::ExpectedEndOfTagX
, topElem->fThisElement->getFullName()
);
}
}
// Make sure we are back on the same reader as where we started
if (topElem->fReaderNum != fReaderMgr.getCurrentReaderNum())
emitError(XMLErrs::PartialTagMarkupError);
// Skip optional whitespace
fReaderMgr.skipPastSpaces();
// Make sure we find the closing bracket
if (!fReaderMgr.skippedChar(chCloseAngle))
{
emitError
(
XMLErrs::UnterminatedEndTag
, topElem->fThisElement->getFullName()
);
}
//
// If validation is enabled, then lets pass him the list of children and
// this element and let him validate it.
//
if (fValidate)
{
int res = fValidator->checkContent
(
topElem->fThisElement
, topElem->fChildren
, topElem->fChildCount
);
if (res >= 0)
{
//
// One of the elements is not valid for the content. NOTE that
// if no children were provided but the content model requires
// them, it comes back with a zero value. But we cannot use that
// to index the child array in this case, and have to put out a
// special message.
//
if (!topElem->fChildCount)
{
fValidator->emitError
(
XMLValid::EmptyNotValidForContent
, topElem->fThisElement->getFormattedContentModel()
);
}
else if ((unsigned int)res >= topElem->fChildCount)
{
fValidator->emitError
(
XMLValid::NotEnoughElemsForCM
, topElem->fThisElement->getFormattedContentModel()
);
}
else
{
fValidator->emitError
(
XMLValid::ElementNotValidForContent
, topElem->fChildren[res]->getRawName()
, topElem->fThisElement->getFormattedContentModel()
);
}
}
// reset xsi:type ComplexTypeInfo
if (fGrammarType == Grammar::SchemaGrammarType) {
((SchemaElementDecl*)topElem->fThisElement)->setXsiComplexTypeInfo(0);
// call matchers and de-activate context
int oldCount = fMatcherStack->getMatcherCount();
if (oldCount ||
((SchemaElementDecl*)topElem->fThisElement)->getIdentityConstraintCount()) {
for (int i = oldCount - 1; i >= 0; i--) {
XPathMatcher* matcher = fMatcherStack->getMatcherAt(i);
matcher->endElement(*(topElem->fThisElement));
}
if (fMatcherStack->size() > 0) {
fMatcherStack->popContext();
}
// handle everything *but* keyref's.
int newCount = fMatcherStack->getMatcherCount();
for (int j = oldCount - 1; j >= newCount; j--) {
XPathMatcher* matcher = fMatcherStack->getMatcherAt(j);
IdentityConstraint* ic = matcher->getIdentityConstraint();
if (ic && (ic->getType() != IdentityConstraint::KEYREF)) {
matcher->endDocumentFragment();
fValueStoreCache->transplant(ic);
}
else if (!ic) {
matcher->endDocumentFragment();
}
}
// now handle keyref's...
for (int k = oldCount - 1; k >= newCount; k--) {
XPathMatcher* matcher = fMatcherStack->getMatcherAt(k);
IdentityConstraint* ic = matcher->getIdentityConstraint();
if (ic && (ic->getType() == IdentityConstraint::KEYREF)) {
ValueStore* values = fValueStoreCache->getValueStoreFor(ic);
if (values) { // nothing to do if nothing matched!
values->endDcocumentFragment(fValueStoreCache);
}
matcher->endDocumentFragment();
}
}
fValueStoreCache->endElement();
}
}
}
// If we have a doc handler, tell it about the end tag
if (fDocHandler)
{
fDocHandler->endElement
(
*topElem->fThisElement
, uriId
, isRoot
, bbPrefix.getRawBuffer()
);
}
// If this was the root, then done with content
gotData = !isRoot;
if (gotData) {
if (fDoNamespaces) {
// Restore the grammar
fGrammar = fElemStack.getCurrentGrammar();
fGrammarType = fGrammar->getGrammarType();
if (fGrammarType == Grammar::SchemaGrammarType && !fValidator->handlesSchema()) {
if (fValidatorFromUser)
ThrowXML(RuntimeException, XMLExcepts::Gen_NoSchemaValidator);
else {
fValidator = fSchemaValidator;
}
}
else if (fGrammarType == Grammar::DTDGrammarType && !fValidator->handlesDTD()) {
if (fValidatorFromUser)
ThrowXML(RuntimeException, XMLExcepts::Gen_NoDTDValidator);
else {
fValidator = fDTDValidator;
}
}
fValidator->setGrammar(fGrammar);
}
// Restore the validation flag
fValidate = fElemStack.getValidationFlag();
}
}
//
// This method is called after the end of the root element, to handle
// any miscellaneous stuff hanging around.
//
void XMLScanner::scanMiscellaneous()
{
// Get a buffer for this work
XMLBufBid bbCData(&fBufMgr);
while (true)
{
try
{
const XMLCh nextCh = fReaderMgr.peekNextChar();
// Watch for end of file and break out
if (!nextCh)
break;
if (nextCh == chOpenAngle)
{
if (checkXMLDecl(true))
{
// Can't have an XML decl here
emitError(XMLErrs::NotValidAfterContent);
fReaderMgr.skipPastChar(chCloseAngle);
}
else if (fReaderMgr.skippedString(XMLUni::fgPIString))
{
scanPI();
}
else if (fReaderMgr.skippedString(XMLUni::fgCommentString))
{
scanComment();
}
else
{
// This can't be possible, so just give up
emitError(XMLErrs::ExpectedCommentOrPI);
fReaderMgr.skipPastChar(chCloseAngle);
}
}
else if (XMLReader::isWhitespace(nextCh))
{
//
// If we have a doc handler, then gather up the spaces and
// call back. Otherwise, just skip over whitespace.
//
if (fDocHandler)
{
fReaderMgr.getSpaces(bbCData.getBuffer());
fDocHandler->ignorableWhitespace
(
bbCData.getRawBuffer()
, bbCData.getLen()
, false
);
}
else
{
fReaderMgr.skipPastSpaces();
}
}
else
{
emitError(XMLErrs::ExpectedCommentOrPI);
fReaderMgr.skipPastChar(chCloseAngle);
}
}
catch(const EndOfEntityException&)
{
//
// Some entity leaked out of the content part of the document. Issue
// a warning and keep going.
//
emitError(XMLErrs::EntityPropogated);
}
}
}
//
// Scans a PI and calls the appropriate callbacks. At entry we have just
// scanned the <? part, and need to now start on the PI target name.
//
void XMLScanner::scanPI()
{
const XMLCh* namePtr = 0;
const XMLCh* targetPtr = 0;
//
// If there are any spaces here, then warn about it. If we aren't in
// 'first error' mode, then we'll come back and can easily pick up
// again by just skipping them.
//
if (fReaderMgr.lookingAtSpace())
{
emitError(XMLErrs::PINameExpected);
fReaderMgr.skipPastSpaces();
}
// Get a buffer for the PI name and scan it in
XMLBufBid bbName(&fBufMgr);
if (!fReaderMgr.getName(bbName.getBuffer()))
{
emitError(XMLErrs::PINameExpected);
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
// Point the name pointer at the raw data
namePtr = bbName.getRawBuffer();
// See if it is some form of 'xml' and emit a warning
if (!XMLString::compareIString(namePtr, XMLUni::fgXMLString))
emitError(XMLErrs::NoPIStartsWithXML);
// If namespaces are enabled, then no colons allowed
if (fDoNamespaces)
{
if (XMLString::indexOf(namePtr, chColon) != -1)
emitError(XMLErrs::ColonNotLegalWithNS);
}
//
// If we don't hit a space next, then the PI has no target. If we do
// then get out the target. Get a buffer for it as well
//
XMLBufBid bbTarget(&fBufMgr);
if (fReaderMgr.skippedSpace())
{
// Skip any leading spaces
fReaderMgr.skipPastSpaces();
bool gotLeadingSurrogate = false;
// It does have a target, so lets move on to deal with that.
while (1)
{
const XMLCh nextCh = fReaderMgr.getNextChar();
// Watch for an end of file, which is always bad here
if (!nextCh)
{
emitError(XMLErrs::UnterminatedPI);
ThrowXML(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF);
}
// Watch for potential terminating character
if (nextCh == chQuestion)
{
// It must be followed by '>' to be a termination of the target
if (fReaderMgr.skippedChar(chCloseAngle))
break;
}
// Check for correct surrogate pairs
if ((nextCh >= 0xD800) && (nextCh <= 0xDBFF))
{
if (gotLeadingSurrogate)
emitError(XMLErrs::Expected2ndSurrogateChar);
else
gotLeadingSurrogate = true;
}
else
{
if (gotLeadingSurrogate)
{
if ((nextCh < 0xDC00) || (nextCh > 0xDFFF))
emitError(XMLErrs::Expected2ndSurrogateChar);
}
// Its got to at least be a valid XML character
else if (!XMLReader::isXMLChar(nextCh)) {
XMLCh tmpBuf[9];
XMLString::binToText
(
nextCh
, tmpBuf
, 8
, 16
);
emitError(XMLErrs::InvalidCharacter, tmpBuf);
}
gotLeadingSurrogate = false;
}
bbTarget.append(nextCh);
}
}
else
{
// No target, but make sure its terminated ok
if (!fReaderMgr.skippedChar(chQuestion))
{
emitError(XMLErrs::UnterminatedPI);
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
if (!fReaderMgr.skippedChar(chCloseAngle))
{
emitError(XMLErrs::UnterminatedPI);
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
}
// Point the target pointer at the raw data
targetPtr = bbTarget.getRawBuffer();
// If we have a handler, then call it
if (fDocHandler)
{
fDocHandler->docPI
(
namePtr
, targetPtr
);
}
}
//
// Scans all the input from the start of the file to the root element.
// There does not have to be anything in the prolog necessarily, but usually
// there is at least an XMLDecl.
//
// On exit from here we are either at the end of the file or about to read
// the opening < of the root element.
//
void XMLScanner::scanProlog()
{
// Get a buffer for whitespace processing
XMLBufBid bbCData(&fBufMgr);
//
// Loop through the prolog. If there is no content, this could go all
// the way to the end of the file.
//
// Note that we use a double loop here to avoid the overhead of the
// setup/teardown of the exception handler on each loop.
//
while (true)
{
try
{
while (true)
{
const XMLCh nextCh = fReaderMgr.peekNextChar();
if (nextCh == chOpenAngle)
{
//
// Ok, it could be the xml decl, a comment, the doc type line,
// or the start of the root element.
//
if (checkXMLDecl(true))
{
// There shall be at lease --ONE-- space in between
// the tag '<?xml' and the VersionInfo.
//
//
// If we are not at line 1, col 6, then the decl was not
// the first text, so its invalid.
//
const XMLReader* curReader = fReaderMgr.getCurrentReader();
if ((curReader->getLineNumber() != 1)
|| (curReader->getColumnNumber() != 7))
{
emitError(XMLErrs::XMLDeclMustBeFirst);
}
scanXMLDecl(Decl_XML);
}
else if (fReaderMgr.skippedString(XMLUni::fgPIString))
{
scanPI();
}
else if (fReaderMgr.skippedString(XMLUni::fgCommentString))
{
scanComment();
}
else if (fReaderMgr.skippedString(XMLUni::fgDocTypeString))
{
scanDocTypeDecl();
// if reusing grammar, this has been validated already in first scan
// skip for performance
if (!fReuseGrammar && fValidate) {
// validate the DTD scan so far
fValidator->preContentValidation(fReuseGrammar);
}
}
else
{
// Assume its the start of the root element
return;
}
}
else if (XMLReader::isWhitespace(nextCh))
{
//
// If we have a document handler then gather up the
// whitespace and call back. Otherwise just skip over spaces.
//
if (fDocHandler)
{
fReaderMgr.getSpaces(bbCData.getBuffer());
fDocHandler->ignorableWhitespace
(
bbCData.getRawBuffer()
, bbCData.getLen()
, false
);
}
else
{
fReaderMgr.skipPastSpaces();
}
}
else
{
emitError(XMLErrs::InvalidDocumentStructure);
fReaderMgr.skipPastChar(chCloseAngle);
}
}
}
catch(const EndOfEntityException&)
{
//
// We should never get an end of entity here. They should only
// occur within the doc type scanning method, and not leak out to
// here.
//
emitError
(
XMLErrs::UnexpectedEOE
, "in prolog"
);
}
}
}
//
// This method handles the high level logic of scanning the DOCType
// declaration. This calls the DTDScanner and kicks off both the scanning of
// the internal subset and the scanning of the external subset, if any.
//
// When we get here the '<!DOCTYPE' part has already been scanned, which is
// what told us that we had a doc type decl to parse.
//
void XMLScanner::scanDocTypeDecl()
{
if (!fReuseGrammar && fValidatorFromUser && !fValidator->handlesDTD())
{
ThrowXML(RuntimeException, XMLExcepts::Gen_NoDTDValidator);
}
//
// We have a doc type. So, create a DTDScanner and
// switch the Grammar to the emptyNamespace one.
//
if (!switchGrammar(XMLUni::fgZeroLenString) && fValidate)
{
fValidator->emitError
(
XMLValid::GrammarNotFound
, XMLUni::fgZeroLenString
);
}
DTDScanner dtdScanner((DTDGrammar*)fGrammar, fEntityDeclPool, fDocTypeHandler);
dtdScanner.setScannerInfo(this, &fReaderMgr, &fBufMgr);
if (fDocTypeHandler)
fDocTypeHandler->resetDocType();
// There must be some space after DOCTYPE
if (!fReaderMgr.skipPastSpaces())
{
emitError(XMLErrs::ExpectedWhitespace);
// Just skip the Doctype declaration and return
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
// Get a buffer for the root element
XMLBufBid bbRootName(&fBufMgr);
//
// Get a name from the input, which should be the name of the root
// element of the upcoming content.
//
fReaderMgr.getName(bbRootName.getBuffer());
if (bbRootName.isEmpty())
{
emitError(XMLErrs::NoRootElemInDOCTYPE);
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
//
// Store the root element name for later check
//
setRootElemName(bbRootName.getRawBuffer());
//
// This element obviously is not going to exist in the element decl
// pool yet, but we need to call docTypeDecl. So force it into
// the element decl pool, marked as being there because it was in
// the DOCTYPE. Later, when its declared, the status will be updated.
//
// Only do this if we are not reusing the validator! If we are reusing,
// then look it up instead. It has to exist!
//
DTDElementDecl* rootDecl;
Janitor<DTDElementDecl> janSrc(0);
if (fReuseGrammar)
{
if (fGrammar->getGrammarType() == Grammar::DTDGrammarType) {
rootDecl = (DTDElementDecl*) fGrammar->getElemDecl(fEmptyNamespaceId, 0, bbRootName.getRawBuffer(), Grammar::TOP_LEVEL_SCOPE);
if (rootDecl)
((DTDGrammar*)fGrammar)->setRootElemId(rootDecl->getId());
else {
rootDecl = new DTDElementDecl(bbRootName.getRawBuffer(), fEmptyNamespaceId);
rootDecl->setCreateReason(DTDElementDecl::AsRootElem);
rootDecl->setExternalElemDeclaration(true);
((DTDGrammar*)fGrammar)->setRootElemId(fGrammar->putElemDecl(rootDecl));
}
}
else {
rootDecl = new DTDElementDecl(bbRootName.getRawBuffer(), fEmptyNamespaceId);
rootDecl->setCreateReason(DTDElementDecl::AsRootElem);
rootDecl->setExternalElemDeclaration(true);
janSrc.reset(rootDecl);
}
}
else
{
rootDecl = new DTDElementDecl(bbRootName.getRawBuffer(), fEmptyNamespaceId);
rootDecl->setCreateReason(DTDElementDecl::AsRootElem);
rootDecl->setExternalElemDeclaration(true);
((DTDGrammar*)fGrammar)->setRootElemId(fGrammar->putElemDecl(rootDecl));
}
// Skip any spaces after the name
fReaderMgr.skipPastSpaces();
//
// And now if we are looking at a >, then we are done. It is not
// required to have an internal or external subset, though why you
// would not escapes me.
//
if (fReaderMgr.skippedChar(chCloseAngle)) {
//
// If we have a doc type handler and advanced callbacks are enabled,
// call the doctype event.
//
if (fDocTypeHandler)
fDocTypeHandler->doctypeDecl(*rootDecl, 0, 0, false);
return;
}
// either internal/external subset
if(!fReuseGrammar) {
if (fValScheme == Val_Auto && !fValidate)
fValidate = true;
}
bool hasIntSubset = false;
bool hasExtSubset = false;
XMLCh* sysId = 0;
XMLCh* pubId = 0;
//
// If the next character is '[' then we have no external subset cause
// there is no system id, just the opening character of the internal
// subset. Else, has to be an id.
//
// Just look at the next char, don't eat it.
if (fReaderMgr.peekNextChar() == chOpenSquare)
{
hasIntSubset = true;
}
else
{
// Indicate we have an external subset
hasExtSubset = true;
fHasNoDTD = false;
// Get buffers for the ids
XMLBufBid bbPubId(&fBufMgr);
XMLBufBid bbSysId(&fBufMgr);
// Get the external subset id
if (!dtdScanner.scanId(bbPubId.getBuffer(), bbSysId.getBuffer(), DTDScanner::IDType_External))
{
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
// Get copies of the ids we got
pubId = XMLString::replicate(bbPubId.getRawBuffer());
sysId = XMLString::replicate(bbSysId.getRawBuffer());
// Skip spaces and check again for the opening of an internal subset
fReaderMgr.skipPastSpaces();
// Just look at the next char, don't eat it.
if (fReaderMgr.peekNextChar() == chOpenSquare) {
hasIntSubset = true;
}
}
// Insure that the ids get cleaned up, if they got allocated
ArrayJanitor<XMLCh> janSysId(sysId);
ArrayJanitor<XMLCh> janPubId(pubId);
//
// If we have a doc type handler and advanced callbacks are enabled,
// call the doctype event.
//
if (fDocTypeHandler)
fDocTypeHandler->doctypeDecl(*rootDecl, pubId, sysId, hasIntSubset);
//
// Ok, if we had an internal subset, we are just past the [ character
// and need to parse that first.
//
if (hasIntSubset)
{
// Eat the opening square bracket
fReaderMgr.getNextChar();
// We can't have any internal subset if we are reusing the validator
if (fReuseGrammar)
ThrowXML(RuntimeException, XMLExcepts::Val_CantHaveIntSS);
//
// And try to scan the internal subset. If we fail, try to recover
// by skipping forward tot he close angle and returning.
//
if (!dtdScanner.scanInternalSubset())
{
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
//
// Do a sanity check that some expanded PE did not propogate out of
// the doctype. This could happen if it was terminated early by bad
// syntax.
//
if (fReaderMgr.getReaderDepth() > 1)
{
emitError(XMLErrs::PEPropogated);
// Ask the reader manager to pop back down to the main level
fReaderMgr.cleanStackBackTo(1);
}
fReaderMgr.skipPastSpaces();
}
// And that should leave us at the closing > of the DOCTYPE line
if (!fReaderMgr.skippedChar(chCloseAngle))
{
//
// Do a special check for the common scenario of an extra ] char at
// the end. This is easy to recover from.
//
if (fReaderMgr.skippedChar(chCloseSquare)
&& fReaderMgr.skippedChar(chCloseAngle))
{
emitError(XMLErrs::ExtraCloseSquare);
}
else
{
emitError(XMLErrs::UnterminatedDOCTYPE);
fReaderMgr.skipPastChar(chCloseAngle);
}
}
//
// If we had an external subset, then we need to deal with that one
// next. If we are reusing the validator, then don't scan it.
//
if (hasExtSubset && !fReuseGrammar && (fLoadExternalDTD || fValidate))
{
// And now create a reader to read this entity
InputSource* srcUsed;
XMLReader* reader = fReaderMgr.createReader
(
sysId
, pubId
, false
, XMLReader::RefFrom_NonLiteral
, XMLReader::Type_General
, XMLReader::Source_External
, srcUsed
);
// Put a janitor on the input source
Janitor<InputSource> janSrc(srcUsed);
//
// If it failed then throw an exception
//
if (!reader)
ThrowXML1(RuntimeException, XMLExcepts::Gen_CouldNotOpenDTD, srcUsed->getSystemId());
//
// In order to make the processing work consistently, we have to
// make this look like an external entity. So create an entity
// decl and fill it in and push it with the reader, as happens
// with an external entity. Put a janitor on it to insure it gets
// cleaned up. The reader manager does not adopt them.
//
const XMLCh gDTDStr[] = { chLatin_D, chLatin_T, chLatin_D , chNull };
DTDEntityDecl* declDTD = new DTDEntityDecl(gDTDStr);
declDTD->setSystemId(sysId);
Janitor<DTDEntityDecl> janDecl(declDTD);
// Mark this one as a throw at end
reader->setThrowAtEnd(true);
// And push it onto the stack, with its pseudo name
fReaderMgr.pushReader(reader, declDTD);
// Tell it its not in an include section
dtdScanner.scanExtSubsetDecl(false);
}
}
bool XMLScanner::scanStartTag(bool& gotData)
{
//
// Assume we will still have data until proven otherwise. It will only
// ever be false if this is the root and its empty.
//
gotData = true;
//
// Get the QName. In this case, we are not doing namespaces, so we just
// use it as is and don't have to break it into parts.
//
if (!fReaderMgr.getName(fQNameBuf))
{
emitError(XMLErrs::ExpectedElementName);
fReaderMgr.skipToChar(chOpenAngle);
return false;
}
// Assume it won't be an empty tag
bool isEmpty = false;
//
// Lets try to look up the element in the validator's element decl pool
// We can pass bogus values for the URI id and the base name. We know that
// this can only be called if we are doing a DTD style validator and that
// he will only look at the QName.
//
// We tell him to fault in a decl if he does not find one.
//
bool wasAdded = false;
XMLElementDecl* elemDecl = fGrammar->findOrAddElemDecl
(
fEmptyNamespaceId
, 0
, 0
, fQNameBuf.getRawBuffer()
, Grammar::TOP_LEVEL_SCOPE
, wasAdded
);
//
// We do something different here according to whether we found the
// element or not.
//
if (wasAdded)
{
// If validating then emit an error
if (fValidate)
{
// This is to tell the reuse Validator that this element was
// faulted-in, was not an element in the validator pool originally
elemDecl->setCreateReason(XMLElementDecl::JustFaultIn);
fValidator->emitError
(
XMLValid::ElementNotDefined
, elemDecl->getFullName()
);
}
}
else
{
// If its not marked declared and validating, then emit an error
if (fValidate && !elemDecl->isDeclared())
{
fValidator->emitError
(
XMLValid::ElementNotDefined
, elemDecl->getFullName()
);
}
}
// See if its the root element
const bool isRoot = fElemStack.isEmpty();
// Expand the element stack and add the new element
fElemStack.addLevel(elemDecl, fReaderMgr.getCurrentReaderNum());
fElemStack.setValidationFlag(fValidate);
// Validate the element
if (fValidate)
fValidator->validateElement(elemDecl);
//
// If this is the first element and we are validating, check the root
// element.
//
if (isRoot)
{
if (fValidate)
{
// If a DocType exists, then check if it matches the root name there.
if (fRootElemName && XMLString::compareString(fQNameBuf.getRawBuffer(), fRootElemName))
fValidator->emitError(XMLValid::RootElemNotLikeDocType);
// Some validators may also want to check the root, call the
// XMLValidator::checkRootElement
if (fValidatorFromUser && !fValidator->checkRootElement(elemDecl->getId()))
fValidator->emitError(XMLValid::RootElemNotLikeDocType);
}
}
else
{
//
// If the element stack is not empty, then add this element as a
// child of the previous top element. If its empty, this is the root
// elem and is not the child of anything.
//
fElemStack.addChild(elemDecl->getElementName(), true);
}
//
// Ask the element decl to clear out the 'provided' flag on all of its
// att defs.
//
elemDecl->resetDefs();
// Skip any whitespace after the name
fReaderMgr.skipPastSpaces();
//
// We loop until we either see a /> or >, handling attribute/value
// pairs until we get there.
//
unsigned int attCount = 0;
unsigned int curAttListSize = fAttrList->size();
while (true)
{
// And get the next non-space character
XMLCh nextCh = fReaderMgr.peekNextChar();
//
// If the next character is not a slash or closed angle bracket,
// then it must be whitespace, since whitespace is required
// between the end of the last attribute and the name of the next
// one.
//
if (attCount)
{
if ((nextCh != chForwardSlash) && (nextCh != chCloseAngle))
{
if (XMLReader::isWhitespace(nextCh))
{
// Ok, skip by them and peek another char
fReaderMgr.skipPastSpaces();
nextCh = fReaderMgr.peekNextChar();
}
else
{
// Emit the error but keep on going
emitError(XMLErrs::ExpectedWhitespace);
}
}
}
//
// Ok, here we first check for any of the special case characters.
// If its not one, then we do the normal case processing, which
// assumes that we've hit an attribute value, Otherwise, we do all
// the special case checks.
//
if (!XMLReader::isSpecialStartTagChar(nextCh))
{
//
// Assume its going to be an attribute, so get a name from
// the input.
//
if (!fReaderMgr.getName(fAttNameBuf))
{
emitError(XMLErrs::ExpectedAttrName);
fReaderMgr.skipPastChar(chCloseAngle);
return false;
}
// And next must be an equal sign
if (!scanEq())
{
static const XMLCh tmpList[] =
{
chSingleQuote, chDoubleQuote, chCloseAngle
, chOpenAngle, chForwardSlash, chNull
};
emitError(XMLErrs::ExpectedEqSign);
//
// Try to sync back up by skipping forward until we either
// hit something meaningful.
//
const XMLCh chFound = fReaderMgr.skipUntilInOrWS(tmpList);
if ((chFound == chCloseAngle) || (chFound == chForwardSlash))
{
// Jump back to top for normal processing of these
continue;
}
else if ((chFound == chSingleQuote)
|| (chFound == chDoubleQuote)
|| XMLReader::isWhitespace(chFound))
{
// Just fall through assuming that the value is to follow
}
else if (chFound == chOpenAngle)
{
// Assume a malformed tag and that new one is starting
emitError(XMLErrs::UnterminatedStartTag, elemDecl->getFullName());
return false;
}
else
{
// Something went really wrong
return false;
}
}
//
// See if this attribute is declared for this element. If we are
// not validating of course it will not be at first, but we will
// fault it into the pool (to avoid lots of redundant errors.)
//
wasAdded = false;
XMLAttDef* attDef = elemDecl->findAttr
(
fAttNameBuf.getRawBuffer()
, 0
, 0
, 0
, XMLElementDecl::AddIfNotFound
, wasAdded
);
if (wasAdded)
{
//
// If there is a validation handler, then we are validating
// so emit an error.
//
if (fValidate)
{
// This is to tell the Validator that this attribute was
// faulted-in, was not an attribute in the attdef originally
attDef->setCreateReason(XMLAttDef::JustFaultIn);
fValidator->emitError
(
XMLValid::AttNotDefinedForElement
, fAttNameBuf.getRawBuffer()
, elemDecl->getFullName()
);
}
}
else
{
// If this attribute was faulted-in and first occurence,
// then emit an error
if (fValidate && attDef->getCreateReason() == XMLAttDef::JustFaultIn
&& !attDef->getProvided())
{
fValidator->emitError
(
XMLValid::AttNotDefinedForElement
, fAttNameBuf.getRawBuffer()
, elemDecl->getFullName()
);
}
}
//
// If its already provided, then there are more than one of
// this attribute in this start tag, so emit an error.
//
if (attDef->getProvided())
{
emitError
(
XMLErrs::AttrAlreadyUsedInSTag
, attDef->getFullName()
, elemDecl->getFullName()
);
}
else
{
// Mark this one as already seen
attDef->setProvided(true);
}
//
// Skip any whitespace before the value and then scan the att
// value. This will come back normalized with entity refs and
// char refs expanded.
//
fReaderMgr.skipPastSpaces();
if (!scanAttValue(attDef, fAttValueBuf))
{
static const XMLCh tmpList[] =
{
chCloseAngle, chOpenAngle, chForwardSlash, chNull
};
emitError(XMLErrs::ExpectedAttrValue);
//
// It failed, so lets try to get synced back up. We skip
// forward until we find some whitespace or one of the
// chars in our list.
//
const XMLCh chFound = fReaderMgr.skipUntilInOrWS(tmpList);
if ((chFound == chCloseAngle)
|| (chFound == chForwardSlash)
|| XMLReader::isWhitespace(chFound))
{
//
// Just fall through and process this attribute, though
// the value will be "".
//
}
else if (chFound == chOpenAngle)
{
// Assume a malformed tag and that new one is starting
emitError(XMLErrs::UnterminatedStartTag, elemDecl->getFullName());
return false;
}
else
{
// Something went really wrong
return false;
}
}
//
// Now that its all stretched out, lets look at its type and
// determine if it has a valid value. It will output any needed
// errors, but we just keep going. We only need to do this if
// we are validating.
//
if (!wasAdded && attDef->getCreateReason() != XMLAttDef::JustFaultIn)
{
// Let the validator pass judgement on the attribute value
if (fValidate)
{
fValidator->validateAttrValue
(
attDef
, fAttValueBuf.getRawBuffer()
);
}
}
//
// Add this attribute to the attribute list that we use to
// pass them to the handler. We reuse its existing elements
// but expand it as required.
//
XMLAttr* curAtt;
if (attCount >= curAttListSize)
{
curAtt = new XMLAttr
(
-1
, fAttNameBuf.getRawBuffer()
, XMLUni::fgZeroLenString
, fAttValueBuf.getRawBuffer()
, attDef->getType()
, true
);
fAttrList->addElement(curAtt);
}
else
{
curAtt = fAttrList->elementAt(attCount);
curAtt->set
(
-1
, fAttNameBuf.getRawBuffer()
, XMLUni::fgZeroLenString
, fAttValueBuf.getRawBuffer()
, attDef->getType()
);
curAtt->setSpecified(true);
}
attCount++;
// And jump back to the top of the loop
continue;
}
//
// It was some special case character so do all of the checks and
// deal with it.
//
if (!nextCh)
ThrowXML(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF);
if (nextCh == chForwardSlash)
{
fReaderMgr.getNextChar();
isEmpty = true;
if (!fReaderMgr.skippedChar(chCloseAngle))
emitError(XMLErrs::UnterminatedStartTag, elemDecl->getFullName());
break;
}
else if (nextCh == chCloseAngle)
{
fReaderMgr.getNextChar();
break;
}
else if (nextCh == chOpenAngle)
{
//
// Check for this one specially, since its going to be common
// and it is kind of auto-recovering since we've already hit the
// next open bracket, which is what we would have seeked to (and
// skipped this whole tag.)
//
emitError(XMLErrs::UnterminatedStartTag, elemDecl->getFullName());
break;
}
else if ((nextCh == chSingleQuote) || (nextCh == chDoubleQuote))
{
//
// Check for this one specially, which is probably a missing
// attribute name, e.g. ="value". Just issue expected name
// error and eat the quoted string, then jump back to the
// top again.
//
emitError(XMLErrs::ExpectedAttrName);
fReaderMgr.getNextChar();
fReaderMgr.skipQuotedString(nextCh);
fReaderMgr.skipPastSpaces();
continue;
}
}
//
// Ok, so lets get an enumerator for the attributes of this element
// and run through them for well formedness and validity checks. But
// make sure that we had any attributes before we do it, since the list
// would have have gotten faulted in anyway.
//
if (elemDecl->hasAttDefs())
{
XMLAttDefList& attDefList = elemDecl->getAttDefList();
while (attDefList.hasMoreElements())
{
// Get the current att def, for convenience and its def type
const XMLAttDef& curDef = attDefList.nextElement();
const XMLAttDef::DefAttTypes defType = curDef.getDefaultType();
if (!curDef.getProvided())
{
if (fValidate)
{
// If we are validating and its required, then an error
if (defType == XMLAttDef::Required)
{
fValidator->emitError
(
XMLValid::RequiredAttrNotProvided
, curDef.getFullName()
);
}
else if ((defType == XMLAttDef::Default) ||
(defType == XMLAttDef::Fixed) )
{
if (fStandalone && curDef.isExternal())
{
//
// XML 1.0 Section 2.9
// Document is standalone, so attributes must not be defaulted.
//
fValidator->emitError(XMLValid::NoDefAttForStandalone, curDef.getFullName(), elemDecl->getFullName());
}
}
}
// Fault in the value if needed, and bump the att count
if ((defType == XMLAttDef::Default)
|| (defType == XMLAttDef::Fixed))
{
XMLAttr* curAtt;
if (attCount >= curAttListSize)
{
curAtt = new XMLAttr
(
-1
, curDef.getFullName()
, XMLUni::fgZeroLenString
, curDef.getValue()
, curDef.getType()
, false
);
fAttrList->addElement(curAtt);
curAttListSize++;
}
else
{
curAtt = fAttrList->elementAt(attCount);
curAtt->set
(
-1
, curDef.getFullName()
, XMLUni::fgZeroLenString
, curDef.getValue()
, curDef.getType()
);
curAtt->setSpecified(false);
}
attCount++;
}
}
}
}
//
// If empty, validate content right now if we are validating and then
// pop the element stack top. Else, we have to update the current stack
// top's namespace mapping elements.
//
if (isEmpty)
{
// If validating, then insure that its legal to have no content
if (fValidate)
{
const int res = fValidator->checkContent(elemDecl, 0, 0);
if (res >= 0)
{
fValidator->emitError
(
XMLValid::ElementNotValidForContent
, elemDecl->getFullName()
, elemDecl->getFormattedContentModel()
);
}
}
// Pop the element stack back off since it'll never be used now
fElemStack.popTop();
// If the elem stack is empty, then it was an empty root
if (isRoot)
gotData = false;
else {
// Restore the validation flag
fValidate = fElemStack.getValidationFlag();
}
}
//
// If we have a document handler, then tell it about this start tag. We
// don't have any URI id to send along, so send fEmptyNamespaceId. We also do not send
// any prefix since its just one big name if we are not doing namespaces.
//
if (fDocHandler)
{
fDocHandler->startElement
(
*elemDecl
, fEmptyNamespaceId
, 0
, *fAttrList
, attCount
, isEmpty
, isRoot
);
}
return true;
}
//
//
// This method is called to scan a start tag when we are processing
// namespaces. There are two different versions of this method, one for
// namespace aware processing an done for non-namespace aware processing.
//
// This method is called after we've scanned the < of a start tag. So we
// have to get the element name, then scan the attributes, after which
// we are either going to see >, />, or attributes followed by one of those
// sequences.
//
bool XMLScanner::scanStartTagNS(bool& gotData)
{
//
// Assume we will still have data until proven otherwise. It will only
// ever be false if this is the root and its empty.
//
gotData = true;
//
// The current position is after the open bracket, so we need to read in
// in the element name.
//
if (!fReaderMgr.getName(fQNameBuf))
{
emitError(XMLErrs::ExpectedElementName);
fReaderMgr.skipToChar(chOpenAngle);
return false;
}
//
// Do a little sanity check here. One common problem is that
// badly encoded files cause getName() to exit above on a
// non-name char (an invalid XML char), then the scan start
// tag below fails. This is misleading, so check here that
// we are looking at a valid XML char.
//
if (!XMLReader::isXMLChar(fReaderMgr.peekNextChar()))
{
XMLCh tmpBuf[9];
XMLString::binToText
(
fReaderMgr.getNextChar()
, tmpBuf
, 8
, 16
);
emitError(XMLErrs::InvalidCharacter, tmpBuf);
}
// See if its the root element
const bool isRoot = fElemStack.isEmpty();
// Skip any whitespace after the name
fReaderMgr.skipPastSpaces();
//
// First we have to do the rawest attribute scan. We don't do any
// normalization of them at all, since we don't know yet what type they
// might be (since we need the element decl in order to do that.)
//
bool isEmpty;
unsigned int attCount = rawAttrScan
(
fQNameBuf.getRawBuffer()
, *fRawAttrList
, isEmpty
);
const bool gotAttrs = (attCount != 0);
// save the contentleafname and currentscope before addlevel, for later use
ContentLeafNameTypeVector* cv = 0;
XMLContentModel* cm = 0;
int currentScope = Grammar::TOP_LEVEL_SCOPE;
if (!isRoot && fGrammarType == Grammar::SchemaGrammarType) {
SchemaElementDecl* tempElement = (SchemaElementDecl*) fElemStack.topElement()->fThisElement;
SchemaElementDecl::ModelTypes modelType = tempElement->getModelType();
if ((modelType == SchemaElementDecl::Mixed_Simple)
|| (modelType == SchemaElementDecl::Mixed_Complex)
|| (modelType == SchemaElementDecl::Children))
{
cm = tempElement->getContentModel();
cv = cm->getContentLeafNameTypeVector();
currentScope = fElemStack.getCurrentScope();
}
}
//
// Now, since we might have to update the namespace map for this element,
// but we don't have the element decl yet, we just tell the element stack
// to expand up to get ready.
//
unsigned int elemDepth = fElemStack.addLevel();
fElemStack.setValidationFlag(fValidate);
// Check if there is any external schema location specified, and if we are at root,
// go through them first before scanning those specified in the instance document
if (isRoot
&& fDoSchema
&& !fReuseGrammar
&& (fExternalSchemaLocation || fExternalNoNamespaceSchemaLocation)) {
if (fExternalSchemaLocation)
parseSchemaLocation(fExternalSchemaLocation);
if (fExternalNoNamespaceSchemaLocation)
resolveSchemaGrammar(fExternalNoNamespaceSchemaLocation, XMLUni::fgZeroLenString);
}
//
// Make an initial pass through the list and find any xmlns attributes or
// schema attributes.
//
if (attCount)
scanRawAttrListforNameSpaces(fRawAttrList, attCount);
//
// Also find any default or fixed xmlns attributes in DTD defined for
// this element.
//
if (fGrammarType == Grammar::DTDGrammarType) {
XMLElementDecl* elemDecl = fGrammar->getElemDecl
(
fEmptyNamespaceId
, 0
, fQNameBuf.getRawBuffer()
, Grammar::TOP_LEVEL_SCOPE
);
if (elemDecl) {
if (elemDecl->hasAttDefs()) {
XMLAttDefList& attDefList = elemDecl->getAttDefList();
while (attDefList.hasMoreElements())
{
// Get the current att def, for convenience and its def type
const XMLAttDef& curDef = attDefList.nextElement();
const XMLAttDef::DefAttTypes defType = curDef.getDefaultType();
// update the NSMap if there are any default/fixed xmlns attributes
if ((defType == XMLAttDef::Default)
|| (defType == XMLAttDef::Fixed))
{
const XMLCh* rawPtr = curDef.getFullName();
if (!XMLString::compareNString(rawPtr, XMLUni::fgXMLNSColonString, 6)
|| !XMLString::compareString(rawPtr, XMLUni::fgXMLNSString))
updateNSMap(rawPtr, curDef.getValue());
}
}
}
}
}
//
// Resolve the qualified name to a URI and name so that we can look up
// the element decl for this element. We have now update the prefix to
// namespace map so we should get the correct element now.
//
unsigned int uriId = resolveQName
(
fQNameBuf.getRawBuffer()
, fNameBuf
, fPrefixBuf
, ElemStack::Mode_Element
);
//if schema, check if we should lax or skip the validation of this element
bool laxThisOne = false;
if (cv) {
QName element(fPrefixBuf.getRawBuffer(), fNameBuf.getRawBuffer(), uriId);
// elementDepth will be > 0, as cv is only constructed if element is not
// root.
laxThisOne = laxElementValidation(&element, cv, cm, elemDepth - 1);
}
//
// Look up the element now in the grammar. This will get us back a
// generic element decl object. We tell him to fault one in if he does
// not find it.
//
bool wasAdded = false;
XMLElementDecl* elemDecl;
const XMLCh* nameRawBuf = fNameBuf.getRawBuffer();
const XMLCh* qnameRawBuf = fQNameBuf.getRawBuffer();
if (uriId != fEmptyNamespaceId) {
// Check in current grammar before switching if necessary
elemDecl = fGrammar->getElemDecl
(
uriId
, nameRawBuf
, qnameRawBuf
, currentScope
);
if (!elemDecl && (fURIStringPool->getId(fGrammar->getTargetNamespace()) != uriId)) {
// not found, switch to the specified grammar
const XMLCh* uriStr = getURIText(uriId);
if (!switchGrammar(uriStr) && fValidate && !laxThisOne)
{
fValidator->emitError
(
XMLValid::GrammarNotFound
,uriStr
);
}
elemDecl = fGrammar->getElemDecl
(
uriId
, nameRawBuf
, qnameRawBuf
, currentScope
);
}
if (!elemDecl && currentScope != Grammar::TOP_LEVEL_SCOPE) {
// if not found, then it may be a reference, try TOP_LEVEL_SCOPE
elemDecl = fGrammar->getElemDecl
(
uriId
, nameRawBuf
, qnameRawBuf
, Grammar::TOP_LEVEL_SCOPE
);
if(!elemDecl) {
// still not found in specified uri
// try emptyNamesapce see if element should be un-qualified.
elemDecl = fGrammar->getElemDecl
(
fEmptyNamespaceId
, nameRawBuf
, qnameRawBuf
, currentScope
);
if (elemDecl && elemDecl->getCreateReason() != XMLElementDecl::JustFaultIn && fValidate) {
fValidator->emitError
(
XMLValid::ElementNotUnQualified
, elemDecl->getFullName()
);
}
}
}
if (!elemDecl) {
// still not found, fault this in and issue error later
elemDecl = fGrammar->putElemDecl(uriId
, nameRawBuf
, fPrefixBuf.getRawBuffer()
, qnameRawBuf
, currentScope);
wasAdded = true;
}
}
else
{
//the element has no prefix,
//thus it is either a non-qualified element defined in current targetNS
//or an element that is defined in the globalNS
//try unqualifed first
elemDecl = fGrammar->getElemDecl
(
uriId
, nameRawBuf
, qnameRawBuf
, currentScope
);
unsigned orgGrammarUri = fURIStringPool->getId(fGrammar->getTargetNamespace());
if (!elemDecl && orgGrammarUri != fEmptyNamespaceId) {
//not found, switch grammar and try globalNS
if (!switchGrammar(XMLUni::fgZeroLenString) && fValidate && !laxThisOne)
{
fValidator->emitError
(
XMLValid::GrammarNotFound
, XMLUni::fgZeroLenString
);
}
elemDecl = fGrammar->getElemDecl
(
uriId
, nameRawBuf
, qnameRawBuf
, currentScope
);
}
if (!elemDecl && currentScope != Grammar::TOP_LEVEL_SCOPE) {
// if not found, then it may be a reference, try TOP_LEVEL_SCOPE
elemDecl = fGrammar->getElemDecl
(
uriId
, nameRawBuf
, qnameRawBuf
, Grammar::TOP_LEVEL_SCOPE
);
if (!elemDecl && orgGrammarUri != fEmptyNamespaceId) {
// still Not found in specified uri
// go to original Grammar again to see if element needs to be fully qualified.
const XMLCh* uriStr = getURIText(orgGrammarUri);
if (!switchGrammar(uriStr) && fValidate && !laxThisOne)
{
fValidator->emitError
(
XMLValid::GrammarNotFound
,uriStr
);
}
elemDecl = fGrammar->getElemDecl
(
orgGrammarUri
, nameRawBuf
, qnameRawBuf
, currentScope
);
if (elemDecl && elemDecl->getCreateReason() != XMLElementDecl::JustFaultIn && fValidate) {
fValidator->emitError
(
XMLValid::ElementNotQualified
, elemDecl->getFullName()
);
}
}
}
if (!elemDecl) {
// still not found, fault this in and issue error later
elemDecl = fGrammar->putElemDecl(uriId
, nameRawBuf
, fPrefixBuf.getRawBuffer()
, qnameRawBuf
, currentScope);
wasAdded = true;
}
}
//
// We do something different here according to whether we found the
// element or not.
//
if (wasAdded)
{
if (laxThisOne) {
fValidate = false;
fElemStack.setValidationFlag(fValidate);
}
// If validating then emit an error
if (fValidate)
{
// This is to tell the reuse Validator that this element was
// faulted-in, was not an element in the grammar pool originally
elemDecl->setCreateReason(XMLElementDecl::JustFaultIn);
fValidator->emitError
(
XMLValid::ElementNotDefined
, elemDecl->getFullName()
);
}
}
else
{
// If its not marked declared and validating, then emit an error
if (!elemDecl->isDeclared()) {
if (laxThisOne) {
fValidate = false;
fElemStack.setValidationFlag(fValidate);
}
if (fValidate)
{
fValidator->emitError
(
XMLValid::ElementNotDefined
, elemDecl->getFullName()
);
}
}
if (fGrammarType == Grammar::SchemaGrammarType)
((SchemaElementDecl*)elemDecl)->setXsiComplexTypeInfo(0);
}
//
// Now we can update the element stack to set the current element
// decl. We expanded the stack above, but couldn't store the element
// decl because we didn't know it yet.
//
fElemStack.setElement(elemDecl, fReaderMgr.getCurrentReaderNum());
fElemStack.setCurrentURI(uriId);
// Validate the element
if (fValidate)
fValidator->validateElement(elemDecl);
if (fGrammarType == Grammar::SchemaGrammarType) {
ComplexTypeInfo* typeinfo = ((SchemaElementDecl*)elemDecl)->getComplexTypeInfo();
if (typeinfo) {
currentScope = typeinfo->getScopeDefined();
// switch grammar if the typeinfo has a different grammar (happens when there is xsi:type)
XMLCh* typeName = typeinfo->getTypeName();
const XMLCh poundStr[] = {chPound, chNull};
if (!XMLString::startsWith(typeName, poundStr)) {
const int comma = XMLString::indexOf(typeName, chComma);
if (comma != -1) {
XMLBuffer prefixBuf(comma+1);
prefixBuf.append(typeName, comma);
const XMLCh* uriStr = prefixBuf.getRawBuffer();
if (!switchGrammar(uriStr) && fValidate && !laxThisOne)
{
fValidator->emitError
(
XMLValid::GrammarNotFound
, prefixBuf.getRawBuffer()
);
}
}
}
}
fElemStack.setCurrentScope(currentScope);
// Set element next state
if (elemDepth >= fElemStateSize) {
resizeElemState();
}
fElemState[elemDepth] = 0;
}
fElemStack.setCurrentGrammar(fGrammar);
//
// If this is the first element and we are validating, check the root
// element.
//
if (isRoot)
{
if (fValidate)
{
// If a DocType exists, then check if it matches the root name there.
if (fRootElemName && XMLString::compareString(qnameRawBuf, fRootElemName))
fValidator->emitError(XMLValid::RootElemNotLikeDocType);
// Some validators may also want to check the root, call the
// XMLValidator::checkRootElement
if (fValidatorFromUser && !fValidator->checkRootElement(elemDecl->getId()))
fValidator->emitError(XMLValid::RootElemNotLikeDocType);
}
}
else
{
//
// If the element stack is not empty, then add this element as a
// child of the previous top element. If its empty, this is the root
// elem and is not the child of anything.
//
fElemStack.addChild(elemDecl->getElementName(), true);
}
//
// Now lets get the fAttrList filled in. This involves faulting in any
// defaulted and fixed attributes and normalizing the values of any that
// we got explicitly.
//
// We update the attCount value with the total number of attributes, but
// it goes in with the number of values we got during the raw scan of
// explictly provided attrs above.
//
attCount = buildAttList(*fRawAttrList, attCount, elemDecl, *fAttrList);
//
// activate identity constraints
//
if (fValidate && fGrammar && fGrammarType == Grammar::SchemaGrammarType) {
unsigned int count = ((SchemaElementDecl*) elemDecl)->getIdentityConstraintCount();
if (count || fMatcherStack->getMatcherCount()) {
fValueStoreCache->startElement();
fMatcherStack->pushContext();
fValueStoreCache->initValueStoresFor((SchemaElementDecl*) elemDecl);
for (unsigned int i = 0; i < count; i++) {
activateSelectorFor(((SchemaElementDecl*) elemDecl)->getIdentityConstraintAt(i));
}
// call all active identity constraints
count = fMatcherStack->getMatcherCount();
for (unsigned int j = 0; j < count; j++) {
XPathMatcher* matcher = fMatcherStack->getMatcherAt(j);
matcher->startElement(*elemDecl, uriId, fPrefixBuf.getRawBuffer(), *fAttrList, attCount);
}
}
}
// Since the element may have default values, call start tag now regardless if it is empty or not
// If we have a document handler, then tell it about this start tag
if (fDocHandler)
{
fDocHandler->startElement
(
*elemDecl
, uriId
, fPrefixBuf.getRawBuffer()
, *fAttrList
, attCount
, false
, isRoot
);
}
//
// If empty, validate content right now if we are validating and then
// pop the element stack top. Else, we have to update the current stack
// top's namespace mapping elements.
//
if (isEmpty)
{
// Pop the element stack back off since it'll never be used now
fElemStack.popTop();
// If validating, then insure that its legal to have no content
if (fValidate)
{
const int res = fValidator->checkContent(elemDecl, 0, 0);
if (res >= 0)
{
fValidator->emitError
(
XMLValid::ElementNotValidForContent
, elemDecl->getFullName()
, elemDecl->getFormattedContentModel()
);
}
if (fGrammarType == Grammar::SchemaGrammarType) {
// reset xsi:type ComplexTypeInfo
((SchemaElementDecl*)elemDecl)->setXsiComplexTypeInfo(0);
// call matchers and de-activate context
int oldCount = fMatcherStack->getMatcherCount();
if (oldCount || ((SchemaElementDecl*) elemDecl)->getIdentityConstraintCount()) {
for (int i = oldCount - 1; i >= 0; i--) {
XPathMatcher* matcher = fMatcherStack->getMatcherAt(i);
matcher->endElement(*elemDecl);
}
if (fMatcherStack->size() > 0) {
fMatcherStack->popContext();
}
// handle everything *but* keyref's.
int newCount = fMatcherStack->getMatcherCount();
for (int j = oldCount - 1; j >= newCount; j--) {
XPathMatcher* matcher = fMatcherStack->getMatcherAt(j);
IdentityConstraint* ic = matcher->getIdentityConstraint();
if (ic && (ic->getType() != IdentityConstraint::KEYREF)) {
matcher->endDocumentFragment();
fValueStoreCache->transplant(ic);
}
else if (!ic) {
matcher->endDocumentFragment();
}
}
// now handle keyref's...
for (int k = oldCount - 1; k >= newCount; k--) {
XPathMatcher* matcher = fMatcherStack->getMatcherAt(k);
IdentityConstraint* ic = matcher->getIdentityConstraint();
if (ic && (ic->getType() == IdentityConstraint::KEYREF)) {
ValueStore* values = fValueStoreCache->getValueStoreFor(ic);
if (values) { // nothing to do if nothing matched!
values->endDcocumentFragment(fValueStoreCache);
}
matcher->endDocumentFragment();
}
}
fValueStoreCache->endElement();
}
}
}
// If we have a doc handler, tell it about the end tag
if (fDocHandler)
{
fDocHandler->endElement
(
*elemDecl
, uriId
, isRoot
, fPrefixBuf.getRawBuffer()
);
}
// If the elem stack is empty, then it was an empty root
if (isRoot)
gotData = false;
else
{
// Restore the grammar
fGrammar = fElemStack.getCurrentGrammar();
fGrammarType = fGrammar->getGrammarType();
if (fGrammarType == Grammar::SchemaGrammarType && !fValidator->handlesSchema()) {
if (fValidatorFromUser)
ThrowXML(RuntimeException, XMLExcepts::Gen_NoSchemaValidator);
else {
fValidator = fSchemaValidator;
}
}
else if (fGrammarType == Grammar::DTDGrammarType && !fValidator->handlesDTD()) {
if (fValidatorFromUser)
ThrowXML(RuntimeException, XMLExcepts::Gen_NoDTDValidator);
else {
fValidator = fDTDValidator;
}
}
fValidator->setGrammar(fGrammar);
// Restore the validation flag
fValidate = fElemStack.getValidationFlag();
}
}
return true;
}
//
// Scans the <?xml .... ?> line. This stuff is all sequential so we don't
// do any state machine loop here. We just bull straight through it. It ends
// past the closing bracket. If there is a document handler, then its called
// on the XMLDecl callback.
//
// On entry, the <?xml has been scanned, and we pick it up from there.
//
// NOTE: In order to provide good recovery from bad XML here, we try to be
// very flexible. No matter what order the stuff is in, we'll keep going
// though we'll issue errors.
//
// The parameter tells us which type of decl we should expect, Text or XML.
// [23] XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
// [77] TextDecl::= '<?xml' VersionInfo? EncodingDecl S? '?>'
//
void XMLScanner::scanXMLDecl(const DeclTypes type)
{
// Get us some buffers to use
XMLBufBid bbVersion(&fBufMgr);
XMLBufBid bbEncoding(&fBufMgr);
XMLBufBid bbStand(&fBufMgr);
XMLBufBid bbDummy(&fBufMgr);
XMLBufBid bbName(&fBufMgr);
//
// We use this little enum and array to keep up with what we found
// and what order we found them in. This lets us get them free form
// without too much overhead, but still know that they were in the
// wrong order.
//
enum Strings
{
VersionString
, EncodingString
, StandaloneString
, UnknownString
, StringCount
};
int flags[StringCount] = { -1, -1, -1, -1 };
//
// Also set up a list of buffers in the right order so that we know
// where to put stuff.
//
XMLBuffer* buffers[StringCount] ;
buffers[0] = &bbVersion.getBuffer();
buffers[1] = &bbEncoding.getBuffer();
buffers[2] = &bbStand.getBuffer();
buffers[3] = &bbDummy.getBuffer();
int curCount = 0;
Strings curString;
XMLBuffer& nameBuf = bbName.getBuffer();
while (true)
{
// Skip any spaces
const unsigned int spaceCount = fReaderMgr.skipPastSpaces();
// If we are looking at a question mark, then break out
if (fReaderMgr.lookingAtChar(chQuestion))
break;
// If this is not the first string, then we require the spaces
if (!spaceCount && curCount)
emitError(XMLErrs::ExpectedWhitespace);
//
// Get characters up to the next whitespace or equal's sign.
//
if (!scanUpToWSOr(nameBuf, chEqual))
emitError(XMLErrs::ExpectedDeclString);
// See if it matches any of our expected strings
if (!XMLString::compareString(nameBuf.getRawBuffer(), XMLUni::fgVersionString))
curString = VersionString;
else if (!XMLString::compareString(nameBuf.getRawBuffer(), XMLUni::fgEncodingString))
curString = EncodingString;
else if (!XMLString::compareString(nameBuf.getRawBuffer(), XMLUni::fgStandaloneString))
curString = StandaloneString;
else
curString = UnknownString;
//
// If its an unknown string, then give that error. Else check to
// see if this one has been done already and give that error.
//
if (curString == UnknownString)
emitError(XMLErrs::ExpectedDeclString, nameBuf.getRawBuffer());
else if (flags[curString] != -1)
emitError(XMLErrs::DeclStringRep, nameBuf.getRawBuffer());
else if (flags[curString] == -1)
flags[curString] = ++curCount;
//
// Scan for an equal's sign. If we don't find it, issue an error
// but keep trying to go on.
//
if (!scanEq())
emitError(XMLErrs::ExpectedEqSign);
//
// Get a quote string into the buffer for the string that we are
// currently working on.
//
if (!getQuotedString(*buffers[curString]))
{
emitError(XMLErrs::ExpectedQuotedString);
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
// And validate the value according which one it was
const XMLCh* rawValue = buffers[curString]->getRawBuffer();
if (curString == VersionString)
{
if (XMLString::compareString(rawValue, XMLUni::fgSupportedVersion))
emitError(XMLErrs::UnsupportedXMLVersion, rawValue);
}
else if (curString == EncodingString)
{
if (!XMLString::isValidEncName(rawValue))
emitError(XMLErrs::BadXMLEncoding, rawValue);
}
else if (curString == StandaloneString)
{
if (!XMLString::compareString(rawValue, XMLUni::fgYesString))
fStandalone = true;
else if (!XMLString::compareString(rawValue, XMLUni::fgNoString))
fStandalone = false;
else
{
emitError(XMLErrs::BadStandalone);
if (!XMLString::compareIString(rawValue, XMLUni::fgYesString))
fStandalone = true;
else if (!XMLString::compareIString(rawValue, XMLUni::fgNoString))
fStandalone = false;
}
}
}
//
// Make sure that the strings present are in order. We don't care about
// which ones are present at this point, just that any there are in the
// right order.
//
int curTop = 0;
for (int index = VersionString; index < StandaloneString; index++)
{
if (flags[index] != -1)
{
if (flags[index] != curTop + 1)
{
emitError(XMLErrs::DeclStringsInWrongOrder);
break;
}
curTop = flags[index];
}
}
//
// If its an XML decl, the version must be present.
// If its a Text decl, then encoding must be present AND standalone must not be present.
//
if ((type == Decl_XML) && (flags[VersionString] == -1))
emitError(XMLErrs::XMLVersionRequired);
else if (type == Decl_Text) {
if (flags[StandaloneString] != -1)
emitError(XMLErrs::StandaloneNotLegal);
if (flags[EncodingString] == -1)
emitError(XMLErrs::EncodingRequired);
}
if (!fReaderMgr.skippedChar(chQuestion))
{
emitError(XMLErrs::UnterminatedXMLDecl);
fReaderMgr.skipPastChar(chCloseAngle);
}
else if (!fReaderMgr.skippedChar(chCloseAngle))
{
emitError(XMLErrs::UnterminatedXMLDecl);
fReaderMgr.skipPastChar(chCloseAngle);
}
//
// If we have a document handler then call the XML Decl callback.
//
// !NOTE! Do this before we possibly update the reader with the
// actual encoding string. Otherwise, we will pass the wrong thing
// for the last parameter!
//
if (fDocHandler)
{
fDocHandler->XMLDecl
(
bbVersion.getRawBuffer()
, bbEncoding.getRawBuffer()
, bbStand.getRawBuffer()
, fReaderMgr.getCurrentEncodingStr()
);
}
//
// Ok, we've now seen the real encoding string, if there was one, so
// lets call back on the current reader and tell it what the real
// encoding string was. If it fails, that's because it represents some
// sort of contradiction with the autosensed format, and it keeps the
// original encoding.
//
// NOTE: This can fail for a number of reasons, such as a bogus encoding
// name or because its in flagrant contradiction of the auto-sensed
// format.
//
if (flags[EncodingString] != -1)
{
if (!fReaderMgr.getCurrentReader()->setEncoding(bbEncoding.getRawBuffer()))
emitError(XMLErrs::ContradictoryEncoding, bbEncoding.getRawBuffer());
}
}
const XMLCh* XMLScanner::getURIText(const unsigned int uriId) const
{
if (fURIStringPool->exists(uriId)) {
// Look up the URI in the string pool and return its id
const XMLCh* value = fURIStringPool->getValueForId(uriId);
if (!value)
return XMLUni::fgZeroLenString;
return value;
}
else
return XMLUni::fgZeroLenString;
}
bool XMLScanner::getURIText( const unsigned int uriId
, XMLBuffer& uriBufToFill) const
{
if (fURIStringPool->exists(uriId)) {
// Look up the URI in the string pool and return its id
const XMLCh* value = fURIStringPool->getValueForId(uriId);
if (!value)
return false;
uriBufToFill.set(value);
return true;
}
else
return false;
}
unsigned int
XMLScanner::resolveQName( const XMLCh* const qName
, XMLBuffer& nameBuf
, XMLBuffer& prefixBuf
, const ElemStack::MapModes mode)
{
// Reset both target buffers in case we don't get anything for either
nameBuf.reset();
prefixBuf.reset();
//
// Lets split out the qName into a URI and name buffer first. The URI
// can be empty.
//
const int colonPos = XMLString::indexOf(qName, chColon);
unsigned int uriId = 0;
if (colonPos == -1)
{
//
// Its all name with no prefix, so put the whole thing into the name
// buffer. Then map the empty string to a URI, since the empty string
// represents the default namespace. This will either return some
// explicit URI which the default namespace is mapped to, or the
// the default global namespace.
//
nameBuf.append(qName);
bool unknown;
uriId = fElemStack.mapPrefixToURI(prefixBuf.getRawBuffer(), mode, unknown);
#if defined(XERCES_DEBUG)
if (unknown)
{
// <TBD> This one should never be unknown
}
#endif
}
else
{
//
// Copy the chars up to but not including the colon into the prefix
// buffer.
//
prefixBuf.append(qName, colonPos);
// And copy over the rest of the chars to the name buffer
nameBuf.append(&qName[colonPos+1]);
//
// Watch for the special namespace prefixes. We always map these to
// special URIs. 'xml' gets mapped to the official URI that its defined
// to map to by the NS spec. xmlns gets mapped to a special place holder
// URI that we define (so that it maps to something checkable.)
//
if (!XMLString::compareString(prefixBuf.getRawBuffer(), XMLUni::fgXMLNSString))
uriId = fXMLNSNamespaceId;
else if (!XMLString::compareString(prefixBuf.getRawBuffer(), XMLUni::fgXMLString))
uriId = fXMLNamespaceId;
else
{
bool unknown;
uriId = fElemStack.mapPrefixToURI(prefixBuf.getRawBuffer(), mode, unknown);
if (unknown)
emitError(XMLErrs::UnknownPrefix, prefixBuf.getRawBuffer());
}
}
return uriId;
}
bool XMLScanner::checkXMLDecl(bool startWithAngle) {
//
// [23] XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
// [24] VersionInfo ::= S 'version' Eq ("'" VersionNum "'" | '"' VersionNum '"')
//
// [3] S ::= (#x20 | #x9 | #xD | #xA)+
//
if (startWithAngle) {
if (fReaderMgr.peekString(XMLUni::fgXMLDeclString)) {
if (fReaderMgr.skippedString(XMLUni::fgXMLDeclStringSpace)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringHTab)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringLF)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringCR))
{
return true;
}
else if (fReaderMgr.skippedString(XMLUni::fgXMLDeclStringSpaceU)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringHTabU)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringLFU)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringCRU))
{
//
// Just in case, check for upper case. If found, issue
// an error, but keep going.
//
emitError(XMLErrs::XMLDeclMustBeLowerCase);
return true;
}
}
}
else {
if (fReaderMgr.peekString(XMLUni::fgXMLString)) {
if (fReaderMgr.skippedString(XMLUni::fgXMLStringSpace)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringHTab)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringLF)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringCR))
{
return true;
}
else if (fReaderMgr.skippedString(XMLUni::fgXMLStringSpaceU)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringHTabU)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringLFU)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringCRU))
{
//
// Just in case, check for upper case. If found, issue
// an error, but keep going.
//
emitError(XMLErrs::XMLDeclMustBeLowerCase);
return true;
}
}
}
return false;
}
// ---------------------------------------------------------------------------
// XMLScanner: Helper methos
// ---------------------------------------------------------------------------
void XMLScanner::resizeElemState() {
unsigned int newSize = fElemStateSize * 2;
unsigned int* newElemState = new unsigned int[newSize];
// Copy the existing values
unsigned int index = 0;
for (; index < fElemStateSize; index++)
newElemState[index] = fElemState[index];
for (; index < newSize; index++)
newElemState[index] = 0;
// Delete the old array and udpate our members
delete [] fElemState;
fElemState = newElemState;
fElemStateSize = newSize;
}
// ---------------------------------------------------------------------------
// XMLScanner: IC activation methos
// ---------------------------------------------------------------------------
void XMLScanner::activateSelectorFor(IdentityConstraint* const ic) {
IC_Selector* selector = ic->getSelector();
if (!selector)
return;
XPathMatcher* matcher = selector->createMatcher(fFieldActivator);
fMatcherStack->addMatcher(matcher);
matcher->startDocumentFragment();
}
|
/*
* 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.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/internal/XMLScanner.hpp>
#include <xercesc/internal/ValidationContextImpl.hpp>
#include <xercesc/util/Janitor.hpp>
#include <xercesc/util/Mutexes.hpp>
#include <xercesc/util/RuntimeException.hpp>
#include <xercesc/util/UnexpectedEOFException.hpp>
#include <xercesc/util/XMLMsgLoader.hpp>
#include <xercesc/util/XMLInitializer.hpp>
#include <xercesc/framework/LocalFileInputSource.hpp>
#include <xercesc/framework/URLInputSource.hpp>
#include <xercesc/framework/XMLDocumentHandler.hpp>
#include <xercesc/framework/XMLEntityHandler.hpp>
#include <xercesc/framework/XMLPScanToken.hpp>
#include <xercesc/framework/XMLValidator.hpp>
#include <xercesc/internal/EndOfEntityException.hpp>
#include <xercesc/validators/DTD/DocTypeHandler.hpp>
#include <xercesc/validators/common/GrammarResolver.hpp>
#include <xercesc/util/OutOfMemoryException.hpp>
#include <xercesc/util/XMLResourceIdentifier.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Local static data
// ---------------------------------------------------------------------------
static XMLUInt32 gScannerId = 0;
static XMLMutex* sScannerMutex = 0;
static XMLMsgLoader* gMsgLoader = 0;
void XMLInitializer::initializeXMLScanner()
{
gMsgLoader = XMLPlatformUtils::loadMsgSet(XMLUni::fgXMLErrDomain);
if (!gMsgLoader)
XMLPlatformUtils::panic(PanicHandler::Panic_CantLoadMsgDomain);
sScannerMutex = new XMLMutex(XMLPlatformUtils::fgMemoryManager);
}
void XMLInitializer::terminateXMLScanner()
{
delete gMsgLoader;
gMsgLoader = 0;
delete sScannerMutex;
sScannerMutex = 0;
}
//
//
typedef JanitorMemFunCall<XMLScanner> CleanupType;
typedef JanitorMemFunCall<ReaderMgr> ReaderMgrResetType;
// ---------------------------------------------------------------------------
// XMLScanner: Constructors and Destructor
// ---------------------------------------------------------------------------
XMLScanner::XMLScanner(XMLValidator* const valToAdopt,
GrammarResolver* const grammarResolver,
MemoryManager* const manager)
: fBufferSize(1024 * 1024)
, fStandardUriConformant(false)
, fCalculateSrcOfs(false)
, fDoNamespaces(false)
, fExitOnFirstFatal(true)
, fValidationConstraintFatal(false)
, fInException(false)
, fStandalone(false)
, fHasNoDTD(true)
, fValidate(false)
, fValidatorFromUser(false)
, fDoSchema(false)
, fSchemaFullChecking(false)
, fIdentityConstraintChecking(true)
, fToCacheGrammar(false)
, fUseCachedGrammar(false)
, fLoadExternalDTD(true)
, fLoadSchema(true)
, fNormalizeData(true)
, fGenerateSyntheticAnnotations(false)
, fValidateAnnotations(false)
, fIgnoreCachedDTD(false)
, fIgnoreAnnotations(false)
, fDisableDefaultEntityResolution(false)
, fSkipDTDValidation(false)
, fHandleMultipleImports(false)
, fErrorCount(0)
, fEntityExpansionLimit(0)
, fEntityExpansionCount(0)
, fEmptyNamespaceId(0)
, fUnknownNamespaceId(0)
, fXMLNamespaceId(0)
, fXMLNSNamespaceId(0)
, fSchemaNamespaceId(0)
, fUIntPool(0)
, fUIntPoolRow(0)
, fUIntPoolCol(0)
, fUIntPoolRowTotal(2)
, fScannerId(0)
, fSequenceId(0)
, fAttrList(0)
, fAttrDupChkRegistry(0)
, fDocHandler(0)
, fDocTypeHandler(0)
, fEntityHandler(0)
, fErrorReporter(0)
, fErrorHandler(0)
, fPSVIHandler(0)
, fValidationContext(0)
, fEntityDeclPoolRetrieved(false)
, fReaderMgr(manager)
, fValidator(valToAdopt)
, fValScheme(Val_Never)
, fGrammarResolver(grammarResolver)
, fGrammarPoolMemoryManager(grammarResolver->getGrammarPoolMemoryManager())
, fGrammar(0)
, fRootGrammar(0)
, fURIStringPool(0)
, fRootElemName(0)
, fExternalSchemaLocation(0)
, fExternalNoNamespaceSchemaLocation(0)
, fSecurityManager(0)
, fXMLVersion(XMLReader::XMLV1_0)
, fMemoryManager(manager)
, fBufMgr(manager)
, fAttNameBuf(1023, manager)
, fAttValueBuf(1023, manager)
, fCDataBuf(1023, manager)
, fQNameBuf(1023, manager)
, fPrefixBuf(1023, manager)
, fURIBuf(1023, manager)
, fWSNormalizeBuf(1023, manager)
, fElemStack(manager)
{
CleanupType cleanup(this, &XMLScanner::cleanUp);
try
{
commonInit();
}
catch(const OutOfMemoryException&)
{
// Don't cleanup when out of memory, since executing the
// code can cause problems.
cleanup.release();
throw;
}
cleanup.release();
}
XMLScanner::XMLScanner( XMLDocumentHandler* const docHandler
, DocTypeHandler* const docTypeHandler
, XMLEntityHandler* const entityHandler
, XMLErrorReporter* const errHandler
, XMLValidator* const valToAdopt
, GrammarResolver* const grammarResolver
, MemoryManager* const manager)
: fBufferSize(1024 * 1024)
, fStandardUriConformant(false)
, fCalculateSrcOfs(false)
, fDoNamespaces(false)
, fExitOnFirstFatal(true)
, fValidationConstraintFatal(false)
, fInException(false)
, fStandalone(false)
, fHasNoDTD(true)
, fValidate(false)
, fValidatorFromUser(false)
, fDoSchema(false)
, fSchemaFullChecking(false)
, fIdentityConstraintChecking(true)
, fToCacheGrammar(false)
, fUseCachedGrammar(false)
, fLoadExternalDTD(true)
, fLoadSchema(true)
, fNormalizeData(true)
, fGenerateSyntheticAnnotations(false)
, fValidateAnnotations(false)
, fIgnoreCachedDTD(false)
, fIgnoreAnnotations(false)
, fDisableDefaultEntityResolution(false)
, fSkipDTDValidation(false)
, fHandleMultipleImports(false)
, fErrorCount(0)
, fEntityExpansionLimit(0)
, fEntityExpansionCount(0)
, fEmptyNamespaceId(0)
, fUnknownNamespaceId(0)
, fXMLNamespaceId(0)
, fXMLNSNamespaceId(0)
, fSchemaNamespaceId(0)
, fUIntPool(0)
, fUIntPoolRow(0)
, fUIntPoolCol(0)
, fUIntPoolRowTotal(2)
, fScannerId(0)
, fSequenceId(0)
, fAttrList(0)
, fAttrDupChkRegistry(0)
, fDocHandler(docHandler)
, fDocTypeHandler(docTypeHandler)
, fEntityHandler(entityHandler)
, fErrorReporter(errHandler)
, fErrorHandler(0)
, fPSVIHandler(0)
, fValidationContext(0)
, fEntityDeclPoolRetrieved(false)
, fReaderMgr(manager)
, fValidator(valToAdopt)
, fValScheme(Val_Never)
, fGrammarResolver(grammarResolver)
, fGrammarPoolMemoryManager(grammarResolver->getGrammarPoolMemoryManager())
, fGrammar(0)
, fRootGrammar(0)
, fURIStringPool(0)
, fRootElemName(0)
, fExternalSchemaLocation(0)
, fExternalNoNamespaceSchemaLocation(0)
, fSecurityManager(0)
, fXMLVersion(XMLReader::XMLV1_0)
, fMemoryManager(manager)
, fBufMgr(manager)
, fAttNameBuf(1023, manager)
, fAttValueBuf(1023, manager)
, fCDataBuf(1023, manager)
, fQNameBuf(1023, manager)
, fPrefixBuf(1023, manager)
, fURIBuf(1023, manager)
, fWSNormalizeBuf(1023, manager)
, fElemStack(manager)
{
CleanupType cleanup(this, &XMLScanner::cleanUp);
try
{
commonInit();
}
catch(const OutOfMemoryException&)
{
// Don't cleanup when out of memory, since executing the
// code can cause problems.
cleanup.release();
throw;
}
cleanup.release();
}
XMLScanner::~XMLScanner()
{
cleanUp();
}
void XMLScanner::setValidator(XMLValidator* const valToAdopt)
{
if (fValidatorFromUser)
delete fValidator;
fValidator = valToAdopt;
fValidatorFromUser = true;
initValidator(fValidator);
}
// ---------------------------------------------------------------------------
// XMLScanner: Main entry point to scan a document
// ---------------------------------------------------------------------------
void XMLScanner::scanDocument( const XMLCh* const systemId)
{
// First we try to parse it as a URL. If that fails, we assume its
// a file and try it that way.
InputSource* srcToUse = 0;
try
{
// Create a temporary URL. Since this is the primary document,
// it has to be fully qualified. If not, then assume we are just
// mistaking a file for a URL.
XMLURL tmpURL(fMemoryManager);
if (XMLURL::parse(systemId, tmpURL)) {
if (tmpURL.isRelative()) {
if (!fStandardUriConformant)
srcToUse = new (fMemoryManager) LocalFileInputSource(systemId, fMemoryManager);
else {
// since this is the top of the try/catch, cannot call ThrowXMLwithMemMgr
// emit the error directly
MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_NoProtocolPresent, fMemoryManager);
fInException = true;
emitError
(
XMLErrs::XMLException_Fatal
, e.getCode()
, e.getMessage()
);
return;
}
}
else
{
if (fStandardUriConformant && tmpURL.hasInvalidChar()) {
MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_MalformedURL, fMemoryManager);
fInException = true;
emitError
(
XMLErrs::XMLException_Fatal
, e.getCode()
, e.getMessage()
);
return;
}
srcToUse = new (fMemoryManager) URLInputSource(tmpURL, fMemoryManager);
}
}
else {
if (!fStandardUriConformant)
srcToUse = new (fMemoryManager) LocalFileInputSource(systemId, fMemoryManager);
else {
// since this is the top of the try/catch, cannot call ThrowXMLwithMemMgr
// emit the error directly
// lazy bypass ... since all MalformedURLException are fatal, no need to check the type
MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_MalformedURL, fMemoryManager);
fInException = true;
emitError
(
XMLErrs::XMLException_Fatal
, e.getCode()
, e.getMessage()
);
return;
}
}
}
catch(const XMLException& excToCatch)
{
// For any other XMLException,
// emit the error and catch any user exception thrown from here.
fInException = true;
if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning)
emitError
(
XMLErrs::XMLException_Warning
, excToCatch.getCode()
, excToCatch.getMessage()
);
else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal)
emitError
(
XMLErrs::XMLException_Fatal
, excToCatch.getCode()
, excToCatch.getMessage()
);
else
emitError
(
XMLErrs::XMLException_Error
, excToCatch.getCode()
, excToCatch.getMessage()
);
return;
}
Janitor<InputSource> janSrc(srcToUse);
scanDocument(*srcToUse);
}
void XMLScanner::scanDocument( const char* const systemId)
{
// We just delegate this to the XMLCh version after transcoding
XMLCh* tmpBuf = XMLString::transcode(systemId, fMemoryManager);
ArrayJanitor<XMLCh> janBuf(tmpBuf, fMemoryManager);
scanDocument(tmpBuf);
}
// This method begins a progressive parse. It scans through the prolog and
// returns a token to be used on subsequent scanNext() calls. If the return
// value is true, then the token is legal and ready for further use. If it
// returns false, then the scan of the prolog failed and the token is not
// going to work on subsequent scanNext() calls.
bool XMLScanner::scanFirst( const XMLCh* const systemId
, XMLPScanToken& toFill)
{
// First we try to parse it as a URL. If that fails, we assume its
// a file and try it that way.
InputSource* srcToUse = 0;
try
{
// Create a temporary URL. Since this is the primary document,
// it has to be fully qualified. If not, then assume we are just
// mistaking a file for a URL.
XMLURL tmpURL(fMemoryManager);
if (XMLURL::parse(systemId, tmpURL)) {
if (tmpURL.isRelative()) {
if (!fStandardUriConformant)
srcToUse = new (fMemoryManager) LocalFileInputSource(systemId, fMemoryManager);
else {
// since this is the top of the try/catch, cannot call ThrowXMLwithMemMgr
// emit the error directly
MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_NoProtocolPresent, fMemoryManager);
fInException = true;
emitError
(
XMLErrs::XMLException_Fatal
, e.getCode()
, e.getMessage()
);
return false;
}
}
else
{
if (fStandardUriConformant && tmpURL.hasInvalidChar()) {
MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_MalformedURL, fMemoryManager);
fInException = true;
emitError
(
XMLErrs::XMLException_Fatal
, e.getCode()
, e.getMessage()
);
return false;
}
srcToUse = new (fMemoryManager) URLInputSource(tmpURL, fMemoryManager);
}
}
else {
if (!fStandardUriConformant)
srcToUse = new (fMemoryManager) LocalFileInputSource(systemId, fMemoryManager);
else {
// since this is the top of the try/catch, cannot call ThrowXMLwithMemMgr
// emit the error directly
// lazy bypass ... since all MalformedURLException are fatal, no need to check the type
MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_MalformedURL);
fInException = true;
emitError
(
XMLErrs::XMLException_Fatal
, e.getCode()
, e.getMessage()
);
return false;
}
}
}
catch(const XMLException& excToCatch)
{
// For any other XMLException,
// emit the error and catch any user exception thrown from here.
fInException = true;
if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning)
emitError
(
XMLErrs::XMLException_Warning
, excToCatch.getCode()
, excToCatch.getMessage()
);
else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal)
emitError
(
XMLErrs::XMLException_Fatal
, excToCatch.getCode()
, excToCatch.getMessage()
);
else
emitError
(
XMLErrs::XMLException_Error
, excToCatch.getCode()
, excToCatch.getMessage()
);
return false;
}
Janitor<InputSource> janSrc(srcToUse);
return scanFirst(*srcToUse, toFill);
}
bool XMLScanner::scanFirst( const char* const systemId
, XMLPScanToken& toFill)
{
// We just delegate this to the XMLCh version after transcoding
XMLCh* tmpBuf = XMLString::transcode(systemId, fMemoryManager);
ArrayJanitor<XMLCh> janBuf(tmpBuf, fMemoryManager);
return scanFirst(tmpBuf, toFill);
}
bool XMLScanner::scanFirst( const InputSource& src
, XMLPScanToken& toFill)
{
// Bump up the sequence id for this new scan cycle. This will invalidate
// any previous tokens we've returned.
fSequenceId++;
ReaderMgrResetType resetReaderMgr(&fReaderMgr, &ReaderMgr::reset);
// Reset the scanner and its plugged in stuff for a new run. This
// resets all the data structures, creates the initial reader and
// pushes it on the stack, and sets up the base document path
scanReset(src);
// If we have a document handler, then call the start document
if (fDocHandler)
fDocHandler->startDocument();
try
{
// Scan the prolog part, which is everything before the root element
// including the DTD subsets. This is all that is done on the scan
// first.
scanProlog();
// If we got to the end of input, then its not a valid XML file.
// Else, go on to scan the content.
if (fReaderMgr.atEOF())
{
emitError(XMLErrs::EmptyMainEntity);
}
}
// NOTE:
//
// In all of the error processing below, the emitError() call MUST come
// before the flush of the reader mgr, or it will fail because it tries
// to find out the position in the XML source of the error.
catch(const XMLErrs::Codes)
{
// This is a 'first failure' exception so return failure
return false;
}
catch(const XMLValid::Codes)
{
// This is a 'first fatal error' type exit, return failure
return false;
}
catch(const XMLException& excToCatch)
{
// Emit the error and catch any user exception thrown from here. Make
// sure in all cases we flush the reader manager.
fInException = true;
try
{
if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning)
emitError
(
XMLErrs::XMLException_Warning
, excToCatch.getCode()
, excToCatch.getMessage()
);
else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal)
emitError
(
XMLErrs::XMLException_Fatal
, excToCatch.getCode()
, excToCatch.getMessage()
);
else
emitError
(
XMLErrs::XMLException_Error
, excToCatch.getCode()
, excToCatch.getMessage()
);
}
catch(const OutOfMemoryException&)
{
// This is a special case for out-of-memory
// conditions, because resetting the ReaderMgr
// can be problematic.
resetReaderMgr.release();
throw;
}
return false;
}
catch(const OutOfMemoryException&)
{
// This is a special case for out-of-memory
// conditions, because resetting the ReaderMgr
// can be problematic.
resetReaderMgr.release();
throw;
}
// Fill in the caller's token to make it legal and return success
toFill.set(fScannerId, fSequenceId);
// Release the object that will reset the ReaderMgr, since there's
// more to scan.
resetReaderMgr.release();
return true;
}
void XMLScanner::scanReset(XMLPScanToken& token)
{
// Make sure this token is still legal
if (!isLegalToken(token))
ThrowXMLwithMemMgr(RuntimeException, XMLExcepts::Scan_BadPScanToken, fMemoryManager);
// Reset the reader manager
fReaderMgr.reset();
// And invalidate any tokens by bumping our sequence number
fSequenceId++;
// Reset our error count
fErrorCount = 0;
}
void XMLScanner::setParseSettings(XMLScanner* const refScanner)
{
setDocHandler(refScanner->getDocHandler());
setDocTypeHandler(refScanner->getDocTypeHandler());
setErrorHandler(refScanner->getErrorHandler());
setErrorReporter(refScanner->getErrorReporter());
setEntityHandler(refScanner->getEntityHandler());
setDoNamespaces(refScanner->getDoNamespaces());
setDoSchema(refScanner->getDoSchema());
setCalculateSrcOfs(refScanner->getCalculateSrcOfs());
setStandardUriConformant(refScanner->getStandardUriConformant());
setExitOnFirstFatal(refScanner->getExitOnFirstFatal());
setValidationConstraintFatal(refScanner->getValidationConstraintFatal());
setIdentityConstraintChecking(refScanner->getIdentityConstraintChecking());
setValidationSchemaFullChecking(refScanner->getValidationSchemaFullChecking());
cacheGrammarFromParse(refScanner->isCachingGrammarFromParse());
useCachedGrammarInParse(refScanner->isUsingCachedGrammarInParse());
setLoadExternalDTD(refScanner->getLoadExternalDTD());
setLoadSchema(refScanner->getLoadSchema());
setNormalizeData(refScanner->getNormalizeData());
setExternalSchemaLocation(refScanner->getExternalSchemaLocation());
setExternalNoNamespaceSchemaLocation(refScanner->getExternalNoNamespaceSchemaLocation());
setValidationScheme(refScanner->getValidationScheme());
setSecurityManager(refScanner->getSecurityManager());
setPSVIHandler(refScanner->getPSVIHandler());
}
// ---------------------------------------------------------------------------
// XMLScanner: Private helper methods.
// ---------------------------------------------------------------------------
// This method handles the common initialization, to avoid having to do
// it redundantly in multiple constructors.
void XMLScanner::commonInit()
{
// We have to do a little init that involves statics, so we have to
// use the mutex to protect it.
{
XMLMutexLock lockInit(sScannerMutex);
// And assign ourselves the next available scanner id
fScannerId = ++gScannerId;
}
// Create the attribute list, which is used to store attribute values
// during start tag processing. Give it a reasonable initial size that
// will serve for most folks, though it will grow as required.
fAttrList = new (fMemoryManager) RefVectorOf<XMLAttr>(32, true, fMemoryManager);
// Create the id ref list. This is used to enforce XML 1.0 ID ref
// semantics, i.e. all id refs must refer to elements that exist
fValidationContext = new (fMemoryManager) ValidationContextImpl(fMemoryManager);
fValidationContext->setElemStack(&fElemStack);
fValidationContext->setScanner(this);
// Create the GrammarResolver
//fGrammarResolver = new GrammarResolver();
// create initial, 64-element, fUIntPool
fUIntPool = (unsigned int **)fMemoryManager->allocate(sizeof(unsigned int *) *fUIntPoolRowTotal);
memset(fUIntPool, 0, sizeof(unsigned int *) * fUIntPoolRowTotal);
fUIntPool[0] = (unsigned int *)fMemoryManager->allocate(sizeof(unsigned int) << 6);
memset(fUIntPool[0], 0, sizeof(unsigned int) << 6);
// Register self as handler for XMLBufferFull events on the CDATA buffer
fCDataBuf.setFullHandler(this, fBufferSize);
if (fValidator) {
fValidatorFromUser = true;
initValidator(fValidator);
}
}
void XMLScanner::cleanUp()
{
delete fAttrList;
delete fAttrDupChkRegistry;
delete fValidationContext;
fMemoryManager->deallocate(fRootElemName);//delete [] fRootElemName;
fMemoryManager->deallocate(fExternalSchemaLocation);//delete [] fExternalSchemaLocation;
fMemoryManager->deallocate(fExternalNoNamespaceSchemaLocation);//delete [] fExternalNoNamespaceSchemaLocation;
// delete fUIntPool
if (fUIntPool)
{
for (unsigned int i=0; i<=fUIntPoolRow; i++)
{
fMemoryManager->deallocate(fUIntPool[i]);
}
fMemoryManager->deallocate(fUIntPool);
}
}
void XMLScanner::initValidator(XMLValidator* theValidator) {
// Tell the validator about the stuff it needs to know in order to
// do its work.
theValidator->setScannerInfo(this, &fReaderMgr, &fBufMgr);
theValidator->setErrorReporter(fErrorReporter);
}
// ---------------------------------------------------------------------------
// XMLScanner: Error emitting methods
// ---------------------------------------------------------------------------
// These methods are called whenever the scanner wants to emit an error.
// It handles getting the message loaded, doing token replacement, etc...
// and then calling the error handler, if its installed.
bool XMLScanner::emitErrorWillThrowException(const XMLErrs::Codes toEmit)
{
if (XMLErrs::isFatal(toEmit) && fExitOnFirstFatal && !fInException)
return true;
return false;
}
void XMLScanner::emitError(const XMLErrs::Codes toEmit)
{
// Bump the error count if it is not a warning
if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)
incrementErrorCount();
if (fErrorReporter)
{
// Load the message into a local for display
const XMLSize_t msgSize = 1023;
XMLCh errText[msgSize + 1];
if (!gMsgLoader->loadMsg(toEmit, errText, msgSize))
{
// <TBD> Probably should load a default msg here
}
// Create a LastExtEntityInfo structure and get the reader manager
// to fill it in for us. This will give us the information about
// the last reader on the stack that was an external entity of some
// sort (i.e. it will ignore internal entities.
ReaderMgr::LastExtEntityInfo lastInfo;
fReaderMgr.getLastExtEntityInfo(lastInfo);
fErrorReporter->error
(
toEmit
, XMLUni::fgXMLErrDomain
, XMLErrs::errorType(toEmit)
, errText
, lastInfo.systemId
, lastInfo.publicId
, lastInfo.lineNumber
, lastInfo.colNumber
);
}
// Bail out if its fatal an we are to give up on the first fatal error
if (emitErrorWillThrowException(toEmit))
throw toEmit;
}
void XMLScanner::emitError( const XMLErrs::Codes toEmit
, const XMLCh* const text1
, const XMLCh* const text2
, const XMLCh* const text3
, const XMLCh* const text4)
{
// Bump the error count if it is not a warning
if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)
incrementErrorCount();
if (fErrorReporter)
{
// Load the message into alocal and replace any tokens found in
// the text.
const XMLSize_t maxChars = 2047;
XMLCh errText[maxChars + 1];
if (!gMsgLoader->loadMsg(toEmit, errText, maxChars, text1, text2, text3, text4, fMemoryManager))
{
// <TBD> Should probably load a default message here
}
// Create a LastExtEntityInfo structure and get the reader manager
// to fill it in for us. This will give us the information about
// the last reader on the stack that was an external entity of some
// sort (i.e. it will ignore internal entities.
ReaderMgr::LastExtEntityInfo lastInfo;
fReaderMgr.getLastExtEntityInfo(lastInfo);
fErrorReporter->error
(
toEmit
, XMLUni::fgXMLErrDomain
, XMLErrs::errorType(toEmit)
, errText
, lastInfo.systemId
, lastInfo.publicId
, lastInfo.lineNumber
, lastInfo.colNumber
);
}
// Bail out if its fatal an we are to give up on the first fatal error
if (emitErrorWillThrowException(toEmit))
throw toEmit;
}
void XMLScanner::emitError( const XMLErrs::Codes toEmit
, const char* const text1
, const char* const text2
, const char* const text3
, const char* const text4)
{
// Bump the error count if it is not a warning
if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)
incrementErrorCount();
if (fErrorReporter)
{
// Load the message into alocal and replace any tokens found in
// the text.
const XMLSize_t maxChars = 2047;
XMLCh errText[maxChars + 1];
if (!gMsgLoader->loadMsg(toEmit, errText, maxChars, text1, text2, text3, text4, fMemoryManager))
{
// <TBD> Should probably load a default message here
}
// Create a LastExtEntityInfo structure and get the reader manager
// to fill it in for us. This will give us the information about
// the last reader on the stack that was an external entity of some
// sort (i.e. it will ignore internal entities.
ReaderMgr::LastExtEntityInfo lastInfo;
fReaderMgr.getLastExtEntityInfo(lastInfo);
fErrorReporter->error
(
toEmit
, XMLUni::fgXMLErrDomain
, XMLErrs::errorType(toEmit)
, errText
, lastInfo.systemId
, lastInfo.publicId
, lastInfo.lineNumber
, lastInfo.colNumber
);
}
// Bail out if its fatal an we are to give up on the first fatal error
if (emitErrorWillThrowException(toEmit))
throw toEmit;
}
void XMLScanner::emitError( const XMLErrs::Codes toEmit
, const XMLExcepts::Codes originalExceptCode
, const XMLCh* const text1
, const XMLCh* const text2
, const XMLCh* const text3
, const XMLCh* const text4)
{
// Bump the error count if it is not a warning
if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)
incrementErrorCount();
if (fErrorReporter)
{
// Load the message into alocal and replace any tokens found in
// the text.
const XMLSize_t maxChars = 2047;
XMLCh errText[maxChars + 1];
if (!gMsgLoader->loadMsg(toEmit, errText, maxChars, text1, text2, text3, text4, fMemoryManager))
{
// <TBD> Should probably load a default message here
}
// Create a LastExtEntityInfo structure and get the reader manager
// to fill it in for us. This will give us the information about
// the last reader on the stack that was an external entity of some
// sort (i.e. it will ignore internal entities.
ReaderMgr::LastExtEntityInfo lastInfo;
fReaderMgr.getLastExtEntityInfo(lastInfo);
fErrorReporter->error
(
originalExceptCode
, XMLUni::fgExceptDomain //fgXMLErrDomain
, XMLErrs::errorType(toEmit)
, errText
, lastInfo.systemId
, lastInfo.publicId
, lastInfo.lineNumber
, lastInfo.colNumber
);
}
// Bail out if its fatal an we are to give up on the first fatal error
if (emitErrorWillThrowException(toEmit))
throw toEmit;
}
// ---------------------------------------------------------------------------
// XMLScanner: Getter methods
// ---------------------------------------------------------------------------
// This method allows the caller to query the current location of the scanner.
// It will return the sys/public ids of the current entity, and the line/col
// position within it.
//
// NOTE: This API returns the location with the last external file. So if its
// currently scanning an entity, the position returned will be the end of
// the entity reference in the file that had the reference.
//
/*bool
XMLScanner::getLastExtLocation( XMLCh* const sysIdToFill
, const unsigned int maxSysIdChars
, XMLCh* const pubIdToFill
, const unsigned int maxPubIdChars
, XMLSSize_t& lineToFill
, XMLSSize_t& colToFill) const
{
// Create a local info object and get it filled in by the reader manager
ReaderMgr::LastExtEntityInfo lastInfo;
fReaderMgr.getLastExtEntityInfo(lastInfo);
// Fill in the line and column number
lineToFill = lastInfo.lineNumber;
colToFill = lastInfo.colNumber;
// And copy over as much of the ids as will fit
sysIdToFill[0] = 0;
if (lastInfo.systemId)
{
if (XMLString::stringLen(lastInfo.systemId) > maxSysIdChars)
return false;
XMLString::copyString(sysIdToFill, lastInfo.systemId);
}
pubIdToFill[0] = 0;
if (lastInfo.publicId)
{
if (XMLString::stringLen(lastInfo.publicId) > maxPubIdChars)
return false;
XMLString::copyString(pubIdToFill, lastInfo.publicId);
}
return true;
}*/
// ---------------------------------------------------------------------------
// XMLScanner: Private scanning methods
// ---------------------------------------------------------------------------
// This method is called after the end of the root element, to handle
// any miscellaneous stuff hanging around.
void XMLScanner::scanMiscellaneous()
{
// Get a buffer for this work
XMLBufBid bbCData(&fBufMgr);
while (true)
{
try
{
const XMLCh nextCh = fReaderMgr.peekNextChar();
// Watch for end of file and break out
if (!nextCh)
break;
if (nextCh == chOpenAngle)
{
if (checkXMLDecl(true))
{
// Can't have an XML decl here
emitError(XMLErrs::NotValidAfterContent);
fReaderMgr.skipPastChar(chCloseAngle);
}
else if (fReaderMgr.skippedString(XMLUni::fgPIString))
{
scanPI();
}
else if (fReaderMgr.skippedString(XMLUni::fgCommentString))
{
scanComment();
}
else
{
// This can't be possible, so just give up
emitError(XMLErrs::ExpectedCommentOrPI);
fReaderMgr.skipPastChar(chCloseAngle);
}
}
else if (fReaderMgr.getCurrentReader()->isWhitespace(nextCh))
{
// If we have a doc handler, then gather up the spaces and
// call back. Otherwise, just skip over whitespace.
if (fDocHandler)
{
fReaderMgr.getSpaces(bbCData.getBuffer());
fDocHandler->ignorableWhitespace
(
bbCData.getRawBuffer()
, bbCData.getLen()
, false
);
}
else
{
fReaderMgr.skipPastSpaces();
}
}
else
{
emitError(XMLErrs::ExpectedCommentOrPI);
fReaderMgr.skipPastChar(chCloseAngle);
}
}
catch(const EndOfEntityException&)
{
// Some entity leaked out of the content part of the document. Issue
// a warning and keep going.
emitError(XMLErrs::EntityPropogated);
}
}
}
// Scans a PI and calls the appropriate callbacks. At entry we have just
// scanned the <? part, and need to now start on the PI target name.
void XMLScanner::scanPI()
{
const XMLCh* namePtr = 0;
const XMLCh* targetPtr = 0;
// If there are any spaces here, then warn about it. If we aren't in
// 'first error' mode, then we'll come back and can easily pick up
// again by just skipping them.
if (fReaderMgr.lookingAtSpace())
{
emitError(XMLErrs::PINameExpected);
fReaderMgr.skipPastSpaces();
}
// Get a buffer for the PI name and scan it in
XMLBufBid bbName(&fBufMgr);
if (!fReaderMgr.getName(bbName.getBuffer()))
{
emitError(XMLErrs::PINameExpected);
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
// Point the name pointer at the raw data
namePtr = bbName.getRawBuffer();
// See if it is some form of 'xml' and emit a warning
//if (!XMLString::compareIString(namePtr, XMLUni::fgXMLString))
if (bbName.getLen() == 3 &&
(((namePtr[0] == chLatin_x) || (namePtr[0] == chLatin_X)) &&
((namePtr[1] == chLatin_m) || (namePtr[1] == chLatin_M)) &&
((namePtr[2] == chLatin_l) || (namePtr[2] == chLatin_L))))
emitError(XMLErrs::NoPIStartsWithXML);
// If namespaces are enabled, then no colons allowed
if (fDoNamespaces)
{
if (XMLString::indexOf(namePtr, chColon) != -1)
emitError(XMLErrs::ColonNotLegalWithNS);
}
// If we don't hit a space next, then the PI has no target. If we do
// then get out the target. Get a buffer for it as well
XMLBufBid bbTarget(&fBufMgr);
if (fReaderMgr.skippedSpace())
{
// Skip any leading spaces
fReaderMgr.skipPastSpaces();
bool gotLeadingSurrogate = false;
// It does have a target, so lets move on to deal with that.
while (1)
{
const XMLCh nextCh = fReaderMgr.getNextChar();
// Watch for an end of file, which is always bad here
if (!nextCh)
{
emitError(XMLErrs::UnterminatedPI);
ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager);
}
// Watch for potential terminating character
if (nextCh == chQuestion)
{
// It must be followed by '>' to be a termination of the target
if (fReaderMgr.skippedChar(chCloseAngle))
break;
}
// Check for correct surrogate pairs
if ((nextCh >= 0xD800) && (nextCh <= 0xDBFF))
{
if (gotLeadingSurrogate)
emitError(XMLErrs::Expected2ndSurrogateChar);
else
gotLeadingSurrogate = true;
}
else
{
if (gotLeadingSurrogate)
{
if ((nextCh < 0xDC00) || (nextCh > 0xDFFF))
emitError(XMLErrs::Expected2ndSurrogateChar);
}
// Its got to at least be a valid XML character
else if (!fReaderMgr.getCurrentReader()->isXMLChar(nextCh)) {
XMLCh tmpBuf[9];
XMLString::binToText
(
nextCh
, tmpBuf
, 8
, 16
, fMemoryManager
);
emitError(XMLErrs::InvalidCharacter, tmpBuf);
}
gotLeadingSurrogate = false;
}
bbTarget.append(nextCh);
}
}
else
{
// No target, but make sure its terminated ok
if (!fReaderMgr.skippedChar(chQuestion))
{
emitError(XMLErrs::UnterminatedPI);
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
if (!fReaderMgr.skippedChar(chCloseAngle))
{
emitError(XMLErrs::UnterminatedPI);
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
}
// Point the target pointer at the raw data
targetPtr = bbTarget.getRawBuffer();
// If we have a handler, then call it
if (fDocHandler)
{
fDocHandler->docPI
(
namePtr
, targetPtr
);
}
//mark PI is seen within the current element
if (! fElemStack.isEmpty())
fElemStack.setCommentOrPISeen();
}
// Scans all the input from the start of the file to the root element.
// There does not have to be anything in the prolog necessarily, but usually
// there is at least an XMLDecl.
//
// On exit from here we are either at the end of the file or about to read
// the opening < of the root element.
void XMLScanner::scanProlog()
{
bool sawDocTypeDecl = false;
// Get a buffer for whitespace processing
XMLBufBid bbCData(&fBufMgr);
// Loop through the prolog. If there is no content, this could go all
// the way to the end of the file.
try
{
while (true)
{
const XMLCh nextCh = fReaderMgr.peekNextChar();
if (nextCh == chOpenAngle)
{
// Ok, it could be the xml decl, a comment, the doc type line,
// or the start of the root element.
if (checkXMLDecl(true))
{
// There shall be at lease --ONE-- space in between
// the tag '<?xml' and the VersionInfo.
//
// If we are not at line 1, col 6, then the decl was not
// the first text, so its invalid.
const XMLReader* curReader = fReaderMgr.getCurrentReader();
if ((curReader->getLineNumber() != 1)
|| (curReader->getColumnNumber() != 7))
{
emitError(XMLErrs::XMLDeclMustBeFirst);
}
scanXMLDecl(Decl_XML);
}
else if (fReaderMgr.skippedString(XMLUni::fgPIString))
{
scanPI();
}
else if (fReaderMgr.skippedString(XMLUni::fgCommentString))
{
scanComment();
}
else if (fReaderMgr.skippedString(XMLUni::fgDocTypeString))
{
if (sawDocTypeDecl) {
emitError(XMLErrs::DuplicateDocTypeDecl);
}
scanDocTypeDecl();
sawDocTypeDecl = true;
// if reusing grammar, this has been validated already in first scan
// skip for performance
if (fValidate && !fGrammar->getValidated()) {
// validate the DTD scan so far
fValidator->preContentValidation(fUseCachedGrammar, true);
}
}
else
{
// Assume its the start of the root element
return;
}
}
else if (fReaderMgr.getCurrentReader()->isWhitespace(nextCh))
{
// If we have a document handler then gather up the
// whitespace and call back. Otherwise just skip over spaces.
if (fDocHandler)
{
fReaderMgr.getSpaces(bbCData.getBuffer());
fDocHandler->ignorableWhitespace
(
bbCData.getRawBuffer()
, bbCData.getLen()
, false
);
}
else
{
fReaderMgr.skipPastSpaces();
}
}
else
{
emitError(XMLErrs::InvalidDocumentStructure);
// Watch for end of file and break out
if (!nextCh)
break;
else
fReaderMgr.skipPastChar(chCloseAngle);
}
}
}
catch(const EndOfEntityException&)
{
// We should never get an end of entity here. They should only
// occur within the doc type scanning method, and not leak out to
// here.
emitError
(
XMLErrs::UnexpectedEOE
, "in prolog"
);
}
}
// Scans the <?xml .... ?> line. This stuff is all sequential so we don't
// do any state machine loop here. We just bull straight through it. It ends
// past the closing bracket. If there is a document handler, then its called
// on the XMLDecl callback.
//
// On entry, the <?xml has been scanned, and we pick it up from there.
//
// NOTE: In order to provide good recovery from bad XML here, we try to be
// very flexible. No matter what order the stuff is in, we'll keep going
// though we'll issue errors.
//
// The parameter tells us which type of decl we should expect, Text or XML.
// [23] XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
// [77] TextDecl::= '<?xml' VersionInfo? EncodingDecl S? '?>'
void XMLScanner::scanXMLDecl(const DeclTypes type)
{
// Get us some buffers to use
XMLBufBid bbVersion(&fBufMgr);
XMLBufBid bbEncoding(&fBufMgr);
XMLBufBid bbStand(&fBufMgr);
XMLBufBid bbDummy(&fBufMgr);
XMLBufBid bbName(&fBufMgr);
// We use this little enum and array to keep up with what we found
// and what order we found them in. This lets us get them free form
// without too much overhead, but still know that they were in the
// wrong order.
enum Strings
{
VersionString
, EncodingString
, StandaloneString
, UnknownString
, StringCount
};
int flags[StringCount] = { -1, -1, -1, -1 };
// Also set up a list of buffers in the right order so that we know
// where to put stuff.
XMLBuffer* buffers[StringCount] ;
buffers[0] = &bbVersion.getBuffer();
buffers[1] = &bbEncoding.getBuffer();
buffers[2] = &bbStand.getBuffer();
buffers[3] = &bbDummy.getBuffer();
int curCount = 0;
Strings curString;
XMLBuffer& nameBuf = bbName.getBuffer();
while (true)
{
// Skip any spaces
const bool spaceCount = fReaderMgr.skipPastSpaces(true);
// If we are looking at a question mark, then break out
if (fReaderMgr.lookingAtChar(chQuestion))
break;
// If this is not the first string, then we require the spaces
if (!spaceCount && curCount)
emitError(XMLErrs::ExpectedWhitespace);
// Get characters up to the next whitespace or equal's sign.
if (!scanUpToWSOr(nameBuf, chEqual))
emitError(XMLErrs::ExpectedDeclString);
// See if it matches any of our expected strings
if (XMLString::equals(nameBuf.getRawBuffer(), XMLUni::fgVersionString))
curString = VersionString;
else if (XMLString::equals(nameBuf.getRawBuffer(), XMLUni::fgEncodingString))
curString = EncodingString;
else if (XMLString::equals(nameBuf.getRawBuffer(), XMLUni::fgStandaloneString))
curString = StandaloneString;
else
curString = UnknownString;
// If its an unknown string, then give that error. Else check to
// see if this one has been done already and give that error.
if (curString == UnknownString)
emitError(XMLErrs::ExpectedDeclString, nameBuf.getRawBuffer());
else if (flags[curString] != -1)
emitError(XMLErrs::DeclStringRep, nameBuf.getRawBuffer());
else if (flags[curString] == -1)
flags[curString] = ++curCount;
// Scan for an equal's sign. If we don't find it, issue an error
// but keep trying to go on.
if (!scanEq(true))
emitError(XMLErrs::ExpectedEqSign);
// Get a quote string into the buffer for the string that we are
// currently working on.
if (!getQuotedString(*buffers[curString]))
{
emitError(XMLErrs::ExpectedQuotedString);
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
// And validate the value according which one it was
const XMLCh* rawValue = buffers[curString]->getRawBuffer();
if (curString == VersionString)
{
if (XMLString::equals(rawValue, XMLUni::fgVersion1_1)) {
if (type == Decl_XML) {
fXMLVersion = XMLReader::XMLV1_1;
fReaderMgr.setXMLVersion(XMLReader::XMLV1_1);
}
else {
if (fXMLVersion != XMLReader::XMLV1_1)
emitError(XMLErrs::UnsupportedXMLVersion, rawValue);
}
}
else if (XMLString::equals(rawValue, XMLUni::fgVersion1_0)) {
if (type == Decl_XML) {
fXMLVersion = XMLReader::XMLV1_0;
fReaderMgr.setXMLVersion(XMLReader::XMLV1_0);
}
}
else
emitError(XMLErrs::UnsupportedXMLVersion, rawValue);
}
else if (curString == EncodingString)
{
if (!XMLString::isValidEncName(rawValue))
emitError(XMLErrs::BadXMLEncoding, rawValue);
}
else if (curString == StandaloneString)
{
if (XMLString::equals(rawValue, XMLUni::fgYesString))
fStandalone = true;
else if (XMLString::equals(rawValue, XMLUni::fgNoString))
fStandalone = false;
else
{
emitError(XMLErrs::BadStandalone);
//if (!XMLString::compareIString(rawValue, XMLUni::fgYesString))
//else if (!XMLString::compareIString(rawValue, XMLUni::fgNoString))
if (buffers[curString]->getLen() == 3 &&
(((rawValue[0] == chLatin_y) || (rawValue[0] == chLatin_Y)) &&
((rawValue[1] == chLatin_e) || (rawValue[1] == chLatin_E)) &&
((rawValue[2] == chLatin_s) || (rawValue[2] == chLatin_S))))
fStandalone = true;
else if (buffers[curString]->getLen() == 2 &&
(((rawValue[0] == chLatin_n) || (rawValue[0] == chLatin_N)) &&
((rawValue[1] == chLatin_o) || (rawValue[1] == chLatin_O))))
fStandalone = false;
}
}
}
// Make sure that the strings present are in order. We don't care about
// which ones are present at this point, just that any there are in the
// right order.
int curTop = 0;
for (int index = VersionString; index < StandaloneString; index++)
{
if (flags[index] != -1)
{
if (flags[index] != curTop + 1)
{
emitError(XMLErrs::DeclStringsInWrongOrder);
break;
}
curTop = flags[index];
}
}
// If its an XML decl, the version must be present.
// If its a Text decl, then encoding must be present AND standalone must not be present.
if ((type == Decl_XML) && (flags[VersionString] == -1))
emitError(XMLErrs::XMLVersionRequired);
else if (type == Decl_Text) {
if (flags[StandaloneString] != -1)
emitError(XMLErrs::StandaloneNotLegal);
if (flags[EncodingString] == -1)
emitError(XMLErrs::EncodingRequired);
}
if (!fReaderMgr.skippedChar(chQuestion))
{
emitError(XMLErrs::UnterminatedXMLDecl);
fReaderMgr.skipPastChar(chCloseAngle);
}
else if (!fReaderMgr.skippedChar(chCloseAngle))
{
emitError(XMLErrs::UnterminatedXMLDecl);
fReaderMgr.skipPastChar(chCloseAngle);
}
// Do this before we possibly update the reader with the
// actual encoding string. Otherwise, we will pass the wrong thing
// for the last parameter!
const XMLCh* actualEnc = fReaderMgr.getCurrentEncodingStr();
// Ok, we've now seen the real encoding string, if there was one, so
// lets call back on the current reader and tell it what the real
// encoding string was. If it fails, that's because it represents some
// sort of contradiction with the autosensed format, and it keeps the
// original encoding.
//
// NOTE: This can fail for a number of reasons, such as a bogus encoding
// name or because its in flagrant contradiction of the auto-sensed
// format.
if (flags[EncodingString] != -1)
{
if (!fReaderMgr.getCurrentReader()->setEncoding(bbEncoding.getRawBuffer()))
emitError(XMLErrs::ContradictoryEncoding, bbEncoding.getRawBuffer());
else
actualEnc = bbEncoding.getRawBuffer();
}
// If we have a document handler then call the XML Decl callback.
if (type == Decl_XML)
{
if (fDocHandler)
fDocHandler->XMLDecl
(
bbVersion.getRawBuffer()
, bbEncoding.getRawBuffer()
, bbStand.getRawBuffer()
, actualEnc
);
}
else if (type == Decl_Text)
{
if (fDocTypeHandler)
fDocTypeHandler->TextDecl
(
bbVersion.getRawBuffer()
, bbEncoding.getRawBuffer()
);
}
}
const XMLCh* XMLScanner::getURIText(const unsigned int uriId) const
{
if (fURIStringPool->exists(uriId)) {
// Look up the URI in the string pool and return its id
const XMLCh* value = fURIStringPool->getValueForId(uriId);
if (!value)
return XMLUni::fgZeroLenString;
return value;
}
else
return XMLUni::fgZeroLenString;
}
bool XMLScanner::getURIText( const unsigned int uriId
, XMLBuffer& uriBufToFill) const
{
if (fURIStringPool->exists(uriId)) {
// Look up the URI in the string pool and return its id
const XMLCh* value = fURIStringPool->getValueForId(uriId);
if (!value)
return false;
uriBufToFill.set(value);
return true;
}
else
return false;
}
bool XMLScanner::checkXMLDecl(bool startWithAngle) {
// [23] XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
// [24] VersionInfo ::= S 'version' Eq ("'" VersionNum "'" | '"' VersionNum '"')
//
// [3] S ::= (#x20 | #x9 | #xD | #xA)+
if (startWithAngle) {
if (fReaderMgr.peekString(XMLUni::fgXMLDeclString)) {
if (fReaderMgr.skippedString(XMLUni::fgXMLDeclStringSpace)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringHTab)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringLF)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringCR))
{
return true;
}
}
else if (fReaderMgr.skippedString(XMLUni::fgXMLDeclStringSpaceU)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringHTabU)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringLFU)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringCRU))
{
// Just in case, check for upper case. If found, issue
// an error, but keep going.
emitError(XMLErrs::XMLDeclMustBeLowerCase);
return true;
}
}
else {
if (fReaderMgr.peekString(XMLUni::fgXMLString)) {
if (fReaderMgr.skippedString(XMLUni::fgXMLStringSpace)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringHTab)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringLF)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringCR))
{
return true;
}
}
else if (fReaderMgr.skippedString(XMLUni::fgXMLStringSpaceU)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringHTabU)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringLFU)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringCRU))
{
// Just in case, check for upper case. If found, issue
// an error, but keep going.
emitError(XMLErrs::XMLDeclMustBeLowerCase);
return true;
}
}
return false;
}
// ---------------------------------------------------------------------------
// XMLScanner: Grammar preparsing
// ---------------------------------------------------------------------------
Grammar* XMLScanner::loadGrammar(const XMLCh* const systemId
, const short grammarType
, const bool toCache)
{
InputSource* srcToUse = 0;
if (fEntityHandler){
ReaderMgr::LastExtEntityInfo lastInfo;
fReaderMgr.getLastExtEntityInfo(lastInfo);
XMLResourceIdentifier resourceIdentifier(XMLResourceIdentifier::ExternalEntity,
systemId, 0, XMLUni::fgZeroLenString, lastInfo.systemId,
&fReaderMgr);
srcToUse = fEntityHandler->resolveEntity(&resourceIdentifier);
}
// First we try to parse it as a URL. If that fails, we assume its
// a file and try it that way.
if (!srcToUse) {
if (fDisableDefaultEntityResolution)
return 0;
try
{
// Create a temporary URL. Since this is the primary document,
// it has to be fully qualified. If not, then assume we are just
// mistaking a file for a URL.
XMLURL tmpURL(fMemoryManager);
if (XMLURL::parse(systemId, tmpURL)) {
if (tmpURL.isRelative())
{
if (!fStandardUriConformant)
srcToUse = new (fMemoryManager) LocalFileInputSource(systemId, fMemoryManager);
else {
// since this is the top of the try/catch, cannot call ThrowXMLwithMemMgr
// emit the error directly
MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_NoProtocolPresent, fMemoryManager);
fInException = true;
emitError
(
XMLErrs::XMLException_Fatal
, e.getCode()
, e.getMessage()
);
return 0;
}
}
else
{
if (fStandardUriConformant && tmpURL.hasInvalidChar()) {
MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_MalformedURL, fMemoryManager);
fInException = true;
emitError
(
XMLErrs::XMLException_Fatal
, e.getCode()
, e.getMessage()
);
return 0;
}
srcToUse = new (fMemoryManager) URLInputSource(tmpURL, fMemoryManager);
}
}
else
{
if (!fStandardUriConformant)
srcToUse = new (fMemoryManager) LocalFileInputSource(systemId, fMemoryManager);
else {
// since this is the top of the try/catch, cannot call ThrowXMLwithMemMgr
// emit the error directly
// lazy bypass ... since all MalformedURLException are fatal, no need to check the type
MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_MalformedURL);
fInException = true;
emitError
(
XMLErrs::XMLException_Fatal
, e.getCode()
, e.getMessage()
);
return 0;
}
}
}
catch(const XMLException& excToCatch)
{
// For any other XMLException,
// emit the error and catch any user exception thrown from here.
fInException = true;
if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning)
emitError
(
XMLErrs::XMLException_Warning
, excToCatch.getCode()
, excToCatch.getMessage()
);
else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal)
emitError
(
XMLErrs::XMLException_Fatal
, excToCatch.getCode()
, excToCatch.getMessage()
);
else
emitError
(
XMLErrs::XMLException_Error
, excToCatch.getCode()
, excToCatch.getMessage()
);
return 0;
}
}
Janitor<InputSource> janSrc(srcToUse);
return loadGrammar(*srcToUse, grammarType, toCache);
}
Grammar* XMLScanner::loadGrammar(const char* const systemId
, const short grammarType
, const bool toCache)
{
// We just delegate this to the XMLCh version after transcoding
XMLCh* tmpBuf = XMLString::transcode(systemId, fMemoryManager);
ArrayJanitor<XMLCh> janBuf(tmpBuf, fMemoryManager);
return loadGrammar(tmpBuf, grammarType, toCache);
}
// ---------------------------------------------------------------------------
// XMLScanner: Setter methods
// ---------------------------------------------------------------------------
void XMLScanner::setURIStringPool(XMLStringPool* const stringPool)
{
fURIStringPool = stringPool;
fEmptyNamespaceId = fURIStringPool->addOrFind(XMLUni::fgZeroLenString);
fUnknownNamespaceId = fURIStringPool->addOrFind(XMLUni::fgUnknownURIName);
fXMLNamespaceId = fURIStringPool->addOrFind(XMLUni::fgXMLURIName);
fXMLNSNamespaceId = fURIStringPool->addOrFind(XMLUni::fgXMLNSURIName);
}
// ---------------------------------------------------------------------------
// XMLScanner: Private helper methods
// ---------------------------------------------------------------------------
/***
* In reusing grammars (cacheing grammar from parse, or use cached grammar), internal
* dtd is allowed conditionally.
*
* In the case of cacheing grammar from parse, it is NOT allowed.
*
* In the case of use cached grammar,
* if external dtd is present and it is parsed before, then it is not allowed,
* otherwise it is allowed.
*
***/
void XMLScanner::checkInternalDTD(bool hasExtSubset
,const XMLCh* const sysId
,const XMLCh* const pubId)
{
if (fToCacheGrammar)
ThrowXMLwithMemMgr(RuntimeException, XMLExcepts::Val_CantHaveIntSS, fMemoryManager);
if (fUseCachedGrammar && hasExtSubset && !fIgnoreCachedDTD)
{
InputSource* sysIdSrc = resolveSystemId(sysId, pubId);
if (sysIdSrc) {
Janitor<InputSource> janSysIdSrc(sysIdSrc);
Grammar* grammar = fGrammarResolver->getGrammar(sysIdSrc->getSystemId());
if (grammar && grammar->getGrammarType() == Grammar::DTDGrammarType)
{
ThrowXMLwithMemMgr(RuntimeException, XMLExcepts::Val_CantHaveIntSS, fMemoryManager);
}
}
}
}
// This method is called after the content scan to insure that all the
// ID/IDREF attributes match up (i.e. that all IDREFs refer to IDs.) This is
// an XML 1.0 rule, so we can do here in the core.
void XMLScanner::checkIDRefs()
{
// Iterate the id ref list. If we find any entries here which are used
// but not declared, then that's an error.
RefHashTableOfEnumerator<XMLRefInfo> refEnum(fValidationContext->getIdRefList(), false, fMemoryManager);
while (refEnum.hasMoreElements())
{
// Get a ref to the current element
const XMLRefInfo& curRef = refEnum.nextElement();
// If its used but not declared, then its an error
if (!curRef.getDeclared() && curRef.getUsed() && fValidate)
fValidator->emitError(XMLValid::IDNotDeclared, curRef.getRefName());
}
}
// This just does a simple check that the passed progressive scan token is
// legal for this scanner.
bool XMLScanner::isLegalToken(const XMLPScanToken& toCheck)
{
return ((fScannerId == toCheck.fScannerId)
&& (fSequenceId == toCheck.fSequenceId));
}
// This method will handle figuring out what the next top level token is
// in the input stream. It will return an enumerated value that indicates
// what it believes the next XML level token must be. It will eat as many
// chars are required to figure out what is next.
XMLScanner::XMLTokens XMLScanner::senseNextToken(XMLSize_t& orgReader)
{
// Get the next character and use it to guesstimate what the next token
// is going to be. We turn on end of entity exceptions when we do this
// in order to catch the scenario where the current entity ended at
// the > of some markup.
XMLCh nextCh=0;
XMLReader* curReader=fReaderMgr.getCurrentReader();
// avoid setting up the ThrowEOEJanitor if we know that we have data in the current reader
if(curReader && curReader->charsLeftInBuffer()>0)
nextCh = fReaderMgr.peekNextChar();
else
{
ThrowEOEJanitor janMgr(&fReaderMgr, true);
nextCh = fReaderMgr.peekNextChar();
}
// If it's not a '<' we must be in content (unless it's a EOF)
//
// This includes entity references '&' of some sort. These must
// be character data because that's the only place a reference can
// occur in content.
if (nextCh != chOpenAngle)
return nextCh?Token_CharData:Token_EOF;
// Ok it had to have been a '<' character. So get it out of the reader
// and store the reader number where we saw it, passing it back to the
// caller.
fReaderMgr.getNextChar();
orgReader = fReaderMgr.getCurrentReaderNum();
// Ok, so lets go through the things that it could be at this point which
// are all some form of markup.
switch(fReaderMgr.peekNextChar())
{
case chForwardSlash:
{
fReaderMgr.getNextChar();
return Token_EndTag;
}
case chBang:
{
static const XMLCh gCDATAStr[] =
{
chBang, chOpenSquare, chLatin_C, chLatin_D, chLatin_A
, chLatin_T, chLatin_A, chNull
};
static const XMLCh gCommentString[] =
{
chBang, chDash, chDash, chNull
};
if (fReaderMgr.skippedString(gCDATAStr))
return Token_CData;
if (fReaderMgr.skippedString(gCommentString))
return Token_Comment;
emitError(XMLErrs::ExpectedCommentOrCDATA);
return Token_Unknown;
}
case chQuestion:
{
// It must be a PI
fReaderMgr.getNextChar();
return Token_PI;
}
}
// Assume its an element name, so return with a start tag token. If it
// turns out not to be, then it will fail when it cannot get a valid tag.
return Token_StartTag;
}
// ---------------------------------------------------------------------------
// XMLScanner: Private parsing methods
// ---------------------------------------------------------------------------
// This guy just scans out a single or double quoted string of characters.
// It does not pass any judgement on the contents and assumes that it is
// illegal to have another quote of the same kind inside the string's
// contents.
//
// NOTE: This is for simple stuff like the strings in the XMLDecl which
// cannot have any entities inside them. So this guy does not handle any
// end of entity stuff.
bool XMLScanner::getQuotedString(XMLBuffer& toFill)
{
// Reset the target buffer
toFill.reset();
// Get the next char which must be a single or double quote
XMLCh quoteCh;
if (!fReaderMgr.skipIfQuote(quoteCh))
return false;
XMLCh nextCh;
// Get another char and see if it matches the starting quote char
while ((nextCh=fReaderMgr.getNextChar())!=quoteCh)
{
// We should never get either an end of file null char here. If we
// do, just fail. It will be handled more gracefully in the higher
// level code that called us.
if (!nextCh)
return false;
// Else add it to the buffer
toFill.append(nextCh);
}
return true;
}
// This method scans a character reference and returns the character that
// was refered to. It assumes that we've already scanned the &# characters
// that prefix the numeric code.
bool XMLScanner::scanCharRef(XMLCh& toFill, XMLCh& second)
{
bool gotOne = false;
unsigned int value = 0;
// Set the radix. Its supposed to be a lower case x if hex. But, in
// order to recover well, we check for an upper and put out an error
// for that.
unsigned int radix = 10;
if (fReaderMgr.skippedChar(chLatin_x))
{
radix = 16;
}
else if (fReaderMgr.skippedChar(chLatin_X))
{
emitError(XMLErrs::HexRadixMustBeLowerCase);
radix = 16;
}
while (true)
{
const XMLCh nextCh = fReaderMgr.peekNextChar();
// Watch for EOF
if (!nextCh)
ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager);
// Break out on the terminating semicolon
if (nextCh == chSemiColon)
{
fReaderMgr.getNextChar();
break;
}
// Convert this char to a binary value, or bail out if its not
// one.
unsigned int nextVal;
if ((nextCh >= chDigit_0) && (nextCh <= chDigit_9))
nextVal = (unsigned int)(nextCh - chDigit_0);
else if ((nextCh >= chLatin_A) && (nextCh <= chLatin_F))
nextVal= (unsigned int)(10 + (nextCh - chLatin_A));
else if ((nextCh >= chLatin_a) && (nextCh <= chLatin_f))
nextVal = (unsigned int)(10 + (nextCh - chLatin_a));
else
{
// Return a zero
toFill = 0;
// If we got at least a sigit, then do an unterminated ref error.
// Else, do an expected a numerical ref thing.
if (gotOne)
emitError(XMLErrs::UnterminatedCharRef);
else
emitError(XMLErrs::ExpectedNumericalCharRef);
// Return failure
return false;
}
// Make sure its valid for the radix. If not, then just eat the
// digit and go on after issueing an error. Else, update the
// running value with this new digit.
if (nextVal >= radix)
{
XMLCh tmpStr[2];
tmpStr[0] = nextCh;
tmpStr[1] = chNull;
emitError(XMLErrs::BadDigitForRadix, tmpStr);
}
else
{
value = (value * radix) + nextVal;
// Guard against overflow.
if (value > 0x10FFFF) {
// Character reference was not in the valid range
emitError(XMLErrs::InvalidCharacterRef);
return false;
}
}
// Indicate that we got at least one good digit
gotOne = true;
// And eat the last char
fReaderMgr.getNextChar();
}
// Return the char (or chars)
// And check if the character expanded is valid or not
if (value >= 0x10000 && value <= 0x10FFFF)
{
value -= 0x10000;
toFill = XMLCh((value >> 10) + 0xD800);
second = XMLCh((value & 0x3FF) + 0xDC00);
}
else if (value <= 0xFFFD)
{
toFill = XMLCh(value);
second = 0;
if (!fReaderMgr.getCurrentReader()->isXMLChar(toFill) && !fReaderMgr.getCurrentReader()->isControlChar(toFill)) {
// Character reference was not in the valid range
emitError(XMLErrs::InvalidCharacterRef);
return false;
}
}
else {
// Character reference was not in the valid range
emitError(XMLErrs::InvalidCharacterRef);
return false;
}
return true;
}
// We get here after the '<!--' part of the comment. We scan past the
// terminating '-->' It will calls the appropriate handler with the comment
// text, if one is provided. A comment can be in either the document or
// the DTD, so the fInDocument flag is used to know which handler to send
// it to.
void XMLScanner::scanComment()
{
enum States
{
InText
, OneDash
, TwoDashes
};
// Get a buffer for this
XMLBufBid bbComment(&fBufMgr);
// Get the comment text into a temp buffer. Be sure to use temp buffer
// two here, since its to be used for stuff that is potentially longer
// than just a name.
States curState = InText;
bool gotLeadingSurrogate = false;
while (true)
{
// Get the next character
const XMLCh nextCh = fReaderMgr.getNextChar();
// Watch for an end of file
if (!nextCh)
{
emitError(XMLErrs::UnterminatedComment);
ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager);
}
// Check for correct surrogate pairs
if ((nextCh >= 0xD800) && (nextCh <= 0xDBFF))
{
if (gotLeadingSurrogate)
emitError(XMLErrs::Expected2ndSurrogateChar);
else
gotLeadingSurrogate = true;
}
else
{
if (gotLeadingSurrogate)
{
if ((nextCh < 0xDC00) || (nextCh > 0xDFFF))
emitError(XMLErrs::Expected2ndSurrogateChar);
}
// Its got to at least be a valid XML character
else if (!fReaderMgr.getCurrentReader()->isXMLChar(nextCh)) {
XMLCh tmpBuf[9];
XMLString::binToText
(
nextCh
, tmpBuf
, 8
, 16
, fMemoryManager
);
emitError(XMLErrs::InvalidCharacter, tmpBuf);
}
gotLeadingSurrogate = false;
}
if (curState == InText)
{
// If its a dash, go to OneDash state. Otherwise take as text
if (nextCh == chDash)
curState = OneDash;
else
bbComment.append(nextCh);
}
else if (curState == OneDash)
{
// If its another dash, then we change to the two dashes states.
// Otherwise, we have to put in the deficit dash and the new
// character and go back to InText.
if (nextCh == chDash)
{
curState = TwoDashes;
}
else
{
bbComment.append(chDash);
bbComment.append(nextCh);
curState = InText;
}
}
else if (curState == TwoDashes)
{
// The next character must be the closing bracket
if (nextCh != chCloseAngle)
{
emitError(XMLErrs::IllegalSequenceInComment);
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
break;
}
}
// If we have an available handler, call back with the comment.
if (fDocHandler)
{
fDocHandler->docComment
(
bbComment.getRawBuffer()
);
}
//mark comment is seen within the current element
if (! fElemStack.isEmpty())
fElemStack.setCommentOrPISeen();
}
// Most equal signs can have white space around them, so this little guy
// just makes the calling code cleaner by eating whitespace.
bool XMLScanner::scanEq(bool inDecl)
{
fReaderMgr.skipPastSpaces(inDecl);
if (fReaderMgr.skippedChar(chEqual))
{
fReaderMgr.skipPastSpaces(inDecl);
return true;
}
return false;
}
XMLSize_t
XMLScanner::scanUpToWSOr(XMLBuffer& toFill, const XMLCh chEndChar)
{
fReaderMgr.getUpToCharOrWS(toFill, chEndChar);
return toFill.getLen();
}
unsigned int *XMLScanner::getNewUIntPtr()
{
// this method hands back a new pointer initialized to 0
unsigned int *retVal;
if(fUIntPoolCol < 64)
{
retVal = fUIntPool[fUIntPoolRow]+fUIntPoolCol;
fUIntPoolCol++;
return retVal;
}
// time to grow the pool...
if(fUIntPoolRow+1 == fUIntPoolRowTotal)
{
// and time to add some space for new rows:
fUIntPoolRowTotal <<= 1;
unsigned int **newArray = (unsigned int **)fMemoryManager->allocate(sizeof(unsigned int *) * fUIntPoolRowTotal );
memcpy(newArray, fUIntPool, (fUIntPoolRow+1) * sizeof(unsigned int *));
fMemoryManager->deallocate(fUIntPool);
fUIntPool = newArray;
// need to 0 out new elements we won't need:
for (unsigned int i=fUIntPoolRow+2; i<fUIntPoolRowTotal; i++)
fUIntPool[i] = 0;
}
// now to add a new row; we just made sure we have space
fUIntPoolRow++;
fUIntPool[fUIntPoolRow] = (unsigned int *)fMemoryManager->allocate(sizeof(unsigned int) << 6);
memset(fUIntPool[fUIntPoolRow], 0, sizeof(unsigned int) << 6);
// point to next element
fUIntPoolCol = 1;
return fUIntPool[fUIntPoolRow];
}
void XMLScanner::resetUIntPool()
{
// to reuse the unsigned int pool--and the hashtables that use it--
// simply reinitialize everything to 0's
for(unsigned int i = 0; i<= fUIntPoolRow; i++)
memset(fUIntPool[i], 0, sizeof(unsigned int) << 6);
}
void XMLScanner::recreateUIntPool()
{
// this allows a bloated unsigned int pool to be dispensed with
// first, delete old fUIntPool
for (unsigned int i=0; i<=fUIntPoolRow; i++)
{
fMemoryManager->deallocate(fUIntPool[i]);
}
fMemoryManager->deallocate(fUIntPool);
fUIntPoolRow = fUIntPoolCol = 0;
fUIntPoolRowTotal = 2;
fUIntPool = (unsigned int **)fMemoryManager->allocate(sizeof(unsigned int *) * fUIntPoolRowTotal);
fUIntPool[0] = (unsigned int *)fMemoryManager->allocate(sizeof(unsigned int) << 6);
memset(fUIntPool[fUIntPoolRow], 0, sizeof(unsigned int) << 6);
fUIntPool[1] = 0;
}
XERCES_CPP_NAMESPACE_END
Add check for NULL (XERCESC-1863)
git-svn-id: 3ec853389310512053d525963cab269c063bb453@802792 13f79535-47bb-0310-9956-ffa450edef68
/*
* 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.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/internal/XMLScanner.hpp>
#include <xercesc/internal/ValidationContextImpl.hpp>
#include <xercesc/util/Janitor.hpp>
#include <xercesc/util/Mutexes.hpp>
#include <xercesc/util/RuntimeException.hpp>
#include <xercesc/util/UnexpectedEOFException.hpp>
#include <xercesc/util/XMLMsgLoader.hpp>
#include <xercesc/util/XMLInitializer.hpp>
#include <xercesc/framework/LocalFileInputSource.hpp>
#include <xercesc/framework/URLInputSource.hpp>
#include <xercesc/framework/XMLDocumentHandler.hpp>
#include <xercesc/framework/XMLEntityHandler.hpp>
#include <xercesc/framework/XMLPScanToken.hpp>
#include <xercesc/framework/XMLValidator.hpp>
#include <xercesc/internal/EndOfEntityException.hpp>
#include <xercesc/validators/DTD/DocTypeHandler.hpp>
#include <xercesc/validators/common/GrammarResolver.hpp>
#include <xercesc/util/OutOfMemoryException.hpp>
#include <xercesc/util/XMLResourceIdentifier.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Local static data
// ---------------------------------------------------------------------------
static XMLUInt32 gScannerId = 0;
static XMLMutex* sScannerMutex = 0;
static XMLMsgLoader* gMsgLoader = 0;
void XMLInitializer::initializeXMLScanner()
{
gMsgLoader = XMLPlatformUtils::loadMsgSet(XMLUni::fgXMLErrDomain);
if (!gMsgLoader)
XMLPlatformUtils::panic(PanicHandler::Panic_CantLoadMsgDomain);
sScannerMutex = new XMLMutex(XMLPlatformUtils::fgMemoryManager);
}
void XMLInitializer::terminateXMLScanner()
{
delete gMsgLoader;
gMsgLoader = 0;
delete sScannerMutex;
sScannerMutex = 0;
}
//
//
typedef JanitorMemFunCall<XMLScanner> CleanupType;
typedef JanitorMemFunCall<ReaderMgr> ReaderMgrResetType;
// ---------------------------------------------------------------------------
// XMLScanner: Constructors and Destructor
// ---------------------------------------------------------------------------
XMLScanner::XMLScanner(XMLValidator* const valToAdopt,
GrammarResolver* const grammarResolver,
MemoryManager* const manager)
: fBufferSize(1024 * 1024)
, fStandardUriConformant(false)
, fCalculateSrcOfs(false)
, fDoNamespaces(false)
, fExitOnFirstFatal(true)
, fValidationConstraintFatal(false)
, fInException(false)
, fStandalone(false)
, fHasNoDTD(true)
, fValidate(false)
, fValidatorFromUser(false)
, fDoSchema(false)
, fSchemaFullChecking(false)
, fIdentityConstraintChecking(true)
, fToCacheGrammar(false)
, fUseCachedGrammar(false)
, fLoadExternalDTD(true)
, fLoadSchema(true)
, fNormalizeData(true)
, fGenerateSyntheticAnnotations(false)
, fValidateAnnotations(false)
, fIgnoreCachedDTD(false)
, fIgnoreAnnotations(false)
, fDisableDefaultEntityResolution(false)
, fSkipDTDValidation(false)
, fHandleMultipleImports(false)
, fErrorCount(0)
, fEntityExpansionLimit(0)
, fEntityExpansionCount(0)
, fEmptyNamespaceId(0)
, fUnknownNamespaceId(0)
, fXMLNamespaceId(0)
, fXMLNSNamespaceId(0)
, fSchemaNamespaceId(0)
, fUIntPool(0)
, fUIntPoolRow(0)
, fUIntPoolCol(0)
, fUIntPoolRowTotal(2)
, fScannerId(0)
, fSequenceId(0)
, fAttrList(0)
, fAttrDupChkRegistry(0)
, fDocHandler(0)
, fDocTypeHandler(0)
, fEntityHandler(0)
, fErrorReporter(0)
, fErrorHandler(0)
, fPSVIHandler(0)
, fValidationContext(0)
, fEntityDeclPoolRetrieved(false)
, fReaderMgr(manager)
, fValidator(valToAdopt)
, fValScheme(Val_Never)
, fGrammarResolver(grammarResolver)
, fGrammarPoolMemoryManager(grammarResolver->getGrammarPoolMemoryManager())
, fGrammar(0)
, fRootGrammar(0)
, fURIStringPool(0)
, fRootElemName(0)
, fExternalSchemaLocation(0)
, fExternalNoNamespaceSchemaLocation(0)
, fSecurityManager(0)
, fXMLVersion(XMLReader::XMLV1_0)
, fMemoryManager(manager)
, fBufMgr(manager)
, fAttNameBuf(1023, manager)
, fAttValueBuf(1023, manager)
, fCDataBuf(1023, manager)
, fQNameBuf(1023, manager)
, fPrefixBuf(1023, manager)
, fURIBuf(1023, manager)
, fWSNormalizeBuf(1023, manager)
, fElemStack(manager)
{
CleanupType cleanup(this, &XMLScanner::cleanUp);
try
{
commonInit();
}
catch(const OutOfMemoryException&)
{
// Don't cleanup when out of memory, since executing the
// code can cause problems.
cleanup.release();
throw;
}
cleanup.release();
}
XMLScanner::XMLScanner( XMLDocumentHandler* const docHandler
, DocTypeHandler* const docTypeHandler
, XMLEntityHandler* const entityHandler
, XMLErrorReporter* const errHandler
, XMLValidator* const valToAdopt
, GrammarResolver* const grammarResolver
, MemoryManager* const manager)
: fBufferSize(1024 * 1024)
, fStandardUriConformant(false)
, fCalculateSrcOfs(false)
, fDoNamespaces(false)
, fExitOnFirstFatal(true)
, fValidationConstraintFatal(false)
, fInException(false)
, fStandalone(false)
, fHasNoDTD(true)
, fValidate(false)
, fValidatorFromUser(false)
, fDoSchema(false)
, fSchemaFullChecking(false)
, fIdentityConstraintChecking(true)
, fToCacheGrammar(false)
, fUseCachedGrammar(false)
, fLoadExternalDTD(true)
, fLoadSchema(true)
, fNormalizeData(true)
, fGenerateSyntheticAnnotations(false)
, fValidateAnnotations(false)
, fIgnoreCachedDTD(false)
, fIgnoreAnnotations(false)
, fDisableDefaultEntityResolution(false)
, fSkipDTDValidation(false)
, fHandleMultipleImports(false)
, fErrorCount(0)
, fEntityExpansionLimit(0)
, fEntityExpansionCount(0)
, fEmptyNamespaceId(0)
, fUnknownNamespaceId(0)
, fXMLNamespaceId(0)
, fXMLNSNamespaceId(0)
, fSchemaNamespaceId(0)
, fUIntPool(0)
, fUIntPoolRow(0)
, fUIntPoolCol(0)
, fUIntPoolRowTotal(2)
, fScannerId(0)
, fSequenceId(0)
, fAttrList(0)
, fAttrDupChkRegistry(0)
, fDocHandler(docHandler)
, fDocTypeHandler(docTypeHandler)
, fEntityHandler(entityHandler)
, fErrorReporter(errHandler)
, fErrorHandler(0)
, fPSVIHandler(0)
, fValidationContext(0)
, fEntityDeclPoolRetrieved(false)
, fReaderMgr(manager)
, fValidator(valToAdopt)
, fValScheme(Val_Never)
, fGrammarResolver(grammarResolver)
, fGrammarPoolMemoryManager(grammarResolver->getGrammarPoolMemoryManager())
, fGrammar(0)
, fRootGrammar(0)
, fURIStringPool(0)
, fRootElemName(0)
, fExternalSchemaLocation(0)
, fExternalNoNamespaceSchemaLocation(0)
, fSecurityManager(0)
, fXMLVersion(XMLReader::XMLV1_0)
, fMemoryManager(manager)
, fBufMgr(manager)
, fAttNameBuf(1023, manager)
, fAttValueBuf(1023, manager)
, fCDataBuf(1023, manager)
, fQNameBuf(1023, manager)
, fPrefixBuf(1023, manager)
, fURIBuf(1023, manager)
, fWSNormalizeBuf(1023, manager)
, fElemStack(manager)
{
CleanupType cleanup(this, &XMLScanner::cleanUp);
try
{
commonInit();
}
catch(const OutOfMemoryException&)
{
// Don't cleanup when out of memory, since executing the
// code can cause problems.
cleanup.release();
throw;
}
cleanup.release();
}
XMLScanner::~XMLScanner()
{
cleanUp();
}
void XMLScanner::setValidator(XMLValidator* const valToAdopt)
{
if (fValidatorFromUser)
delete fValidator;
fValidator = valToAdopt;
fValidatorFromUser = true;
initValidator(fValidator);
}
// ---------------------------------------------------------------------------
// XMLScanner: Main entry point to scan a document
// ---------------------------------------------------------------------------
void XMLScanner::scanDocument( const XMLCh* const systemId)
{
// First we try to parse it as a URL. If that fails, we assume its
// a file and try it that way.
InputSource* srcToUse = 0;
try
{
// Create a temporary URL. Since this is the primary document,
// it has to be fully qualified. If not, then assume we are just
// mistaking a file for a URL.
XMLURL tmpURL(fMemoryManager);
if (XMLURL::parse(systemId, tmpURL)) {
if (tmpURL.isRelative()) {
if (!fStandardUriConformant)
srcToUse = new (fMemoryManager) LocalFileInputSource(systemId, fMemoryManager);
else {
// since this is the top of the try/catch, cannot call ThrowXMLwithMemMgr
// emit the error directly
MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_NoProtocolPresent, fMemoryManager);
fInException = true;
emitError
(
XMLErrs::XMLException_Fatal
, e.getCode()
, e.getMessage()
);
return;
}
}
else
{
if (fStandardUriConformant && tmpURL.hasInvalidChar()) {
MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_MalformedURL, fMemoryManager);
fInException = true;
emitError
(
XMLErrs::XMLException_Fatal
, e.getCode()
, e.getMessage()
);
return;
}
srcToUse = new (fMemoryManager) URLInputSource(tmpURL, fMemoryManager);
}
}
else {
if (!fStandardUriConformant)
srcToUse = new (fMemoryManager) LocalFileInputSource(systemId, fMemoryManager);
else {
// since this is the top of the try/catch, cannot call ThrowXMLwithMemMgr
// emit the error directly
// lazy bypass ... since all MalformedURLException are fatal, no need to check the type
MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_MalformedURL, fMemoryManager);
fInException = true;
emitError
(
XMLErrs::XMLException_Fatal
, e.getCode()
, e.getMessage()
);
return;
}
}
}
catch(const XMLException& excToCatch)
{
// For any other XMLException,
// emit the error and catch any user exception thrown from here.
fInException = true;
if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning)
emitError
(
XMLErrs::XMLException_Warning
, excToCatch.getCode()
, excToCatch.getMessage()
);
else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal)
emitError
(
XMLErrs::XMLException_Fatal
, excToCatch.getCode()
, excToCatch.getMessage()
);
else
emitError
(
XMLErrs::XMLException_Error
, excToCatch.getCode()
, excToCatch.getMessage()
);
return;
}
Janitor<InputSource> janSrc(srcToUse);
scanDocument(*srcToUse);
}
void XMLScanner::scanDocument( const char* const systemId)
{
// We just delegate this to the XMLCh version after transcoding
XMLCh* tmpBuf = XMLString::transcode(systemId, fMemoryManager);
ArrayJanitor<XMLCh> janBuf(tmpBuf, fMemoryManager);
scanDocument(tmpBuf);
}
// This method begins a progressive parse. It scans through the prolog and
// returns a token to be used on subsequent scanNext() calls. If the return
// value is true, then the token is legal and ready for further use. If it
// returns false, then the scan of the prolog failed and the token is not
// going to work on subsequent scanNext() calls.
bool XMLScanner::scanFirst( const XMLCh* const systemId
, XMLPScanToken& toFill)
{
// First we try to parse it as a URL. If that fails, we assume its
// a file and try it that way.
InputSource* srcToUse = 0;
try
{
// Create a temporary URL. Since this is the primary document,
// it has to be fully qualified. If not, then assume we are just
// mistaking a file for a URL.
XMLURL tmpURL(fMemoryManager);
if (XMLURL::parse(systemId, tmpURL)) {
if (tmpURL.isRelative()) {
if (!fStandardUriConformant)
srcToUse = new (fMemoryManager) LocalFileInputSource(systemId, fMemoryManager);
else {
// since this is the top of the try/catch, cannot call ThrowXMLwithMemMgr
// emit the error directly
MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_NoProtocolPresent, fMemoryManager);
fInException = true;
emitError
(
XMLErrs::XMLException_Fatal
, e.getCode()
, e.getMessage()
);
return false;
}
}
else
{
if (fStandardUriConformant && tmpURL.hasInvalidChar()) {
MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_MalformedURL, fMemoryManager);
fInException = true;
emitError
(
XMLErrs::XMLException_Fatal
, e.getCode()
, e.getMessage()
);
return false;
}
srcToUse = new (fMemoryManager) URLInputSource(tmpURL, fMemoryManager);
}
}
else {
if (!fStandardUriConformant)
srcToUse = new (fMemoryManager) LocalFileInputSource(systemId, fMemoryManager);
else {
// since this is the top of the try/catch, cannot call ThrowXMLwithMemMgr
// emit the error directly
// lazy bypass ... since all MalformedURLException are fatal, no need to check the type
MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_MalformedURL);
fInException = true;
emitError
(
XMLErrs::XMLException_Fatal
, e.getCode()
, e.getMessage()
);
return false;
}
}
}
catch(const XMLException& excToCatch)
{
// For any other XMLException,
// emit the error and catch any user exception thrown from here.
fInException = true;
if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning)
emitError
(
XMLErrs::XMLException_Warning
, excToCatch.getCode()
, excToCatch.getMessage()
);
else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal)
emitError
(
XMLErrs::XMLException_Fatal
, excToCatch.getCode()
, excToCatch.getMessage()
);
else
emitError
(
XMLErrs::XMLException_Error
, excToCatch.getCode()
, excToCatch.getMessage()
);
return false;
}
Janitor<InputSource> janSrc(srcToUse);
return scanFirst(*srcToUse, toFill);
}
bool XMLScanner::scanFirst( const char* const systemId
, XMLPScanToken& toFill)
{
// We just delegate this to the XMLCh version after transcoding
XMLCh* tmpBuf = XMLString::transcode(systemId, fMemoryManager);
ArrayJanitor<XMLCh> janBuf(tmpBuf, fMemoryManager);
return scanFirst(tmpBuf, toFill);
}
bool XMLScanner::scanFirst( const InputSource& src
, XMLPScanToken& toFill)
{
// Bump up the sequence id for this new scan cycle. This will invalidate
// any previous tokens we've returned.
fSequenceId++;
ReaderMgrResetType resetReaderMgr(&fReaderMgr, &ReaderMgr::reset);
// Reset the scanner and its plugged in stuff for a new run. This
// resets all the data structures, creates the initial reader and
// pushes it on the stack, and sets up the base document path
scanReset(src);
// If we have a document handler, then call the start document
if (fDocHandler)
fDocHandler->startDocument();
try
{
// Scan the prolog part, which is everything before the root element
// including the DTD subsets. This is all that is done on the scan
// first.
scanProlog();
// If we got to the end of input, then its not a valid XML file.
// Else, go on to scan the content.
if (fReaderMgr.atEOF())
{
emitError(XMLErrs::EmptyMainEntity);
}
}
// NOTE:
//
// In all of the error processing below, the emitError() call MUST come
// before the flush of the reader mgr, or it will fail because it tries
// to find out the position in the XML source of the error.
catch(const XMLErrs::Codes)
{
// This is a 'first failure' exception so return failure
return false;
}
catch(const XMLValid::Codes)
{
// This is a 'first fatal error' type exit, return failure
return false;
}
catch(const XMLException& excToCatch)
{
// Emit the error and catch any user exception thrown from here. Make
// sure in all cases we flush the reader manager.
fInException = true;
try
{
if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning)
emitError
(
XMLErrs::XMLException_Warning
, excToCatch.getCode()
, excToCatch.getMessage()
);
else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal)
emitError
(
XMLErrs::XMLException_Fatal
, excToCatch.getCode()
, excToCatch.getMessage()
);
else
emitError
(
XMLErrs::XMLException_Error
, excToCatch.getCode()
, excToCatch.getMessage()
);
}
catch(const OutOfMemoryException&)
{
// This is a special case for out-of-memory
// conditions, because resetting the ReaderMgr
// can be problematic.
resetReaderMgr.release();
throw;
}
return false;
}
catch(const OutOfMemoryException&)
{
// This is a special case for out-of-memory
// conditions, because resetting the ReaderMgr
// can be problematic.
resetReaderMgr.release();
throw;
}
// Fill in the caller's token to make it legal and return success
toFill.set(fScannerId, fSequenceId);
// Release the object that will reset the ReaderMgr, since there's
// more to scan.
resetReaderMgr.release();
return true;
}
void XMLScanner::scanReset(XMLPScanToken& token)
{
// Make sure this token is still legal
if (!isLegalToken(token))
ThrowXMLwithMemMgr(RuntimeException, XMLExcepts::Scan_BadPScanToken, fMemoryManager);
// Reset the reader manager
fReaderMgr.reset();
// And invalidate any tokens by bumping our sequence number
fSequenceId++;
// Reset our error count
fErrorCount = 0;
}
void XMLScanner::setParseSettings(XMLScanner* const refScanner)
{
setDocHandler(refScanner->getDocHandler());
setDocTypeHandler(refScanner->getDocTypeHandler());
setErrorHandler(refScanner->getErrorHandler());
setErrorReporter(refScanner->getErrorReporter());
setEntityHandler(refScanner->getEntityHandler());
setDoNamespaces(refScanner->getDoNamespaces());
setDoSchema(refScanner->getDoSchema());
setCalculateSrcOfs(refScanner->getCalculateSrcOfs());
setStandardUriConformant(refScanner->getStandardUriConformant());
setExitOnFirstFatal(refScanner->getExitOnFirstFatal());
setValidationConstraintFatal(refScanner->getValidationConstraintFatal());
setIdentityConstraintChecking(refScanner->getIdentityConstraintChecking());
setValidationSchemaFullChecking(refScanner->getValidationSchemaFullChecking());
cacheGrammarFromParse(refScanner->isCachingGrammarFromParse());
useCachedGrammarInParse(refScanner->isUsingCachedGrammarInParse());
setLoadExternalDTD(refScanner->getLoadExternalDTD());
setLoadSchema(refScanner->getLoadSchema());
setNormalizeData(refScanner->getNormalizeData());
setExternalSchemaLocation(refScanner->getExternalSchemaLocation());
setExternalNoNamespaceSchemaLocation(refScanner->getExternalNoNamespaceSchemaLocation());
setValidationScheme(refScanner->getValidationScheme());
setSecurityManager(refScanner->getSecurityManager());
setPSVIHandler(refScanner->getPSVIHandler());
}
// ---------------------------------------------------------------------------
// XMLScanner: Private helper methods.
// ---------------------------------------------------------------------------
// This method handles the common initialization, to avoid having to do
// it redundantly in multiple constructors.
void XMLScanner::commonInit()
{
// We have to do a little init that involves statics, so we have to
// use the mutex to protect it.
{
XMLMutexLock lockInit(sScannerMutex);
// And assign ourselves the next available scanner id
fScannerId = ++gScannerId;
}
// Create the attribute list, which is used to store attribute values
// during start tag processing. Give it a reasonable initial size that
// will serve for most folks, though it will grow as required.
fAttrList = new (fMemoryManager) RefVectorOf<XMLAttr>(32, true, fMemoryManager);
// Create the id ref list. This is used to enforce XML 1.0 ID ref
// semantics, i.e. all id refs must refer to elements that exist
fValidationContext = new (fMemoryManager) ValidationContextImpl(fMemoryManager);
fValidationContext->setElemStack(&fElemStack);
fValidationContext->setScanner(this);
// Create the GrammarResolver
//fGrammarResolver = new GrammarResolver();
// create initial, 64-element, fUIntPool
fUIntPool = (unsigned int **)fMemoryManager->allocate(sizeof(unsigned int *) *fUIntPoolRowTotal);
memset(fUIntPool, 0, sizeof(unsigned int *) * fUIntPoolRowTotal);
fUIntPool[0] = (unsigned int *)fMemoryManager->allocate(sizeof(unsigned int) << 6);
memset(fUIntPool[0], 0, sizeof(unsigned int) << 6);
// Register self as handler for XMLBufferFull events on the CDATA buffer
fCDataBuf.setFullHandler(this, fBufferSize);
if (fValidator) {
fValidatorFromUser = true;
initValidator(fValidator);
}
}
void XMLScanner::cleanUp()
{
delete fAttrList;
delete fAttrDupChkRegistry;
delete fValidationContext;
fMemoryManager->deallocate(fRootElemName);//delete [] fRootElemName;
fMemoryManager->deallocate(fExternalSchemaLocation);//delete [] fExternalSchemaLocation;
fMemoryManager->deallocate(fExternalNoNamespaceSchemaLocation);//delete [] fExternalNoNamespaceSchemaLocation;
// delete fUIntPool
if (fUIntPool)
{
for (unsigned int i=0; i<=fUIntPoolRow; i++)
{
fMemoryManager->deallocate(fUIntPool[i]);
}
fMemoryManager->deallocate(fUIntPool);
}
}
void XMLScanner::initValidator(XMLValidator* theValidator) {
// Tell the validator about the stuff it needs to know in order to
// do its work.
theValidator->setScannerInfo(this, &fReaderMgr, &fBufMgr);
theValidator->setErrorReporter(fErrorReporter);
}
// ---------------------------------------------------------------------------
// XMLScanner: Error emitting methods
// ---------------------------------------------------------------------------
// These methods are called whenever the scanner wants to emit an error.
// It handles getting the message loaded, doing token replacement, etc...
// and then calling the error handler, if its installed.
bool XMLScanner::emitErrorWillThrowException(const XMLErrs::Codes toEmit)
{
if (XMLErrs::isFatal(toEmit) && fExitOnFirstFatal && !fInException)
return true;
return false;
}
void XMLScanner::emitError(const XMLErrs::Codes toEmit)
{
// Bump the error count if it is not a warning
if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)
incrementErrorCount();
if (fErrorReporter)
{
// Load the message into a local for display
const XMLSize_t msgSize = 1023;
XMLCh errText[msgSize + 1];
if (!gMsgLoader->loadMsg(toEmit, errText, msgSize))
{
// <TBD> Probably should load a default msg here
}
// Create a LastExtEntityInfo structure and get the reader manager
// to fill it in for us. This will give us the information about
// the last reader on the stack that was an external entity of some
// sort (i.e. it will ignore internal entities.
ReaderMgr::LastExtEntityInfo lastInfo;
fReaderMgr.getLastExtEntityInfo(lastInfo);
fErrorReporter->error
(
toEmit
, XMLUni::fgXMLErrDomain
, XMLErrs::errorType(toEmit)
, errText
, lastInfo.systemId
, lastInfo.publicId
, lastInfo.lineNumber
, lastInfo.colNumber
);
}
// Bail out if its fatal an we are to give up on the first fatal error
if (emitErrorWillThrowException(toEmit))
throw toEmit;
}
void XMLScanner::emitError( const XMLErrs::Codes toEmit
, const XMLCh* const text1
, const XMLCh* const text2
, const XMLCh* const text3
, const XMLCh* const text4)
{
// Bump the error count if it is not a warning
if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)
incrementErrorCount();
if (fErrorReporter)
{
// Load the message into alocal and replace any tokens found in
// the text.
const XMLSize_t maxChars = 2047;
XMLCh errText[maxChars + 1];
if (!gMsgLoader->loadMsg(toEmit, errText, maxChars, text1, text2, text3, text4, fMemoryManager))
{
// <TBD> Should probably load a default message here
}
// Create a LastExtEntityInfo structure and get the reader manager
// to fill it in for us. This will give us the information about
// the last reader on the stack that was an external entity of some
// sort (i.e. it will ignore internal entities.
ReaderMgr::LastExtEntityInfo lastInfo;
fReaderMgr.getLastExtEntityInfo(lastInfo);
fErrorReporter->error
(
toEmit
, XMLUni::fgXMLErrDomain
, XMLErrs::errorType(toEmit)
, errText
, lastInfo.systemId
, lastInfo.publicId
, lastInfo.lineNumber
, lastInfo.colNumber
);
}
// Bail out if its fatal an we are to give up on the first fatal error
if (emitErrorWillThrowException(toEmit))
throw toEmit;
}
void XMLScanner::emitError( const XMLErrs::Codes toEmit
, const char* const text1
, const char* const text2
, const char* const text3
, const char* const text4)
{
// Bump the error count if it is not a warning
if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)
incrementErrorCount();
if (fErrorReporter)
{
// Load the message into alocal and replace any tokens found in
// the text.
const XMLSize_t maxChars = 2047;
XMLCh errText[maxChars + 1];
if (!gMsgLoader->loadMsg(toEmit, errText, maxChars, text1, text2, text3, text4, fMemoryManager))
{
// <TBD> Should probably load a default message here
}
// Create a LastExtEntityInfo structure and get the reader manager
// to fill it in for us. This will give us the information about
// the last reader on the stack that was an external entity of some
// sort (i.e. it will ignore internal entities.
ReaderMgr::LastExtEntityInfo lastInfo;
fReaderMgr.getLastExtEntityInfo(lastInfo);
fErrorReporter->error
(
toEmit
, XMLUni::fgXMLErrDomain
, XMLErrs::errorType(toEmit)
, errText
, lastInfo.systemId
, lastInfo.publicId
, lastInfo.lineNumber
, lastInfo.colNumber
);
}
// Bail out if its fatal an we are to give up on the first fatal error
if (emitErrorWillThrowException(toEmit))
throw toEmit;
}
void XMLScanner::emitError( const XMLErrs::Codes toEmit
, const XMLExcepts::Codes originalExceptCode
, const XMLCh* const text1
, const XMLCh* const text2
, const XMLCh* const text3
, const XMLCh* const text4)
{
// Bump the error count if it is not a warning
if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)
incrementErrorCount();
if (fErrorReporter)
{
// Load the message into alocal and replace any tokens found in
// the text.
const XMLSize_t maxChars = 2047;
XMLCh errText[maxChars + 1];
if (!gMsgLoader->loadMsg(toEmit, errText, maxChars, text1, text2, text3, text4, fMemoryManager))
{
// <TBD> Should probably load a default message here
}
// Create a LastExtEntityInfo structure and get the reader manager
// to fill it in for us. This will give us the information about
// the last reader on the stack that was an external entity of some
// sort (i.e. it will ignore internal entities.
ReaderMgr::LastExtEntityInfo lastInfo;
fReaderMgr.getLastExtEntityInfo(lastInfo);
fErrorReporter->error
(
originalExceptCode
, XMLUni::fgExceptDomain //fgXMLErrDomain
, XMLErrs::errorType(toEmit)
, errText
, lastInfo.systemId
, lastInfo.publicId
, lastInfo.lineNumber
, lastInfo.colNumber
);
}
// Bail out if its fatal an we are to give up on the first fatal error
if (emitErrorWillThrowException(toEmit))
throw toEmit;
}
// ---------------------------------------------------------------------------
// XMLScanner: Getter methods
// ---------------------------------------------------------------------------
// This method allows the caller to query the current location of the scanner.
// It will return the sys/public ids of the current entity, and the line/col
// position within it.
//
// NOTE: This API returns the location with the last external file. So if its
// currently scanning an entity, the position returned will be the end of
// the entity reference in the file that had the reference.
//
/*bool
XMLScanner::getLastExtLocation( XMLCh* const sysIdToFill
, const unsigned int maxSysIdChars
, XMLCh* const pubIdToFill
, const unsigned int maxPubIdChars
, XMLSSize_t& lineToFill
, XMLSSize_t& colToFill) const
{
// Create a local info object and get it filled in by the reader manager
ReaderMgr::LastExtEntityInfo lastInfo;
fReaderMgr.getLastExtEntityInfo(lastInfo);
// Fill in the line and column number
lineToFill = lastInfo.lineNumber;
colToFill = lastInfo.colNumber;
// And copy over as much of the ids as will fit
sysIdToFill[0] = 0;
if (lastInfo.systemId)
{
if (XMLString::stringLen(lastInfo.systemId) > maxSysIdChars)
return false;
XMLString::copyString(sysIdToFill, lastInfo.systemId);
}
pubIdToFill[0] = 0;
if (lastInfo.publicId)
{
if (XMLString::stringLen(lastInfo.publicId) > maxPubIdChars)
return false;
XMLString::copyString(pubIdToFill, lastInfo.publicId);
}
return true;
}*/
// ---------------------------------------------------------------------------
// XMLScanner: Private scanning methods
// ---------------------------------------------------------------------------
// This method is called after the end of the root element, to handle
// any miscellaneous stuff hanging around.
void XMLScanner::scanMiscellaneous()
{
// Get a buffer for this work
XMLBufBid bbCData(&fBufMgr);
while (true)
{
try
{
const XMLCh nextCh = fReaderMgr.peekNextChar();
// Watch for end of file and break out
if (!nextCh)
break;
if (nextCh == chOpenAngle)
{
if (checkXMLDecl(true))
{
// Can't have an XML decl here
emitError(XMLErrs::NotValidAfterContent);
fReaderMgr.skipPastChar(chCloseAngle);
}
else if (fReaderMgr.skippedString(XMLUni::fgPIString))
{
scanPI();
}
else if (fReaderMgr.skippedString(XMLUni::fgCommentString))
{
scanComment();
}
else
{
// This can't be possible, so just give up
emitError(XMLErrs::ExpectedCommentOrPI);
fReaderMgr.skipPastChar(chCloseAngle);
}
}
else if (fReaderMgr.getCurrentReader()->isWhitespace(nextCh))
{
// If we have a doc handler, then gather up the spaces and
// call back. Otherwise, just skip over whitespace.
if (fDocHandler)
{
fReaderMgr.getSpaces(bbCData.getBuffer());
fDocHandler->ignorableWhitespace
(
bbCData.getRawBuffer()
, bbCData.getLen()
, false
);
}
else
{
fReaderMgr.skipPastSpaces();
}
}
else
{
emitError(XMLErrs::ExpectedCommentOrPI);
fReaderMgr.skipPastChar(chCloseAngle);
}
}
catch(const EndOfEntityException&)
{
// Some entity leaked out of the content part of the document. Issue
// a warning and keep going.
emitError(XMLErrs::EntityPropogated);
}
}
}
// Scans a PI and calls the appropriate callbacks. At entry we have just
// scanned the <? part, and need to now start on the PI target name.
void XMLScanner::scanPI()
{
const XMLCh* namePtr = 0;
const XMLCh* targetPtr = 0;
// If there are any spaces here, then warn about it. If we aren't in
// 'first error' mode, then we'll come back and can easily pick up
// again by just skipping them.
if (fReaderMgr.lookingAtSpace())
{
emitError(XMLErrs::PINameExpected);
fReaderMgr.skipPastSpaces();
}
// Get a buffer for the PI name and scan it in
XMLBufBid bbName(&fBufMgr);
if (!fReaderMgr.getName(bbName.getBuffer()))
{
emitError(XMLErrs::PINameExpected);
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
// Point the name pointer at the raw data
namePtr = bbName.getRawBuffer();
// See if it is some form of 'xml' and emit a warning
//if (!XMLString::compareIString(namePtr, XMLUni::fgXMLString))
if (bbName.getLen() == 3 &&
(((namePtr[0] == chLatin_x) || (namePtr[0] == chLatin_X)) &&
((namePtr[1] == chLatin_m) || (namePtr[1] == chLatin_M)) &&
((namePtr[2] == chLatin_l) || (namePtr[2] == chLatin_L))))
emitError(XMLErrs::NoPIStartsWithXML);
// If namespaces are enabled, then no colons allowed
if (fDoNamespaces)
{
if (XMLString::indexOf(namePtr, chColon) != -1)
emitError(XMLErrs::ColonNotLegalWithNS);
}
// If we don't hit a space next, then the PI has no target. If we do
// then get out the target. Get a buffer for it as well
XMLBufBid bbTarget(&fBufMgr);
if (fReaderMgr.skippedSpace())
{
// Skip any leading spaces
fReaderMgr.skipPastSpaces();
bool gotLeadingSurrogate = false;
// It does have a target, so lets move on to deal with that.
while (1)
{
const XMLCh nextCh = fReaderMgr.getNextChar();
// Watch for an end of file, which is always bad here
if (!nextCh)
{
emitError(XMLErrs::UnterminatedPI);
ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager);
}
// Watch for potential terminating character
if (nextCh == chQuestion)
{
// It must be followed by '>' to be a termination of the target
if (fReaderMgr.skippedChar(chCloseAngle))
break;
}
// Check for correct surrogate pairs
if ((nextCh >= 0xD800) && (nextCh <= 0xDBFF))
{
if (gotLeadingSurrogate)
emitError(XMLErrs::Expected2ndSurrogateChar);
else
gotLeadingSurrogate = true;
}
else
{
if (gotLeadingSurrogate)
{
if ((nextCh < 0xDC00) || (nextCh > 0xDFFF))
emitError(XMLErrs::Expected2ndSurrogateChar);
}
// Its got to at least be a valid XML character
else if (!fReaderMgr.getCurrentReader()->isXMLChar(nextCh)) {
XMLCh tmpBuf[9];
XMLString::binToText
(
nextCh
, tmpBuf
, 8
, 16
, fMemoryManager
);
emitError(XMLErrs::InvalidCharacter, tmpBuf);
}
gotLeadingSurrogate = false;
}
bbTarget.append(nextCh);
}
}
else
{
// No target, but make sure its terminated ok
if (!fReaderMgr.skippedChar(chQuestion))
{
emitError(XMLErrs::UnterminatedPI);
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
if (!fReaderMgr.skippedChar(chCloseAngle))
{
emitError(XMLErrs::UnterminatedPI);
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
}
// Point the target pointer at the raw data
targetPtr = bbTarget.getRawBuffer();
// If we have a handler, then call it
if (fDocHandler)
{
fDocHandler->docPI
(
namePtr
, targetPtr
);
}
//mark PI is seen within the current element
if (! fElemStack.isEmpty())
fElemStack.setCommentOrPISeen();
}
// Scans all the input from the start of the file to the root element.
// There does not have to be anything in the prolog necessarily, but usually
// there is at least an XMLDecl.
//
// On exit from here we are either at the end of the file or about to read
// the opening < of the root element.
void XMLScanner::scanProlog()
{
bool sawDocTypeDecl = false;
// Get a buffer for whitespace processing
XMLBufBid bbCData(&fBufMgr);
// Loop through the prolog. If there is no content, this could go all
// the way to the end of the file.
try
{
while (true)
{
const XMLCh nextCh = fReaderMgr.peekNextChar();
if (nextCh == chOpenAngle)
{
// Ok, it could be the xml decl, a comment, the doc type line,
// or the start of the root element.
if (checkXMLDecl(true))
{
// There shall be at lease --ONE-- space in between
// the tag '<?xml' and the VersionInfo.
//
// If we are not at line 1, col 6, then the decl was not
// the first text, so its invalid.
const XMLReader* curReader = fReaderMgr.getCurrentReader();
if ((curReader->getLineNumber() != 1)
|| (curReader->getColumnNumber() != 7))
{
emitError(XMLErrs::XMLDeclMustBeFirst);
}
scanXMLDecl(Decl_XML);
}
else if (fReaderMgr.skippedString(XMLUni::fgPIString))
{
scanPI();
}
else if (fReaderMgr.skippedString(XMLUni::fgCommentString))
{
scanComment();
}
else if (fReaderMgr.skippedString(XMLUni::fgDocTypeString))
{
if (sawDocTypeDecl) {
emitError(XMLErrs::DuplicateDocTypeDecl);
}
scanDocTypeDecl();
sawDocTypeDecl = true;
// if reusing grammar, this has been validated already in first scan
// skip for performance
if (fValidate && fGrammar && !fGrammar->getValidated()) {
// validate the DTD scan so far
fValidator->preContentValidation(fUseCachedGrammar, true);
}
}
else
{
// Assume its the start of the root element
return;
}
}
else if (fReaderMgr.getCurrentReader()->isWhitespace(nextCh))
{
// If we have a document handler then gather up the
// whitespace and call back. Otherwise just skip over spaces.
if (fDocHandler)
{
fReaderMgr.getSpaces(bbCData.getBuffer());
fDocHandler->ignorableWhitespace
(
bbCData.getRawBuffer()
, bbCData.getLen()
, false
);
}
else
{
fReaderMgr.skipPastSpaces();
}
}
else
{
emitError(XMLErrs::InvalidDocumentStructure);
// Watch for end of file and break out
if (!nextCh)
break;
else
fReaderMgr.skipPastChar(chCloseAngle);
}
}
}
catch(const EndOfEntityException&)
{
// We should never get an end of entity here. They should only
// occur within the doc type scanning method, and not leak out to
// here.
emitError
(
XMLErrs::UnexpectedEOE
, "in prolog"
);
}
}
// Scans the <?xml .... ?> line. This stuff is all sequential so we don't
// do any state machine loop here. We just bull straight through it. It ends
// past the closing bracket. If there is a document handler, then its called
// on the XMLDecl callback.
//
// On entry, the <?xml has been scanned, and we pick it up from there.
//
// NOTE: In order to provide good recovery from bad XML here, we try to be
// very flexible. No matter what order the stuff is in, we'll keep going
// though we'll issue errors.
//
// The parameter tells us which type of decl we should expect, Text or XML.
// [23] XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
// [77] TextDecl::= '<?xml' VersionInfo? EncodingDecl S? '?>'
void XMLScanner::scanXMLDecl(const DeclTypes type)
{
// Get us some buffers to use
XMLBufBid bbVersion(&fBufMgr);
XMLBufBid bbEncoding(&fBufMgr);
XMLBufBid bbStand(&fBufMgr);
XMLBufBid bbDummy(&fBufMgr);
XMLBufBid bbName(&fBufMgr);
// We use this little enum and array to keep up with what we found
// and what order we found them in. This lets us get them free form
// without too much overhead, but still know that they were in the
// wrong order.
enum Strings
{
VersionString
, EncodingString
, StandaloneString
, UnknownString
, StringCount
};
int flags[StringCount] = { -1, -1, -1, -1 };
// Also set up a list of buffers in the right order so that we know
// where to put stuff.
XMLBuffer* buffers[StringCount] ;
buffers[0] = &bbVersion.getBuffer();
buffers[1] = &bbEncoding.getBuffer();
buffers[2] = &bbStand.getBuffer();
buffers[3] = &bbDummy.getBuffer();
int curCount = 0;
Strings curString;
XMLBuffer& nameBuf = bbName.getBuffer();
while (true)
{
// Skip any spaces
const bool spaceCount = fReaderMgr.skipPastSpaces(true);
// If we are looking at a question mark, then break out
if (fReaderMgr.lookingAtChar(chQuestion))
break;
// If this is not the first string, then we require the spaces
if (!spaceCount && curCount)
emitError(XMLErrs::ExpectedWhitespace);
// Get characters up to the next whitespace or equal's sign.
if (!scanUpToWSOr(nameBuf, chEqual))
emitError(XMLErrs::ExpectedDeclString);
// See if it matches any of our expected strings
if (XMLString::equals(nameBuf.getRawBuffer(), XMLUni::fgVersionString))
curString = VersionString;
else if (XMLString::equals(nameBuf.getRawBuffer(), XMLUni::fgEncodingString))
curString = EncodingString;
else if (XMLString::equals(nameBuf.getRawBuffer(), XMLUni::fgStandaloneString))
curString = StandaloneString;
else
curString = UnknownString;
// If its an unknown string, then give that error. Else check to
// see if this one has been done already and give that error.
if (curString == UnknownString)
emitError(XMLErrs::ExpectedDeclString, nameBuf.getRawBuffer());
else if (flags[curString] != -1)
emitError(XMLErrs::DeclStringRep, nameBuf.getRawBuffer());
else if (flags[curString] == -1)
flags[curString] = ++curCount;
// Scan for an equal's sign. If we don't find it, issue an error
// but keep trying to go on.
if (!scanEq(true))
emitError(XMLErrs::ExpectedEqSign);
// Get a quote string into the buffer for the string that we are
// currently working on.
if (!getQuotedString(*buffers[curString]))
{
emitError(XMLErrs::ExpectedQuotedString);
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
// And validate the value according which one it was
const XMLCh* rawValue = buffers[curString]->getRawBuffer();
if (curString == VersionString)
{
if (XMLString::equals(rawValue, XMLUni::fgVersion1_1)) {
if (type == Decl_XML) {
fXMLVersion = XMLReader::XMLV1_1;
fReaderMgr.setXMLVersion(XMLReader::XMLV1_1);
}
else {
if (fXMLVersion != XMLReader::XMLV1_1)
emitError(XMLErrs::UnsupportedXMLVersion, rawValue);
}
}
else if (XMLString::equals(rawValue, XMLUni::fgVersion1_0)) {
if (type == Decl_XML) {
fXMLVersion = XMLReader::XMLV1_0;
fReaderMgr.setXMLVersion(XMLReader::XMLV1_0);
}
}
else
emitError(XMLErrs::UnsupportedXMLVersion, rawValue);
}
else if (curString == EncodingString)
{
if (!XMLString::isValidEncName(rawValue))
emitError(XMLErrs::BadXMLEncoding, rawValue);
}
else if (curString == StandaloneString)
{
if (XMLString::equals(rawValue, XMLUni::fgYesString))
fStandalone = true;
else if (XMLString::equals(rawValue, XMLUni::fgNoString))
fStandalone = false;
else
{
emitError(XMLErrs::BadStandalone);
//if (!XMLString::compareIString(rawValue, XMLUni::fgYesString))
//else if (!XMLString::compareIString(rawValue, XMLUni::fgNoString))
if (buffers[curString]->getLen() == 3 &&
(((rawValue[0] == chLatin_y) || (rawValue[0] == chLatin_Y)) &&
((rawValue[1] == chLatin_e) || (rawValue[1] == chLatin_E)) &&
((rawValue[2] == chLatin_s) || (rawValue[2] == chLatin_S))))
fStandalone = true;
else if (buffers[curString]->getLen() == 2 &&
(((rawValue[0] == chLatin_n) || (rawValue[0] == chLatin_N)) &&
((rawValue[1] == chLatin_o) || (rawValue[1] == chLatin_O))))
fStandalone = false;
}
}
}
// Make sure that the strings present are in order. We don't care about
// which ones are present at this point, just that any there are in the
// right order.
int curTop = 0;
for (int index = VersionString; index < StandaloneString; index++)
{
if (flags[index] != -1)
{
if (flags[index] != curTop + 1)
{
emitError(XMLErrs::DeclStringsInWrongOrder);
break;
}
curTop = flags[index];
}
}
// If its an XML decl, the version must be present.
// If its a Text decl, then encoding must be present AND standalone must not be present.
if ((type == Decl_XML) && (flags[VersionString] == -1))
emitError(XMLErrs::XMLVersionRequired);
else if (type == Decl_Text) {
if (flags[StandaloneString] != -1)
emitError(XMLErrs::StandaloneNotLegal);
if (flags[EncodingString] == -1)
emitError(XMLErrs::EncodingRequired);
}
if (!fReaderMgr.skippedChar(chQuestion))
{
emitError(XMLErrs::UnterminatedXMLDecl);
fReaderMgr.skipPastChar(chCloseAngle);
}
else if (!fReaderMgr.skippedChar(chCloseAngle))
{
emitError(XMLErrs::UnterminatedXMLDecl);
fReaderMgr.skipPastChar(chCloseAngle);
}
// Do this before we possibly update the reader with the
// actual encoding string. Otherwise, we will pass the wrong thing
// for the last parameter!
const XMLCh* actualEnc = fReaderMgr.getCurrentEncodingStr();
// Ok, we've now seen the real encoding string, if there was one, so
// lets call back on the current reader and tell it what the real
// encoding string was. If it fails, that's because it represents some
// sort of contradiction with the autosensed format, and it keeps the
// original encoding.
//
// NOTE: This can fail for a number of reasons, such as a bogus encoding
// name or because its in flagrant contradiction of the auto-sensed
// format.
if (flags[EncodingString] != -1)
{
if (!fReaderMgr.getCurrentReader()->setEncoding(bbEncoding.getRawBuffer()))
emitError(XMLErrs::ContradictoryEncoding, bbEncoding.getRawBuffer());
else
actualEnc = bbEncoding.getRawBuffer();
}
// If we have a document handler then call the XML Decl callback.
if (type == Decl_XML)
{
if (fDocHandler)
fDocHandler->XMLDecl
(
bbVersion.getRawBuffer()
, bbEncoding.getRawBuffer()
, bbStand.getRawBuffer()
, actualEnc
);
}
else if (type == Decl_Text)
{
if (fDocTypeHandler)
fDocTypeHandler->TextDecl
(
bbVersion.getRawBuffer()
, bbEncoding.getRawBuffer()
);
}
}
const XMLCh* XMLScanner::getURIText(const unsigned int uriId) const
{
if (fURIStringPool->exists(uriId)) {
// Look up the URI in the string pool and return its id
const XMLCh* value = fURIStringPool->getValueForId(uriId);
if (!value)
return XMLUni::fgZeroLenString;
return value;
}
else
return XMLUni::fgZeroLenString;
}
bool XMLScanner::getURIText( const unsigned int uriId
, XMLBuffer& uriBufToFill) const
{
if (fURIStringPool->exists(uriId)) {
// Look up the URI in the string pool and return its id
const XMLCh* value = fURIStringPool->getValueForId(uriId);
if (!value)
return false;
uriBufToFill.set(value);
return true;
}
else
return false;
}
bool XMLScanner::checkXMLDecl(bool startWithAngle) {
// [23] XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
// [24] VersionInfo ::= S 'version' Eq ("'" VersionNum "'" | '"' VersionNum '"')
//
// [3] S ::= (#x20 | #x9 | #xD | #xA)+
if (startWithAngle) {
if (fReaderMgr.peekString(XMLUni::fgXMLDeclString)) {
if (fReaderMgr.skippedString(XMLUni::fgXMLDeclStringSpace)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringHTab)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringLF)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringCR))
{
return true;
}
}
else if (fReaderMgr.skippedString(XMLUni::fgXMLDeclStringSpaceU)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringHTabU)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringLFU)
|| fReaderMgr.skippedString(XMLUni::fgXMLDeclStringCRU))
{
// Just in case, check for upper case. If found, issue
// an error, but keep going.
emitError(XMLErrs::XMLDeclMustBeLowerCase);
return true;
}
}
else {
if (fReaderMgr.peekString(XMLUni::fgXMLString)) {
if (fReaderMgr.skippedString(XMLUni::fgXMLStringSpace)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringHTab)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringLF)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringCR))
{
return true;
}
}
else if (fReaderMgr.skippedString(XMLUni::fgXMLStringSpaceU)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringHTabU)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringLFU)
|| fReaderMgr.skippedString(XMLUni::fgXMLStringCRU))
{
// Just in case, check for upper case. If found, issue
// an error, but keep going.
emitError(XMLErrs::XMLDeclMustBeLowerCase);
return true;
}
}
return false;
}
// ---------------------------------------------------------------------------
// XMLScanner: Grammar preparsing
// ---------------------------------------------------------------------------
Grammar* XMLScanner::loadGrammar(const XMLCh* const systemId
, const short grammarType
, const bool toCache)
{
InputSource* srcToUse = 0;
if (fEntityHandler){
ReaderMgr::LastExtEntityInfo lastInfo;
fReaderMgr.getLastExtEntityInfo(lastInfo);
XMLResourceIdentifier resourceIdentifier(XMLResourceIdentifier::ExternalEntity,
systemId, 0, XMLUni::fgZeroLenString, lastInfo.systemId,
&fReaderMgr);
srcToUse = fEntityHandler->resolveEntity(&resourceIdentifier);
}
// First we try to parse it as a URL. If that fails, we assume its
// a file and try it that way.
if (!srcToUse) {
if (fDisableDefaultEntityResolution)
return 0;
try
{
// Create a temporary URL. Since this is the primary document,
// it has to be fully qualified. If not, then assume we are just
// mistaking a file for a URL.
XMLURL tmpURL(fMemoryManager);
if (XMLURL::parse(systemId, tmpURL)) {
if (tmpURL.isRelative())
{
if (!fStandardUriConformant)
srcToUse = new (fMemoryManager) LocalFileInputSource(systemId, fMemoryManager);
else {
// since this is the top of the try/catch, cannot call ThrowXMLwithMemMgr
// emit the error directly
MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_NoProtocolPresent, fMemoryManager);
fInException = true;
emitError
(
XMLErrs::XMLException_Fatal
, e.getCode()
, e.getMessage()
);
return 0;
}
}
else
{
if (fStandardUriConformant && tmpURL.hasInvalidChar()) {
MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_MalformedURL, fMemoryManager);
fInException = true;
emitError
(
XMLErrs::XMLException_Fatal
, e.getCode()
, e.getMessage()
);
return 0;
}
srcToUse = new (fMemoryManager) URLInputSource(tmpURL, fMemoryManager);
}
}
else
{
if (!fStandardUriConformant)
srcToUse = new (fMemoryManager) LocalFileInputSource(systemId, fMemoryManager);
else {
// since this is the top of the try/catch, cannot call ThrowXMLwithMemMgr
// emit the error directly
// lazy bypass ... since all MalformedURLException are fatal, no need to check the type
MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_MalformedURL);
fInException = true;
emitError
(
XMLErrs::XMLException_Fatal
, e.getCode()
, e.getMessage()
);
return 0;
}
}
}
catch(const XMLException& excToCatch)
{
// For any other XMLException,
// emit the error and catch any user exception thrown from here.
fInException = true;
if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning)
emitError
(
XMLErrs::XMLException_Warning
, excToCatch.getCode()
, excToCatch.getMessage()
);
else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal)
emitError
(
XMLErrs::XMLException_Fatal
, excToCatch.getCode()
, excToCatch.getMessage()
);
else
emitError
(
XMLErrs::XMLException_Error
, excToCatch.getCode()
, excToCatch.getMessage()
);
return 0;
}
}
Janitor<InputSource> janSrc(srcToUse);
return loadGrammar(*srcToUse, grammarType, toCache);
}
Grammar* XMLScanner::loadGrammar(const char* const systemId
, const short grammarType
, const bool toCache)
{
// We just delegate this to the XMLCh version after transcoding
XMLCh* tmpBuf = XMLString::transcode(systemId, fMemoryManager);
ArrayJanitor<XMLCh> janBuf(tmpBuf, fMemoryManager);
return loadGrammar(tmpBuf, grammarType, toCache);
}
// ---------------------------------------------------------------------------
// XMLScanner: Setter methods
// ---------------------------------------------------------------------------
void XMLScanner::setURIStringPool(XMLStringPool* const stringPool)
{
fURIStringPool = stringPool;
fEmptyNamespaceId = fURIStringPool->addOrFind(XMLUni::fgZeroLenString);
fUnknownNamespaceId = fURIStringPool->addOrFind(XMLUni::fgUnknownURIName);
fXMLNamespaceId = fURIStringPool->addOrFind(XMLUni::fgXMLURIName);
fXMLNSNamespaceId = fURIStringPool->addOrFind(XMLUni::fgXMLNSURIName);
}
// ---------------------------------------------------------------------------
// XMLScanner: Private helper methods
// ---------------------------------------------------------------------------
/***
* In reusing grammars (cacheing grammar from parse, or use cached grammar), internal
* dtd is allowed conditionally.
*
* In the case of cacheing grammar from parse, it is NOT allowed.
*
* In the case of use cached grammar,
* if external dtd is present and it is parsed before, then it is not allowed,
* otherwise it is allowed.
*
***/
void XMLScanner::checkInternalDTD(bool hasExtSubset
,const XMLCh* const sysId
,const XMLCh* const pubId)
{
if (fToCacheGrammar)
ThrowXMLwithMemMgr(RuntimeException, XMLExcepts::Val_CantHaveIntSS, fMemoryManager);
if (fUseCachedGrammar && hasExtSubset && !fIgnoreCachedDTD)
{
InputSource* sysIdSrc = resolveSystemId(sysId, pubId);
if (sysIdSrc) {
Janitor<InputSource> janSysIdSrc(sysIdSrc);
Grammar* grammar = fGrammarResolver->getGrammar(sysIdSrc->getSystemId());
if (grammar && grammar->getGrammarType() == Grammar::DTDGrammarType)
{
ThrowXMLwithMemMgr(RuntimeException, XMLExcepts::Val_CantHaveIntSS, fMemoryManager);
}
}
}
}
// This method is called after the content scan to insure that all the
// ID/IDREF attributes match up (i.e. that all IDREFs refer to IDs.) This is
// an XML 1.0 rule, so we can do here in the core.
void XMLScanner::checkIDRefs()
{
// Iterate the id ref list. If we find any entries here which are used
// but not declared, then that's an error.
RefHashTableOfEnumerator<XMLRefInfo> refEnum(fValidationContext->getIdRefList(), false, fMemoryManager);
while (refEnum.hasMoreElements())
{
// Get a ref to the current element
const XMLRefInfo& curRef = refEnum.nextElement();
// If its used but not declared, then its an error
if (!curRef.getDeclared() && curRef.getUsed() && fValidate)
fValidator->emitError(XMLValid::IDNotDeclared, curRef.getRefName());
}
}
// This just does a simple check that the passed progressive scan token is
// legal for this scanner.
bool XMLScanner::isLegalToken(const XMLPScanToken& toCheck)
{
return ((fScannerId == toCheck.fScannerId)
&& (fSequenceId == toCheck.fSequenceId));
}
// This method will handle figuring out what the next top level token is
// in the input stream. It will return an enumerated value that indicates
// what it believes the next XML level token must be. It will eat as many
// chars are required to figure out what is next.
XMLScanner::XMLTokens XMLScanner::senseNextToken(XMLSize_t& orgReader)
{
// Get the next character and use it to guesstimate what the next token
// is going to be. We turn on end of entity exceptions when we do this
// in order to catch the scenario where the current entity ended at
// the > of some markup.
XMLCh nextCh=0;
XMLReader* curReader=fReaderMgr.getCurrentReader();
// avoid setting up the ThrowEOEJanitor if we know that we have data in the current reader
if(curReader && curReader->charsLeftInBuffer()>0)
nextCh = fReaderMgr.peekNextChar();
else
{
ThrowEOEJanitor janMgr(&fReaderMgr, true);
nextCh = fReaderMgr.peekNextChar();
}
// If it's not a '<' we must be in content (unless it's a EOF)
//
// This includes entity references '&' of some sort. These must
// be character data because that's the only place a reference can
// occur in content.
if (nextCh != chOpenAngle)
return nextCh?Token_CharData:Token_EOF;
// Ok it had to have been a '<' character. So get it out of the reader
// and store the reader number where we saw it, passing it back to the
// caller.
fReaderMgr.getNextChar();
orgReader = fReaderMgr.getCurrentReaderNum();
// Ok, so lets go through the things that it could be at this point which
// are all some form of markup.
switch(fReaderMgr.peekNextChar())
{
case chForwardSlash:
{
fReaderMgr.getNextChar();
return Token_EndTag;
}
case chBang:
{
static const XMLCh gCDATAStr[] =
{
chBang, chOpenSquare, chLatin_C, chLatin_D, chLatin_A
, chLatin_T, chLatin_A, chNull
};
static const XMLCh gCommentString[] =
{
chBang, chDash, chDash, chNull
};
if (fReaderMgr.skippedString(gCDATAStr))
return Token_CData;
if (fReaderMgr.skippedString(gCommentString))
return Token_Comment;
emitError(XMLErrs::ExpectedCommentOrCDATA);
return Token_Unknown;
}
case chQuestion:
{
// It must be a PI
fReaderMgr.getNextChar();
return Token_PI;
}
}
// Assume its an element name, so return with a start tag token. If it
// turns out not to be, then it will fail when it cannot get a valid tag.
return Token_StartTag;
}
// ---------------------------------------------------------------------------
// XMLScanner: Private parsing methods
// ---------------------------------------------------------------------------
// This guy just scans out a single or double quoted string of characters.
// It does not pass any judgement on the contents and assumes that it is
// illegal to have another quote of the same kind inside the string's
// contents.
//
// NOTE: This is for simple stuff like the strings in the XMLDecl which
// cannot have any entities inside them. So this guy does not handle any
// end of entity stuff.
bool XMLScanner::getQuotedString(XMLBuffer& toFill)
{
// Reset the target buffer
toFill.reset();
// Get the next char which must be a single or double quote
XMLCh quoteCh;
if (!fReaderMgr.skipIfQuote(quoteCh))
return false;
XMLCh nextCh;
// Get another char and see if it matches the starting quote char
while ((nextCh=fReaderMgr.getNextChar())!=quoteCh)
{
// We should never get either an end of file null char here. If we
// do, just fail. It will be handled more gracefully in the higher
// level code that called us.
if (!nextCh)
return false;
// Else add it to the buffer
toFill.append(nextCh);
}
return true;
}
// This method scans a character reference and returns the character that
// was refered to. It assumes that we've already scanned the &# characters
// that prefix the numeric code.
bool XMLScanner::scanCharRef(XMLCh& toFill, XMLCh& second)
{
bool gotOne = false;
unsigned int value = 0;
// Set the radix. Its supposed to be a lower case x if hex. But, in
// order to recover well, we check for an upper and put out an error
// for that.
unsigned int radix = 10;
if (fReaderMgr.skippedChar(chLatin_x))
{
radix = 16;
}
else if (fReaderMgr.skippedChar(chLatin_X))
{
emitError(XMLErrs::HexRadixMustBeLowerCase);
radix = 16;
}
while (true)
{
const XMLCh nextCh = fReaderMgr.peekNextChar();
// Watch for EOF
if (!nextCh)
ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager);
// Break out on the terminating semicolon
if (nextCh == chSemiColon)
{
fReaderMgr.getNextChar();
break;
}
// Convert this char to a binary value, or bail out if its not
// one.
unsigned int nextVal;
if ((nextCh >= chDigit_0) && (nextCh <= chDigit_9))
nextVal = (unsigned int)(nextCh - chDigit_0);
else if ((nextCh >= chLatin_A) && (nextCh <= chLatin_F))
nextVal= (unsigned int)(10 + (nextCh - chLatin_A));
else if ((nextCh >= chLatin_a) && (nextCh <= chLatin_f))
nextVal = (unsigned int)(10 + (nextCh - chLatin_a));
else
{
// Return a zero
toFill = 0;
// If we got at least a sigit, then do an unterminated ref error.
// Else, do an expected a numerical ref thing.
if (gotOne)
emitError(XMLErrs::UnterminatedCharRef);
else
emitError(XMLErrs::ExpectedNumericalCharRef);
// Return failure
return false;
}
// Make sure its valid for the radix. If not, then just eat the
// digit and go on after issueing an error. Else, update the
// running value with this new digit.
if (nextVal >= radix)
{
XMLCh tmpStr[2];
tmpStr[0] = nextCh;
tmpStr[1] = chNull;
emitError(XMLErrs::BadDigitForRadix, tmpStr);
}
else
{
value = (value * radix) + nextVal;
// Guard against overflow.
if (value > 0x10FFFF) {
// Character reference was not in the valid range
emitError(XMLErrs::InvalidCharacterRef);
return false;
}
}
// Indicate that we got at least one good digit
gotOne = true;
// And eat the last char
fReaderMgr.getNextChar();
}
// Return the char (or chars)
// And check if the character expanded is valid or not
if (value >= 0x10000 && value <= 0x10FFFF)
{
value -= 0x10000;
toFill = XMLCh((value >> 10) + 0xD800);
second = XMLCh((value & 0x3FF) + 0xDC00);
}
else if (value <= 0xFFFD)
{
toFill = XMLCh(value);
second = 0;
if (!fReaderMgr.getCurrentReader()->isXMLChar(toFill) && !fReaderMgr.getCurrentReader()->isControlChar(toFill)) {
// Character reference was not in the valid range
emitError(XMLErrs::InvalidCharacterRef);
return false;
}
}
else {
// Character reference was not in the valid range
emitError(XMLErrs::InvalidCharacterRef);
return false;
}
return true;
}
// We get here after the '<!--' part of the comment. We scan past the
// terminating '-->' It will calls the appropriate handler with the comment
// text, if one is provided. A comment can be in either the document or
// the DTD, so the fInDocument flag is used to know which handler to send
// it to.
void XMLScanner::scanComment()
{
enum States
{
InText
, OneDash
, TwoDashes
};
// Get a buffer for this
XMLBufBid bbComment(&fBufMgr);
// Get the comment text into a temp buffer. Be sure to use temp buffer
// two here, since its to be used for stuff that is potentially longer
// than just a name.
States curState = InText;
bool gotLeadingSurrogate = false;
while (true)
{
// Get the next character
const XMLCh nextCh = fReaderMgr.getNextChar();
// Watch for an end of file
if (!nextCh)
{
emitError(XMLErrs::UnterminatedComment);
ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager);
}
// Check for correct surrogate pairs
if ((nextCh >= 0xD800) && (nextCh <= 0xDBFF))
{
if (gotLeadingSurrogate)
emitError(XMLErrs::Expected2ndSurrogateChar);
else
gotLeadingSurrogate = true;
}
else
{
if (gotLeadingSurrogate)
{
if ((nextCh < 0xDC00) || (nextCh > 0xDFFF))
emitError(XMLErrs::Expected2ndSurrogateChar);
}
// Its got to at least be a valid XML character
else if (!fReaderMgr.getCurrentReader()->isXMLChar(nextCh)) {
XMLCh tmpBuf[9];
XMLString::binToText
(
nextCh
, tmpBuf
, 8
, 16
, fMemoryManager
);
emitError(XMLErrs::InvalidCharacter, tmpBuf);
}
gotLeadingSurrogate = false;
}
if (curState == InText)
{
// If its a dash, go to OneDash state. Otherwise take as text
if (nextCh == chDash)
curState = OneDash;
else
bbComment.append(nextCh);
}
else if (curState == OneDash)
{
// If its another dash, then we change to the two dashes states.
// Otherwise, we have to put in the deficit dash and the new
// character and go back to InText.
if (nextCh == chDash)
{
curState = TwoDashes;
}
else
{
bbComment.append(chDash);
bbComment.append(nextCh);
curState = InText;
}
}
else if (curState == TwoDashes)
{
// The next character must be the closing bracket
if (nextCh != chCloseAngle)
{
emitError(XMLErrs::IllegalSequenceInComment);
fReaderMgr.skipPastChar(chCloseAngle);
return;
}
break;
}
}
// If we have an available handler, call back with the comment.
if (fDocHandler)
{
fDocHandler->docComment
(
bbComment.getRawBuffer()
);
}
//mark comment is seen within the current element
if (! fElemStack.isEmpty())
fElemStack.setCommentOrPISeen();
}
// Most equal signs can have white space around them, so this little guy
// just makes the calling code cleaner by eating whitespace.
bool XMLScanner::scanEq(bool inDecl)
{
fReaderMgr.skipPastSpaces(inDecl);
if (fReaderMgr.skippedChar(chEqual))
{
fReaderMgr.skipPastSpaces(inDecl);
return true;
}
return false;
}
XMLSize_t
XMLScanner::scanUpToWSOr(XMLBuffer& toFill, const XMLCh chEndChar)
{
fReaderMgr.getUpToCharOrWS(toFill, chEndChar);
return toFill.getLen();
}
unsigned int *XMLScanner::getNewUIntPtr()
{
// this method hands back a new pointer initialized to 0
unsigned int *retVal;
if(fUIntPoolCol < 64)
{
retVal = fUIntPool[fUIntPoolRow]+fUIntPoolCol;
fUIntPoolCol++;
return retVal;
}
// time to grow the pool...
if(fUIntPoolRow+1 == fUIntPoolRowTotal)
{
// and time to add some space for new rows:
fUIntPoolRowTotal <<= 1;
unsigned int **newArray = (unsigned int **)fMemoryManager->allocate(sizeof(unsigned int *) * fUIntPoolRowTotal );
memcpy(newArray, fUIntPool, (fUIntPoolRow+1) * sizeof(unsigned int *));
fMemoryManager->deallocate(fUIntPool);
fUIntPool = newArray;
// need to 0 out new elements we won't need:
for (unsigned int i=fUIntPoolRow+2; i<fUIntPoolRowTotal; i++)
fUIntPool[i] = 0;
}
// now to add a new row; we just made sure we have space
fUIntPoolRow++;
fUIntPool[fUIntPoolRow] = (unsigned int *)fMemoryManager->allocate(sizeof(unsigned int) << 6);
memset(fUIntPool[fUIntPoolRow], 0, sizeof(unsigned int) << 6);
// point to next element
fUIntPoolCol = 1;
return fUIntPool[fUIntPoolRow];
}
void XMLScanner::resetUIntPool()
{
// to reuse the unsigned int pool--and the hashtables that use it--
// simply reinitialize everything to 0's
for(unsigned int i = 0; i<= fUIntPoolRow; i++)
memset(fUIntPool[i], 0, sizeof(unsigned int) << 6);
}
void XMLScanner::recreateUIntPool()
{
// this allows a bloated unsigned int pool to be dispensed with
// first, delete old fUIntPool
for (unsigned int i=0; i<=fUIntPoolRow; i++)
{
fMemoryManager->deallocate(fUIntPool[i]);
}
fMemoryManager->deallocate(fUIntPool);
fUIntPoolRow = fUIntPoolCol = 0;
fUIntPoolRowTotal = 2;
fUIntPool = (unsigned int **)fMemoryManager->allocate(sizeof(unsigned int *) * fUIntPoolRowTotal);
fUIntPool[0] = (unsigned int *)fMemoryManager->allocate(sizeof(unsigned int) << 6);
memset(fUIntPool[fUIntPoolRow], 0, sizeof(unsigned int) << 6);
fUIntPool[1] = 0;
}
XERCES_CPP_NAMESPACE_END
|
/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include "RequiredPlugin.h"
#include <sofa/core/ObjectFactory.h>
#include <sofa/helper/system/PluginManager.h>
namespace sofa
{
namespace component
{
namespace misc
{
SOFA_DECL_CLASS(RequiredPlugin)
int RequiredPluginClass = core::RegisterObject("Load required plugin")
.add< RequiredPlugin >();
RequiredPlugin::RequiredPlugin()
: pluginName( initData(&pluginName, "pluginName", "Name of the plugin to loaded. If this is empty, the name of this component is used as plugin name."))
{
this->f_printLog.setValue(true); // print log by default, to identify which pluging is responsible in case of a crash during loading
}
void RequiredPlugin::parse(sofa::core::objectmodel::BaseObjectDescription* arg)
{
Inherit1::parse(arg);
if (!pluginName.getValue().empty() || !name.getValue().empty())
loadPlugin();
}
void RequiredPlugin::loadPlugin()
{
std::string pluginPath = pluginName.getValue();
if(pluginPath.empty()) pluginPath = name.getValue();
std::string mainPluginPath = pluginPath;
sout << "Loading " << pluginPath << sendl;
if (sofa::helper::system::PluginManager::getInstance().loadPlugin(mainPluginPath)) // mainPluginPath is modified here...
{
sout << "Loaded " << mainPluginPath << sendl;
sofa::helper::system::PluginManager::getInstance().init();
}
// try to load the eventual plugin gui
pluginPath = pluginPath + "_gui";
if (sofa::helper::system::PluginManager::getInstance().loadPlugin(pluginPath,NULL))
{
sout << "Loaded " << pluginPath << sendl;
sofa::helper::system::PluginManager::getInstance().init();
}
}
}
}
}
r10514/sofa : plugin_gui cleaner fix
Former-commit-id: a23c5b62bae9df01760c020f0caf179ffc046cff
/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include "RequiredPlugin.h"
#include <sofa/core/ObjectFactory.h>
#include <sofa/helper/system/PluginManager.h>
namespace sofa
{
namespace component
{
namespace misc
{
SOFA_DECL_CLASS(RequiredPlugin)
int RequiredPluginClass = core::RegisterObject("Load required plugin")
.add< RequiredPlugin >();
RequiredPlugin::RequiredPlugin()
: pluginName( initData(&pluginName, "pluginName", "Name of the plugin to loaded. If this is empty, the name of this component is used as plugin name."))
{
this->f_printLog.setValue(true); // print log by default, to identify which pluging is responsible in case of a crash during loading
}
void RequiredPlugin::parse(sofa::core::objectmodel::BaseObjectDescription* arg)
{
Inherit1::parse(arg);
if (!pluginName.getValue().empty() || !name.getValue().empty())
loadPlugin();
}
void RequiredPlugin::loadPlugin()
{
if(pluginName.getValue().empty()) pluginName.setValue( name.getValue() );
std::string pluginPath = pluginName.getValue();
sout << "Loading " << pluginPath << sendl;
if (sofa::helper::system::PluginManager::getInstance().loadPlugin(pluginPath)) // pluginPath is modified here
{
sout << "Loaded " << pluginPath << sendl;
sofa::helper::system::PluginManager::getInstance().init();
}
// try to load the eventual plugin gui
pluginPath = pluginName.getValue() + "_gui";
if (sofa::helper::system::PluginManager::getInstance().loadPlugin(pluginPath,NULL))
{
sout << "Loaded " << pluginPath << sendl;
sofa::helper::system::PluginManager::getInstance().init();
}
}
}
}
}
|
#ifndef PIXELBOOST_DISABLE_BOX2D
#include "Box2D/Box2D.h"
#include "pixelboost/logic/component/physics/2d/staticBody.h"
#include "pixelboost/logic/component/transform.h"
#include "pixelboost/logic/message/transform.h"
#include "pixelboost/logic/entity.h"
#include "pixelboost/physics/2d/helpers.h"
using namespace pb;
StaticBody2DComponent::StaticBody2DComponent(Entity* parent, b2World* world, BodyType type, glm::vec2 size)
: PhysicsComponent(parent)
, _World(world)
{
pb::TransformComponent* transform = GetParent()->GetComponentByType<pb::TransformComponent>();
glm::vec3 position = transform->GetPosition();
b2BodyDef bodyDef;
bodyDef.position = b2Vec2(position.x, position.y);
bodyDef.type = b2_staticBody;
bodyDef.userData = this;
b2FixtureDef fixtureDef;
switch (type)
{
case kBodyTypeCircle:
{
b2CircleShape circle;
circle.m_radius = size.x;
fixtureDef.shape = &circle;
break;
}
case kBodyTypeRect:
{
b2PolygonShape rect;
rect.SetAsBox(size.x, size.y);
fixtureDef.shape = ▭
break;
}
}
_Body = world->CreateBody(&bodyDef);
_Body->CreateFixture(&fixtureDef);
GetParent()->RegisterMessageHandler(TransformChangedMessage::GetStaticType(), Entity::MessageHandler(this, &StaticBody2DComponent::OnTransformChanged));
}
StaticBody2DComponent::StaticBody2DComponent(Entity* parent, b2World* world, FixtureDefinition2D& definition)
: PhysicsComponent(parent)
, _World(world)
{
pb::TransformComponent* transform = GetParent()->GetComponentByType<pb::TransformComponent>();
glm::vec3 position = transform->GetPosition();
glm::vec3 scale = transform->GetScale();
_Body = PhysicsHelpers2D::CreateBodyFromDefinition(world, definition, glm::vec2(position.x,position.y), this, glm::vec2(scale.x, scale.y));
_Body->SetTransform(b2Vec2(position.x, position.y), glm::radians(transform->GetRotation().z));
GetParent()->RegisterMessageHandler(TransformChangedMessage::GetStaticType(), Entity::MessageHandler(this, &StaticBody2DComponent::OnTransformChanged));
}
StaticBody2DComponent::~StaticBody2DComponent()
{
GetParent()->UnregisterMessageHandler(TransformChangedMessage::GetStaticType(), Entity::MessageHandler(this, &StaticBody2DComponent::OnTransformChanged));
_World->DestroyBody(_Body);
}
pb::Uid StaticBody2DComponent::GetType()
{
return GetStaticType();
}
pb::Uid StaticBody2DComponent::GetStaticType()
{
return TypeHash("staticBody2D");
}
void StaticBody2DComponent::SetSensor(bool isSensor)
{
b2Fixture* fixture = _Body->GetFixtureList();
while (fixture)
{
fixture->SetSensor(isSensor);
fixture = fixture->GetNext();
}
}
void StaticBody2DComponent::OnTransformChanged(Uid sender, const Message& message)
{
UpdateTransform();
}
void StaticBody2DComponent::UpdateTransform()
{
TransformComponent* transform = GetParent()->GetComponentByType<TransformComponent>();
if (transform)
{
glm::vec3 position = transform->GetPosition();
glm::vec3 rotation = transform->GetRotation();
_Body->SetTransform(b2Vec2(position.x, position.y), rotation.z);
}
}
#endif
Fix use of out of scope variable
#ifndef PIXELBOOST_DISABLE_BOX2D
#include "Box2D/Box2D.h"
#include "pixelboost/logic/component/physics/2d/staticBody.h"
#include "pixelboost/logic/component/transform.h"
#include "pixelboost/logic/message/transform.h"
#include "pixelboost/logic/entity.h"
#include "pixelboost/physics/2d/helpers.h"
using namespace pb;
StaticBody2DComponent::StaticBody2DComponent(Entity* parent, b2World* world, BodyType type, glm::vec2 size)
: PhysicsComponent(parent)
, _World(world)
{
pb::TransformComponent* transform = GetParent()->GetComponentByType<pb::TransformComponent>();
glm::vec3 position = transform->GetPosition();
b2BodyDef bodyDef;
bodyDef.position = b2Vec2(position.x, position.y);
bodyDef.type = b2_staticBody;
bodyDef.userData = this;
b2FixtureDef fixtureDef;
b2CircleShape circle;
b2PolygonShape rect;
switch (type)
{
case kBodyTypeCircle:
{
circle.m_radius = size.x;
fixtureDef.shape = &circle;
break;
}
case kBodyTypeRect:
{
rect.SetAsBox(size.x, size.y);
fixtureDef.shape = ▭
break;
}
}
_Body = world->CreateBody(&bodyDef);
_Body->CreateFixture(&fixtureDef);
GetParent()->RegisterMessageHandler(TransformChangedMessage::GetStaticType(), Entity::MessageHandler(this, &StaticBody2DComponent::OnTransformChanged));
}
StaticBody2DComponent::StaticBody2DComponent(Entity* parent, b2World* world, FixtureDefinition2D& definition)
: PhysicsComponent(parent)
, _World(world)
{
pb::TransformComponent* transform = GetParent()->GetComponentByType<pb::TransformComponent>();
glm::vec3 position = transform->GetPosition();
glm::vec3 scale = transform->GetScale();
_Body = PhysicsHelpers2D::CreateBodyFromDefinition(world, definition, glm::vec2(position.x,position.y), this, glm::vec2(scale.x, scale.y));
_Body->SetTransform(b2Vec2(position.x, position.y), glm::radians(transform->GetRotation().z));
GetParent()->RegisterMessageHandler(TransformChangedMessage::GetStaticType(), Entity::MessageHandler(this, &StaticBody2DComponent::OnTransformChanged));
}
StaticBody2DComponent::~StaticBody2DComponent()
{
GetParent()->UnregisterMessageHandler(TransformChangedMessage::GetStaticType(), Entity::MessageHandler(this, &StaticBody2DComponent::OnTransformChanged));
_World->DestroyBody(_Body);
}
pb::Uid StaticBody2DComponent::GetType()
{
return GetStaticType();
}
pb::Uid StaticBody2DComponent::GetStaticType()
{
return TypeHash("staticBody2D");
}
void StaticBody2DComponent::SetSensor(bool isSensor)
{
b2Fixture* fixture = _Body->GetFixtureList();
while (fixture)
{
fixture->SetSensor(isSensor);
fixture = fixture->GetNext();
}
}
void StaticBody2DComponent::OnTransformChanged(Uid sender, const Message& message)
{
UpdateTransform();
}
void StaticBody2DComponent::UpdateTransform()
{
TransformComponent* transform = GetParent()->GetComponentByType<TransformComponent>();
if (transform)
{
glm::vec3 position = transform->GetPosition();
glm::vec3 rotation = transform->GetRotation();
_Body->SetTransform(b2Vec2(position.x, position.y), rotation.z);
}
}
#endif |
/*
Copyright (c) 2015, Ford Motor Company
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 Ford Motor Company 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 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 "application_manager/state_controller_impl.h"
#include "application_manager/usage_statistics.h"
#include "utils/helpers.h"
#include "utils/make_shared.h"
#include "connection_handler/connection_handler.h"
namespace application_manager {
CREATE_LOGGERPTR_GLOBAL(logger_, "StateControllerImpl")
bool IsStatusChanged(HmiStatePtr old_state, HmiStatePtr new_state) {
if (old_state->hmi_level() != new_state->hmi_level() ||
old_state->audio_streaming_state() !=
new_state->audio_streaming_state() ||
old_state->system_context() != new_state->system_context()) {
return true;
}
return false;
}
StateControllerImpl::StateControllerImpl(ApplicationManager& app_mngr)
: EventObserver(app_mngr.event_dispatcher()), app_mngr_(app_mngr) {
subscribe_on_event(hmi_apis::FunctionID::BasicCommunication_OnAppActivated);
subscribe_on_event(hmi_apis::FunctionID::BasicCommunication_OnAppDeactivated);
subscribe_on_event(hmi_apis::FunctionID::TTS_Started);
subscribe_on_event(hmi_apis::FunctionID::TTS_Stopped);
subscribe_on_event(hmi_apis::FunctionID::VR_Started);
subscribe_on_event(hmi_apis::FunctionID::VR_Stopped);
subscribe_on_event(hmi_apis::FunctionID::BasicCommunication_OnEventChanged);
}
void StateControllerImpl::SetRegularState(ApplicationSharedPtr app,
HmiStatePtr state,
const bool send_activate_app) {
CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
LOG4CXX_AUTO_TRACE(logger_);
if (!app) {
LOG4CXX_ERROR(logger_, "Invalid application pointer");
return;
}
DCHECK_OR_RETURN_VOID(state);
DCHECK_OR_RETURN_VOID(state->state_id() == HmiState::STATE_ID_REGULAR);
if (state->hmi_level() == mobile_apis::HMILevel::INVALID_ENUM ||
state->audio_streaming_state() ==
mobile_apis::AudioStreamingState::INVALID_ENUM ||
state->system_context() == mobile_apis::SystemContext::INVALID_ENUM) {
LOG4CXX_ERROR(logger_, "Get invalid state");
return;
}
if (app->is_resuming() && !IsResumptionAllowed(app, state)) {
return;
}
HmiStatePtr resolved_state = ResolveHmiState(app, state);
if (!resolved_state) {
state->set_state_id(HmiState::STATE_ID_POSTPONED);
app->SetPostponedState(state);
return;
}
hmi_apis::Common_HMILevel::eType hmi_level =
static_cast<hmi_apis::Common_HMILevel::eType>(
resolved_state->hmi_level());
const bool is_full_allowed = (hmi_apis::Common_HMILevel::FULL == hmi_level);
if (send_activate_app && is_full_allowed) {
const int64_t corr_id = SendBCActivateApp(app, hmi_level, true);
if (-1 != corr_id) {
subscribe_on_event(hmi_apis::FunctionID::BasicCommunication_ActivateApp,
corr_id);
waiting_for_activate[app->app_id()] = resolved_state;
return;
}
LOG4CXX_ERROR(logger_, "Unable to send BC.ActivateApp");
return;
}
ApplyRegularState(app, resolved_state);
}
void StateControllerImpl::SetRegularState(
ApplicationSharedPtr app,
const mobile_apis::HMILevel::eType hmi_level,
const mobile_apis::AudioStreamingState::eType audio_state,
const bool send_activate_app) {
CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
LOG4CXX_AUTO_TRACE(logger_);
if (!app) {
LOG4CXX_ERROR(logger_, "Invalid application pointer");
return;
}
HmiStatePtr prev_regular = app->RegularHmiState();
DCHECK_OR_RETURN_VOID(prev_regular);
HmiStatePtr hmi_state =
CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
DCHECK_OR_RETURN_VOID(hmi_state);
hmi_state->set_hmi_level(hmi_level);
hmi_state->set_audio_streaming_state(audio_state);
hmi_state->set_system_context(prev_regular->system_context());
SetRegularState(app, hmi_state, send_activate_app);
}
void StateControllerImpl::SetRegularState(
ApplicationSharedPtr app,
const mobile_apis::HMILevel::eType hmi_level,
const bool send_activate_app) {
using namespace mobile_apis;
using namespace helpers;
CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
LOG4CXX_AUTO_TRACE(logger_);
if (!app) {
LOG4CXX_ERROR(logger_, "Invalid application pointer");
return;
}
const HmiStatePtr hmi_state =
CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
DCHECK_OR_RETURN_VOID(hmi_state);
hmi_state->set_hmi_level(hmi_level);
hmi_state->set_audio_streaming_state(CalcAudioState(app, hmi_level));
hmi_state->set_system_context(SystemContext::SYSCTXT_MAIN);
SetRegularState(app, hmi_state, send_activate_app);
}
void StateControllerImpl::SetRegularState(
ApplicationSharedPtr app,
const mobile_apis::HMILevel::eType hmi_level,
const mobile_apis::AudioStreamingState::eType audio_state,
const mobile_apis::SystemContext::eType system_context,
const bool send_activate_app) {
CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
LOG4CXX_AUTO_TRACE(logger_);
if (!app) {
LOG4CXX_ERROR(logger_, "Invalid application pointer");
return;
}
HmiStatePtr hmi_state =
CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
DCHECK_OR_RETURN_VOID(hmi_state);
hmi_state->set_hmi_level(hmi_level);
hmi_state->set_audio_streaming_state(audio_state);
hmi_state->set_system_context(system_context);
SetRegularState(app, hmi_state, send_activate_app);
}
void StateControllerImpl::SetRegularState(
ApplicationSharedPtr app, const mobile_apis::HMILevel::eType hmi_level) {
CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
LOG4CXX_AUTO_TRACE(logger_);
if (!app) {
LOG4CXX_ERROR(logger_, "Invalid application pointer");
return;
}
HmiStatePtr prev_state = app->RegularHmiState();
HmiStatePtr hmi_state =
CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
DCHECK_OR_RETURN_VOID(hmi_state);
hmi_state->set_hmi_level(hmi_level);
hmi_state->set_audio_streaming_state(CalcAudioState(app, hmi_level));
hmi_state->set_system_context(prev_state
? prev_state->system_context()
: mobile_apis::SystemContext::SYSCTXT_MAIN);
SetRegularState(app, hmi_state);
}
void StateControllerImpl::SetRegularState(
ApplicationSharedPtr app,
const mobile_apis::SystemContext::eType system_context) {
CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
LOG4CXX_AUTO_TRACE(logger_);
if (!app) {
LOG4CXX_ERROR(logger_, "Invalid application pointer");
return;
}
HmiStatePtr prev_regular = app->RegularHmiState();
DCHECK_OR_RETURN_VOID(prev_regular);
HmiStatePtr hmi_state =
CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
DCHECK_OR_RETURN_VOID(hmi_state);
hmi_state->set_hmi_level(prev_regular->hmi_level());
hmi_state->set_audio_streaming_state(
CalcAudioState(app, prev_regular->hmi_level()));
hmi_state->set_system_context(system_context);
SetRegularState(app, hmi_state, false);
}
void StateControllerImpl::SetRegularState(
ApplicationSharedPtr app,
const mobile_apis::AudioStreamingState::eType audio_state) {
CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
LOG4CXX_AUTO_TRACE(logger_);
if (!app) {
LOG4CXX_ERROR(logger_, "Invalid application pointer");
return;
}
HmiStatePtr prev_state = app->RegularHmiState();
DCHECK_OR_RETURN_VOID(prev_state);
HmiStatePtr hmi_state =
CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
DCHECK_OR_RETURN_VOID(hmi_state);
hmi_state->set_hmi_level(prev_state->hmi_level());
hmi_state->set_audio_streaming_state(audio_state);
hmi_state->set_system_context(prev_state->system_context());
SetRegularState(app, hmi_state, false);
}
void StateControllerImpl::SetRegularState(ApplicationSharedPtr app,
HmiStatePtr state) {
CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
LOG4CXX_AUTO_TRACE(logger_);
if (!app) {
LOG4CXX_ERROR(logger_, "Invalid application pointer");
return;
}
DCHECK_OR_RETURN_VOID(state);
if (mobile_apis::HMILevel::HMI_FULL == state->hmi_level()) {
SetRegularState(app, state, true);
} else {
SetRegularState(app, state, false);
}
}
void StateControllerImpl::HmiLevelConflictResolver::operator()(
ApplicationSharedPtr to_resolve) {
using namespace mobile_apis;
using namespace helpers;
DCHECK_OR_RETURN_VOID(state_ctrl_);
if (to_resolve == applied_)
return;
HmiStatePtr cur_state = to_resolve->RegularHmiState();
const bool applied_grabs_audio =
Compare<HMILevel::eType, EQ, ONE>(
state_->hmi_level(), HMILevel::HMI_FULL, HMILevel::HMI_LIMITED) &&
applied_->IsAudioApplication();
const bool applied_grabs_full = state_->hmi_level() == HMILevel::HMI_FULL;
const bool to_resolve_handles_full =
cur_state->hmi_level() == HMILevel::HMI_FULL;
const bool to_resolve_handles_audio =
Compare<HMILevel::eType, EQ, ONE>(
cur_state->hmi_level(), HMILevel::HMI_FULL, HMILevel::HMI_LIMITED) &&
to_resolve->IsAudioApplication();
const bool same_app_type = state_ctrl_->IsSameAppType(applied_, to_resolve);
// If applied Hmi state is FULL:
// all not audio applications will get BACKGROUND
// all applications with same HMI type will get BACKGROUND
// all audio applications with other HMI type(navi, vc, media) in FULL will
// get LIMMITED HMI level
// If applied Hmi state is LIMITED:
// all applications with other HMI types will save HMI states
// all not audio applications will save HMI states
// all applications with same HMI type will get BACKGROUND
// If applied Hmi state is BACKGROUND:
// all applications will save HMI states
HMILevel::eType result_hmi_level = cur_state->hmi_level();
if (applied_grabs_full && to_resolve_handles_audio && !same_app_type)
result_hmi_level = HMILevel::HMI_LIMITED;
if ((applied_grabs_full && to_resolve_handles_full &&
!to_resolve->IsAudioApplication()) ||
(applied_grabs_audio && to_resolve_handles_audio && same_app_type))
result_hmi_level = HMILevel::HMI_BACKGROUND;
if (cur_state->hmi_level() != result_hmi_level) {
LOG4CXX_DEBUG(logger_,
"Application " << to_resolve->app_id()
<< " will change HMI level to "
<< result_hmi_level);
state_ctrl_->SetupRegularHmiState(to_resolve,
result_hmi_level,
result_hmi_level == HMILevel::HMI_LIMITED
? AudioStreamingState::AUDIBLE
: AudioStreamingState::NOT_AUDIBLE);
} else {
LOG4CXX_DEBUG(logger_,
"Application " << to_resolve->app_id()
<< " will not change HMI level");
}
}
HmiStatePtr StateControllerImpl::ResolveHmiState(ApplicationSharedPtr app,
HmiStatePtr state) const {
using namespace mobile_apis;
using namespace helpers;
LOG4CXX_AUTO_TRACE(logger_);
LOG4CXX_DEBUG(logger_,
"State to resolve: hmi_level "
<< state->hmi_level() << ", audio_state "
<< state->audio_streaming_state() << ", system_context "
<< state->system_context());
HmiStatePtr available_state =
CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
DCHECK_OR_RETURN(available_state, HmiStatePtr());
available_state->set_hmi_level(state->hmi_level());
available_state->set_audio_streaming_state(state->audio_streaming_state());
available_state->set_system_context(state->system_context());
if (app->is_resuming()) {
HMILevel::eType available_level =
GetAvailableHmiLevel(app, state->hmi_level());
available_state->set_hmi_level(available_level);
available_state->set_audio_streaming_state(
CalcAudioState(app, available_level));
}
return IsStateAvailable(app, available_state) ? available_state
: HmiStatePtr();
}
bool StateControllerImpl::IsResumptionAllowed(ApplicationSharedPtr app,
HmiStatePtr state) const {
LOG4CXX_AUTO_TRACE(logger_);
using namespace helpers;
using namespace mobile_apis;
if (!app->is_resuming() ||
!Compare<HMILevel::eType, EQ, ONE>(
state->hmi_level(), HMILevel::HMI_FULL, HMILevel::HMI_LIMITED)) {
LOG4CXX_DEBUG(logger_, "Application is not in resuming mode.");
return true;
}
if (IsTempStateActive(HmiState::StateID::STATE_ID_AUDIO_SOURCE) &&
app->is_media_application()) {
LOG4CXX_DEBUG(logger_,
"Resumption for media app is not allowed. "
<< "AUDIO_SOURCE event is active");
return false;
}
if (IsTempStateActive(HmiState::StateID::STATE_ID_EMBEDDED_NAVI) &&
app->is_navi()) {
LOG4CXX_DEBUG(logger_,
"Resumption for navi app is not allowed. "
<< "EMBEDDED_NAVI event is active");
return false;
}
return true;
}
mobile_apis::HMILevel::eType StateControllerImpl::GetAvailableHmiLevel(
ApplicationSharedPtr app, mobile_apis::HMILevel::eType hmi_level) const {
using namespace mobile_apis;
using namespace helpers;
LOG4CXX_AUTO_TRACE(logger_);
mobile_apis::HMILevel::eType result = hmi_level;
if (!Compare<HMILevel::eType, EQ, ONE>(
hmi_level, HMILevel::HMI_FULL, HMILevel::HMI_LIMITED)) {
return result;
}
const bool is_audio_app = app->IsAudioApplication();
const bool does_audio_app_with_same_type_exist =
app_mngr_.IsAppTypeExistsInFullOrLimited(app);
if (HMILevel::HMI_LIMITED == hmi_level) {
if (!is_audio_app || does_audio_app_with_same_type_exist) {
result = app_mngr_.GetDefaultHmiLevel(app);
}
return result;
}
const bool is_active_app_exist = app_mngr_.active_application();
if (is_audio_app) {
if (does_audio_app_with_same_type_exist) {
result = app_mngr_.GetDefaultHmiLevel(app);
} else if (is_active_app_exist) {
result = mobile_apis::HMILevel::HMI_LIMITED;
} else if (app->is_navi() &&
IsTempStateActive(HmiState::StateID::STATE_ID_AUDIO_SOURCE)) {
LOG4CXX_DEBUG(logger_,
"Navigation app will be resumed to LIMITED, "
"because of AUDIO_SOURCE ia active.");
result = mobile_apis::HMILevel::HMI_LIMITED;
} else if (app->is_media_application() &&
IsTempStateActive(HmiState::StateID::STATE_ID_EMBEDDED_NAVI)) {
LOG4CXX_DEBUG(logger_,
"Media app will be resumed to LIMITED, "
"because of EMBEDDED_NAVI is active.");
result = mobile_apis::HMILevel::HMI_LIMITED;
}
} else if (is_active_app_exist) {
result = app_mngr_.GetDefaultHmiLevel(app);
}
return result;
}
bool StateControllerImpl::IsStateAvailable(ApplicationSharedPtr app,
HmiStatePtr state) const {
using namespace mobile_apis;
using namespace helpers;
LOG4CXX_AUTO_TRACE(logger_);
LOG4CXX_DEBUG(logger_,
"Checking state: hmi_level "
<< state->hmi_level() << ", audio_state "
<< state->audio_streaming_state() << ", system_context "
<< state->system_context());
if (app->is_resuming()) {
return IsStateAvailableForResumption(app, state);
}
if (IsTempStateActive(HmiState::StateID::STATE_ID_AUDIO_SOURCE) ||
IsTempStateActive(HmiState::StateID::STATE_ID_EMBEDDED_NAVI)) {
if (HMILevel::HMI_FULL == state->hmi_level()) {
LOG4CXX_DEBUG(logger_,
"AUDIO_SOURCE or EMBEDDED_NAVI is active."
<< " Requested state is not available");
return false;
}
}
LOG4CXX_DEBUG(logger_, "Requested state is available");
return true;
}
bool StateControllerImpl::IsStateAvailableForResumption(
ApplicationSharedPtr app, HmiStatePtr state) const {
LOG4CXX_AUTO_TRACE(logger_);
using namespace mobile_apis;
using namespace helpers;
if (!app->is_resuming() ||
!Compare<HMILevel::eType, EQ, ONE>(
state->hmi_level(), HMILevel::HMI_FULL, HMILevel::HMI_LIMITED)) {
LOG4CXX_DEBUG(logger_,
"Application is not in resuming mode."
<< " Requested state is available");
return true;
}
if (IsTempStateActive(HmiState::StateID::STATE_ID_VR_SESSION) ||
IsTempStateActive(HmiState::StateID::STATE_ID_SAFETY_MODE)) {
LOG4CXX_DEBUG(logger_,
"Requested state is not available. "
<< "VR session or emergency event is active");
return false;
}
if (IsTempStateActive(HmiState::StateID::STATE_ID_PHONE_CALL) &&
app->is_media_application()) {
LOG4CXX_DEBUG(logger_,
"Requested state for media application "
<< "is not available. Phone call is active");
return false;
}
if (IsTempStateActive(HmiState::StateID::STATE_ID_DEACTIVATE_HMI)) {
LOG4CXX_DEBUG(logger_,
"Requested state is not available. "
<< "Deactivate HMI event is active");
return false;
}
LOG4CXX_DEBUG(logger_, "Requested state is available");
return true;
}
void StateControllerImpl::SetupRegularHmiState(ApplicationSharedPtr app,
HmiStatePtr state) {
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
LOG4CXX_AUTO_TRACE(logger_);
DCHECK_OR_RETURN_VOID(state);
LOG4CXX_DEBUG(logger_,
"hmi_level " << state->hmi_level() << ", audio_state "
<< state->audio_streaming_state()
<< ", system_context " << state->system_context());
HmiStatePtr curr_state = app->CurrentHmiState();
HmiStatePtr old_state =
CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
DCHECK_OR_RETURN_VOID(old_state);
old_state->set_hmi_level(curr_state->hmi_level());
old_state->set_audio_streaming_state(curr_state->audio_streaming_state());
old_state->set_system_context(curr_state->system_context());
app->SetRegularState(state);
if (HMILevel::HMI_LIMITED == state->hmi_level() && app->is_resuming()) {
LOG4CXX_DEBUG(logger_,
"Resuming to LIMITED level. "
<< "Send OnResumeAudioSource notification");
MessageHelper::SendOnResumeAudioSourceToHMI(app->app_id(), app_mngr_);
}
app->set_is_resuming(false);
HmiStatePtr new_state = app->CurrentHmiState();
OnStateChanged(app, old_state, new_state);
}
void StateControllerImpl::SetupRegularHmiState(
ApplicationSharedPtr app,
const mobile_apis::HMILevel::eType hmi_level,
const mobile_apis::AudioStreamingState::eType audio_state) {
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
using helpers::Compare;
LOG4CXX_AUTO_TRACE(logger_);
DCHECK_OR_RETURN_VOID(app);
HmiStatePtr prev_state = app->RegularHmiState();
DCHECK_OR_RETURN_VOID(prev_state);
HmiStatePtr new_state =
CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
DCHECK_OR_RETURN_VOID(new_state);
new_state->set_hmi_level(hmi_level);
new_state->set_audio_streaming_state(audio_state);
new_state->set_system_context(prev_state->system_context());
SetupRegularHmiState(app, new_state);
}
void StateControllerImpl::ApplyRegularState(ApplicationSharedPtr app,
HmiStatePtr state) {
LOG4CXX_AUTO_TRACE(logger_);
DCHECK_OR_RETURN_VOID(app);
DCHECK_OR_RETURN_VOID(state);
DCHECK_OR_RETURN_VOID(state->state_id() == HmiState::STATE_ID_REGULAR);
SetupRegularHmiState(app, state);
ForEachApplication<HmiLevelConflictResolver>(
HmiLevelConflictResolver(app, state, this));
}
bool StateControllerImpl::IsSameAppType(ApplicationConstSharedPtr app1,
ApplicationConstSharedPtr app2) {
const bool both_media =
app1->is_media_application() && app2->is_media_application();
const bool both_navi = app1->is_navi() && app2->is_navi();
const bool both_vc = app1->is_voice_communication_supported() &&
app2->is_voice_communication_supported();
const bool both_simple =
!app1->IsAudioApplication() && !app2->IsAudioApplication();
return both_simple || both_media || both_navi || both_vc;
}
void StateControllerImpl::on_event(const event_engine::Event& event) {
using smart_objects::SmartObject;
using event_engine::Event;
using namespace hmi_apis;
namespace FunctionID = hmi_apis::FunctionID;
LOG4CXX_AUTO_TRACE(logger_);
const SmartObject& message = event.smart_object();
const FunctionID::eType id = static_cast<FunctionID::eType>(event.id());
switch (id) {
case FunctionID::BasicCommunication_ActivateApp: {
OnActivateAppResponse(message);
break;
}
case FunctionID::BasicCommunication_OnAppActivated: {
OnAppActivated(message);
break;
}
case FunctionID::BasicCommunication_OnAppDeactivated: {
OnAppDeactivated(message);
break;
}
case FunctionID::VR_Started: {
ApplyTempState<HmiState::STATE_ID_VR_SESSION>();
break;
}
case FunctionID::VR_Stopped: {
CancelTempState<HmiState::STATE_ID_VR_SESSION>();
break;
}
case FunctionID::TTS_Started: {
ApplyTempState<HmiState::STATE_ID_TTS_SESSION>();
break;
}
case FunctionID::TTS_Stopped: {
CancelTempState<HmiState::STATE_ID_TTS_SESSION>();
break;
}
case FunctionID::BasicCommunication_OnEventChanged: {
bool is_active =
message[strings::msg_params][hmi_notification::is_active].asBool();
const uint32_t id =
message[strings::msg_params][hmi_notification::event_name].asUInt();
// TODO(AOleynik): Add verification/conversion check here
Common_EventTypes::eType state_id =
static_cast<Common_EventTypes::eType>(id);
if (is_active) {
if (Common_EventTypes::AUDIO_SOURCE == state_id) {
ApplyTempState<HmiState::STATE_ID_AUDIO_SOURCE>();
break;
}
if (Common_EventTypes::EMBEDDED_NAVI == state_id) {
ApplyTempState<HmiState::STATE_ID_EMBEDDED_NAVI>();
break;
}
if (Common_EventTypes::PHONE_CALL == state_id) {
ApplyTempState<HmiState::STATE_ID_PHONE_CALL>();
break;
}
if (Common_EventTypes::EMERGENCY_EVENT == state_id) {
ApplyTempState<HmiState::STATE_ID_SAFETY_MODE>();
break;
}
if (Common_EventTypes::DEACTIVATE_HMI == state_id) {
ApplyTempState<HmiState::STATE_ID_DEACTIVATE_HMI>();
break;
}
} else {
if (Common_EventTypes::AUDIO_SOURCE == state_id) {
CancelTempState<HmiState::STATE_ID_AUDIO_SOURCE>();
break;
}
if (Common_EventTypes::EMBEDDED_NAVI == state_id) {
CancelTempState<HmiState::STATE_ID_EMBEDDED_NAVI>();
break;
}
if (Common_EventTypes::PHONE_CALL == state_id) {
CancelTempState<HmiState::STATE_ID_PHONE_CALL>();
break;
}
if (Common_EventTypes::EMERGENCY_EVENT == state_id) {
CancelTempState<HmiState::STATE_ID_SAFETY_MODE>();
break;
}
if (Common_EventTypes::DEACTIVATE_HMI == state_id) {
CancelTempState<HmiState::STATE_ID_DEACTIVATE_HMI>();
break;
}
}
break;
}
default:
break;
}
}
void StateControllerImpl::OnStateChanged(ApplicationSharedPtr app,
HmiStatePtr old_state,
HmiStatePtr new_state) {
LOG4CXX_AUTO_TRACE(logger_);
DCHECK_OR_RETURN_VOID(app);
DCHECK_OR_RETURN_VOID(old_state);
DCHECK_OR_RETURN_VOID(new_state);
LOG4CXX_DEBUG(logger_,
"old: hmi_level " << old_state->hmi_level() << ", audio_state "
<< old_state->audio_streaming_state()
<< ", system_context "
<< old_state->system_context());
LOG4CXX_DEBUG(logger_,
"new: hmi_level " << new_state->hmi_level() << ", audio_state "
<< new_state->audio_streaming_state()
<< ", system_context "
<< new_state->system_context());
if (IsStatusChanged(old_state, new_state)) {
app_mngr_.SendHMIStatusNotification(app);
if (new_state->hmi_level() == mobile_apis::HMILevel::HMI_NONE) {
app->ResetDataInNone();
}
app_mngr_.OnHMILevelChanged(
app->app_id(), old_state->hmi_level(), new_state->hmi_level());
app->usage_report().RecordHmiStateChanged(new_state->hmi_level());
} else {
LOG4CXX_ERROR(logger_, "Status not changed");
}
}
bool StateControllerImpl::IsTempStateActive(HmiState::StateID ID) const {
sync_primitives::AutoLock autolock(active_states_lock_);
StateIDList::const_iterator itr =
std::find(active_states_.begin(), active_states_.end(), ID);
return active_states_.end() != itr;
}
void StateControllerImpl::OnApplicationRegistered(
ApplicationSharedPtr app,
const mobile_apis::HMILevel::eType default_level) {
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
namespace SystemContext = mobile_apis::SystemContext;
LOG4CXX_AUTO_TRACE(logger_);
DCHECK_OR_RETURN_VOID(app);
active_states_lock_.Acquire();
StateIDList::iterator it = active_states_.begin();
for (; it != active_states_.end(); ++it) {
HmiStatePtr new_state = CreateHmiState(app->app_id(), *it);
DCHECK_OR_RETURN_VOID(new_state);
DCHECK_OR_RETURN_VOID(new_state->state_id() != HmiState::STATE_ID_REGULAR);
HmiStatePtr old_hmi_state = app->CurrentHmiState();
new_state->set_parent(old_hmi_state);
app->AddHMIState(new_state);
}
active_states_lock_.Release();
HmiStatePtr default_state =
CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
DCHECK_OR_RETURN_VOID(default_state);
default_state->set_hmi_level(default_level);
default_state->set_audio_streaming_state(CalcAudioState(app, default_level));
default_state->set_system_context(SystemContext::SYSCTXT_MAIN);
HmiStatePtr initial_state = app->RegularHmiState();
app->SetRegularState(default_state);
HmiStatePtr new_state = app->CurrentHmiState();
OnStateChanged(app, initial_state, new_state);
}
int64_t StateControllerImpl::SendBCActivateApp(
ApplicationConstSharedPtr app,
hmi_apis::Common_HMILevel::eType level,
bool send_policy_priority) {
LOG4CXX_AUTO_TRACE(logger_);
smart_objects::SmartObjectSPtr bc_activate_app_request =
MessageHelper::GetBCActivateAppRequestToHMI(
app,
app_mngr_.connection_handler().get_session_observer(),
app_mngr_.GetPolicyHandler(),
level,
send_policy_priority,
app_mngr_);
if (!bc_activate_app_request) {
LOG4CXX_ERROR(logger_, "Unable to create BC.ActivateAppRequest");
return -1;
}
if (!app_mngr_.ManageHMICommand(bc_activate_app_request)) {
LOG4CXX_ERROR(logger_, "Unable to send BC.ActivateAppRequest");
return -1;
}
const int64_t corr_id =
(*bc_activate_app_request)[strings::params][strings::correlation_id]
.asInt();
return corr_id;
}
void StateControllerImpl::ApplyPostponedStateForApp(ApplicationSharedPtr app) {
LOG4CXX_AUTO_TRACE(logger_);
HmiStatePtr state = app->PostponedHmiState();
if (state) {
app->RemovePostponedState();
state->set_state_id(HmiState::STATE_ID_REGULAR);
SetRegularState(app, state);
}
}
void StateControllerImpl::TempStateStarted(HmiState::StateID ID) {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock autolock(active_states_lock_);
StateIDList::iterator it =
std::find(active_states_.begin(), active_states_.end(), ID);
if (it == active_states_.end()) {
active_states_.push_back(ID);
} else {
LOG4CXX_ERROR(logger_, "StateID " << ID << " is already active");
}
}
void StateControllerImpl::TempStateStopped(HmiState::StateID ID) {
LOG4CXX_AUTO_TRACE(logger_);
{
sync_primitives::AutoLock autolock(active_states_lock_);
active_states_.remove(ID);
}
ForEachApplication(std::bind1st(
std::mem_fun(&StateControllerImpl::ApplyPostponedStateForApp), this));
}
void StateControllerImpl::DeactivateApp(ApplicationSharedPtr app) {
using namespace mobile_apis;
LOG4CXX_AUTO_TRACE(logger_);
DCHECK_OR_RETURN_VOID(app);
HmiStatePtr regular = app->RegularHmiState();
DCHECK_OR_RETURN_VOID(regular);
HmiStatePtr new_regular = utils::MakeShared<HmiState>(*regular);
if (app->IsAudioApplication()) {
new_regular->set_hmi_level(HMILevel::HMI_LIMITED);
new_regular->set_audio_streaming_state(AudioStreamingState::AUDIBLE);
} else {
new_regular->set_hmi_level(HMILevel::HMI_BACKGROUND);
new_regular->set_audio_streaming_state(AudioStreamingState::NOT_AUDIBLE);
}
SetRegularState(app, new_regular, false);
}
void StateControllerImpl::OnActivateAppResponse(
const smart_objects::SmartObject& message) {
const hmi_apis::Common_Result::eType code =
static_cast<hmi_apis::Common_Result::eType>(
message[strings::params][hmi_response::code].asInt());
const int32_t correlation_id =
message[strings::params][strings::correlation_id].asInt();
const uint32_t hmi_app_id = app_mngr_.application_id(correlation_id);
ApplicationSharedPtr application =
app_mngr_.application_by_hmi_app(hmi_app_id);
if (application && hmi_apis::Common_Result::SUCCESS == code) {
HmiStatePtr pending_state = waiting_for_activate[application->app_id()];
DCHECK_OR_RETURN_VOID(pending_state);
ApplyRegularState(application, pending_state);
}
}
void StateControllerImpl::OnAppActivated(
const smart_objects::SmartObject& message) {
using namespace mobile_apis;
LOG4CXX_AUTO_TRACE(logger_);
uint32_t app_id = message[strings::msg_params][strings::app_id].asUInt();
ApplicationSharedPtr app = app_mngr_.application(app_id);
if (!app) {
LOG4CXX_ERROR(logger_, "Application with id " << app_id << " not found");
return;
}
SetRegularState(app, HMILevel::HMI_FULL, true);
}
void StateControllerImpl::OnAppDeactivated(
const smart_objects::SmartObject& message) {
using namespace hmi_apis;
using namespace mobile_apis;
using namespace helpers;
LOG4CXX_AUTO_TRACE(logger_);
uint32_t app_id = message[strings::msg_params][strings::app_id].asUInt();
ApplicationSharedPtr app = app_mngr_.application(app_id);
if (!app) {
LOG4CXX_ERROR(logger_, "Application with id " << app_id << " not found");
return;
}
if (HMILevel::HMI_FULL != app->hmi_level()) {
return;
}
// TODO(AOleynik): Need to delete DeactivateReason and modify OnAppDeactivated
// when HMI will support that, otherwise won't be testable
DeactivateApp(app);
}
void StateControllerImpl::OnNaviStreamingStarted() {
ApplyTempState<HmiState::STATE_ID_NAVI_STREAMING>();
}
void StateControllerImpl::OnNaviStreamingStopped() {
CancelTempState<HmiState::STATE_ID_NAVI_STREAMING>();
}
bool StateControllerImpl::IsStateActive(HmiState::StateID state_id) const {
LOG4CXX_AUTO_TRACE(logger_);
switch (state_id) {
case HmiState::STATE_ID_CURRENT:
case HmiState::STATE_ID_REGULAR:
return true;
default:
return IsTempStateActive(state_id);
}
return false;
}
HmiStatePtr StateControllerImpl::CreateHmiState(
uint32_t app_id, HmiState::StateID state_id) const {
using namespace utils;
LOG4CXX_AUTO_TRACE(logger_);
HmiStatePtr new_state;
switch (state_id) {
case HmiState::STATE_ID_PHONE_CALL: {
new_state = MakeShared<PhoneCallHmiState>(app_id, app_mngr_);
break;
}
case HmiState::STATE_ID_SAFETY_MODE: {
new_state = MakeShared<SafetyModeHmiState>(app_id, app_mngr_);
break;
}
case HmiState::STATE_ID_VR_SESSION: {
new_state = MakeShared<VRHmiState>(app_id, app_mngr_);
break;
}
case HmiState::STATE_ID_TTS_SESSION: {
new_state = MakeShared<TTSHmiState>(app_id, app_mngr_);
break;
}
case HmiState::STATE_ID_NAVI_STREAMING: {
new_state = MakeShared<NaviStreamingHmiState>(app_id, app_mngr_);
break;
}
case HmiState::STATE_ID_REGULAR: {
new_state = MakeShared<HmiState>(app_id, app_mngr_);
break;
}
case HmiState::STATE_ID_POSTPONED: {
new_state = MakeShared<HmiState>(app_id, app_mngr_, state_id);
break;
}
case HmiState::STATE_ID_DEACTIVATE_HMI: {
new_state = MakeShared<DeactivateHMI>(app_id, app_mngr_);
break;
}
case HmiState::STATE_ID_AUDIO_SOURCE: {
new_state = MakeShared<AudioSource>(app_id, app_mngr_);
break;
}
case HmiState::STATE_ID_EMBEDDED_NAVI: {
new_state = MakeShared<EmbeddedNavi>(app_id, app_mngr_);
break;
}
default:
LOG4CXX_FATAL(logger_, "Invalid state_id " << state_id);
NOTREACHED();
break;
}
return new_state;
}
mobile_apis::AudioStreamingState::eType StateControllerImpl::CalcAudioState(
ApplicationSharedPtr app,
const mobile_apis::HMILevel::eType hmi_level) const {
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
using helpers::Compare;
using helpers::EQ;
using helpers::ONE;
AudioStreamingState::eType audio_state = AudioStreamingState::NOT_AUDIBLE;
if (Compare<HMILevel::eType, EQ, ONE>(
hmi_level, HMILevel::HMI_FULL, HMILevel::HMI_LIMITED)) {
if (app->IsAudioApplication()) {
audio_state = AudioStreamingState::AUDIBLE;
}
}
return audio_state;
}
} // namespace application_manager
Fix SDL BC.ActivateApp for NONE level
Fixed problem that SDL BC.ActivateApp wasn't sent in case of user replies
"NO" for data consent prompt.
The problem was in additional check that SDL BC.ActivateApp could be sent only if
HMI level was FULL. But in case of negative user reply HMI level must be NONE.
Therefore this check was deleted.
Related: APPLINK-30617
/*
Copyright (c) 2015, Ford Motor Company
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 Ford Motor Company 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 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 "application_manager/state_controller_impl.h"
#include "application_manager/usage_statistics.h"
#include "utils/helpers.h"
#include "utils/make_shared.h"
#include "connection_handler/connection_handler.h"
namespace application_manager {
CREATE_LOGGERPTR_GLOBAL(logger_, "StateControllerImpl")
bool IsStatusChanged(HmiStatePtr old_state, HmiStatePtr new_state) {
if (old_state->hmi_level() != new_state->hmi_level() ||
old_state->audio_streaming_state() !=
new_state->audio_streaming_state() ||
old_state->system_context() != new_state->system_context()) {
return true;
}
return false;
}
StateControllerImpl::StateControllerImpl(ApplicationManager& app_mngr)
: EventObserver(app_mngr.event_dispatcher()), app_mngr_(app_mngr) {
subscribe_on_event(hmi_apis::FunctionID::BasicCommunication_OnAppActivated);
subscribe_on_event(hmi_apis::FunctionID::BasicCommunication_OnAppDeactivated);
subscribe_on_event(hmi_apis::FunctionID::TTS_Started);
subscribe_on_event(hmi_apis::FunctionID::TTS_Stopped);
subscribe_on_event(hmi_apis::FunctionID::VR_Started);
subscribe_on_event(hmi_apis::FunctionID::VR_Stopped);
subscribe_on_event(hmi_apis::FunctionID::BasicCommunication_OnEventChanged);
}
void StateControllerImpl::SetRegularState(ApplicationSharedPtr app,
HmiStatePtr state,
const bool send_activate_app) {
CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
LOG4CXX_AUTO_TRACE(logger_);
if (!app) {
LOG4CXX_ERROR(logger_, "Invalid application pointer");
return;
}
DCHECK_OR_RETURN_VOID(state);
DCHECK_OR_RETURN_VOID(state->state_id() == HmiState::STATE_ID_REGULAR);
if (state->hmi_level() == mobile_apis::HMILevel::INVALID_ENUM ||
state->audio_streaming_state() ==
mobile_apis::AudioStreamingState::INVALID_ENUM ||
state->system_context() == mobile_apis::SystemContext::INVALID_ENUM) {
LOG4CXX_ERROR(logger_, "Get invalid state");
return;
}
if (app->is_resuming() && !IsResumptionAllowed(app, state)) {
return;
}
HmiStatePtr resolved_state = ResolveHmiState(app, state);
if (!resolved_state) {
state->set_state_id(HmiState::STATE_ID_POSTPONED);
app->SetPostponedState(state);
return;
}
hmi_apis::Common_HMILevel::eType hmi_level =
static_cast<hmi_apis::Common_HMILevel::eType>(
resolved_state->hmi_level());
if (send_activate_app) {
const int64_t corr_id = SendBCActivateApp(app, hmi_level, true);
if (-1 != corr_id) {
subscribe_on_event(hmi_apis::FunctionID::BasicCommunication_ActivateApp,
corr_id);
waiting_for_activate[app->app_id()] = resolved_state;
return;
}
LOG4CXX_ERROR(logger_, "Unable to send BC.ActivateApp");
return;
}
ApplyRegularState(app, resolved_state);
}
void StateControllerImpl::SetRegularState(
ApplicationSharedPtr app,
const mobile_apis::HMILevel::eType hmi_level,
const mobile_apis::AudioStreamingState::eType audio_state,
const bool send_activate_app) {
CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
LOG4CXX_AUTO_TRACE(logger_);
if (!app) {
LOG4CXX_ERROR(logger_, "Invalid application pointer");
return;
}
HmiStatePtr prev_regular = app->RegularHmiState();
DCHECK_OR_RETURN_VOID(prev_regular);
HmiStatePtr hmi_state =
CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
DCHECK_OR_RETURN_VOID(hmi_state);
hmi_state->set_hmi_level(hmi_level);
hmi_state->set_audio_streaming_state(audio_state);
hmi_state->set_system_context(prev_regular->system_context());
SetRegularState(app, hmi_state, send_activate_app);
}
void StateControllerImpl::SetRegularState(
ApplicationSharedPtr app,
const mobile_apis::HMILevel::eType hmi_level,
const bool send_activate_app) {
using namespace mobile_apis;
using namespace helpers;
CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
LOG4CXX_AUTO_TRACE(logger_);
if (!app) {
LOG4CXX_ERROR(logger_, "Invalid application pointer");
return;
}
const HmiStatePtr hmi_state =
CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
DCHECK_OR_RETURN_VOID(hmi_state);
hmi_state->set_hmi_level(hmi_level);
hmi_state->set_audio_streaming_state(CalcAudioState(app, hmi_level));
hmi_state->set_system_context(SystemContext::SYSCTXT_MAIN);
SetRegularState(app, hmi_state, send_activate_app);
}
void StateControllerImpl::SetRegularState(
ApplicationSharedPtr app,
const mobile_apis::HMILevel::eType hmi_level,
const mobile_apis::AudioStreamingState::eType audio_state,
const mobile_apis::SystemContext::eType system_context,
const bool send_activate_app) {
CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
LOG4CXX_AUTO_TRACE(logger_);
if (!app) {
LOG4CXX_ERROR(logger_, "Invalid application pointer");
return;
}
HmiStatePtr hmi_state =
CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
DCHECK_OR_RETURN_VOID(hmi_state);
hmi_state->set_hmi_level(hmi_level);
hmi_state->set_audio_streaming_state(audio_state);
hmi_state->set_system_context(system_context);
SetRegularState(app, hmi_state, send_activate_app);
}
void StateControllerImpl::SetRegularState(
ApplicationSharedPtr app, const mobile_apis::HMILevel::eType hmi_level) {
CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
LOG4CXX_AUTO_TRACE(logger_);
if (!app) {
LOG4CXX_ERROR(logger_, "Invalid application pointer");
return;
}
HmiStatePtr prev_state = app->RegularHmiState();
HmiStatePtr hmi_state =
CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
DCHECK_OR_RETURN_VOID(hmi_state);
hmi_state->set_hmi_level(hmi_level);
hmi_state->set_audio_streaming_state(CalcAudioState(app, hmi_level));
hmi_state->set_system_context(prev_state
? prev_state->system_context()
: mobile_apis::SystemContext::SYSCTXT_MAIN);
SetRegularState(app, hmi_state);
}
void StateControllerImpl::SetRegularState(
ApplicationSharedPtr app,
const mobile_apis::SystemContext::eType system_context) {
CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
LOG4CXX_AUTO_TRACE(logger_);
if (!app) {
LOG4CXX_ERROR(logger_, "Invalid application pointer");
return;
}
HmiStatePtr prev_regular = app->RegularHmiState();
DCHECK_OR_RETURN_VOID(prev_regular);
HmiStatePtr hmi_state =
CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
DCHECK_OR_RETURN_VOID(hmi_state);
hmi_state->set_hmi_level(prev_regular->hmi_level());
hmi_state->set_audio_streaming_state(
CalcAudioState(app, prev_regular->hmi_level()));
hmi_state->set_system_context(system_context);
SetRegularState(app, hmi_state, false);
}
void StateControllerImpl::SetRegularState(
ApplicationSharedPtr app,
const mobile_apis::AudioStreamingState::eType audio_state) {
CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
LOG4CXX_AUTO_TRACE(logger_);
if (!app) {
LOG4CXX_ERROR(logger_, "Invalid application pointer");
return;
}
HmiStatePtr prev_state = app->RegularHmiState();
DCHECK_OR_RETURN_VOID(prev_state);
HmiStatePtr hmi_state =
CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
DCHECK_OR_RETURN_VOID(hmi_state);
hmi_state->set_hmi_level(prev_state->hmi_level());
hmi_state->set_audio_streaming_state(audio_state);
hmi_state->set_system_context(prev_state->system_context());
SetRegularState(app, hmi_state, false);
}
void StateControllerImpl::SetRegularState(ApplicationSharedPtr app,
HmiStatePtr state) {
CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
LOG4CXX_AUTO_TRACE(logger_);
if (!app) {
LOG4CXX_ERROR(logger_, "Invalid application pointer");
return;
}
DCHECK_OR_RETURN_VOID(state);
if (mobile_apis::HMILevel::HMI_FULL == state->hmi_level()) {
SetRegularState(app, state, true);
} else {
SetRegularState(app, state, false);
}
}
void StateControllerImpl::HmiLevelConflictResolver::operator()(
ApplicationSharedPtr to_resolve) {
using namespace mobile_apis;
using namespace helpers;
DCHECK_OR_RETURN_VOID(state_ctrl_);
if (to_resolve == applied_)
return;
HmiStatePtr cur_state = to_resolve->RegularHmiState();
const bool applied_grabs_audio =
Compare<HMILevel::eType, EQ, ONE>(
state_->hmi_level(), HMILevel::HMI_FULL, HMILevel::HMI_LIMITED) &&
applied_->IsAudioApplication();
const bool applied_grabs_full = state_->hmi_level() == HMILevel::HMI_FULL;
const bool to_resolve_handles_full =
cur_state->hmi_level() == HMILevel::HMI_FULL;
const bool to_resolve_handles_audio =
Compare<HMILevel::eType, EQ, ONE>(
cur_state->hmi_level(), HMILevel::HMI_FULL, HMILevel::HMI_LIMITED) &&
to_resolve->IsAudioApplication();
const bool same_app_type = state_ctrl_->IsSameAppType(applied_, to_resolve);
// If applied Hmi state is FULL:
// all not audio applications will get BACKGROUND
// all applications with same HMI type will get BACKGROUND
// all audio applications with other HMI type(navi, vc, media) in FULL will
// get LIMMITED HMI level
// If applied Hmi state is LIMITED:
// all applications with other HMI types will save HMI states
// all not audio applications will save HMI states
// all applications with same HMI type will get BACKGROUND
// If applied Hmi state is BACKGROUND:
// all applications will save HMI states
HMILevel::eType result_hmi_level = cur_state->hmi_level();
if (applied_grabs_full && to_resolve_handles_audio && !same_app_type)
result_hmi_level = HMILevel::HMI_LIMITED;
if ((applied_grabs_full && to_resolve_handles_full &&
!to_resolve->IsAudioApplication()) ||
(applied_grabs_audio && to_resolve_handles_audio && same_app_type))
result_hmi_level = HMILevel::HMI_BACKGROUND;
if (cur_state->hmi_level() != result_hmi_level) {
LOG4CXX_DEBUG(logger_,
"Application " << to_resolve->app_id()
<< " will change HMI level to "
<< result_hmi_level);
state_ctrl_->SetupRegularHmiState(to_resolve,
result_hmi_level,
result_hmi_level == HMILevel::HMI_LIMITED
? AudioStreamingState::AUDIBLE
: AudioStreamingState::NOT_AUDIBLE);
} else {
LOG4CXX_DEBUG(logger_,
"Application " << to_resolve->app_id()
<< " will not change HMI level");
}
}
HmiStatePtr StateControllerImpl::ResolveHmiState(ApplicationSharedPtr app,
HmiStatePtr state) const {
using namespace mobile_apis;
using namespace helpers;
LOG4CXX_AUTO_TRACE(logger_);
LOG4CXX_DEBUG(logger_,
"State to resolve: hmi_level "
<< state->hmi_level() << ", audio_state "
<< state->audio_streaming_state() << ", system_context "
<< state->system_context());
HmiStatePtr available_state =
CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
DCHECK_OR_RETURN(available_state, HmiStatePtr());
available_state->set_hmi_level(state->hmi_level());
available_state->set_audio_streaming_state(state->audio_streaming_state());
available_state->set_system_context(state->system_context());
if (app->is_resuming()) {
HMILevel::eType available_level =
GetAvailableHmiLevel(app, state->hmi_level());
available_state->set_hmi_level(available_level);
available_state->set_audio_streaming_state(
CalcAudioState(app, available_level));
}
return IsStateAvailable(app, available_state) ? available_state
: HmiStatePtr();
}
bool StateControllerImpl::IsResumptionAllowed(ApplicationSharedPtr app,
HmiStatePtr state) const {
LOG4CXX_AUTO_TRACE(logger_);
using namespace helpers;
using namespace mobile_apis;
if (!app->is_resuming() ||
!Compare<HMILevel::eType, EQ, ONE>(
state->hmi_level(), HMILevel::HMI_FULL, HMILevel::HMI_LIMITED)) {
LOG4CXX_DEBUG(logger_, "Application is not in resuming mode.");
return true;
}
if (IsTempStateActive(HmiState::StateID::STATE_ID_AUDIO_SOURCE) &&
app->is_media_application()) {
LOG4CXX_DEBUG(logger_,
"Resumption for media app is not allowed. "
<< "AUDIO_SOURCE event is active");
return false;
}
if (IsTempStateActive(HmiState::StateID::STATE_ID_EMBEDDED_NAVI) &&
app->is_navi()) {
LOG4CXX_DEBUG(logger_,
"Resumption for navi app is not allowed. "
<< "EMBEDDED_NAVI event is active");
return false;
}
return true;
}
mobile_apis::HMILevel::eType StateControllerImpl::GetAvailableHmiLevel(
ApplicationSharedPtr app, mobile_apis::HMILevel::eType hmi_level) const {
using namespace mobile_apis;
using namespace helpers;
LOG4CXX_AUTO_TRACE(logger_);
mobile_apis::HMILevel::eType result = hmi_level;
if (!Compare<HMILevel::eType, EQ, ONE>(
hmi_level, HMILevel::HMI_FULL, HMILevel::HMI_LIMITED)) {
return result;
}
const bool is_audio_app = app->IsAudioApplication();
const bool does_audio_app_with_same_type_exist =
app_mngr_.IsAppTypeExistsInFullOrLimited(app);
if (HMILevel::HMI_LIMITED == hmi_level) {
if (!is_audio_app || does_audio_app_with_same_type_exist) {
result = app_mngr_.GetDefaultHmiLevel(app);
}
return result;
}
const bool is_active_app_exist = app_mngr_.active_application();
if (is_audio_app) {
if (does_audio_app_with_same_type_exist) {
result = app_mngr_.GetDefaultHmiLevel(app);
} else if (is_active_app_exist) {
result = mobile_apis::HMILevel::HMI_LIMITED;
} else if (app->is_navi() &&
IsTempStateActive(HmiState::StateID::STATE_ID_AUDIO_SOURCE)) {
LOG4CXX_DEBUG(logger_,
"Navigation app will be resumed to LIMITED, "
"because of AUDIO_SOURCE ia active.");
result = mobile_apis::HMILevel::HMI_LIMITED;
} else if (app->is_media_application() &&
IsTempStateActive(HmiState::StateID::STATE_ID_EMBEDDED_NAVI)) {
LOG4CXX_DEBUG(logger_,
"Media app will be resumed to LIMITED, "
"because of EMBEDDED_NAVI is active.");
result = mobile_apis::HMILevel::HMI_LIMITED;
}
} else if (is_active_app_exist) {
result = app_mngr_.GetDefaultHmiLevel(app);
}
return result;
}
bool StateControllerImpl::IsStateAvailable(ApplicationSharedPtr app,
HmiStatePtr state) const {
using namespace mobile_apis;
using namespace helpers;
LOG4CXX_AUTO_TRACE(logger_);
LOG4CXX_DEBUG(logger_,
"Checking state: hmi_level "
<< state->hmi_level() << ", audio_state "
<< state->audio_streaming_state() << ", system_context "
<< state->system_context());
if (app->is_resuming()) {
return IsStateAvailableForResumption(app, state);
}
if (IsTempStateActive(HmiState::StateID::STATE_ID_AUDIO_SOURCE) ||
IsTempStateActive(HmiState::StateID::STATE_ID_EMBEDDED_NAVI)) {
if (HMILevel::HMI_FULL == state->hmi_level()) {
LOG4CXX_DEBUG(logger_,
"AUDIO_SOURCE or EMBEDDED_NAVI is active."
<< " Requested state is not available");
return false;
}
}
LOG4CXX_DEBUG(logger_, "Requested state is available");
return true;
}
bool StateControllerImpl::IsStateAvailableForResumption(
ApplicationSharedPtr app, HmiStatePtr state) const {
LOG4CXX_AUTO_TRACE(logger_);
using namespace mobile_apis;
using namespace helpers;
if (!app->is_resuming() ||
!Compare<HMILevel::eType, EQ, ONE>(
state->hmi_level(), HMILevel::HMI_FULL, HMILevel::HMI_LIMITED)) {
LOG4CXX_DEBUG(logger_,
"Application is not in resuming mode."
<< " Requested state is available");
return true;
}
if (IsTempStateActive(HmiState::StateID::STATE_ID_VR_SESSION) ||
IsTempStateActive(HmiState::StateID::STATE_ID_SAFETY_MODE)) {
LOG4CXX_DEBUG(logger_,
"Requested state is not available. "
<< "VR session or emergency event is active");
return false;
}
if (IsTempStateActive(HmiState::StateID::STATE_ID_PHONE_CALL) &&
app->is_media_application()) {
LOG4CXX_DEBUG(logger_,
"Requested state for media application "
<< "is not available. Phone call is active");
return false;
}
if (IsTempStateActive(HmiState::StateID::STATE_ID_DEACTIVATE_HMI)) {
LOG4CXX_DEBUG(logger_,
"Requested state is not available. "
<< "Deactivate HMI event is active");
return false;
}
LOG4CXX_DEBUG(logger_, "Requested state is available");
return true;
}
void StateControllerImpl::SetupRegularHmiState(ApplicationSharedPtr app,
HmiStatePtr state) {
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
LOG4CXX_AUTO_TRACE(logger_);
DCHECK_OR_RETURN_VOID(state);
LOG4CXX_DEBUG(logger_,
"hmi_level " << state->hmi_level() << ", audio_state "
<< state->audio_streaming_state()
<< ", system_context " << state->system_context());
HmiStatePtr curr_state = app->CurrentHmiState();
HmiStatePtr old_state =
CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
DCHECK_OR_RETURN_VOID(old_state);
old_state->set_hmi_level(curr_state->hmi_level());
old_state->set_audio_streaming_state(curr_state->audio_streaming_state());
old_state->set_system_context(curr_state->system_context());
app->SetRegularState(state);
if (HMILevel::HMI_LIMITED == state->hmi_level() && app->is_resuming()) {
LOG4CXX_DEBUG(logger_,
"Resuming to LIMITED level. "
<< "Send OnResumeAudioSource notification");
MessageHelper::SendOnResumeAudioSourceToHMI(app->app_id(), app_mngr_);
}
app->set_is_resuming(false);
HmiStatePtr new_state = app->CurrentHmiState();
OnStateChanged(app, old_state, new_state);
}
void StateControllerImpl::SetupRegularHmiState(
ApplicationSharedPtr app,
const mobile_apis::HMILevel::eType hmi_level,
const mobile_apis::AudioStreamingState::eType audio_state) {
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
using helpers::Compare;
LOG4CXX_AUTO_TRACE(logger_);
DCHECK_OR_RETURN_VOID(app);
HmiStatePtr prev_state = app->RegularHmiState();
DCHECK_OR_RETURN_VOID(prev_state);
HmiStatePtr new_state =
CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
DCHECK_OR_RETURN_VOID(new_state);
new_state->set_hmi_level(hmi_level);
new_state->set_audio_streaming_state(audio_state);
new_state->set_system_context(prev_state->system_context());
SetupRegularHmiState(app, new_state);
}
void StateControllerImpl::ApplyRegularState(ApplicationSharedPtr app,
HmiStatePtr state) {
LOG4CXX_AUTO_TRACE(logger_);
DCHECK_OR_RETURN_VOID(app);
DCHECK_OR_RETURN_VOID(state);
DCHECK_OR_RETURN_VOID(state->state_id() == HmiState::STATE_ID_REGULAR);
SetupRegularHmiState(app, state);
ForEachApplication<HmiLevelConflictResolver>(
HmiLevelConflictResolver(app, state, this));
}
bool StateControllerImpl::IsSameAppType(ApplicationConstSharedPtr app1,
ApplicationConstSharedPtr app2) {
const bool both_media =
app1->is_media_application() && app2->is_media_application();
const bool both_navi = app1->is_navi() && app2->is_navi();
const bool both_vc = app1->is_voice_communication_supported() &&
app2->is_voice_communication_supported();
const bool both_simple =
!app1->IsAudioApplication() && !app2->IsAudioApplication();
return both_simple || both_media || both_navi || both_vc;
}
void StateControllerImpl::on_event(const event_engine::Event& event) {
using smart_objects::SmartObject;
using event_engine::Event;
using namespace hmi_apis;
namespace FunctionID = hmi_apis::FunctionID;
LOG4CXX_AUTO_TRACE(logger_);
const SmartObject& message = event.smart_object();
const FunctionID::eType id = static_cast<FunctionID::eType>(event.id());
switch (id) {
case FunctionID::BasicCommunication_ActivateApp: {
OnActivateAppResponse(message);
break;
}
case FunctionID::BasicCommunication_OnAppActivated: {
OnAppActivated(message);
break;
}
case FunctionID::BasicCommunication_OnAppDeactivated: {
OnAppDeactivated(message);
break;
}
case FunctionID::VR_Started: {
ApplyTempState<HmiState::STATE_ID_VR_SESSION>();
break;
}
case FunctionID::VR_Stopped: {
CancelTempState<HmiState::STATE_ID_VR_SESSION>();
break;
}
case FunctionID::TTS_Started: {
ApplyTempState<HmiState::STATE_ID_TTS_SESSION>();
break;
}
case FunctionID::TTS_Stopped: {
CancelTempState<HmiState::STATE_ID_TTS_SESSION>();
break;
}
case FunctionID::BasicCommunication_OnEventChanged: {
bool is_active =
message[strings::msg_params][hmi_notification::is_active].asBool();
const uint32_t id =
message[strings::msg_params][hmi_notification::event_name].asUInt();
// TODO(AOleynik): Add verification/conversion check here
Common_EventTypes::eType state_id =
static_cast<Common_EventTypes::eType>(id);
if (is_active) {
if (Common_EventTypes::AUDIO_SOURCE == state_id) {
ApplyTempState<HmiState::STATE_ID_AUDIO_SOURCE>();
break;
}
if (Common_EventTypes::EMBEDDED_NAVI == state_id) {
ApplyTempState<HmiState::STATE_ID_EMBEDDED_NAVI>();
break;
}
if (Common_EventTypes::PHONE_CALL == state_id) {
ApplyTempState<HmiState::STATE_ID_PHONE_CALL>();
break;
}
if (Common_EventTypes::EMERGENCY_EVENT == state_id) {
ApplyTempState<HmiState::STATE_ID_SAFETY_MODE>();
break;
}
if (Common_EventTypes::DEACTIVATE_HMI == state_id) {
ApplyTempState<HmiState::STATE_ID_DEACTIVATE_HMI>();
break;
}
} else {
if (Common_EventTypes::AUDIO_SOURCE == state_id) {
CancelTempState<HmiState::STATE_ID_AUDIO_SOURCE>();
break;
}
if (Common_EventTypes::EMBEDDED_NAVI == state_id) {
CancelTempState<HmiState::STATE_ID_EMBEDDED_NAVI>();
break;
}
if (Common_EventTypes::PHONE_CALL == state_id) {
CancelTempState<HmiState::STATE_ID_PHONE_CALL>();
break;
}
if (Common_EventTypes::EMERGENCY_EVENT == state_id) {
CancelTempState<HmiState::STATE_ID_SAFETY_MODE>();
break;
}
if (Common_EventTypes::DEACTIVATE_HMI == state_id) {
CancelTempState<HmiState::STATE_ID_DEACTIVATE_HMI>();
break;
}
}
break;
}
default:
break;
}
}
void StateControllerImpl::OnStateChanged(ApplicationSharedPtr app,
HmiStatePtr old_state,
HmiStatePtr new_state) {
LOG4CXX_AUTO_TRACE(logger_);
DCHECK_OR_RETURN_VOID(app);
DCHECK_OR_RETURN_VOID(old_state);
DCHECK_OR_RETURN_VOID(new_state);
LOG4CXX_DEBUG(logger_,
"old: hmi_level " << old_state->hmi_level() << ", audio_state "
<< old_state->audio_streaming_state()
<< ", system_context "
<< old_state->system_context());
LOG4CXX_DEBUG(logger_,
"new: hmi_level " << new_state->hmi_level() << ", audio_state "
<< new_state->audio_streaming_state()
<< ", system_context "
<< new_state->system_context());
if (IsStatusChanged(old_state, new_state)) {
app_mngr_.SendHMIStatusNotification(app);
if (new_state->hmi_level() == mobile_apis::HMILevel::HMI_NONE) {
app->ResetDataInNone();
}
app_mngr_.OnHMILevelChanged(
app->app_id(), old_state->hmi_level(), new_state->hmi_level());
app->usage_report().RecordHmiStateChanged(new_state->hmi_level());
} else {
LOG4CXX_ERROR(logger_, "Status not changed");
}
}
bool StateControllerImpl::IsTempStateActive(HmiState::StateID ID) const {
sync_primitives::AutoLock autolock(active_states_lock_);
StateIDList::const_iterator itr =
std::find(active_states_.begin(), active_states_.end(), ID);
return active_states_.end() != itr;
}
void StateControllerImpl::OnApplicationRegistered(
ApplicationSharedPtr app,
const mobile_apis::HMILevel::eType default_level) {
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
namespace SystemContext = mobile_apis::SystemContext;
LOG4CXX_AUTO_TRACE(logger_);
DCHECK_OR_RETURN_VOID(app);
active_states_lock_.Acquire();
StateIDList::iterator it = active_states_.begin();
for (; it != active_states_.end(); ++it) {
HmiStatePtr new_state = CreateHmiState(app->app_id(), *it);
DCHECK_OR_RETURN_VOID(new_state);
DCHECK_OR_RETURN_VOID(new_state->state_id() != HmiState::STATE_ID_REGULAR);
HmiStatePtr old_hmi_state = app->CurrentHmiState();
new_state->set_parent(old_hmi_state);
app->AddHMIState(new_state);
}
active_states_lock_.Release();
HmiStatePtr default_state =
CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
DCHECK_OR_RETURN_VOID(default_state);
default_state->set_hmi_level(default_level);
default_state->set_audio_streaming_state(CalcAudioState(app, default_level));
default_state->set_system_context(SystemContext::SYSCTXT_MAIN);
HmiStatePtr initial_state = app->RegularHmiState();
app->SetRegularState(default_state);
HmiStatePtr new_state = app->CurrentHmiState();
OnStateChanged(app, initial_state, new_state);
}
int64_t StateControllerImpl::SendBCActivateApp(
ApplicationConstSharedPtr app,
hmi_apis::Common_HMILevel::eType level,
bool send_policy_priority) {
LOG4CXX_AUTO_TRACE(logger_);
smart_objects::SmartObjectSPtr bc_activate_app_request =
MessageHelper::GetBCActivateAppRequestToHMI(
app,
app_mngr_.connection_handler().get_session_observer(),
app_mngr_.GetPolicyHandler(),
level,
send_policy_priority,
app_mngr_);
if (!bc_activate_app_request) {
LOG4CXX_ERROR(logger_, "Unable to create BC.ActivateAppRequest");
return -1;
}
if (!app_mngr_.ManageHMICommand(bc_activate_app_request)) {
LOG4CXX_ERROR(logger_, "Unable to send BC.ActivateAppRequest");
return -1;
}
const int64_t corr_id =
(*bc_activate_app_request)[strings::params][strings::correlation_id]
.asInt();
return corr_id;
}
void StateControllerImpl::ApplyPostponedStateForApp(ApplicationSharedPtr app) {
LOG4CXX_AUTO_TRACE(logger_);
HmiStatePtr state = app->PostponedHmiState();
if (state) {
app->RemovePostponedState();
state->set_state_id(HmiState::STATE_ID_REGULAR);
SetRegularState(app, state);
}
}
void StateControllerImpl::TempStateStarted(HmiState::StateID ID) {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock autolock(active_states_lock_);
StateIDList::iterator it =
std::find(active_states_.begin(), active_states_.end(), ID);
if (it == active_states_.end()) {
active_states_.push_back(ID);
} else {
LOG4CXX_ERROR(logger_, "StateID " << ID << " is already active");
}
}
void StateControllerImpl::TempStateStopped(HmiState::StateID ID) {
LOG4CXX_AUTO_TRACE(logger_);
{
sync_primitives::AutoLock autolock(active_states_lock_);
active_states_.remove(ID);
}
ForEachApplication(std::bind1st(
std::mem_fun(&StateControllerImpl::ApplyPostponedStateForApp), this));
}
void StateControllerImpl::DeactivateApp(ApplicationSharedPtr app) {
using namespace mobile_apis;
LOG4CXX_AUTO_TRACE(logger_);
DCHECK_OR_RETURN_VOID(app);
HmiStatePtr regular = app->RegularHmiState();
DCHECK_OR_RETURN_VOID(regular);
HmiStatePtr new_regular = utils::MakeShared<HmiState>(*regular);
if (app->IsAudioApplication()) {
new_regular->set_hmi_level(HMILevel::HMI_LIMITED);
new_regular->set_audio_streaming_state(AudioStreamingState::AUDIBLE);
} else {
new_regular->set_hmi_level(HMILevel::HMI_BACKGROUND);
new_regular->set_audio_streaming_state(AudioStreamingState::NOT_AUDIBLE);
}
SetRegularState(app, new_regular, false);
}
void StateControllerImpl::OnActivateAppResponse(
const smart_objects::SmartObject& message) {
const hmi_apis::Common_Result::eType code =
static_cast<hmi_apis::Common_Result::eType>(
message[strings::params][hmi_response::code].asInt());
const int32_t correlation_id =
message[strings::params][strings::correlation_id].asInt();
const uint32_t hmi_app_id = app_mngr_.application_id(correlation_id);
ApplicationSharedPtr application =
app_mngr_.application_by_hmi_app(hmi_app_id);
if (application && hmi_apis::Common_Result::SUCCESS == code) {
HmiStatePtr pending_state = waiting_for_activate[application->app_id()];
DCHECK_OR_RETURN_VOID(pending_state);
ApplyRegularState(application, pending_state);
}
}
void StateControllerImpl::OnAppActivated(
const smart_objects::SmartObject& message) {
using namespace mobile_apis;
LOG4CXX_AUTO_TRACE(logger_);
uint32_t app_id = message[strings::msg_params][strings::app_id].asUInt();
ApplicationSharedPtr app = app_mngr_.application(app_id);
if (!app) {
LOG4CXX_ERROR(logger_, "Application with id " << app_id << " not found");
return;
}
SetRegularState(app, HMILevel::HMI_FULL, true);
}
void StateControllerImpl::OnAppDeactivated(
const smart_objects::SmartObject& message) {
using namespace hmi_apis;
using namespace mobile_apis;
using namespace helpers;
LOG4CXX_AUTO_TRACE(logger_);
uint32_t app_id = message[strings::msg_params][strings::app_id].asUInt();
ApplicationSharedPtr app = app_mngr_.application(app_id);
if (!app) {
LOG4CXX_ERROR(logger_, "Application with id " << app_id << " not found");
return;
}
if (HMILevel::HMI_FULL != app->hmi_level()) {
return;
}
// TODO(AOleynik): Need to delete DeactivateReason and modify OnAppDeactivated
// when HMI will support that, otherwise won't be testable
DeactivateApp(app);
}
void StateControllerImpl::OnNaviStreamingStarted() {
ApplyTempState<HmiState::STATE_ID_NAVI_STREAMING>();
}
void StateControllerImpl::OnNaviStreamingStopped() {
CancelTempState<HmiState::STATE_ID_NAVI_STREAMING>();
}
bool StateControllerImpl::IsStateActive(HmiState::StateID state_id) const {
LOG4CXX_AUTO_TRACE(logger_);
switch (state_id) {
case HmiState::STATE_ID_CURRENT:
case HmiState::STATE_ID_REGULAR:
return true;
default:
return IsTempStateActive(state_id);
}
return false;
}
HmiStatePtr StateControllerImpl::CreateHmiState(
uint32_t app_id, HmiState::StateID state_id) const {
using namespace utils;
LOG4CXX_AUTO_TRACE(logger_);
HmiStatePtr new_state;
switch (state_id) {
case HmiState::STATE_ID_PHONE_CALL: {
new_state = MakeShared<PhoneCallHmiState>(app_id, app_mngr_);
break;
}
case HmiState::STATE_ID_SAFETY_MODE: {
new_state = MakeShared<SafetyModeHmiState>(app_id, app_mngr_);
break;
}
case HmiState::STATE_ID_VR_SESSION: {
new_state = MakeShared<VRHmiState>(app_id, app_mngr_);
break;
}
case HmiState::STATE_ID_TTS_SESSION: {
new_state = MakeShared<TTSHmiState>(app_id, app_mngr_);
break;
}
case HmiState::STATE_ID_NAVI_STREAMING: {
new_state = MakeShared<NaviStreamingHmiState>(app_id, app_mngr_);
break;
}
case HmiState::STATE_ID_REGULAR: {
new_state = MakeShared<HmiState>(app_id, app_mngr_);
break;
}
case HmiState::STATE_ID_POSTPONED: {
new_state = MakeShared<HmiState>(app_id, app_mngr_, state_id);
break;
}
case HmiState::STATE_ID_DEACTIVATE_HMI: {
new_state = MakeShared<DeactivateHMI>(app_id, app_mngr_);
break;
}
case HmiState::STATE_ID_AUDIO_SOURCE: {
new_state = MakeShared<AudioSource>(app_id, app_mngr_);
break;
}
case HmiState::STATE_ID_EMBEDDED_NAVI: {
new_state = MakeShared<EmbeddedNavi>(app_id, app_mngr_);
break;
}
default:
LOG4CXX_FATAL(logger_, "Invalid state_id " << state_id);
NOTREACHED();
break;
}
return new_state;
}
mobile_apis::AudioStreamingState::eType StateControllerImpl::CalcAudioState(
ApplicationSharedPtr app,
const mobile_apis::HMILevel::eType hmi_level) const {
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
using helpers::Compare;
using helpers::EQ;
using helpers::ONE;
AudioStreamingState::eType audio_state = AudioStreamingState::NOT_AUDIBLE;
if (Compare<HMILevel::eType, EQ, ONE>(
hmi_level, HMILevel::HMI_FULL, HMILevel::HMI_LIMITED)) {
if (app->IsAudioApplication()) {
audio_state = AudioStreamingState::AUDIBLE;
}
}
return audio_state;
}
} // namespace application_manager
|
/* Copyright (C) 2004 MySQL AB
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; version 2 of the License.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/*
Utility program used to signal a safe_process it's time to shutdown
Usage:
safe_kill <pid>
*/
#include <windows.h>
#include <stdio.h>
int main(int argc, const char** argv )
{
DWORD pid= -1;
HANDLE shutdown_event;
char safe_process_name[32]= {0};
int retry_open_event= 100;
if (argc != 2) {
fprintf(stderr, "safe_kill <pid>\n");
exit(2);
}
pid= atoi(argv[1]);
_snprintf(safe_process_name, sizeof(safe_process_name), "safe_process[%d]", pid);
/* Open the event to signal */
while ((shutdown_event=
OpenEvent(EVENT_MODIFY_STATE, FALSE, safe_process_name)) == NULL)
{
fprintf(stderr, "Failed to open shutdown_event '%s', error: %d\n",
safe_process_name, GetLastError());
/* Just check to see if pid exists */
HANDLE pid_handle= OpenProcess(SYNCHRONIZE, FALSE, pid);
if (pid_handle == NULL)
fprintf(stderr, "Could not open process with pid %d, error: %d\n", pid);
else
CloseHandle(pid_handle);
if (retry_open_event--)
{
fprintf(stderr, "retrying...\n");
Sleep(100); /* In milli seconds */
}
else
{
fprintf(stderr, "No more retries, exiting");
exit(1);
}
}
if(SetEvent(shutdown_event) == 0)
{
fprintf(stderr, "Failed to signal shutdown_event '%s', error: %d\n",
safe_process_name, GetLastError());
CloseHandle(shutdown_event);
exit(1);
}
CloseHandle(shutdown_event);
exit(0);
}
Ignore all common signals
Just retry OpenEvent a couple of times with a "yield" in between
/* Copyright (C) 2004 MySQL AB
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; version 2 of the License.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/*
Utility program used to signal a safe_process it's time to shutdown
Usage:
safe_kill <pid>
*/
#include <windows.h>
#include <stdio.h>
#include <signal.h>
int main(int argc, const char** argv )
{
DWORD pid= -1;
HANDLE shutdown_event;
char safe_process_name[32]= {0};
int retry_open_event= 100;
/* Ignore any signals */
signal(SIGINT, SIG_IGN);
signal(SIGBREAK, SIG_IGN);
signal(SIGTERM, SIG_IGN);
if (argc != 2) {
fprintf(stderr, "safe_kill <pid>\n");
exit(2);
}
pid= atoi(argv[1]);
_snprintf(safe_process_name, sizeof(safe_process_name),
"safe_process[%d]", pid);
/* Open the event to signal */
while ((shutdown_event=
OpenEvent(EVENT_MODIFY_STATE, FALSE, safe_process_name)) == NULL)
{
if (retry_open_event--)
Sleep(0); /* yield */
else
{
fprintf(stderr, "Failed to open shutdown_event '%s', error: %d\n",
safe_process_name, GetLastError());
exit(3);
}
}
if(SetEvent(shutdown_event) == 0)
{
fprintf(stderr, "Failed to signal shutdown_event '%s', error: %d\n",
safe_process_name, GetLastError());
CloseHandle(shutdown_event);
exit(4);
}
CloseHandle(shutdown_event);
exit(0);
}
|
#pragma once
#include "event_queue.hpp"
#include <mpark/variant.hpp>
#include <nlohmann/json.hpp>
#include <optional>
#include <pqrs/json.hpp>
namespace krbn {
namespace manipulator {
class event_definition {
public:
enum class type {
none,
key_code,
consumer_key_code,
pointing_button,
any,
shell_command,
select_input_source,
set_variable,
mouse_key,
};
using value_t = mpark::variant<mpark::monostate,
key_code,
consumer_key_code,
pointing_button,
type, // For any
std::string, // For shell_command
std::vector<pqrs::osx::input_source_selector::specifier>, // For select_input_source
std::pair<std::string, int>, // For set_variable
mouse_key // For mouse_key
>;
event_definition(void) : type_(type::none),
value_(mpark::monostate()) {
}
virtual ~event_definition(void) {
}
type get_type(void) const {
return type_;
}
const value_t& get_value(void) const {
return value_;
}
std::optional<key_code> get_key_code(void) const {
if (type_ == type::key_code) {
return mpark::get<key_code>(value_);
}
return std::nullopt;
}
std::optional<consumer_key_code> get_consumer_key_code(void) const {
if (type_ == type::consumer_key_code) {
return mpark::get<consumer_key_code>(value_);
}
return std::nullopt;
}
std::optional<pointing_button> get_pointing_button(void) const {
if (type_ == type::pointing_button) {
return mpark::get<pointing_button>(value_);
}
return std::nullopt;
}
std::optional<type> get_any_type(void) const {
if (type_ == type::any) {
return mpark::get<type>(value_);
}
return std::nullopt;
}
std::optional<std::string> get_shell_command(void) const {
if (type_ == type::shell_command) {
return mpark::get<std::string>(value_);
}
return std::nullopt;
}
std::optional<std::vector<pqrs::osx::input_source_selector::specifier>> get_input_source_specifiers(void) const {
if (type_ == type::select_input_source) {
return mpark::get<std::vector<pqrs::osx::input_source_selector::specifier>>(value_);
}
return std::nullopt;
}
std::optional<std::pair<std::string, int>> get_set_variable(void) const {
if (type_ == type::set_variable) {
return mpark::get<std::pair<std::string, int>>(value_);
}
return std::nullopt;
}
std::optional<mouse_key> get_mouse_key(void) const {
if (type_ == type::mouse_key) {
return mpark::get<mouse_key>(value_);
}
return std::nullopt;
}
std::optional<event_queue::event> to_event(void) const {
switch (type_) {
case type::none:
return std::nullopt;
case type::key_code:
return event_queue::event(mpark::get<key_code>(value_));
case type::consumer_key_code:
return event_queue::event(mpark::get<consumer_key_code>(value_));
case type::pointing_button:
return event_queue::event(mpark::get<pointing_button>(value_));
case type::any:
return std::nullopt;
case type::shell_command:
return event_queue::event::make_shell_command_event(mpark::get<std::string>(value_));
case type::select_input_source:
return event_queue::event::make_select_input_source_event(mpark::get<std::vector<pqrs::osx::input_source_selector::specifier>>(value_));
case type::set_variable:
return event_queue::event::make_set_variable_event(mpark::get<std::pair<std::string, int>>(value_));
case type::mouse_key:
return event_queue::event::make_mouse_key_event(mpark::get<mouse_key>(value_));
}
}
bool handle_json(const std::string& key,
const nlohmann::json& value,
const nlohmann::json& json) {
// Set type_ and values.
// ----------------------------------------
// key_code
if (key == "key_code") {
check_type(json);
if (!value.is_string()) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be string, but is `{1}`", key, value.dump()));
}
if (auto key_code = types::make_key_code(value.get<std::string>())) {
type_ = type::key_code;
value_ = *key_code;
} else {
throw pqrs::json::unmarshal_error(fmt::format("unknown `{0}`: `{1}`", key, value.dump()));
}
return true;
}
// ----------------------------------------
// consumer_key_code
if (key == "consumer_key_code") {
check_type(json);
if (!value.is_string()) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be string, but is `{1}`", key, value.dump()));
}
if (auto consumer_key_code = types::make_consumer_key_code(value.get<std::string>())) {
type_ = type::consumer_key_code;
value_ = *consumer_key_code;
} else {
throw pqrs::json::unmarshal_error(fmt::format("unknown `{0}`: `{1}`", key, value.dump()));
}
return true;
}
// ----------------------------------------
// pointing_button
if (key == "pointing_button") {
check_type(json);
if (!value.is_string()) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be string, but is `{1}`", key, value.dump()));
}
if (auto pointing_button = types::make_pointing_button(value.get<std::string>())) {
type_ = type::pointing_button;
value_ = *pointing_button;
} else {
throw pqrs::json::unmarshal_error(fmt::format("unknown `{0}`: `{1}`", key, value.dump()));
}
return true;
}
// ----------------------------------------
// any
if (key == "any") {
check_type(json);
if (!value.is_string()) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be string, but is `{1}`", key, value.dump()));
}
if (value == "key_code") {
type_ = type::any;
value_ = type::key_code;
} else if (value == "consumer_key_code") {
type_ = type::any;
value_ = type::consumer_key_code;
} else if (value == "pointing_button") {
type_ = type::any;
value_ = type::pointing_button;
} else {
throw pqrs::json::unmarshal_error(fmt::format("unknown `{0}`: `{1}`", key, value.dump()));
}
return true;
}
// ----------------------------------------
// shell_command
if (key == "shell_command") {
check_type(json);
if (!value.is_string()) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be string, but is `{1}`", key, value.dump()));
}
type_ = type::shell_command;
value_ = value.get<std::string>();
return true;
}
// ----------------------------------------
// select_input_source
if (key == "select_input_source") {
check_type(json);
std::vector<pqrs::osx::input_source_selector::specifier> input_source_specifiers;
if (value.is_object()) {
input_source_specifiers.push_back(value.get<pqrs::osx::input_source_selector::specifier>());
} else if (value.is_array()) {
input_source_specifiers = value.get<std::vector<pqrs::osx::input_source_selector::specifier>>();
} else {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be object or array of objects, but is `{1}`", key, value.dump()));
}
type_ = type::select_input_source;
value_ = input_source_specifiers;
return true;
}
// ----------------------------------------
// set_variable
if (key == "set_variable") {
check_type(json);
if (!value.is_object()) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be object, but is `{1}`", key, value.dump()));
}
// name
std::string variable_name;
{
auto it = value.find("name");
if (it == std::end(value)) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}.name` is not found in `{1}`", key, value.dump()));
}
if (!it.value().is_string()) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}.name` must be string, but is `{1}`", key, it.value().dump()));
}
variable_name = it.value().get<std::string>();
}
// value
int variable_value;
{
auto it = value.find("value");
if (it == std::end(value)) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}.value` is not found in `{1}`", key, value.dump()));
}
if (!it.value().is_number()) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}.value` must be number, but is `{1}`", key, it.value().dump()));
}
variable_value = it.value().get<int>();
}
type_ = type::set_variable;
value_ = std::make_pair(variable_name, variable_value);
return true;
}
// ----------------------------------------
// mouse_key
if (key == "mouse_key") {
check_type(json);
if (!value.is_object()) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be object, but is `{1}`", key, value.dump()));
}
type_ = type::mouse_key;
value_ = mouse_key(value);
return true;
}
if (key == "description") {
// Do nothing
return true;
}
return false;
}
void check_type(const nlohmann::json& json) const {
if (type_ != type::none) {
throw pqrs::json::unmarshal_error(fmt::format("multiple types are specified: `{0}`", json.dump()));
}
}
protected:
type type_;
value_t value_;
};
} // namespace manipulator
} // namespace krbn
update error messages
#pragma once
#include "event_queue.hpp"
#include <mpark/variant.hpp>
#include <nlohmann/json.hpp>
#include <optional>
#include <pqrs/json.hpp>
namespace krbn {
namespace manipulator {
class event_definition {
public:
enum class type {
none,
key_code,
consumer_key_code,
pointing_button,
any,
shell_command,
select_input_source,
set_variable,
mouse_key,
};
using value_t = mpark::variant<mpark::monostate,
key_code,
consumer_key_code,
pointing_button,
type, // For any
std::string, // For shell_command
std::vector<pqrs::osx::input_source_selector::specifier>, // For select_input_source
std::pair<std::string, int>, // For set_variable
mouse_key // For mouse_key
>;
event_definition(void) : type_(type::none),
value_(mpark::monostate()) {
}
virtual ~event_definition(void) {
}
type get_type(void) const {
return type_;
}
const value_t& get_value(void) const {
return value_;
}
std::optional<key_code> get_key_code(void) const {
if (type_ == type::key_code) {
return mpark::get<key_code>(value_);
}
return std::nullopt;
}
std::optional<consumer_key_code> get_consumer_key_code(void) const {
if (type_ == type::consumer_key_code) {
return mpark::get<consumer_key_code>(value_);
}
return std::nullopt;
}
std::optional<pointing_button> get_pointing_button(void) const {
if (type_ == type::pointing_button) {
return mpark::get<pointing_button>(value_);
}
return std::nullopt;
}
std::optional<type> get_any_type(void) const {
if (type_ == type::any) {
return mpark::get<type>(value_);
}
return std::nullopt;
}
std::optional<std::string> get_shell_command(void) const {
if (type_ == type::shell_command) {
return mpark::get<std::string>(value_);
}
return std::nullopt;
}
std::optional<std::vector<pqrs::osx::input_source_selector::specifier>> get_input_source_specifiers(void) const {
if (type_ == type::select_input_source) {
return mpark::get<std::vector<pqrs::osx::input_source_selector::specifier>>(value_);
}
return std::nullopt;
}
std::optional<std::pair<std::string, int>> get_set_variable(void) const {
if (type_ == type::set_variable) {
return mpark::get<std::pair<std::string, int>>(value_);
}
return std::nullopt;
}
std::optional<mouse_key> get_mouse_key(void) const {
if (type_ == type::mouse_key) {
return mpark::get<mouse_key>(value_);
}
return std::nullopt;
}
std::optional<event_queue::event> to_event(void) const {
switch (type_) {
case type::none:
return std::nullopt;
case type::key_code:
return event_queue::event(mpark::get<key_code>(value_));
case type::consumer_key_code:
return event_queue::event(mpark::get<consumer_key_code>(value_));
case type::pointing_button:
return event_queue::event(mpark::get<pointing_button>(value_));
case type::any:
return std::nullopt;
case type::shell_command:
return event_queue::event::make_shell_command_event(mpark::get<std::string>(value_));
case type::select_input_source:
return event_queue::event::make_select_input_source_event(mpark::get<std::vector<pqrs::osx::input_source_selector::specifier>>(value_));
case type::set_variable:
return event_queue::event::make_set_variable_event(mpark::get<std::pair<std::string, int>>(value_));
case type::mouse_key:
return event_queue::event::make_mouse_key_event(mpark::get<mouse_key>(value_));
}
}
bool handle_json(const std::string& key,
const nlohmann::json& value,
const nlohmann::json& json) {
// Set type_ and values.
// ----------------------------------------
// key_code
if (key == "key_code") {
check_type(json);
if (!value.is_string()) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be string, but is `{1}`", key, value.dump()));
}
if (auto key_code = types::make_key_code(value.get<std::string>())) {
type_ = type::key_code;
value_ = *key_code;
} else {
throw pqrs::json::unmarshal_error(fmt::format("unknown `{0}`: `{1}`", key, value.dump()));
}
return true;
}
// ----------------------------------------
// consumer_key_code
if (key == "consumer_key_code") {
check_type(json);
if (!value.is_string()) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be string, but is `{1}`", key, value.dump()));
}
if (auto consumer_key_code = types::make_consumer_key_code(value.get<std::string>())) {
type_ = type::consumer_key_code;
value_ = *consumer_key_code;
} else {
throw pqrs::json::unmarshal_error(fmt::format("unknown `{0}`: `{1}`", key, value.dump()));
}
return true;
}
// ----------------------------------------
// pointing_button
if (key == "pointing_button") {
check_type(json);
if (!value.is_string()) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be string, but is `{1}`", key, value.dump()));
}
if (auto pointing_button = types::make_pointing_button(value.get<std::string>())) {
type_ = type::pointing_button;
value_ = *pointing_button;
} else {
throw pqrs::json::unmarshal_error(fmt::format("unknown `{0}`: `{1}`", key, value.dump()));
}
return true;
}
// ----------------------------------------
// any
if (key == "any") {
check_type(json);
if (!value.is_string()) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be string, but is `{1}`", key, value.dump()));
}
if (value == "key_code") {
type_ = type::any;
value_ = type::key_code;
} else if (value == "consumer_key_code") {
type_ = type::any;
value_ = type::consumer_key_code;
} else if (value == "pointing_button") {
type_ = type::any;
value_ = type::pointing_button;
} else {
throw pqrs::json::unmarshal_error(fmt::format("unknown `{0}`: `{1}`", key, value.dump()));
}
return true;
}
// ----------------------------------------
// shell_command
if (key == "shell_command") {
check_type(json);
if (!value.is_string()) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be string, but is `{1}`", key, value.dump()));
}
type_ = type::shell_command;
value_ = value.get<std::string>();
return true;
}
// ----------------------------------------
// select_input_source
if (key == "select_input_source") {
check_type(json);
std::vector<pqrs::osx::input_source_selector::specifier> input_source_specifiers;
if (value.is_object()) {
try {
input_source_specifiers.push_back(value.get<pqrs::osx::input_source_selector::specifier>());
} catch (const pqrs::json::unmarshal_error& e) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` error: {1}", key, e.what()));
}
} else if (value.is_array()) {
try {
input_source_specifiers = value.get<std::vector<pqrs::osx::input_source_selector::specifier>>();
} catch (const pqrs::json::unmarshal_error& e) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` error: {1}", key, e.what()));
}
} else {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be object or array of objects, but is `{1}`", key, value.dump()));
}
type_ = type::select_input_source;
value_ = input_source_specifiers;
return true;
}
// ----------------------------------------
// set_variable
if (key == "set_variable") {
check_type(json);
if (!value.is_object()) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be object, but is `{1}`", key, value.dump()));
}
// name
std::string variable_name;
{
auto it = value.find("name");
if (it == std::end(value)) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}.name` is not found in `{1}`", key, value.dump()));
}
if (!it.value().is_string()) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}.name` must be string, but is `{1}`", key, it.value().dump()));
}
variable_name = it.value().get<std::string>();
}
// value
int variable_value;
{
auto it = value.find("value");
if (it == std::end(value)) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}.value` is not found in `{1}`", key, value.dump()));
}
if (!it.value().is_number()) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}.value` must be number, but is `{1}`", key, it.value().dump()));
}
variable_value = it.value().get<int>();
}
type_ = type::set_variable;
value_ = std::make_pair(variable_name, variable_value);
return true;
}
// ----------------------------------------
// mouse_key
if (key == "mouse_key") {
check_type(json);
if (!value.is_object()) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be object, but is `{1}`", key, value.dump()));
}
type_ = type::mouse_key;
value_ = mouse_key(value);
return true;
}
if (key == "description") {
// Do nothing
return true;
}
return false;
}
void check_type(const nlohmann::json& json) const {
if (type_ != type::none) {
throw pqrs::json::unmarshal_error(fmt::format("multiple types are specified: `{0}`", json.dump()));
}
}
protected:
type type_;
value_t value_;
};
} // namespace manipulator
} // namespace krbn
|
/*
* DesktopWin32DetectRHome.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef _WIN32
#error DesktopDetectRHome.cpp is Windows-specific
#endif
#include "DesktopDetectRHome.hpp"
#include <windows.h>
#include <boost/bind.hpp>
#include <core/system/System.hpp>
#include "DesktopRVersion.hpp"
using namespace core;
namespace desktop {
bool prepareEnvironment(Options &options)
{
bool forceUi = ::GetAsyncKeyState(VK_CONTROL) & ~1;
RVersion rVersion = detectRVersion(forceUi);
if (!rVersion.isValid())
return false;
system::setenv("R_HOME", rVersion.homeDir().toStdString());
std::string path =
QDir::toNativeSeparators(rVersion.binDir()).toStdString() + ";" +
system::getenv("PATH");
system::setenv("PATH", path);
return true;
}
} // namespace desktop
cherry pick: use 8.3 path for R_HOME on windows
/*
* DesktopWin32DetectRHome.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef _WIN32
#error DesktopDetectRHome.cpp is Windows-specific
#endif
#include "DesktopDetectRHome.hpp"
#include <windows.h>
#include <boost/bind.hpp>
#include <core/system/System.hpp>
#include "DesktopRVersion.hpp"
using namespace core;
namespace desktop {
bool prepareEnvironment(Options &options)
{
bool forceUi = ::GetAsyncKeyState(VK_CONTROL) & ~1;
RVersion rVersion = detectRVersion(forceUi);
if (!rVersion.isValid())
return false;
// get the short path version of the home dir
std::string homePath =
QDir::toNativeSeparators(rVersion.homeDir()).toStdString();
DWORD len = ::GetShortPathName(homePath.c_str(), NULL, 0);
std::vector<TCHAR> buffer(len, 0);
if (::GetShortPathName(homePath.c_str(), &(buffer[0]), len) != 0)
{
// copy path to string and assign it we got one
std::string shortHomePath(&(buffer[0]));
if (!shortHomePath.empty())
homePath = shortHomePath;
}
else
{
LOG_ERROR(systemError(::GetLastError(), ERROR_LOCATION));
}
// set R_HOME
system::setenv("R_HOME", homePath);
std::string path =
QDir::toNativeSeparators(rVersion.binDir()).toStdString() + ";" +
system::getenv("PATH");
system::setenv("PATH", path);
return true;
}
} // namespace desktop
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p10/procedures/hwp/perv/p10_setup_sbe_config.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p10_setup_sbe_config.C
///
/// @brief proc setup sbe config
//------------------------------------------------------------------------------
// *HWP HW Maintainer : Anusha Reddy (anusrang@in.ibm.com)
// *HWP FW Maintainer : Raja Das (rajadas2@in.ibm.com)
// *HWP Consumed by : FSP
//------------------------------------------------------------------------------
#include <p10_setup_sbe_config.H>
#include <p10_scom_perv.H>
#include <p10_sbe_scratch_regs.H>
#include <p10_frequency_buckets.H>
///
/// @brief Calculate GARD vector based on functional target states
///
/// @tparam T template parameter, target type
/// @param[in] i_target_chip Processor chip target
/// @param[out] o_gard_vector GARD vector (1-bit indicates non-functional)
/// valid data left-aligned from 0..<num chiplets of type T-1>
///
/// @return fapi::ReturnCode. FAPI2_RC_SUCCESS if success, else error code.
///
template<fapi2::TargetType T>
fapi2::ReturnCode
p10_sbe_scratch_calc_gard_vector(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip,
uint32_t& o_gard_vector)
{
fapi2::buffer<uint32_t> l_functional = 0;
fapi2::ATTR_CONTAINED_IPL_TYPE_Type l_attr_contained_ipl_type;
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CONTAINED_IPL_TYPE, FAPI_SYSTEM, l_attr_contained_ipl_type),
"Error from FAPI_ATTR_GET (ATTR_CONTAINED_IPL_TYPE)");
// no desire to enable async chiplets in contained modes, use gard vector
// content to enforce this
if ((l_attr_contained_ipl_type != fapi2::ENUM_ATTR_CONTAINED_IPL_TYPE_NONE) &&
((T == fapi2::TARGET_TYPE_PEC) ||
(T == fapi2::TARGET_TYPE_MC) ||
(T == fapi2::TARGET_TYPE_PAUC) ||
(T == fapi2::TARGET_TYPE_PAU) ||
(T == fapi2::TARGET_TYPE_IOHS)))
{
goto fapi_try_exit;
}
for (const auto& l_tgt : i_target_chip.getChildren<T>(fapi2::TARGET_STATE_FUNCTIONAL))
{
fapi2::ATTR_CHIP_UNIT_POS_Type l_unit_pos;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_tgt, l_unit_pos),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS, functional)");
FAPI_TRY(l_functional.setBit(l_unit_pos),
"Error from setBit (functional, unit target pos: %d)", l_unit_pos);
}
fapi_try_exit:
FAPI_DBG("Functional : 0x%08X", l_functional);
o_gard_vector = ~l_functional;
FAPI_DBG("Gard vector : 0x%08X", o_gard_vector);
return fapi2::current_err;
}
///
/// @brief Calculate IOHS region GARD vectors based on functional target states
/// and designated link usage
///
/// @param[in] i_target_chip Processor chip target
/// @param[out] o_ndl_gard_vector NDL GARD vector (1-bit indicates non-functional)
/// valid data left-aligned from 0..7
///
/// @return fapi::ReturnCode. FAPI2_RC_SUCCESS if success, else error code.
///
fapi2::ReturnCode
p10_sbe_scratch_calc_iohs_region_gard_vectors(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip,
uint32_t& o_ndl_gard_vector)
{
fapi2::buffer<uint32_t> l_ndl_functional = 0;
for (const auto& l_tgt : i_target_chip.getChildren<fapi2::TARGET_TYPE_IOHS>(fapi2::TARGET_STATE_FUNCTIONAL))
{
fapi2::ATTR_IOHS_CONFIG_MODE_Type l_iohs_config_mode;
fapi2::ATTR_CHIP_UNIT_POS_Type l_unit_pos;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IOHS_CONFIG_MODE, l_tgt, l_iohs_config_mode),
"Error from FAPI_ATTR_GET (ATTR_IOHS_CONFIG_MODE");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_tgt, l_unit_pos),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
if ((l_iohs_config_mode != fapi2::ENUM_ATTR_IOHS_CONFIG_MODE_SMPX) &&
(l_iohs_config_mode != fapi2::ENUM_ATTR_IOHS_CONFIG_MODE_SMPA))
{
FAPI_TRY(l_ndl_functional.setBit(l_unit_pos));
}
}
o_ndl_gard_vector = ~l_ndl_functional;
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Lookup MC frequency bucket attribute values given platform frequency
/// attributes
///
/// @param[in] i_target_chip Processor chip target
/// @param[in] o_attr_mc_pll_bucket PLL bucket attribute value
///
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode
p10_sbe_scratch_regs_get_mc_pll_bucket(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip,
fapi2::ATTR_MC_PLL_BUCKET_Type o_attr_mc_pll_bucket)
{
FAPI_DBG("Start");
for (const auto l_mc_target : i_target_chip.getChildren<fapi2::TARGET_TYPE_MC>(fapi2::TARGET_STATE_FUNCTIONAL))
{
fapi2::ATTR_FREQ_MC_MHZ_Type l_attr_freq_mc_mhz;
fapi2::ATTR_CHIP_UNIT_POS_Type l_unit_num;
bool l_bucket_found = false;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_MC_MHZ, l_mc_target, l_attr_freq_mc_mhz),
"Error from FAPI_ATTR_GET (ATTR_FREQ_MC_MHZ)");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_mc_target, l_unit_num),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
for (auto l_bucket = 0; l_bucket < MEM_PLL_FREQ_BUCKETS; l_bucket++)
{
if (l_attr_freq_mc_mhz == MEM_PLL_FREQ_LIST[l_bucket])
{
l_bucket_found = true;
o_attr_mc_pll_bucket[l_unit_num] = l_bucket;
break;
}
}
FAPI_ASSERT(l_bucket_found,
fapi2::P10_SBE_SCRATCH_REGS_MC_FREQ_LOOKUP_ERR()
.set_TARGET_CHIP(i_target_chip)
.set_TARGET_MC(l_mc_target)
.set_FREQ_MC_MHZ(l_attr_freq_mc_mhz),
"Requested MC frequency (%d MHz) not found in p10_frequency_buckets.H!",
l_attr_freq_mc_mhz);
}
fapi_try_exit:
FAPI_DBG("End");
return fapi2::current_err;
}
///
/// @brief Lookup IOHS frequency bucket attribute values given platform frequency
/// attributes
///
/// @param[in] i_target_chip Processor chip target
/// @param[in] o_attr_iohs_pll_bucket PLL bucket attribute value
///
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode
p10_sbe_scratch_regs_get_iohs_pll_bucket(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip,
fapi2::ATTR_IOHS_PLL_BUCKET_Type o_attr_iohs_pll_bucket)
{
FAPI_DBG("Start");
for (const auto l_iohs_target : i_target_chip.getChildren<fapi2::TARGET_TYPE_IOHS>(fapi2::TARGET_STATE_FUNCTIONAL))
{
fapi2::ATTR_FREQ_IOHS_MHZ_Type l_attr_freq_iohs_mhz;
fapi2::ATTR_CHIP_UNIT_POS_Type l_unit_num;
bool l_bucket_found = false;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_IOHS_MHZ, l_iohs_target, l_attr_freq_iohs_mhz),
"Error from FAPI_ATTR_GET (ATTR_FREQ_IOHS_MHZ)");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_iohs_target, l_unit_num),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
for (auto l_bucket = 0; l_bucket < IOHS_PLL_FREQ_BUCKETS; l_bucket++)
{
if (l_attr_freq_iohs_mhz == IOHS_PLL_FREQ_LIST[l_bucket])
{
l_bucket_found = true;
o_attr_iohs_pll_bucket[l_unit_num] = l_bucket;
break;
}
}
FAPI_ASSERT(l_bucket_found,
fapi2::P10_SBE_SCRATCH_REGS_IOHS_FREQ_LOOKUP_ERR()
.set_TARGET_CHIP(i_target_chip)
.set_TARGET_IOHS(l_iohs_target)
.set_FREQ_IOHS_MHZ(l_attr_freq_iohs_mhz),
"Requested IOHS frequency (%d MHz) not found in p10_frequency_buckets.H!",
l_attr_freq_iohs_mhz);
}
fapi_try_exit:
FAPI_DBG("End");
return fapi2::current_err;
}
// description in header
fapi2::ReturnCode p10_setup_sbe_config(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
using namespace scomt::perv;
fapi2::buffer<uint32_t> l_scratch8_reg = 0;
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
FAPI_INF("p10_setup_sbe_config:: Entering ...");
FAPI_TRY(fapi2::getCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_8_FSI,
l_scratch8_reg),
"Error reading Scratch 8 mailbox register");
// set_scratch1_reg -- set EQ chiplet PG
{
fapi2::buffer<uint32_t> l_scratch1_reg = 0;
uint32_t l_core_gard_vector;
// CORE
FAPI_DBG("Calculating CORE region gard vector");
FAPI_TRY(p10_sbe_scratch_calc_gard_vector<fapi2::TARGET_TYPE_CORE>(i_target_chip,
l_core_gard_vector),
"Error from p10_sbe_scratch_calc_gard_vector (core)");
l_scratch1_reg.insert<CORE_GARD_STARTBIT, CORE_GARD_LENGTH, GARD_VECTOR_STARTBIT>(l_core_gard_vector);
FAPI_DBG("Setting up value of Scratch 1 mailbox register");
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_1_FSI,
l_scratch1_reg),
"Error writing Scratch 1 mailbox register");
l_scratch8_reg.setBit<SCRATCH1_REG_VALID_BIT>();
}
// set_scratch2_reg -- set TP/N0/N1/PCI/MC/PAU/IOHS chiplet PG
{
fapi2::buffer<uint32_t> l_scratch2_reg = 0;
uint32_t l_pci_gard_vector;
uint32_t l_nmmu_gard_vector;
uint32_t l_mc_gard_vector;
uint32_t l_pauc_gard_vector;
uint32_t l_pau_gard_vector;
uint32_t l_iohs_gard_vector;
// PCI
FAPI_DBG("Calculating PCI chiplet gard vector");
FAPI_TRY(p10_sbe_scratch_calc_gard_vector<fapi2::TARGET_TYPE_PEC>(i_target_chip,
l_pci_gard_vector),
"Error from p10_sbe_scratch_calc_gard_vector (pec)");
l_scratch2_reg.insert<PCI_GARD_STARTBIT, PCI_GARD_LENGTH, GARD_VECTOR_STARTBIT>(l_pci_gard_vector);
// NMMU1
FAPI_DBG("Calculating NMMU region gard vector");
FAPI_TRY(p10_sbe_scratch_calc_gard_vector<fapi2::TARGET_TYPE_NMMU>(i_target_chip,
l_nmmu_gard_vector),
"Error from p10_sbe_scratch_calc_gard_vector (nmmu)");
l_scratch2_reg.insert<NMMU1_GARD_BIT, 1, 1>(l_nmmu_gard_vector);
// MC
FAPI_DBG("Calculating MC chiplet gard vector");
FAPI_TRY(p10_sbe_scratch_calc_gard_vector<fapi2::TARGET_TYPE_MC>(i_target_chip,
l_mc_gard_vector),
"Error from p10_sbe_scratch_calc_gard_vector (mc)");
l_scratch2_reg.insert<MC_GARD_STARTBIT, MC_GARD_LENGTH, GARD_VECTOR_STARTBIT>(l_mc_gard_vector);
// PAUC
FAPI_DBG("Calculating PAUC chiplet gard vector");
FAPI_TRY(p10_sbe_scratch_calc_gard_vector<fapi2::TARGET_TYPE_PAUC>(i_target_chip,
l_pauc_gard_vector),
"Error from p10_sbe_scratch_calc_gard_vector (pauc)");
l_scratch2_reg.insert<PAUC_GARD_STARTBIT, PAUC_GARD_LENGTH, GARD_VECTOR_STARTBIT>(l_pauc_gard_vector);
// PAU
FAPI_DBG("Calculating PAU region gard vector");
FAPI_TRY(p10_sbe_scratch_calc_gard_vector<fapi2::TARGET_TYPE_PAU>(i_target_chip,
l_pau_gard_vector),
"Error from p10_sbe_scratch_calc_gard_vector (pau)");
l_scratch2_reg.insert<PAU_GARD_STARTBIT, PAU_GARD_LENGTH, GARD_VECTOR_STARTBIT>(l_pau_gard_vector);
// IOHS
FAPI_DBG("Calculating IOHS chiplet gard vector");
FAPI_TRY(p10_sbe_scratch_calc_gard_vector<fapi2::TARGET_TYPE_IOHS>(i_target_chip,
l_iohs_gard_vector),
"Error from p10_sbe_scratch_calc_gard_vector (iohs)");
l_scratch2_reg.insert<IOHS_GARD_STARTBIT, IOHS_GARD_LENGTH, GARD_VECTOR_STARTBIT>(l_iohs_gard_vector);
FAPI_DBG("Setting up value of Scratch 2 mailbox register");
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_2_FSI,
l_scratch2_reg),
"Error writing Scratch 2 mailbox register");
l_scratch8_reg.setBit<SCRATCH2_REG_VALID_BIT>();
}
// set_scratch3_reg -- FW Mode/Control flags
{
fapi2::buffer<uint32_t> l_scratch3_reg = 0;
fapi2::ATTR_BOOT_FLAGS_Type l_attr_boot_flags;
FAPI_DBG("Reading ATTR_BOOT_FLAGS");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_BOOT_FLAGS, FAPI_SYSTEM, l_attr_boot_flags),
"Error from FAPI_ATTR_GET (ATTR_BOOT_FLAGS)");
l_scratch3_reg.insertFromRight<ATTR_BOOT_FLAGS_STARTBIT, ATTR_BOOT_FLAGS_LENGTH>(l_attr_boot_flags);
FAPI_DBG("Setting up value of Scratch 3 mailbox register");
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_3_FSI,
l_scratch3_reg),
"Error writing Scratch 3 mailbox register");
l_scratch8_reg.setBit<SCRATCH3_REG_VALID_BIT>();
}
// set_scratch4_reg -- Nest/Boot frequency
{
fapi2::buffer<uint32_t> l_scratch4_reg = 0;
fapi2::ATTR_I2C_BUS_DIV_REF_Type l_attr_i2c_bus_div_ref;
fapi2::ATTR_FREQ_CORE_BOOT_MHZ_Type l_attr_freq_core_boot_mhz;
FAPI_DBG("Reading ATTR_I2C_BUS_DIV_REF, ATTR_FREQ_CORE_BOOT_MHZ");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_I2C_BUS_DIV_REF, i_target_chip, l_attr_i2c_bus_div_ref),
"Error from FAPI_ATTR_GET (ATTR_I2C_BUS_DIV_REF");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_CORE_BOOT_MHZ, i_target_chip, l_attr_freq_core_boot_mhz),
"Error from FAPI_ATTR_GET (ATTR_FREQ_CORE_BOOT_MHZ");
l_scratch4_reg.insertFromRight<ATTR_I2C_BUS_DIV_REF_STARTBIT, ATTR_I2C_BUS_DIV_REF_LENGTH>(l_attr_i2c_bus_div_ref);
l_scratch4_reg.insertFromRight<ATTR_FREQ_CORE_BOOT_MHZ_STARTBIT, ATTR_FREQ_CORE_BOOT_MHZ_LENGTH>
(l_attr_freq_core_boot_mhz);
FAPI_DBG("Setting up value of Scratch 4 mailbox register");
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_4_FSI,
l_scratch4_reg),
"Error writing Scratch 4 mailbox register");
l_scratch8_reg.setBit<SCRATCH4_REG_VALID_BIT>();
}
// set_scratch5_reg -- HWP control flags/PLL muxes
{
fapi2::buffer<uint32_t> l_scratch5_reg = 0;
fapi2::ATTR_SYSTEM_IPL_PHASE_Type l_attr_system_ipl_phase;
fapi2::ATTR_CONTAINED_IPL_TYPE_Type l_attr_contained_ipl_type;
fapi2::ATTR_RUNN_MODE_Type l_attr_runn_mode;
fapi2::ATTR_DISABLE_HBBL_VECTORS_Type l_attr_disable_hbbl_vectors;
fapi2::ATTR_SBE_SELECT_EX_POLICY_Type l_attr_sbe_select_ex_policy;
fapi2::ATTR_CLOCK_MUX_IOHS_LCPLL_INPUT_Type l_attr_clock_mux_iohs_lcpll_input;
fapi2::ATTR_CLOCK_MUX_PCI_LCPLL_INPUT_Type l_attr_clock_mux_pci_lcpll_input;
FAPI_DBG("Reading ATTR_SYSTEM_IPL_PHASE, ATTR_CONTAINED_IPL_TYPE");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_IPL_PHASE, FAPI_SYSTEM, l_attr_system_ipl_phase),
"Error from FAPI_ATTR_GET (ATTR_SYSTEM_IPL_PHASE)");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CONTAINED_IPL_TYPE, FAPI_SYSTEM, l_attr_contained_ipl_type),
"Error from FAPI_ATTR_GET (ATTR_CONTAINED_IPL_TYPE)");
if (l_attr_contained_ipl_type == fapi2::ENUM_ATTR_CONTAINED_IPL_TYPE_CACHE)
{
l_scratch5_reg.insertFromRight<IPL_TYPE_STARTBIT, IPL_TYPE_LENGTH>(IPL_TYPE_CACHE_CONTAINED);
}
else if (l_attr_contained_ipl_type == fapi2::ENUM_ATTR_CONTAINED_IPL_TYPE_CHIP)
{
l_scratch5_reg.insertFromRight<IPL_TYPE_STARTBIT, IPL_TYPE_LENGTH>(IPL_TYPE_CHIP_CONTAINED);
}
else
{
l_scratch5_reg.insertFromRight<IPL_TYPE_STARTBIT, IPL_TYPE_LENGTH>(IPL_TYPE_HOSTBOOT);
}
FAPI_DBG("Reading ATTR_RUNN_MODE");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_RUNN_MODE, FAPI_SYSTEM, l_attr_runn_mode),
"Error from FAPI_ATTR_GET (ATTR_RUNN_MODE)");
if (l_attr_runn_mode == fapi2::ENUM_ATTR_RUNN_MODE_ON)
{
l_scratch5_reg.setBit<ATTR_RUNN_MODE_BIT>();
}
else
{
l_scratch5_reg.clearBit<ATTR_RUNN_MODE_BIT>();
}
FAPI_DBG("Reading ATTR_DISABLE_HBBL_VECTORS");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_DISABLE_HBBL_VECTORS, FAPI_SYSTEM, l_attr_disable_hbbl_vectors),
"Error from FAPI_ATTR_GET (ATTR_DISABLE_HBBL_VECTORS)");
if (l_attr_disable_hbbl_vectors == fapi2::ENUM_ATTR_DISABLE_HBBL_VECTORS_TRUE)
{
l_scratch5_reg.setBit<ATTR_DISABLE_HBBL_VECTORS_BIT>();
}
else
{
l_scratch5_reg.clearBit<ATTR_DISABLE_HBBL_VECTORS_BIT>();
}
FAPI_DBG("Reading ATTR_SBE_SELECT_EX_POLICY");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SBE_SELECT_EX_POLICY, FAPI_SYSTEM, l_attr_sbe_select_ex_policy),
"Error from FAPI_ATTR_GET (ATTR_SBE_SELECT_EX_POLICY)");
l_scratch5_reg.insertFromRight<ATTR_SBE_SELECT_EX_POLICY_STARTBIT, ATTR_SBE_SELECT_EX_POLICY_LENGTH>
(l_attr_sbe_select_ex_policy);
FAPI_DBG("Reading IOHS PLL mux attributes");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CLOCK_MUX_IOHS_LCPLL_INPUT, i_target_chip, l_attr_clock_mux_iohs_lcpll_input),
"Error from FAPI_ATTR_GET (ATTR_CLOCK_MUX_IOHS_LCPLL_INPUT)");
for (const auto& l_iohs_target : i_target_chip.getChildren<fapi2::TARGET_TYPE_IOHS>(fapi2::TARGET_STATE_FUNCTIONAL))
{
fapi2::ATTR_CHIP_UNIT_POS_Type l_attr_chip_unit_pos;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_iohs_target, l_attr_chip_unit_pos),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
FAPI_TRY(l_scratch5_reg.insertFromRight(l_attr_clock_mux_iohs_lcpll_input[l_attr_chip_unit_pos],
ATTR_CLOCK_MUX_IOHS_LCPLL_INPUT_STARTBIT +
(ATTR_CLOCK_MUX_IOHS_LCPLL_INPUT_LENGTH * l_attr_chip_unit_pos),
ATTR_CLOCK_MUX_IOHS_LCPLL_INPUT_LENGTH));
}
FAPI_DBG("Reading PCI PLL mux attributes");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CLOCK_MUX_PCI_LCPLL_INPUT, i_target_chip, l_attr_clock_mux_pci_lcpll_input),
"Error from FAPI_ATTR_GET (ATTR_CLOCK_MUX_PCI_LCPLL_INPUT)");
for (const auto& l_pci_target : i_target_chip.getChildren<fapi2::TARGET_TYPE_PEC>(fapi2::TARGET_STATE_FUNCTIONAL))
{
fapi2::ATTR_CHIP_UNIT_POS_Type l_attr_chip_unit_pos;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_pci_target, l_attr_chip_unit_pos),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
FAPI_TRY(l_scratch5_reg.insertFromRight(l_attr_clock_mux_pci_lcpll_input[l_attr_chip_unit_pos],
ATTR_CLOCK_MUX_PCI_LCPLL_INPUT_STARTBIT +
(ATTR_CLOCK_MUX_PCI_LCPLL_INPUT_LENGTH * l_attr_chip_unit_pos),
ATTR_CLOCK_MUX_PCI_LCPLL_INPUT_LENGTH));
}
FAPI_DBG("Setting up value of Scratch_reg5");
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_5_FSI,
l_scratch5_reg),
"Error writing Scratch 5 mailbox register");
l_scratch8_reg.setBit<SCRATCH5_REG_VALID_BIT>();
}
// set_scratch6_reg -- Master/slave, node/chip selection, PLL bypass controls
{
fapi2::buffer<uint32_t> l_scratch6_reg = 0;
fapi2::ATTR_CP_PLLTODFLT_BYPASS_Type l_attr_cp_plltodflt_bypass;
fapi2::ATTR_CP_PLLNESTFLT_BYPASS_Type l_attr_cp_pllnestflt_bypass;
fapi2::ATTR_CP_PLLIOFLT_BYPASS_Type l_attr_cp_pllioflt_bypass;
fapi2::ATTR_CP_PLLIOSSFLT_BYPASS_Type l_attr_cp_plliossflt_bypass;
fapi2::ATTR_NEST_DPLL_BYPASS_Type l_attr_nest_dpll_bypass;
fapi2::ATTR_PAU_DPLL_BYPASS_Type l_attr_pau_dpll_bypass;
fapi2::ATTR_IO_TANK_PLL_BYPASS_Type l_attr_io_tank_pll_bypass;
fapi2::ATTR_PROC_FABRIC_EFF_TOPOLOGY_ID_Type l_attr_proc_fabric_eff_topology_id;
fapi2::ATTR_PROC_FABRIC_TOPOLOGY_MODE_Type l_attr_proc_fabric_topology_mode;
fapi2::ATTR_PROC_FABRIC_BROADCAST_MODE_Type l_attr_proc_fabric_broadcast_mode;
fapi2::ATTR_PROC_SBE_MASTER_CHIP_Type l_attr_proc_sbe_master_chip;
fapi2::ATTR_PROC_FABRIC_TOPOLOGY_ID_Type l_attr_proc_fabric_topology_id;
FAPI_DBG("Reading filter PLL bypass attributes");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CP_PLLTODFLT_BYPASS, i_target_chip, l_attr_cp_plltodflt_bypass),
"Error from FAPI_ATTR_GET (ATTR_CP_PLLTODFLT_BYPASS)");
l_scratch6_reg.writeBit<ATTR_CP_PLLTODFLT_BYPASS_BIT>(l_attr_cp_plltodflt_bypass ==
fapi2::ENUM_ATTR_CP_PLLTODFLT_BYPASS_BYPASS);
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CP_PLLNESTFLT_BYPASS, i_target_chip, l_attr_cp_pllnestflt_bypass),
"Error from FAPI_ATTR_GET (ATTR_CP_PLLNESTFLT_BYPASS)");
l_scratch6_reg.writeBit<ATTR_CP_PLLNESTFLT_BYPASS_BIT>(l_attr_cp_pllnestflt_bypass ==
fapi2::ENUM_ATTR_CP_PLLNESTFLT_BYPASS_BYPASS);
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CP_PLLIOFLT_BYPASS, i_target_chip, l_attr_cp_pllioflt_bypass),
"Error from FAPI_ATTR_GET (ATTR_CP_PLLIOFLT_BYPASS)");
l_scratch6_reg.writeBit<ATTR_CP_PLLIOFLT_BYPASS_BIT>(l_attr_cp_pllioflt_bypass ==
fapi2::ENUM_ATTR_CP_PLLIOFLT_BYPASS_BYPASS);
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CP_PLLIOSSFLT_BYPASS, i_target_chip, l_attr_cp_plliossflt_bypass),
"Error from FAPI_ATTR_GET (ATTR_CP_PLLIOSSFLT_BYPASS)");
l_scratch6_reg.writeBit<ATTR_CP_PLLIOSSFLT_BYPASS_BIT>(l_attr_cp_plliossflt_bypass ==
fapi2::ENUM_ATTR_CP_PLLIOSSFLT_BYPASS_BYPASS);
FAPI_DBG("Reading DPLL bypass attributes");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_NEST_DPLL_BYPASS, i_target_chip, l_attr_nest_dpll_bypass),
"Error from FAPI_ATTR_GET (ATTR_NEST_DPLL_BYPASS");
l_scratch6_reg.writeBit<ATTR_NEST_DPLL_BYPASS_BIT>(l_attr_nest_dpll_bypass == fapi2::ENUM_ATTR_NEST_DPLL_BYPASS_BYPASS);
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PAU_DPLL_BYPASS, i_target_chip, l_attr_pau_dpll_bypass),
"Error from FAPI_ATTR_GET (ATTR_PAU_DPLL_BYPASS");
l_scratch6_reg.writeBit<ATTR_PAU_DPLL_BYPASS_BIT>(l_attr_pau_dpll_bypass == fapi2::ENUM_ATTR_PAU_DPLL_BYPASS_BYPASS);
FAPI_DBG("Reading tank PLL bypass attributes");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IO_TANK_PLL_BYPASS, i_target_chip, l_attr_io_tank_pll_bypass));
l_scratch6_reg.writeBit<ATTR_IO_TANK_PLL_BYPASS_BIT>(l_attr_io_tank_pll_bypass ==
fapi2::ENUM_ATTR_IO_TANK_PLL_BYPASS_BYPASS);
FAPI_DBG("Reading master SBE attribute");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_SBE_MASTER_CHIP, i_target_chip, l_attr_proc_sbe_master_chip),
"Error from FAPI_ATTR_GET (ATTR_PROC_SBE_MASTER_CHIP)");
l_scratch6_reg.writeBit<ATTR_PROC_SBE_MASTER_CHIP_BIT>(l_attr_proc_sbe_master_chip ==
fapi2::ENUM_ATTR_PROC_SBE_MASTER_CHIP_TRUE);
FAPI_DBG("Reading fabric topology/broadcast attributes");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_EFF_TOPOLOGY_ID, i_target_chip, l_attr_proc_fabric_eff_topology_id),
"Error from FAPI_ATTR_GET (ATTR_PROC_FABRIC_EFF_TOPOLOGY_ID)");
l_scratch6_reg.insertFromRight<ATTR_PROC_FABRIC_EFF_TOPOLOGY_ID_STARTBIT, ATTR_PROC_FABRIC_EFF_TOPOLOGY_ID_LENGTH>
(l_attr_proc_fabric_eff_topology_id);
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_TOPOLOGY_MODE, FAPI_SYSTEM, l_attr_proc_fabric_topology_mode),
"Error from FAPI_ATTR_GET (ATTR_PROC_FABRIC_TOPOLOGY_MODE");
if (l_attr_proc_fabric_topology_mode == fapi2::ENUM_ATTR_PROC_FABRIC_TOPOLOGY_MODE_MODE1)
{
l_scratch6_reg.setBit<ATTR_PROC_FABRIC_TOPOLOGY_MODE_BIT>();
}
else
{
l_scratch6_reg.clearBit<ATTR_PROC_FABRIC_TOPOLOGY_MODE_BIT>();
}
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_BROADCAST_MODE, FAPI_SYSTEM, l_attr_proc_fabric_broadcast_mode),
"Error from FAPI_ATTR_GET (ATTR_PROC_FABRIC_BROADCAST_MODE");
l_scratch6_reg.insertFromRight<ATTR_PROC_FABRIC_BROADCAST_MODE_STARTBIT, ATTR_PROC_FABRIC_BROADCAST_MODE_LENGTH>
(l_attr_proc_fabric_broadcast_mode);
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_TOPOLOGY_ID, i_target_chip, l_attr_proc_fabric_topology_id),
"Error from FAPI_ATTR_GET (ATTR_PROC_FABRIC_TOPOLOGY_ID");
l_scratch6_reg.insertFromRight< ATTR_PROC_FABRIC_TOPOLOGY_ID_STARTBIT, ATTR_PROC_FABRIC_TOPOLOGY_ID_LENGTH>
(l_attr_proc_fabric_topology_id);
FAPI_DBG("Setting up value of Scratch_reg6");
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_6_FSI,
l_scratch6_reg),
"Error writing Scratch 6 mailbox register");
l_scratch8_reg.setBit<SCRATCH6_REG_VALID_BIT>();
}
// set_scratch7_reg - IOHS region gard / chip contained active cores vector
{
fapi2::buffer<uint32_t> l_scratch7_reg = 0;
fapi2::ATTR_CONTAINED_IPL_TYPE_Type l_attr_contained_ipl_type;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CONTAINED_IPL_TYPE, FAPI_SYSTEM, l_attr_contained_ipl_type),
"Error from FAPI_ATTR_GET (ATTR_CONTAINED_IPL_TYPE)");
if (l_attr_contained_ipl_type == fapi2::ENUM_ATTR_CONTAINED_IPL_TYPE_NONE)
{
uint32_t l_ndl_gard_vector;
FAPI_DBG("Setting up IOHS NDL gard records");
FAPI_TRY(p10_sbe_scratch_calc_iohs_region_gard_vectors(i_target_chip,
l_ndl_gard_vector),
"Error from p10_sbe_scratch_calc_iohs_region_gard_vectors");
l_scratch7_reg.insert<NDL_GARD_STARTBIT, NDL_GARD_LENGTH, GARD_VECTOR_STARTBIT>(l_ndl_gard_vector);
}
else
{
fapi2::ATTR_CHIP_CONTAINED_ACTIVE_CORES_VEC_Type l_attr_chip_contained_active_cores_vec;
FAPI_DBG("Setting up chip contained active cores vector");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_CONTAINED_ACTIVE_CORES_VEC, i_target_chip,
l_attr_chip_contained_active_cores_vec),
"Error from FAPI_ATTR_GET (ATTR_CHIP_CONTAINED_ACTIVE_CORES_VEC)");
l_scratch7_reg.insertFromRight<ATTR_CHIP_CONTAINED_ACTIVE_CORES_VEC_STARTBIT, ATTR_CHIP_CONTAINED_ACTIVE_CORES_VEC_LENGTH>
(l_attr_chip_contained_active_cores_vec);
}
FAPI_DBG("Setting up value of Scratch_reg7");
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_7_FSI,
l_scratch7_reg),
"Error writing Scratch 7 mailbox register");
l_scratch8_reg.setBit<SCRATCH7_REG_VALID_BIT>();
}
// set_scratch9_reg - PAU/MC frequency
{
fapi2::buffer<uint32_t> l_scratch9_reg = 0;
fapi2::ATTR_FREQ_PAU_MHZ_Type l_attr_freq_pau_mhz;
fapi2::ATTR_MC_PLL_BUCKET_Type l_attr_mc_pll_bucket = { 0 };
fapi2::ATTR_NDL_MESHCTRL_SETUP_Type l_attr_ndl_meshctrl_setup;
FAPI_DBG("Reading ATTR_FREQ_PAU_MHZ");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_PAU_MHZ, FAPI_SYSTEM, l_attr_freq_pau_mhz),
"Error from FAPI_ATTR_GET (ATTR_FREQ_PAU_MHZ");
l_scratch9_reg.insertFromRight<ATTR_FREQ_PAU_MHZ_STARTBIT, ATTR_FREQ_PAU_MHZ_LENGTH>(l_attr_freq_pau_mhz);
// calculate bucket index based on desired frequency
FAPI_DBG("Setting up MC PLL bucket values");
FAPI_TRY(p10_sbe_scratch_regs_get_mc_pll_bucket(i_target_chip, l_attr_mc_pll_bucket),
"Error from p10_sbe_scratch_regs_get_mc_pll_bucket");
FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_MC_PLL_BUCKET, i_target_chip, l_attr_mc_pll_bucket),
"Error from FAPI_ATTR_SET (ATTR_MC_PLL_BUCKET)");
for (const auto& l_mc_target : i_target_chip.getChildren<fapi2::TARGET_TYPE_MC>(fapi2::TARGET_STATE_FUNCTIONAL))
{
fapi2::ATTR_CHIP_UNIT_POS_Type l_attr_chip_unit_pos;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_mc_target, l_attr_chip_unit_pos),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
FAPI_TRY(l_scratch9_reg.insertFromRight(l_attr_mc_pll_bucket[l_attr_chip_unit_pos],
ATTR_MC_PLL_BUCKET_STARTBIT +
(ATTR_MC_PLL_BUCKET_LENGTH * l_attr_chip_unit_pos),
ATTR_MC_PLL_BUCKET_LENGTH));
}
FAPI_DBG("Reading ATTR_NDL_MESHCTRL_SETUP");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_NDL_MESHCTRL_SETUP, i_target_chip, l_attr_ndl_meshctrl_setup),
"Error from FAPI_ATTR_GET (ATTR_NDL_MESHCTRL_SETUP)");
l_scratch9_reg.insertFromRight<ATTR_NDL_MESHCTRL_SETUP_STARTBIT, ATTR_NDL_MESHCTRL_SETUP_LENGTH>
(l_attr_ndl_meshctrl_setup);
FAPI_DBG("Setting up value of Scratch_reg9");
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_9_FSI,
l_scratch9_reg),
"Error writing Scratch 9 mailbox register");
l_scratch8_reg.setBit<SCRATCH9_REG_VALID_BIT>();
}
// set_scratch10_reg - IOHS frequency / chip contained backing caches vector
{
fapi2::buffer<uint32_t> l_scratch10_reg = 0;
fapi2::ATTR_CONTAINED_IPL_TYPE_Type l_attr_contained_ipl_type;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CONTAINED_IPL_TYPE, FAPI_SYSTEM, l_attr_contained_ipl_type),
"Error from FAPI_ATTR_GET (ATTR_CONTAINED_IPL_TYPE)");
if (l_attr_contained_ipl_type == fapi2::ENUM_ATTR_CONTAINED_IPL_TYPE_NONE)
{
fapi2::ATTR_IOHS_PLL_BUCKET_Type l_attr_iohs_pll_bucket = { 0 };
// calculate bucket index based on desired frequency
FAPI_DBG("Setting up IOHS PLL bucket values");
FAPI_TRY(p10_sbe_scratch_regs_get_iohs_pll_bucket(i_target_chip, l_attr_iohs_pll_bucket),
"Error from p10_sbe_scratch_regs_get_iohs_pll_bucket");
FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_IOHS_PLL_BUCKET, i_target_chip, l_attr_iohs_pll_bucket),
"Error from FAPI_ATTR_SET (ATTR_IOHS_PLL_BUCKET)");
for (const auto& l_iohs_target : i_target_chip.getChildren<fapi2::TARGET_TYPE_IOHS>(fapi2::TARGET_STATE_FUNCTIONAL))
{
fapi2::ATTR_CHIP_UNIT_POS_Type l_attr_chip_unit_pos;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_iohs_target, l_attr_chip_unit_pos),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
FAPI_TRY(l_scratch10_reg.insertFromRight(l_attr_iohs_pll_bucket[l_attr_chip_unit_pos],
ATTR_IOHS_PLL_BUCKET_STARTBIT +
(ATTR_IOHS_PLL_BUCKET_LENGTH * l_attr_chip_unit_pos),
ATTR_IOHS_PLL_BUCKET_LENGTH));
}
}
else
{
fapi2::ATTR_CHIP_CONTAINED_BACKING_CACHES_VEC_Type l_attr_chip_contained_backing_caches_vec;
FAPI_DBG("Setting up chip contained backing caches vector");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_CONTAINED_BACKING_CACHES_VEC, i_target_chip,
l_attr_chip_contained_backing_caches_vec),
"Error from FAPI_ATTR_GET (ATTR_CHIP_CONTAINED_BACKING_CACHES_VEC)");
l_scratch10_reg.insertFromRight<ATTR_CHIP_CONTAINED_BACKING_CACHES_VEC_STARTBIT, ATTR_CHIP_CONTAINED_BACKING_CACHES_VEC_LENGTH>
(l_attr_chip_contained_backing_caches_vec);
}
FAPI_DBG("Setting up value of Scratch_reg10");
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_10_FSI,
l_scratch10_reg),
"Error writing Scratch 10 mailbox register");
l_scratch8_reg.setBit<SCRATCH10_REG_VALID_BIT>();
}
FAPI_DBG("Setting up value of Scratch_reg8 (valid)");
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_8_FSI,
l_scratch8_reg),
"Error writing Scratch 8 mailbox register");
FAPI_INF("p10_setup_sbe_config: Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
Implement cache-/chip-contained IPL changes
Some procedures need to behave differently when booting in cache- or
chip-contained modes. Changes implemented:
- p10_mcs_setup:
MCs are deconfigured so skip this procedure entirely in both cache-
and chip-contained modes
- p10_sbe_attr_setup:
- p10_setup_sbe_config:
Guard ATTR_CHIP_CONTAINED_ACTIVE_CORES_VEC and
ATTR_CHIP_CONTAINED_BACKING_CACHES_VEC with chip-contained mode
Change-Id: Ibd87bfb6392f34b98d9885525fa52784200daf44
Reviewed-on: http://rchgit01.rchland.ibm.com/gerrit1/82046
Tested-by: Jenkins Server <8e3f934e4c44875bc48d33da3ea13d93ba9a233f@us.ibm.com>
Tested-by: PPE CI <dc75934ba5befb9221434e67a247b93aec46b36b@us.ibm.com>
Tested-by: Hostboot CI <52521565bd8ea18a2b112942dce4f4220a97c2c8@us.ibm.com>
Reviewed-by: Joseph J McGill <4a85c6614f9f065f63d8fd57cde15e48af07ea2a@us.ibm.com>
Reviewed-on: http://rchgit01.rchland.ibm.com/gerrit1/82087
Reviewed-by: Nicholas E Bofferding <fb8db48116bc8a69e29dd8cdb037246f232f4af5@us.ibm.com>
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p10/procedures/hwp/perv/p10_setup_sbe_config.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p10_setup_sbe_config.C
///
/// @brief proc setup sbe config
//------------------------------------------------------------------------------
// *HWP HW Maintainer : Anusha Reddy (anusrang@in.ibm.com)
// *HWP FW Maintainer : Raja Das (rajadas2@in.ibm.com)
// *HWP Consumed by : FSP
//------------------------------------------------------------------------------
#include <p10_setup_sbe_config.H>
#include <p10_scom_perv.H>
#include <p10_sbe_scratch_regs.H>
#include <p10_frequency_buckets.H>
///
/// @brief Calculate GARD vector based on functional target states
///
/// @tparam T template parameter, target type
/// @param[in] i_target_chip Processor chip target
/// @param[out] o_gard_vector GARD vector (1-bit indicates non-functional)
/// valid data left-aligned from 0..<num chiplets of type T-1>
///
/// @return fapi::ReturnCode. FAPI2_RC_SUCCESS if success, else error code.
///
template<fapi2::TargetType T>
fapi2::ReturnCode
p10_sbe_scratch_calc_gard_vector(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip,
uint32_t& o_gard_vector)
{
fapi2::buffer<uint32_t> l_functional = 0;
fapi2::ATTR_CONTAINED_IPL_TYPE_Type l_attr_contained_ipl_type;
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CONTAINED_IPL_TYPE, FAPI_SYSTEM, l_attr_contained_ipl_type),
"Error from FAPI_ATTR_GET (ATTR_CONTAINED_IPL_TYPE)");
// no desire to enable async chiplets in contained modes, use gard vector
// content to enforce this
if ((l_attr_contained_ipl_type != fapi2::ENUM_ATTR_CONTAINED_IPL_TYPE_NONE) &&
((T == fapi2::TARGET_TYPE_PEC) ||
(T == fapi2::TARGET_TYPE_MC) ||
(T == fapi2::TARGET_TYPE_PAUC) ||
(T == fapi2::TARGET_TYPE_PAU) ||
(T == fapi2::TARGET_TYPE_IOHS)))
{
goto fapi_try_exit;
}
for (const auto& l_tgt : i_target_chip.getChildren<T>(fapi2::TARGET_STATE_FUNCTIONAL))
{
fapi2::ATTR_CHIP_UNIT_POS_Type l_unit_pos;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_tgt, l_unit_pos),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS, functional)");
FAPI_TRY(l_functional.setBit(l_unit_pos),
"Error from setBit (functional, unit target pos: %d)", l_unit_pos);
}
fapi_try_exit:
FAPI_DBG("Functional : 0x%08X", l_functional);
o_gard_vector = ~l_functional;
FAPI_DBG("Gard vector : 0x%08X", o_gard_vector);
return fapi2::current_err;
}
///
/// @brief Calculate IOHS region GARD vectors based on functional target states
/// and designated link usage
///
/// @param[in] i_target_chip Processor chip target
/// @param[out] o_ndl_gard_vector NDL GARD vector (1-bit indicates non-functional)
/// valid data left-aligned from 0..7
///
/// @return fapi::ReturnCode. FAPI2_RC_SUCCESS if success, else error code.
///
fapi2::ReturnCode
p10_sbe_scratch_calc_iohs_region_gard_vectors(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip,
uint32_t& o_ndl_gard_vector)
{
fapi2::buffer<uint32_t> l_ndl_functional = 0;
for (const auto& l_tgt : i_target_chip.getChildren<fapi2::TARGET_TYPE_IOHS>(fapi2::TARGET_STATE_FUNCTIONAL))
{
fapi2::ATTR_IOHS_CONFIG_MODE_Type l_iohs_config_mode;
fapi2::ATTR_CHIP_UNIT_POS_Type l_unit_pos;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IOHS_CONFIG_MODE, l_tgt, l_iohs_config_mode),
"Error from FAPI_ATTR_GET (ATTR_IOHS_CONFIG_MODE");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_tgt, l_unit_pos),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
if ((l_iohs_config_mode != fapi2::ENUM_ATTR_IOHS_CONFIG_MODE_SMPX) &&
(l_iohs_config_mode != fapi2::ENUM_ATTR_IOHS_CONFIG_MODE_SMPA))
{
FAPI_TRY(l_ndl_functional.setBit(l_unit_pos));
}
}
o_ndl_gard_vector = ~l_ndl_functional;
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Lookup MC frequency bucket attribute values given platform frequency
/// attributes
///
/// @param[in] i_target_chip Processor chip target
/// @param[in] o_attr_mc_pll_bucket PLL bucket attribute value
///
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode
p10_sbe_scratch_regs_get_mc_pll_bucket(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip,
fapi2::ATTR_MC_PLL_BUCKET_Type o_attr_mc_pll_bucket)
{
FAPI_DBG("Start");
for (const auto l_mc_target : i_target_chip.getChildren<fapi2::TARGET_TYPE_MC>(fapi2::TARGET_STATE_FUNCTIONAL))
{
fapi2::ATTR_FREQ_MC_MHZ_Type l_attr_freq_mc_mhz;
fapi2::ATTR_CHIP_UNIT_POS_Type l_unit_num;
bool l_bucket_found = false;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_MC_MHZ, l_mc_target, l_attr_freq_mc_mhz),
"Error from FAPI_ATTR_GET (ATTR_FREQ_MC_MHZ)");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_mc_target, l_unit_num),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
for (auto l_bucket = 0; l_bucket < MEM_PLL_FREQ_BUCKETS; l_bucket++)
{
if (l_attr_freq_mc_mhz == MEM_PLL_FREQ_LIST[l_bucket])
{
l_bucket_found = true;
o_attr_mc_pll_bucket[l_unit_num] = l_bucket;
break;
}
}
FAPI_ASSERT(l_bucket_found,
fapi2::P10_SBE_SCRATCH_REGS_MC_FREQ_LOOKUP_ERR()
.set_TARGET_CHIP(i_target_chip)
.set_TARGET_MC(l_mc_target)
.set_FREQ_MC_MHZ(l_attr_freq_mc_mhz),
"Requested MC frequency (%d MHz) not found in p10_frequency_buckets.H!",
l_attr_freq_mc_mhz);
}
fapi_try_exit:
FAPI_DBG("End");
return fapi2::current_err;
}
///
/// @brief Lookup IOHS frequency bucket attribute values given platform frequency
/// attributes
///
/// @param[in] i_target_chip Processor chip target
/// @param[in] o_attr_iohs_pll_bucket PLL bucket attribute value
///
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode
p10_sbe_scratch_regs_get_iohs_pll_bucket(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip,
fapi2::ATTR_IOHS_PLL_BUCKET_Type o_attr_iohs_pll_bucket)
{
FAPI_DBG("Start");
for (const auto l_iohs_target : i_target_chip.getChildren<fapi2::TARGET_TYPE_IOHS>(fapi2::TARGET_STATE_FUNCTIONAL))
{
fapi2::ATTR_FREQ_IOHS_MHZ_Type l_attr_freq_iohs_mhz;
fapi2::ATTR_CHIP_UNIT_POS_Type l_unit_num;
bool l_bucket_found = false;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_IOHS_MHZ, l_iohs_target, l_attr_freq_iohs_mhz),
"Error from FAPI_ATTR_GET (ATTR_FREQ_IOHS_MHZ)");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_iohs_target, l_unit_num),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
for (auto l_bucket = 0; l_bucket < IOHS_PLL_FREQ_BUCKETS; l_bucket++)
{
if (l_attr_freq_iohs_mhz == IOHS_PLL_FREQ_LIST[l_bucket])
{
l_bucket_found = true;
o_attr_iohs_pll_bucket[l_unit_num] = l_bucket;
break;
}
}
FAPI_ASSERT(l_bucket_found,
fapi2::P10_SBE_SCRATCH_REGS_IOHS_FREQ_LOOKUP_ERR()
.set_TARGET_CHIP(i_target_chip)
.set_TARGET_IOHS(l_iohs_target)
.set_FREQ_IOHS_MHZ(l_attr_freq_iohs_mhz),
"Requested IOHS frequency (%d MHz) not found in p10_frequency_buckets.H!",
l_attr_freq_iohs_mhz);
}
fapi_try_exit:
FAPI_DBG("End");
return fapi2::current_err;
}
// description in header
fapi2::ReturnCode p10_setup_sbe_config(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
using namespace scomt::perv;
fapi2::buffer<uint32_t> l_scratch8_reg = 0;
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
FAPI_INF("p10_setup_sbe_config:: Entering ...");
FAPI_TRY(fapi2::getCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_8_FSI,
l_scratch8_reg),
"Error reading Scratch 8 mailbox register");
// set_scratch1_reg -- set EQ chiplet PG
{
fapi2::buffer<uint32_t> l_scratch1_reg = 0;
uint32_t l_core_gard_vector;
// CORE
FAPI_DBG("Calculating CORE region gard vector");
FAPI_TRY(p10_sbe_scratch_calc_gard_vector<fapi2::TARGET_TYPE_CORE>(i_target_chip,
l_core_gard_vector),
"Error from p10_sbe_scratch_calc_gard_vector (core)");
l_scratch1_reg.insert<CORE_GARD_STARTBIT, CORE_GARD_LENGTH, GARD_VECTOR_STARTBIT>(l_core_gard_vector);
FAPI_DBG("Setting up value of Scratch 1 mailbox register");
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_1_FSI,
l_scratch1_reg),
"Error writing Scratch 1 mailbox register");
l_scratch8_reg.setBit<SCRATCH1_REG_VALID_BIT>();
}
// set_scratch2_reg -- set TP/N0/N1/PCI/MC/PAU/IOHS chiplet PG
{
fapi2::buffer<uint32_t> l_scratch2_reg = 0;
uint32_t l_pci_gard_vector;
uint32_t l_nmmu_gard_vector;
uint32_t l_mc_gard_vector;
uint32_t l_pauc_gard_vector;
uint32_t l_pau_gard_vector;
uint32_t l_iohs_gard_vector;
// PCI
FAPI_DBG("Calculating PCI chiplet gard vector");
FAPI_TRY(p10_sbe_scratch_calc_gard_vector<fapi2::TARGET_TYPE_PEC>(i_target_chip,
l_pci_gard_vector),
"Error from p10_sbe_scratch_calc_gard_vector (pec)");
l_scratch2_reg.insert<PCI_GARD_STARTBIT, PCI_GARD_LENGTH, GARD_VECTOR_STARTBIT>(l_pci_gard_vector);
// NMMU1
FAPI_DBG("Calculating NMMU region gard vector");
FAPI_TRY(p10_sbe_scratch_calc_gard_vector<fapi2::TARGET_TYPE_NMMU>(i_target_chip,
l_nmmu_gard_vector),
"Error from p10_sbe_scratch_calc_gard_vector (nmmu)");
l_scratch2_reg.insert<NMMU1_GARD_BIT, 1, 1>(l_nmmu_gard_vector);
// MC
FAPI_DBG("Calculating MC chiplet gard vector");
FAPI_TRY(p10_sbe_scratch_calc_gard_vector<fapi2::TARGET_TYPE_MC>(i_target_chip,
l_mc_gard_vector),
"Error from p10_sbe_scratch_calc_gard_vector (mc)");
l_scratch2_reg.insert<MC_GARD_STARTBIT, MC_GARD_LENGTH, GARD_VECTOR_STARTBIT>(l_mc_gard_vector);
// PAUC
FAPI_DBG("Calculating PAUC chiplet gard vector");
FAPI_TRY(p10_sbe_scratch_calc_gard_vector<fapi2::TARGET_TYPE_PAUC>(i_target_chip,
l_pauc_gard_vector),
"Error from p10_sbe_scratch_calc_gard_vector (pauc)");
l_scratch2_reg.insert<PAUC_GARD_STARTBIT, PAUC_GARD_LENGTH, GARD_VECTOR_STARTBIT>(l_pauc_gard_vector);
// PAU
FAPI_DBG("Calculating PAU region gard vector");
FAPI_TRY(p10_sbe_scratch_calc_gard_vector<fapi2::TARGET_TYPE_PAU>(i_target_chip,
l_pau_gard_vector),
"Error from p10_sbe_scratch_calc_gard_vector (pau)");
l_scratch2_reg.insert<PAU_GARD_STARTBIT, PAU_GARD_LENGTH, GARD_VECTOR_STARTBIT>(l_pau_gard_vector);
// IOHS
FAPI_DBG("Calculating IOHS chiplet gard vector");
FAPI_TRY(p10_sbe_scratch_calc_gard_vector<fapi2::TARGET_TYPE_IOHS>(i_target_chip,
l_iohs_gard_vector),
"Error from p10_sbe_scratch_calc_gard_vector (iohs)");
l_scratch2_reg.insert<IOHS_GARD_STARTBIT, IOHS_GARD_LENGTH, GARD_VECTOR_STARTBIT>(l_iohs_gard_vector);
FAPI_DBG("Setting up value of Scratch 2 mailbox register");
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_2_FSI,
l_scratch2_reg),
"Error writing Scratch 2 mailbox register");
l_scratch8_reg.setBit<SCRATCH2_REG_VALID_BIT>();
}
// set_scratch3_reg -- FW Mode/Control flags
{
fapi2::buffer<uint32_t> l_scratch3_reg = 0;
fapi2::ATTR_BOOT_FLAGS_Type l_attr_boot_flags;
FAPI_DBG("Reading ATTR_BOOT_FLAGS");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_BOOT_FLAGS, FAPI_SYSTEM, l_attr_boot_flags),
"Error from FAPI_ATTR_GET (ATTR_BOOT_FLAGS)");
l_scratch3_reg.insertFromRight<ATTR_BOOT_FLAGS_STARTBIT, ATTR_BOOT_FLAGS_LENGTH>(l_attr_boot_flags);
FAPI_DBG("Setting up value of Scratch 3 mailbox register");
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_3_FSI,
l_scratch3_reg),
"Error writing Scratch 3 mailbox register");
l_scratch8_reg.setBit<SCRATCH3_REG_VALID_BIT>();
}
// set_scratch4_reg -- Nest/Boot frequency
{
fapi2::buffer<uint32_t> l_scratch4_reg = 0;
fapi2::ATTR_I2C_BUS_DIV_REF_Type l_attr_i2c_bus_div_ref;
fapi2::ATTR_FREQ_CORE_BOOT_MHZ_Type l_attr_freq_core_boot_mhz;
FAPI_DBG("Reading ATTR_I2C_BUS_DIV_REF, ATTR_FREQ_CORE_BOOT_MHZ");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_I2C_BUS_DIV_REF, i_target_chip, l_attr_i2c_bus_div_ref),
"Error from FAPI_ATTR_GET (ATTR_I2C_BUS_DIV_REF");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_CORE_BOOT_MHZ, i_target_chip, l_attr_freq_core_boot_mhz),
"Error from FAPI_ATTR_GET (ATTR_FREQ_CORE_BOOT_MHZ");
l_scratch4_reg.insertFromRight<ATTR_I2C_BUS_DIV_REF_STARTBIT, ATTR_I2C_BUS_DIV_REF_LENGTH>(l_attr_i2c_bus_div_ref);
l_scratch4_reg.insertFromRight<ATTR_FREQ_CORE_BOOT_MHZ_STARTBIT, ATTR_FREQ_CORE_BOOT_MHZ_LENGTH>
(l_attr_freq_core_boot_mhz);
FAPI_DBG("Setting up value of Scratch 4 mailbox register");
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_4_FSI,
l_scratch4_reg),
"Error writing Scratch 4 mailbox register");
l_scratch8_reg.setBit<SCRATCH4_REG_VALID_BIT>();
}
// set_scratch5_reg -- HWP control flags/PLL muxes
{
fapi2::buffer<uint32_t> l_scratch5_reg = 0;
fapi2::ATTR_SYSTEM_IPL_PHASE_Type l_attr_system_ipl_phase;
fapi2::ATTR_CONTAINED_IPL_TYPE_Type l_attr_contained_ipl_type;
fapi2::ATTR_RUNN_MODE_Type l_attr_runn_mode;
fapi2::ATTR_DISABLE_HBBL_VECTORS_Type l_attr_disable_hbbl_vectors;
fapi2::ATTR_SBE_SELECT_EX_POLICY_Type l_attr_sbe_select_ex_policy;
fapi2::ATTR_CLOCK_MUX_IOHS_LCPLL_INPUT_Type l_attr_clock_mux_iohs_lcpll_input;
fapi2::ATTR_CLOCK_MUX_PCI_LCPLL_INPUT_Type l_attr_clock_mux_pci_lcpll_input;
FAPI_DBG("Reading ATTR_SYSTEM_IPL_PHASE, ATTR_CONTAINED_IPL_TYPE");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_IPL_PHASE, FAPI_SYSTEM, l_attr_system_ipl_phase),
"Error from FAPI_ATTR_GET (ATTR_SYSTEM_IPL_PHASE)");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CONTAINED_IPL_TYPE, FAPI_SYSTEM, l_attr_contained_ipl_type),
"Error from FAPI_ATTR_GET (ATTR_CONTAINED_IPL_TYPE)");
if (l_attr_contained_ipl_type == fapi2::ENUM_ATTR_CONTAINED_IPL_TYPE_CACHE)
{
l_scratch5_reg.insertFromRight<IPL_TYPE_STARTBIT, IPL_TYPE_LENGTH>(IPL_TYPE_CACHE_CONTAINED);
}
else if (l_attr_contained_ipl_type == fapi2::ENUM_ATTR_CONTAINED_IPL_TYPE_CHIP)
{
l_scratch5_reg.insertFromRight<IPL_TYPE_STARTBIT, IPL_TYPE_LENGTH>(IPL_TYPE_CHIP_CONTAINED);
}
else
{
l_scratch5_reg.insertFromRight<IPL_TYPE_STARTBIT, IPL_TYPE_LENGTH>(IPL_TYPE_HOSTBOOT);
}
FAPI_DBG("Reading ATTR_RUNN_MODE");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_RUNN_MODE, FAPI_SYSTEM, l_attr_runn_mode),
"Error from FAPI_ATTR_GET (ATTR_RUNN_MODE)");
if (l_attr_runn_mode == fapi2::ENUM_ATTR_RUNN_MODE_ON)
{
l_scratch5_reg.setBit<ATTR_RUNN_MODE_BIT>();
}
else
{
l_scratch5_reg.clearBit<ATTR_RUNN_MODE_BIT>();
}
FAPI_DBG("Reading ATTR_DISABLE_HBBL_VECTORS");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_DISABLE_HBBL_VECTORS, FAPI_SYSTEM, l_attr_disable_hbbl_vectors),
"Error from FAPI_ATTR_GET (ATTR_DISABLE_HBBL_VECTORS)");
if (l_attr_disable_hbbl_vectors == fapi2::ENUM_ATTR_DISABLE_HBBL_VECTORS_TRUE)
{
l_scratch5_reg.setBit<ATTR_DISABLE_HBBL_VECTORS_BIT>();
}
else
{
l_scratch5_reg.clearBit<ATTR_DISABLE_HBBL_VECTORS_BIT>();
}
FAPI_DBG("Reading ATTR_SBE_SELECT_EX_POLICY");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SBE_SELECT_EX_POLICY, FAPI_SYSTEM, l_attr_sbe_select_ex_policy),
"Error from FAPI_ATTR_GET (ATTR_SBE_SELECT_EX_POLICY)");
l_scratch5_reg.insertFromRight<ATTR_SBE_SELECT_EX_POLICY_STARTBIT, ATTR_SBE_SELECT_EX_POLICY_LENGTH>
(l_attr_sbe_select_ex_policy);
FAPI_DBG("Reading IOHS PLL mux attributes");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CLOCK_MUX_IOHS_LCPLL_INPUT, i_target_chip, l_attr_clock_mux_iohs_lcpll_input),
"Error from FAPI_ATTR_GET (ATTR_CLOCK_MUX_IOHS_LCPLL_INPUT)");
for (const auto& l_iohs_target : i_target_chip.getChildren<fapi2::TARGET_TYPE_IOHS>(fapi2::TARGET_STATE_FUNCTIONAL))
{
fapi2::ATTR_CHIP_UNIT_POS_Type l_attr_chip_unit_pos;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_iohs_target, l_attr_chip_unit_pos),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
FAPI_TRY(l_scratch5_reg.insertFromRight(l_attr_clock_mux_iohs_lcpll_input[l_attr_chip_unit_pos],
ATTR_CLOCK_MUX_IOHS_LCPLL_INPUT_STARTBIT +
(ATTR_CLOCK_MUX_IOHS_LCPLL_INPUT_LENGTH * l_attr_chip_unit_pos),
ATTR_CLOCK_MUX_IOHS_LCPLL_INPUT_LENGTH));
}
FAPI_DBG("Reading PCI PLL mux attributes");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CLOCK_MUX_PCI_LCPLL_INPUT, i_target_chip, l_attr_clock_mux_pci_lcpll_input),
"Error from FAPI_ATTR_GET (ATTR_CLOCK_MUX_PCI_LCPLL_INPUT)");
for (const auto& l_pci_target : i_target_chip.getChildren<fapi2::TARGET_TYPE_PEC>(fapi2::TARGET_STATE_FUNCTIONAL))
{
fapi2::ATTR_CHIP_UNIT_POS_Type l_attr_chip_unit_pos;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_pci_target, l_attr_chip_unit_pos),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
FAPI_TRY(l_scratch5_reg.insertFromRight(l_attr_clock_mux_pci_lcpll_input[l_attr_chip_unit_pos],
ATTR_CLOCK_MUX_PCI_LCPLL_INPUT_STARTBIT +
(ATTR_CLOCK_MUX_PCI_LCPLL_INPUT_LENGTH * l_attr_chip_unit_pos),
ATTR_CLOCK_MUX_PCI_LCPLL_INPUT_LENGTH));
}
FAPI_DBG("Setting up value of Scratch_reg5");
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_5_FSI,
l_scratch5_reg),
"Error writing Scratch 5 mailbox register");
l_scratch8_reg.setBit<SCRATCH5_REG_VALID_BIT>();
}
// set_scratch6_reg -- Master/slave, node/chip selection, PLL bypass controls
{
fapi2::buffer<uint32_t> l_scratch6_reg = 0;
fapi2::ATTR_CP_PLLTODFLT_BYPASS_Type l_attr_cp_plltodflt_bypass;
fapi2::ATTR_CP_PLLNESTFLT_BYPASS_Type l_attr_cp_pllnestflt_bypass;
fapi2::ATTR_CP_PLLIOFLT_BYPASS_Type l_attr_cp_pllioflt_bypass;
fapi2::ATTR_CP_PLLIOSSFLT_BYPASS_Type l_attr_cp_plliossflt_bypass;
fapi2::ATTR_NEST_DPLL_BYPASS_Type l_attr_nest_dpll_bypass;
fapi2::ATTR_PAU_DPLL_BYPASS_Type l_attr_pau_dpll_bypass;
fapi2::ATTR_IO_TANK_PLL_BYPASS_Type l_attr_io_tank_pll_bypass;
fapi2::ATTR_PROC_FABRIC_EFF_TOPOLOGY_ID_Type l_attr_proc_fabric_eff_topology_id;
fapi2::ATTR_PROC_FABRIC_TOPOLOGY_MODE_Type l_attr_proc_fabric_topology_mode;
fapi2::ATTR_PROC_FABRIC_BROADCAST_MODE_Type l_attr_proc_fabric_broadcast_mode;
fapi2::ATTR_PROC_SBE_MASTER_CHIP_Type l_attr_proc_sbe_master_chip;
fapi2::ATTR_PROC_FABRIC_TOPOLOGY_ID_Type l_attr_proc_fabric_topology_id;
FAPI_DBG("Reading filter PLL bypass attributes");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CP_PLLTODFLT_BYPASS, i_target_chip, l_attr_cp_plltodflt_bypass),
"Error from FAPI_ATTR_GET (ATTR_CP_PLLTODFLT_BYPASS)");
l_scratch6_reg.writeBit<ATTR_CP_PLLTODFLT_BYPASS_BIT>(l_attr_cp_plltodflt_bypass ==
fapi2::ENUM_ATTR_CP_PLLTODFLT_BYPASS_BYPASS);
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CP_PLLNESTFLT_BYPASS, i_target_chip, l_attr_cp_pllnestflt_bypass),
"Error from FAPI_ATTR_GET (ATTR_CP_PLLNESTFLT_BYPASS)");
l_scratch6_reg.writeBit<ATTR_CP_PLLNESTFLT_BYPASS_BIT>(l_attr_cp_pllnestflt_bypass ==
fapi2::ENUM_ATTR_CP_PLLNESTFLT_BYPASS_BYPASS);
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CP_PLLIOFLT_BYPASS, i_target_chip, l_attr_cp_pllioflt_bypass),
"Error from FAPI_ATTR_GET (ATTR_CP_PLLIOFLT_BYPASS)");
l_scratch6_reg.writeBit<ATTR_CP_PLLIOFLT_BYPASS_BIT>(l_attr_cp_pllioflt_bypass ==
fapi2::ENUM_ATTR_CP_PLLIOFLT_BYPASS_BYPASS);
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CP_PLLIOSSFLT_BYPASS, i_target_chip, l_attr_cp_plliossflt_bypass),
"Error from FAPI_ATTR_GET (ATTR_CP_PLLIOSSFLT_BYPASS)");
l_scratch6_reg.writeBit<ATTR_CP_PLLIOSSFLT_BYPASS_BIT>(l_attr_cp_plliossflt_bypass ==
fapi2::ENUM_ATTR_CP_PLLIOSSFLT_BYPASS_BYPASS);
FAPI_DBG("Reading DPLL bypass attributes");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_NEST_DPLL_BYPASS, i_target_chip, l_attr_nest_dpll_bypass),
"Error from FAPI_ATTR_GET (ATTR_NEST_DPLL_BYPASS");
l_scratch6_reg.writeBit<ATTR_NEST_DPLL_BYPASS_BIT>(l_attr_nest_dpll_bypass == fapi2::ENUM_ATTR_NEST_DPLL_BYPASS_BYPASS);
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PAU_DPLL_BYPASS, i_target_chip, l_attr_pau_dpll_bypass),
"Error from FAPI_ATTR_GET (ATTR_PAU_DPLL_BYPASS");
l_scratch6_reg.writeBit<ATTR_PAU_DPLL_BYPASS_BIT>(l_attr_pau_dpll_bypass == fapi2::ENUM_ATTR_PAU_DPLL_BYPASS_BYPASS);
FAPI_DBG("Reading tank PLL bypass attributes");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IO_TANK_PLL_BYPASS, i_target_chip, l_attr_io_tank_pll_bypass));
l_scratch6_reg.writeBit<ATTR_IO_TANK_PLL_BYPASS_BIT>(l_attr_io_tank_pll_bypass ==
fapi2::ENUM_ATTR_IO_TANK_PLL_BYPASS_BYPASS);
FAPI_DBG("Reading master SBE attribute");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_SBE_MASTER_CHIP, i_target_chip, l_attr_proc_sbe_master_chip),
"Error from FAPI_ATTR_GET (ATTR_PROC_SBE_MASTER_CHIP)");
l_scratch6_reg.writeBit<ATTR_PROC_SBE_MASTER_CHIP_BIT>(l_attr_proc_sbe_master_chip ==
fapi2::ENUM_ATTR_PROC_SBE_MASTER_CHIP_TRUE);
FAPI_DBG("Reading fabric topology/broadcast attributes");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_EFF_TOPOLOGY_ID, i_target_chip, l_attr_proc_fabric_eff_topology_id),
"Error from FAPI_ATTR_GET (ATTR_PROC_FABRIC_EFF_TOPOLOGY_ID)");
l_scratch6_reg.insertFromRight<ATTR_PROC_FABRIC_EFF_TOPOLOGY_ID_STARTBIT, ATTR_PROC_FABRIC_EFF_TOPOLOGY_ID_LENGTH>
(l_attr_proc_fabric_eff_topology_id);
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_TOPOLOGY_MODE, FAPI_SYSTEM, l_attr_proc_fabric_topology_mode),
"Error from FAPI_ATTR_GET (ATTR_PROC_FABRIC_TOPOLOGY_MODE");
if (l_attr_proc_fabric_topology_mode == fapi2::ENUM_ATTR_PROC_FABRIC_TOPOLOGY_MODE_MODE1)
{
l_scratch6_reg.setBit<ATTR_PROC_FABRIC_TOPOLOGY_MODE_BIT>();
}
else
{
l_scratch6_reg.clearBit<ATTR_PROC_FABRIC_TOPOLOGY_MODE_BIT>();
}
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_BROADCAST_MODE, FAPI_SYSTEM, l_attr_proc_fabric_broadcast_mode),
"Error from FAPI_ATTR_GET (ATTR_PROC_FABRIC_BROADCAST_MODE");
l_scratch6_reg.insertFromRight<ATTR_PROC_FABRIC_BROADCAST_MODE_STARTBIT, ATTR_PROC_FABRIC_BROADCAST_MODE_LENGTH>
(l_attr_proc_fabric_broadcast_mode);
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_TOPOLOGY_ID, i_target_chip, l_attr_proc_fabric_topology_id),
"Error from FAPI_ATTR_GET (ATTR_PROC_FABRIC_TOPOLOGY_ID");
l_scratch6_reg.insertFromRight< ATTR_PROC_FABRIC_TOPOLOGY_ID_STARTBIT, ATTR_PROC_FABRIC_TOPOLOGY_ID_LENGTH>
(l_attr_proc_fabric_topology_id);
FAPI_DBG("Setting up value of Scratch_reg6");
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_6_FSI,
l_scratch6_reg),
"Error writing Scratch 6 mailbox register");
l_scratch8_reg.setBit<SCRATCH6_REG_VALID_BIT>();
}
// set_scratch7_reg - IOHS region gard / chip contained active cores vector
{
fapi2::buffer<uint32_t> l_scratch7_reg = 0;
fapi2::ATTR_CONTAINED_IPL_TYPE_Type l_attr_contained_ipl_type;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CONTAINED_IPL_TYPE, FAPI_SYSTEM, l_attr_contained_ipl_type),
"Error from FAPI_ATTR_GET (ATTR_CONTAINED_IPL_TYPE)");
if (l_attr_contained_ipl_type == fapi2::ENUM_ATTR_CONTAINED_IPL_TYPE_NONE)
{
uint32_t l_ndl_gard_vector;
FAPI_DBG("Setting up IOHS NDL gard records");
FAPI_TRY(p10_sbe_scratch_calc_iohs_region_gard_vectors(i_target_chip,
l_ndl_gard_vector),
"Error from p10_sbe_scratch_calc_iohs_region_gard_vectors");
l_scratch7_reg.insert<NDL_GARD_STARTBIT, NDL_GARD_LENGTH, GARD_VECTOR_STARTBIT>(l_ndl_gard_vector);
}
else if (l_attr_contained_ipl_type == fapi2::ENUM_ATTR_CONTAINED_IPL_TYPE_CHIP)
{
fapi2::ATTR_CHIP_CONTAINED_ACTIVE_CORES_VEC_Type l_attr_chip_contained_active_cores_vec;
FAPI_DBG("Setting up chip contained active cores vector");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_CONTAINED_ACTIVE_CORES_VEC, i_target_chip,
l_attr_chip_contained_active_cores_vec),
"Error from FAPI_ATTR_GET (ATTR_CHIP_CONTAINED_ACTIVE_CORES_VEC)");
l_scratch7_reg.insertFromRight<ATTR_CHIP_CONTAINED_ACTIVE_CORES_VEC_STARTBIT, ATTR_CHIP_CONTAINED_ACTIVE_CORES_VEC_LENGTH>
(l_attr_chip_contained_active_cores_vec);
}
FAPI_DBG("Setting up value of Scratch_reg7");
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_7_FSI,
l_scratch7_reg),
"Error writing Scratch 7 mailbox register");
l_scratch8_reg.setBit<SCRATCH7_REG_VALID_BIT>();
}
// set_scratch9_reg - PAU/MC frequency
{
fapi2::buffer<uint32_t> l_scratch9_reg = 0;
fapi2::ATTR_FREQ_PAU_MHZ_Type l_attr_freq_pau_mhz;
fapi2::ATTR_MC_PLL_BUCKET_Type l_attr_mc_pll_bucket = { 0 };
fapi2::ATTR_NDL_MESHCTRL_SETUP_Type l_attr_ndl_meshctrl_setup;
FAPI_DBG("Reading ATTR_FREQ_PAU_MHZ");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_PAU_MHZ, FAPI_SYSTEM, l_attr_freq_pau_mhz),
"Error from FAPI_ATTR_GET (ATTR_FREQ_PAU_MHZ");
l_scratch9_reg.insertFromRight<ATTR_FREQ_PAU_MHZ_STARTBIT, ATTR_FREQ_PAU_MHZ_LENGTH>(l_attr_freq_pau_mhz);
// calculate bucket index based on desired frequency
FAPI_DBG("Setting up MC PLL bucket values");
FAPI_TRY(p10_sbe_scratch_regs_get_mc_pll_bucket(i_target_chip, l_attr_mc_pll_bucket),
"Error from p10_sbe_scratch_regs_get_mc_pll_bucket");
FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_MC_PLL_BUCKET, i_target_chip, l_attr_mc_pll_bucket),
"Error from FAPI_ATTR_SET (ATTR_MC_PLL_BUCKET)");
for (const auto& l_mc_target : i_target_chip.getChildren<fapi2::TARGET_TYPE_MC>(fapi2::TARGET_STATE_FUNCTIONAL))
{
fapi2::ATTR_CHIP_UNIT_POS_Type l_attr_chip_unit_pos;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_mc_target, l_attr_chip_unit_pos),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
FAPI_TRY(l_scratch9_reg.insertFromRight(l_attr_mc_pll_bucket[l_attr_chip_unit_pos],
ATTR_MC_PLL_BUCKET_STARTBIT +
(ATTR_MC_PLL_BUCKET_LENGTH * l_attr_chip_unit_pos),
ATTR_MC_PLL_BUCKET_LENGTH));
}
FAPI_DBG("Reading ATTR_NDL_MESHCTRL_SETUP");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_NDL_MESHCTRL_SETUP, i_target_chip, l_attr_ndl_meshctrl_setup),
"Error from FAPI_ATTR_GET (ATTR_NDL_MESHCTRL_SETUP)");
l_scratch9_reg.insertFromRight<ATTR_NDL_MESHCTRL_SETUP_STARTBIT, ATTR_NDL_MESHCTRL_SETUP_LENGTH>
(l_attr_ndl_meshctrl_setup);
FAPI_DBG("Setting up value of Scratch_reg9");
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_9_FSI,
l_scratch9_reg),
"Error writing Scratch 9 mailbox register");
l_scratch8_reg.setBit<SCRATCH9_REG_VALID_BIT>();
}
// set_scratch10_reg - IOHS frequency / chip contained backing caches vector
{
fapi2::buffer<uint32_t> l_scratch10_reg = 0;
fapi2::ATTR_CONTAINED_IPL_TYPE_Type l_attr_contained_ipl_type;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CONTAINED_IPL_TYPE, FAPI_SYSTEM, l_attr_contained_ipl_type),
"Error from FAPI_ATTR_GET (ATTR_CONTAINED_IPL_TYPE)");
if (l_attr_contained_ipl_type == fapi2::ENUM_ATTR_CONTAINED_IPL_TYPE_NONE)
{
fapi2::ATTR_IOHS_PLL_BUCKET_Type l_attr_iohs_pll_bucket = { 0 };
// calculate bucket index based on desired frequency
FAPI_DBG("Setting up IOHS PLL bucket values");
FAPI_TRY(p10_sbe_scratch_regs_get_iohs_pll_bucket(i_target_chip, l_attr_iohs_pll_bucket),
"Error from p10_sbe_scratch_regs_get_iohs_pll_bucket");
FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_IOHS_PLL_BUCKET, i_target_chip, l_attr_iohs_pll_bucket),
"Error from FAPI_ATTR_SET (ATTR_IOHS_PLL_BUCKET)");
for (const auto& l_iohs_target : i_target_chip.getChildren<fapi2::TARGET_TYPE_IOHS>(fapi2::TARGET_STATE_FUNCTIONAL))
{
fapi2::ATTR_CHIP_UNIT_POS_Type l_attr_chip_unit_pos;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_iohs_target, l_attr_chip_unit_pos),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
FAPI_TRY(l_scratch10_reg.insertFromRight(l_attr_iohs_pll_bucket[l_attr_chip_unit_pos],
ATTR_IOHS_PLL_BUCKET_STARTBIT +
(ATTR_IOHS_PLL_BUCKET_LENGTH * l_attr_chip_unit_pos),
ATTR_IOHS_PLL_BUCKET_LENGTH));
}
}
else if (l_attr_contained_ipl_type == fapi2::ENUM_ATTR_CONTAINED_IPL_TYPE_CHIP)
{
fapi2::ATTR_CHIP_CONTAINED_BACKING_CACHES_VEC_Type l_attr_chip_contained_backing_caches_vec;
FAPI_DBG("Setting up chip contained backing caches vector");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_CONTAINED_BACKING_CACHES_VEC, i_target_chip,
l_attr_chip_contained_backing_caches_vec),
"Error from FAPI_ATTR_GET (ATTR_CHIP_CONTAINED_BACKING_CACHES_VEC)");
l_scratch10_reg.insertFromRight<ATTR_CHIP_CONTAINED_BACKING_CACHES_VEC_STARTBIT, ATTR_CHIP_CONTAINED_BACKING_CACHES_VEC_LENGTH>
(l_attr_chip_contained_backing_caches_vec);
}
FAPI_DBG("Setting up value of Scratch_reg10");
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_10_FSI,
l_scratch10_reg),
"Error writing Scratch 10 mailbox register");
l_scratch8_reg.setBit<SCRATCH10_REG_VALID_BIT>();
}
FAPI_DBG("Setting up value of Scratch_reg8 (valid)");
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_8_FSI,
l_scratch8_reg),
"Error writing Scratch 8 mailbox register");
FAPI_INF("p10_setup_sbe_config: Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/customize/p9_xip_customize.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
#include <p9_xip_customize.H>
#include <p9_xip_image.h>
#include <p9_ring_identification.H>
#include <p9_get_mvpd_ring.H>
#include <p9_tor.H>
#include <p9_scan_compression.H>
#include <p9_infrastruct_help.H>
#include <p9_ringId.H>
using namespace fapi2;
#define MBOX_ATTR_WRITE(ID,TARGET,IMAGE) \
{ \
fapi2::ID##_Type ID##_attrVal; \
FAPI_TRY(FAPI_ATTR_GET(fapi2::ID,TARGET,ID##_attrVal),\
"MBOX_ATTR_WRITE: Error getting %s", #ID); \
FAPI_TRY(p9_xip_set_scalar(IMAGE,#ID,ID##_attrVal),\
"MBOX_ATTR_WRITE: Error writing attr %s to seeprom image",\
#ID); \
}
fapi2::ReturnCode writeMboxRegs (
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_proc_target,
void* i_image)
{
FAPI_DBG ("writeMboxRegs Entering...");
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
MBOX_ATTR_WRITE (ATTR_I2C_BUS_DIV_REF, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_EQ_GARD, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_EC_GARD, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_NEST_PLL_BUCKET, FAPI_SYSTEM, i_image);
MBOX_ATTR_WRITE (ATTR_BOOT_FREQ_MULT, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_CLOCK_PLL_MUX, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_DPLL_BYPASS, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_SS_FILTER_BYPASS, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_CP_FILTER_BYPASS, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_IO_FILTER_BYPASS, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_NEST_MEM_X_O_PCI_BYPASS, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_SYSTEM_IPL_PHASE, FAPI_SYSTEM, i_image);
MBOX_ATTR_WRITE (ATTR_SYS_FORCE_ALL_CORES, FAPI_SYSTEM, i_image);
MBOX_ATTR_WRITE (ATTR_RISK_LEVEL, FAPI_SYSTEM, i_image);
MBOX_ATTR_WRITE (ATTR_DISABLE_HBBL_VECTORS, FAPI_SYSTEM, i_image);
MBOX_ATTR_WRITE (ATTR_MC_SYNC_MODE, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_PROC_SBE_MASTER_CHIP, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_PROC_FABRIC_GROUP_ID, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_PROC_FABRIC_CHIP_ID, i_proc_target, i_image);
fapi_try_exit:
FAPI_DBG("writeMboxRegs Exiting...");
return fapi2::current_err;
}
fapi2::ReturnCode writePG(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_proc_target,
void* i_image)
{
const uint8_t IMG_PG_ENTRIES = 64;
const uint16_t DEFAULT_PG_VAL = 0xffff;
FAPI_DBG ("writePG Entering...");
// Make all chiplets "not good".
for (auto l_pg_idx = 0; l_pg_idx < IMG_PG_ENTRIES; l_pg_idx++)
{
FAPI_TRY( p9_xip_set_element(i_image, "ATTR_PG", l_pg_idx, DEFAULT_PG_VAL),
"Error (1) from p9_xip_set_element (idx %d)", l_pg_idx );
}
for (auto l_perv_tgt : i_proc_target.getChildren<fapi2::TARGET_TYPE_PERV>())
{
uint8_t l_unit_id = 0;
uint16_t l_pg_data = 0;
uint8_t l_pg_idx = 0;
FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_perv_tgt, l_unit_id),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)" );
FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_PG, l_perv_tgt, l_pg_data),
"Error from FAPI_ATTR_GET (ATTR_PG)" );
l_pg_idx = l_unit_id;
FAPI_ASSERT( l_pg_idx < IMG_PG_ENTRIES,
fapi2::XIPC_BAD_PG_XLATE().
set_CHIP_TARGET(i_proc_target).
set_CHIP_UNIT_POS(l_unit_id).
set_PG_INDEX(l_pg_idx),
"Code bug: Invalid translation from PERV chip unit position to image PG index" );
// Update the image
FAPI_TRY( p9_xip_set_element(i_image, "ATTR_PG", l_pg_idx, l_pg_data),
"Error (2) from p9_xip_set_element (idx %d)", l_pg_idx );
FAPI_DBG("Write value of pg_data[%d] = %08X", l_pg_idx, l_pg_data);
}
for (auto l_pg_idx = 0; l_pg_idx < IMG_PG_ENTRIES; l_pg_idx++)
{
uint64_t l_val;
FAPI_TRY( p9_xip_get_element(i_image, "ATTR_PG", l_pg_idx, &l_val),
"Error from p9_xip_get_element (idx %d)", l_pg_idx );
FAPI_DBG("Read value of pg_data[%d] = %08X", l_pg_idx, l_val);
}
fapi_try_exit:
FAPI_DBG ("writePG Exiting...");
return fapi2::current_err;
}
// Function: _fetch_and_insert_vpd_rings()
//
// Parameter list:
// const fapi::Target &i_target: Processor chip target.
// void* i_ringSection: Ptr to ring section.
// uint32_t& io_ringSectionSize: Running ring section size
// uint32_t i_maxRingSectionSize: Max ring section size
// uint8_t i_sysPhase: ={HB_SBE, RT_CME, RT_SGPE}
// void* i_vpdRing: VPD ring buffer.
// uint32_t i_vpdRingSize: Size of VPD ring buffer.
// void* i_ringBuf2: Ring work buffer.
// uint32_t i_ringBufSize2: Size of ring work buffer.
// const RingIdList i_ring: The ring ID list (#G or #R list)
// uint32_t& io_bootCoreMask: Desired (in) and actual (out) boot cores.
//
fapi2::ReturnCode _fetch_and_insert_vpd_rings(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_proc_target,
void* i_ringSection,
uint32_t& io_ringSectionSize,
uint32_t i_maxRingSectionSize,
uint8_t i_sysPhase,
void* i_vpdRing,
uint32_t i_vpdRingSize,
void* i_ringBuf2,
uint32_t i_ringBufSize2,
const RingIdList i_ring,
uint32_t& io_bootCoreMask )
{
ReturnCode l_fapiRc = fapi2::FAPI2_RC_SUCCESS;
int l_rc = 0;
uint8_t l_chipletId;
uint8_t l_ringsPerChipletId = 0;
uint8_t l_instanceIdMax;
uint8_t l_evenOdd;
uint64_t l_evenOddMaskStart;
uint64_t l_evenOddMask; // 0:even, 1:odd
uint8_t bSkipRing = 0;
FAPI_DBG("Entering _fetch_and_insert_vpd_rings");
// Filter out GPTR requests. Not supported in DD1. Coming in through initfiles instead.
if (i_ring.vpdRingClass == VPD_RING_CLASS_GPTR)
{
FAPI_INF("Skipping extraction of GPTR ring...");
fapi2::current_err = l_fapiRc;
goto fapi_try_exit;
}
// For EX rings, there's two rings listed in the Mvpd per [EQ] chipletId
// listed in ring_identification.C: One for each of the two EX, even and odd.
// Each of these two rings have the same [EQ] chipletId encoded in their
// iv_chipletId (current RS4 header) or iv_scanAddress (next gen RS4 header).
// They are distinguished by their even-odd bits in iv_scanSelect as follows:
if (i_ring.vpdRingClass == VPD_RING_CLASS_EX_INS)
{
l_ringsPerChipletId = 2;
switch (i_ring.ringId)
{
case ex_l3_refr_time:
case ex_l3_refr_repr:
l_evenOddMaskStart = ((uint64_t)0x00080000) << 32;
break;
case ex_l2_repr:
l_evenOddMaskStart = ((uint64_t)0x00800000) << 32;
break;
case ex_l3_repr:
l_evenOddMaskStart = ((uint64_t)0x02000000) << 32;
break;
default:
FAPI_ASSERT( false,
fapi2::XIPC_MVPD_RING_ID_MESS().
set_CHIP_TARGET(i_proc_target).
set_RING_ID(i_ring.ringId),
"Code bug: Wrong assumption about supported ringIds in this context. "
"ringId=%d(=0x%x)(=ringId.ringName) is not allowed here. ",
i_ring.ringId, i_ring.ringId, i_ring.ringName );
break;
}
}
else
{
l_ringsPerChipletId = 1;
l_evenOddMaskStart = 0;
}
// We use ring.instanceIdMax column to govern max value of instanceIdMax (i.e., the
// max chipletId). But unlike in P8, in P9 we will not search for chipletId=0xff in P9
// MVPD. It is no longer used in the MVPD. We merely keep the multicast Id, 0xff, in
// the ring list for now, just in case it is needed later on.
if (i_ring.instanceIdMax == 0xff)
{
l_instanceIdMax = i_ring.instanceIdMin;
}
else
{
l_instanceIdMax = i_ring.instanceIdMax;
}
for (l_chipletId = i_ring.instanceIdMin; l_chipletId <= l_instanceIdMax; l_chipletId++)
{
for (l_evenOdd = 0; l_evenOdd < l_ringsPerChipletId; l_evenOdd++)
{
l_evenOddMask = l_evenOddMaskStart >> l_evenOdd;
FAPI_INF("_fetch_and_insert_vpd_rings: (ringId,chipletId) = (0x%02X,0x%02x)",
i_ring.ringId, l_chipletId);
auto l_vpdRingSize = i_vpdRingSize;
MvpdKeyword l_mvpdKeyword;
switch (i_ring.vpdKeyword)
{
case VPD_KEYWORD_PDG: // #G Time rings
l_mvpdKeyword = fapi2::MVPD_KEYWORD_PDG;
break;
case VPD_KEYWORD_PDR: // #R Repair rings
l_mvpdKeyword = fapi2::MVPD_KEYWORD_PDR;
break;
default:
FAPI_ASSERT( false,
fapi2::XIPC_INVALID_VPD_KEYWORD().
set_CHIP_TARGET(i_proc_target).
set_VPD_KEYWORD(i_ring.vpdKeyword),
"Code bug: Unsupported value of vpdKeyword (=%d)",
i_ring.vpdKeyword );
break;
}
/////////////////////////////////////////////////////////////////////
// Fetch rings from the MVPD:
/////////////////////////////////////////////////////////////////////
// If an EC ring is an instance ring, then check if EC chipletId is represented in bootCoreMask,
// and only fetch if it is.
// If an EX/EQ ring is an instance ring, then check if the associated EC chipletId range in
// in bootCoreMask is represented by at least one EC chipletId, and fetch it if it is.
// Otherwise the ring is a common ring which we always must fetch.
bSkipRing = 0;
if ( i_ring.vpdRingClass == VPD_RING_CLASS_EQ_INS &&
(i_sysPhase == SYSPHASE_HB_SBE || i_sysPhase == SYSPHASE_RT_SGPE) )
{
// Fetch EQ instance ring
// - Fetch for SBE and SGPE only.
if ( ((0x0000000F << ((NUM_OF_QUADS - 1)*CORES_PER_QUAD)) >> ((l_chipletId - i_ring.instanceIdMin)*CORES_PER_QUAD)) &
io_bootCoreMask )
{
l_fapiRc = getMvpdRing( MVPD_RECORD_CP00,
l_mvpdKeyword,
i_proc_target,
l_chipletId,
l_evenOddMask,
i_ring.ringId,
(uint8_t*)i_vpdRing,
l_vpdRingSize );
}
else
{
bSkipRing = 1;
}
}
else if ( i_ring.vpdRingClass == VPD_RING_CLASS_EX_INS &&
(i_sysPhase == SYSPHASE_HB_SBE || i_sysPhase == SYSPHASE_RT_SGPE) )
{
// Fetch EX instance ring
// - Fetch for SBE and SGPE only.
if ( ((0x0000000F << ((NUM_OF_QUADS - 1)*CORES_PER_QUAD)) >> ((l_chipletId - i_ring.instanceIdMin)*CORES_PER_QUAD)) &
io_bootCoreMask )
{
l_fapiRc = getMvpdRing( MVPD_RECORD_CP00,
l_mvpdKeyword,
i_proc_target,
l_chipletId,
l_evenOddMask,
i_ring.ringId,
(uint8_t*)i_vpdRing,
l_vpdRingSize );
}
else
{
bSkipRing = 1;
}
}
else if ( i_ring.vpdRingClass == VPD_RING_CLASS_EC_INS &&
(i_sysPhase == SYSPHASE_HB_SBE || i_sysPhase == SYSPHASE_RT_CME) )
{
// Fetch EC instance ring
// - Fetch for SBE and CME only.
if ( ((0x00000001 << (NUM_OF_CORES - 1)) >> (l_chipletId - i_ring.instanceIdMin)) & io_bootCoreMask )
{
l_fapiRc = getMvpdRing( MVPD_RECORD_CP00,
l_mvpdKeyword,
i_proc_target,
l_chipletId,
l_evenOddMask,
i_ring.ringId,
(uint8_t*)i_vpdRing,
l_vpdRingSize );
}
else
{
bSkipRing = 1;
}
}
else if ( i_sysPhase == SYSPHASE_HB_SBE ||
(i_sysPhase == SYSPHASE_RT_CME && i_ring.vpdRingClass == VPD_RING_CLASS_EC) ||
(i_sysPhase == SYSPHASE_RT_SGPE && (i_ring.vpdRingClass == VPD_RING_CLASS_EX ||
i_ring.vpdRingClass == VPD_RING_CLASS_EQ)) )
{
// Fetch common ring
// - Fetch all VPD rings for SBE.
// - Fetch only EC VPD rings for CME.
// - Fetch only EX+EQ VPD rings for SGPE.
l_fapiRc = getMvpdRing( MVPD_RECORD_CP00,
l_mvpdKeyword,
i_proc_target,
l_chipletId,
l_evenOddMask,
i_ring.ringId,
(uint8_t*)i_vpdRing,
l_vpdRingSize );
}
else
{
bSkipRing = 1;
}
///////////////////////////////////////////////////////////////////////
//Append VPD ring to the ring section
///////////////////////////////////////////////////////////////////////
if (bSkipRing)
{
continue;
}
else if (l_fapiRc == fapi2::FAPI2_RC_SUCCESS)
{
auto l_vpdChipletId = ((CompressedScanData*)i_vpdRing)->iv_chipletId;
// Even though success, checking that chipletId didn't somehow get
// messed up (code bug).
//@TODO: Modify this when chipletId becomes part of iv_scanAddress
// as part of RS4 shrinkage (RTC158101).
FAPI_ASSERT( l_vpdChipletId == l_chipletId,
fapi2::XIPC_MVPD_CHIPLET_ID_MESS().
set_CHIP_TARGET(i_proc_target).
set_CHIPLET_ID(l_chipletId).
set_MVPD_CHIPLET_ID(l_vpdChipletId).
set_RING_ID(i_ring.ringId),
"_fetch_and_insert_vpd_rings: Code bug: VPD ring's chipletId"
" in scan container (=0x%X) doesn't match the requested"
" chipletId (=0x%X)",
l_vpdChipletId, l_chipletId );
// Even though success, checking for accidental buffer overflow (code bug).
FAPI_ASSERT( l_vpdRingSize <= i_vpdRingSize,
fapi2::XIPC_MVPD_RING_SIZE_MESS().
set_CHIP_TARGET(i_proc_target).
set_RING_ID(i_ring.ringId).
set_CHIPLET_ID(l_chipletId).
set_RING_BUFFER_SIZE(i_vpdRingSize).
set_MVPD_RING_SIZE(l_vpdRingSize),
"_fetch_and_insert_vpd_rings: Code bug: VPD ring size (=0x%X) exceeds"
" allowed ring buffer size (=0x%X)",
l_vpdRingSize, i_vpdRingSize );
//@TODO: Remove following line asap. Temporary fix until Sgro starts using
// latest p9_scan_compression.H.
// Also fix p9_mvpd_ring_funcs.C to look for entire RS4_MAGIC string.
// Actually, do all the above in connection with RS4 header
// shrinkage (RTC158101 and RTC159801).
((CompressedScanData*)i_vpdRing)->iv_magic = htobe32(RS4_MAGIC);
// Check if ring is a flush ring, i.e. if it is redundant, meaning that it will
// result in no change.
int redundant = 0;
l_rc = rs4_redundant((CompressedScanData*)i_vpdRing, &redundant);
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_RS4_REDUNDANT_ERROR().
set_CHIP_TARGET(i_proc_target).
set_RING_ID(i_ring.ringId).
set_CHIPLET_ID(l_chipletId),
"rs4_redundant: Failed w/rc=%i for "
"ringId=0x%02X, chipletId=0x%02X ",
l_rc, i_ring.ringId, l_chipletId );
if (redundant)
{
FAPI_DBG("Skipping redundant VPD ring: ringId=0x%02X, chipletId=0x%02X ", i_ring.ringId, l_chipletId);
fapi2::current_err = fapi2::FAPI2_RC_SUCCESS;
// Note that we do not want to exit here. There could be content in the next
// instance. We're just not appending the current redundant one.
}
else
{
//@TODO: Temporary fix to convert VPD RS4 container format to
// to RingLayout format. Remove/replace in connection
// with RS4 header shrinkage (RTC158101)
uint32_t i;
for (i = 0; i < l_vpdRingSize; i++)
{
*(((uint8_t*)i_vpdRing) + l_vpdRingSize - 1 + sizeof(P9_TOR::RingLayout_t) - i) =
*(((uint8_t*)i_vpdRing) + l_vpdRingSize - 1 - i);
}
uint32_t l_sizeOfThisRing = l_vpdRingSize + sizeof(P9_TOR::RingLayout_t);
((P9_TOR::RingLayout_t*)i_vpdRing)->sizeOfThis = htobe32(l_sizeOfThisRing);
((P9_TOR::RingLayout_t*)i_vpdRing)->sizeOfCmsk = 0;
((P9_TOR::RingLayout_t*)i_vpdRing)->sizeOfMeta = 0;
// Checking for potential image overflow BEFORE appending the ring.
if ( (io_ringSectionSize + l_sizeOfThisRing) > i_maxRingSectionSize )
{
//@TODO: We can't update bootCoreMask until RTC158106. So for now
// we're simply returning the requested bootCoreMask. Thus,
// should there be an overflow condition before RTC158106
// gets implemented (i.e., inserting VPD rings in EC order),
// we would manually have to scale back on the requested
// cores in the initialled supplied io_bootCoreMask arg to
// xip_customize.
FAPI_ASSERT( false,
fapi2::XIPC_IMAGE_WOULD_OVERFLOW().
set_CHIP_TARGET(i_proc_target).
set_CURRENT_RING_SECTION_SIZE(io_ringSectionSize).
set_SIZE_OF_THIS_RING(l_sizeOfThisRing).
set_MAX_RING_SECTION_SIZE(i_maxRingSectionSize).
set_RING_ID(i_ring.ringId).
set_CHIPLET_ID(l_chipletId).
set_CURRENT_BOOT_CORE_MASK(io_bootCoreMask),
"Ran out of image buffer space trying to append a ring"
" to the .rings section" );
}
//------------------------------------------
// Now, append the ring to the ring section
//------------------------------------------
// Calculate the chiplet TOR index
uint8_t l_chipletTorId = l_chipletId +
(l_chipletId - i_ring.instanceIdMin ) * (l_ringsPerChipletId - 1) +
l_evenOdd;
switch (i_sysPhase)
{
case SYSPHASE_HB_SBE:
l_rc = tor_append_ring(
i_ringSection,
io_ringSectionSize, // In: Exact size. Out: Updated size.
i_ringBuf2,
i_ringBufSize2, // Max size.
(RingID)i_ring.ringId,
P9_TOR::SBE, // We're working on the SBE image
P9_TOR::ALLRING, // No-care
BASE, // All VPD rings are Base ringVariant
l_chipletTorId, // Chiplet instance TOR Index
i_vpdRing ); // The VPD RS4 ring container
if (l_rc == TOR_APPEND_RING_DONE)
{
FAPI_INF("Successfully added VPD ring: (ringId,evenOdd,chipletId)=(0x%02X,0x%X,0x%02X)",
i_ring.ringId, l_evenOdd, l_chipletId);
}
else
{
FAPI_ASSERT( false,
fapi2::XIPC_TOR_APPEND_RING_FAILED().
set_CHIP_TARGET(i_proc_target).
set_TOR_RC(l_rc),
"tor_append_ring() failed w/l_rc=%d",
l_rc );
}
break;
case SYSPHASE_RT_CME:
l_rc = tor_append_ring(
i_ringSection,
io_ringSectionSize, // In: Exact size. Out: Updated size.
i_ringBuf2,
i_ringBufSize2, // Max size.
(RingID)i_ring.ringId,
P9_TOR::CME, // We're working on the SBE image
P9_TOR::ALLRING, // No-care
BASE, // All VPD rings are Base ringVariant
l_chipletTorId, // Chiplet instance ID
i_vpdRing ); // The VPD RS4 ring container
if (l_rc == TOR_APPEND_RING_DONE)
{
FAPI_INF("Successfully added VPD ring: (ringId,evenOdd,chipletId)=(0x%02X,0x%X,0x%02X)",
i_ring.ringId, l_evenOdd, l_chipletId);
}
else
{
FAPI_ASSERT( false,
fapi2::XIPC_TOR_APPEND_RING_FAILED().
set_CHIP_TARGET(i_proc_target).
set_TOR_RC(l_rc),
"tor_append_ring() failed w/l_rc=%d",
l_rc );
}
FAPI_DBG("(After tor_append) io_ringSectionSize = %d", io_ringSectionSize);
break;
case SYSPHASE_RT_SGPE:
l_rc = tor_append_ring(
i_ringSection,
io_ringSectionSize, // In: Exact size. Out: Updated size.
i_ringBuf2,
i_ringBufSize2, // Max size.
(RingID)i_ring.ringId,
P9_TOR::SGPE, // We're working on the SGPE image
P9_TOR::ALLRING, // No-care
BASE, // All VPD rings are Base ringVariant
l_chipletTorId, // Chiplet instance ID
i_vpdRing ); // The VPD RS4 ring container
if (l_rc == TOR_APPEND_RING_DONE)
{
FAPI_INF("Successfully added VPD ring: (ringId,evenOdd,chipletId)=(0x%02X,0x%X,0x%02X)",
i_ring.ringId, l_evenOdd, l_chipletId);
}
else
{
FAPI_ASSERT( false,
fapi2::XIPC_TOR_APPEND_RING_FAILED().
set_CHIP_TARGET(i_proc_target).
set_TOR_RC(l_rc),
"tor_append_ring() failed w/l_rc=%d",
l_rc );
}
FAPI_DBG("(After tor_append) io_ringSectionSize = %d", io_ringSectionSize);
break;
default:
FAPI_ASSERT( false,
fapi2::XIPC_INVALID_SYSPHASE_PARM().
set_CHIP_TARGET(i_proc_target).
set_SYSPHASE(i_sysPhase).
set_OCCURRENCE(2),
"Code bug: Unsupported value of sysPhase (=%d)",
i_sysPhase );
break;
} // End switch(sysPhase)
} // End if(redundant)
}
else if (l_fapiRc.isRC(RC_MVPD_RING_NOT_FOUND))
{
// No match, do nothing. Next chipletId.
//@TODO: Uncomment the following after PowerOn. Also, need to come
// to agreement whether this should be fatal error or not.
// For now, for PO, it's considered benigh and noise and is
// being commented out.
//FAPI_INF("_fetch_and_insert_vpd_rings():"
// "(ringId,chipletId)=(0x%X,0x%X) not found.",
// i_ring.ringId, l_chipletId);
fapi2::current_err = fapi2::FAPI2_RC_SUCCESS;
}
else
{
//--------------------------
// Handle other error cases
//--------------------------
// getMvpdRing failed due to insufficient ring buffer space.
// Assumption here is that getMvpdRing returns required buffer size
// in l_vpdRingSize (and which it does!).
FAPI_ASSERT( !l_fapiRc.isRC(RC_MVPD_RING_BUFFER_TOO_SMALL),
fapi2::XIPC_MVPD_RING_SIZE_TOO_BIG().
set_CHIP_TARGET(i_proc_target).
set_RING_ID(i_ring.ringId).
set_CHIPLET_ID(l_chipletId).
set_RING_BUFFER_SIZE(i_vpdRingSize).
set_MVPD_RING_SIZE(l_vpdRingSize),
"_fetch_and_insert_vpd_rings(): VPD ring size (=0x%X) exceeds"
" allowed ring buffer size (=0x%X)",
l_vpdRingSize, i_vpdRingSize );
// getMvpdRing failed due to invalid record data magic word.
FAPI_ASSERT( !l_fapiRc.isRC(RC_MVPD_INVALID_RS4_HEADER),
fapi2::XIPC_MVPD_INVALID_RECORD_DATA().
set_CHIP_TARGET(i_proc_target).
set_RING_ID(i_ring.ringId).
set_CHIPLET_ID(l_chipletId),
"_fetch_and_insert_vpd_rings(): MVPD has invalid record data" );
// getMvpdRing failed for some other reason aside from above handled cases.
if (l_fapiRc != fapi2::FAPI2_RC_SUCCESS)
{
FAPI_ERR("_fetch_and_insert_vpd_rings(): getMvpdRing failed "
" w/rc=0x%08X", (uint64_t)l_fapiRc);
fapi2::current_err = l_fapiRc;
goto fapi_try_exit;
}
} // End if(bSkipRing)
} // Loop on evenOdd
} //Loop on chipletId
fapi_try_exit:
FAPI_DBG("Exiting _fetch_and_insert_vpd_rings");
return fapi2::current_err;
}
// Function: fetch_and_insert_vpd_rings()
//
// Parameter list:
// const fapi::Target &i_target: Processor chip target.
// void* i_ringSection: Ptr to ring section.
// uint32_t& io_ringSectionSize: Running size
// uint32_t i_maxRingSectionSize: Max size
// uint8_t i_sysPhase: ={IPL, RT_CME, RT_SGPE}
// void* i_vpdRing: VPD ring buffer.
// uint32_t i_vpdRingSize: Size of VPD ring buffer.
// void* i_ringBuf2: Ring work buffer.
// uint32_t i_ringBufSize2: Size of ring work buffer.
// uint32_t& io_bootCoreMask: Desired (in) and actual (out) boot cores.
//
fapi2::ReturnCode fetch_and_insert_vpd_rings(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_proc_target,
void* i_ringSection,
uint32_t& io_ringSectionSize, // Running size
uint32_t i_maxRingSectionSize, // Max size
uint8_t i_sysPhase,
void* i_vpdRing,
uint32_t i_vpdRingSize,
void* i_ringBuf2,
uint32_t i_ringBufSize2,
uint32_t& io_bootCoreMask )
{
FAPI_DBG("Entering fetch_and_insert_vpd_rings");
// Walk through all Vpd rings and add any that's there to the image.
// Do this in two steps:
// 1- Add all NEST rings
// 2- Add QUAD rings in EC order
// 1- Add all common rings
for (auto vpdType = 0; vpdType < NUM_OF_VPD_TYPES; vpdType++)
{
const RingIdList* l_ring_id_list = ALL_VPD_RINGS[vpdType].ringIdList;
auto l_ring_id_list_size = ALL_VPD_RINGS[vpdType].ringIdListSize;
for (size_t iRing = 0; iRing < l_ring_id_list_size; iRing++)
{
if (l_ring_id_list[iRing].vpdRingClass != VPD_RING_CLASS_EQ_INS &&
l_ring_id_list[iRing].vpdRingClass != VPD_RING_CLASS_EX_INS &&
l_ring_id_list[iRing].vpdRingClass != VPD_RING_CLASS_EC_INS)
{
FAPI_TRY( _fetch_and_insert_vpd_rings( i_proc_target,
i_ringSection,
io_ringSectionSize,
i_maxRingSectionSize,
i_sysPhase,
i_vpdRing,
i_vpdRingSize,
i_ringBuf2,
i_ringBufSize2,
l_ring_id_list[iRing],
io_bootCoreMask ),
"fetch_and_insert_vpd_rings(): Failed to execute "
"_fetch_and_insert_vpd_rings() w/rc:0x%.8x",
(uint64_t)fapi2::current_err );
FAPI_DBG("(CMN) io_ringSectionSize = %d", io_ringSectionSize);
}
} //Loop on ringId
} //Loop on VPD types
// 2- Add all instance [QUAD-level] rings in EC order - TBD
//@TODO: For now, just add everything though honoring bootCoreMask with
// which we can control any potential overfilling of the image
// by manually ditching cores in bootCoreMask until it fits. For
// the actual VPD ring insertion order effort in RTC158106, we need
// a dual fetch_and_insert_{common,instance}_vpd_rings where the
// common part pretty much is already completed in the above step
// #1. The step #2 instance part needs updating to ditch looping
// over vpdType and instead loop over chipletId to fill up one
// core chipletId "column" at a time (RTC158106).
for (auto vpdType = 0; vpdType < NUM_OF_VPD_TYPES; vpdType++)
{
const RingIdList* l_ring_id_list = ALL_VPD_RINGS[vpdType].ringIdList;
auto l_ring_id_list_size = ALL_VPD_RINGS[vpdType].ringIdListSize;
for (size_t iRing = 0; iRing < l_ring_id_list_size; iRing++)
{
if (l_ring_id_list[iRing].vpdRingClass == VPD_RING_CLASS_EQ_INS ||
l_ring_id_list[iRing].vpdRingClass == VPD_RING_CLASS_EX_INS ||
l_ring_id_list[iRing].vpdRingClass == VPD_RING_CLASS_EC_INS)
{
FAPI_TRY( _fetch_and_insert_vpd_rings( i_proc_target,
i_ringSection,
io_ringSectionSize,
i_maxRingSectionSize,
i_sysPhase,
i_vpdRing,
i_vpdRingSize,
i_ringBuf2,
i_ringBufSize2,
l_ring_id_list[iRing],
io_bootCoreMask ),
"fetch_and_insert_vpd_rings(): Failed to execute "
"_fetch_and_insert_vpd_rings() w/rc:0x%.8x",
(uint64_t)fapi2::current_err );
FAPI_DBG("(INS) io_ringSectionSize = %d", io_ringSectionSize);
} // if (Quad instance ring)
} // Loop on ringId
} //Loop on VPD types
fapi_try_exit:
FAPI_DBG("Exiting fetch_and_insert_vpd_rings");
return fapi2::current_err;
}
fapi2::ReturnCode p9_xip_customize (
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_proc_target,
void* io_image,
uint32_t& io_imageSize, // In: Max, Out: Actual
void* io_ringSectionBuf,
uint32_t& io_ringSectionBufSize, // In: Max, Out: Actual
uint8_t i_sysPhase,
uint8_t i_modeBuild,
void* io_ringBuf1,
uint32_t i_ringBufSize1,
void* io_ringBuf2,
uint32_t i_ringBufSize2,
uint32_t& io_bootCoreMask ) // Bits(8:31) = EC00:EC23
{
fapi2::ReturnCode l_fapiRc = fapi2::FAPI2_RC_SUCCESS;
fapi2::ReturnCode l_fapiRc2 = fapi2::FAPI2_RC_SUCCESS;
int l_rc = 0; // Non-fapi RC
P9XipSection l_xipRingsSection;
uint32_t l_initialImageSize;
uint32_t l_imageSizeWithoutRings;
uint32_t l_maxImageSize, l_imageSize;
uint32_t l_maxRingSectionSize;
uint32_t l_sectionOffset = 1;
uint8_t attrDdLevel = 0;
uint32_t l_requestedBootCoreMask = (i_sysPhase == SYSPHASE_HB_SBE) ? io_bootCoreMask : 0x00FFFFFF;
void* l_hwRingsSection;
FAPI_DBG ("Entering p9_xip_customize w/sysPhase=%d...", i_sysPhase);
io_bootCoreMask = l_requestedBootCoreMask;
//-------------------------------------------
// Check some input buffer parameters:
// - sysPhase, modeBuild are checked later
// - log the initial image size
// - more buffer size checks in big switch()
//-------------------------------------------
FAPI_ASSERT( io_image != NULL &&
io_ringSectionBuf != NULL &&
io_ringBuf1 != NULL &&
io_ringBuf2 != NULL,
fapi2::XIPC_INVALID_INPUT_BUFFER_PARM().
set_CHIP_TARGET(i_proc_target).
set_IMAGE_BUF(io_image).
set_RING_SECTION_BUF(io_ringSectionBuf).
set_RING_BUF1(io_ringBuf1).
set_RING_BUF2(io_ringBuf2),
"One or more invalid input buffer pointers:\n"
" io_image=0x%016llx\n"
" io_ringSectionBuf=0x%016llx\n"
" io_ringBuf1=0x%016llx\n"
" io_ringBuf2=0x%016llx\n",
(uintptr_t)io_image,
(uintptr_t)io_ringSectionBuf,
(uintptr_t)io_ringBuf1,
(uintptr_t)io_ringBuf2 );
l_rc = p9_xip_image_size(io_image, &l_initialImageSize);
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_XIP_API_MISC_ERROR().
set_CHIP_TARGET(i_proc_target).
set_XIP_RC(l_rc).
set_OCCURRENCE(1),
"p9_xip_image_size() failed (1) w/rc=0x%08X",
(uint32_t)l_rc );
FAPI_ASSERT( io_imageSize >= l_initialImageSize &&
io_ringSectionBufSize == MAX_SEEPROM_IMAGE_SIZE &&
i_ringBufSize1 == MAX_RING_BUF_SIZE &&
i_ringBufSize2 == MAX_RING_BUF_SIZE,
fapi2::XIPC_INVALID_INPUT_BUFFER_SIZE_PARM().
set_CHIP_TARGET(i_proc_target).
set_INPUT_IMAGE_SIZE(l_initialImageSize).
set_IMAGE_BUF_SIZE(io_imageSize).
set_RING_SECTION_BUF_SIZE(io_ringSectionBufSize).
set_RING_BUF_SIZE1(i_ringBufSize1).
set_RING_BUF_SIZE2(i_ringBufSize2).
set_OCCURRENCE(1),
"One or more invalid input buffer sizes:\n"
" l_initialImageSize=0x%016llx\n"
" io_imageSize=0x%016llx\n"
" io_ringSectionBufSize=0x%016llx\n"
" i_ringBufSize1=0x%016llx\n"
" i_ringBufSize2=0x%016llx\n",
(uintptr_t)l_initialImageSize,
(uintptr_t)io_imageSize,
(uintptr_t)io_ringSectionBufSize,
(uintptr_t)i_ringBufSize1,
(uintptr_t)i_ringBufSize2 );
FAPI_DBG("Input image size: %d", l_initialImageSize);
///////////////////////////////////////////////////////////////////////////
// CUSTOMIZE item: Write mailbox attributes
// System phase: HB_SBE
///////////////////////////////////////////////////////////////////////////
if (i_sysPhase == SYSPHASE_HB_SBE)
{
FAPI_TRY(writeMboxRegs(i_proc_target, io_image),
"p9_xip_customize: error writing mbox regs in SBE image rc=0x%.8x",
(uint64_t)fapi2::current_err);
FAPI_TRY(writePG(i_proc_target, io_image),
"p9_xip_customize: error writing PG data in SBE image rc=0x%.8x",
(uint64_t)fapi2::current_err);
}
//////////////////////////////////////////////////////////////////////////
// CUSTOMIZE item: Append VPD rings to ring section
// System phase: All phases
//------------------------------------------------------------------------
// Notes:
// Do some sysPhase specific initial operations:
// - Set max image size
// - Copy image's sysPhase specific [sub-]section into separate ring
// section buffer
// - Delete (IPL sysPhase only) .rings, since we need to append later
//////////////////////////////////////////////////////////////////////////
switch (i_sysPhase)
{
case SYSPHASE_HB_SBE:
FAPI_DBG("Image size before any updates: %d", l_initialImageSize);
FAPI_ASSERT( io_imageSize >= MAX_SEEPROM_IMAGE_SIZE &&
io_ringSectionBufSize == MAX_SEEPROM_IMAGE_SIZE,
fapi2::XIPC_INVALID_INPUT_BUFFER_SIZE_PARM().
set_CHIP_TARGET(i_proc_target).
set_INPUT_IMAGE_SIZE(l_initialImageSize).
set_IMAGE_BUF_SIZE(io_imageSize).
set_RING_SECTION_BUF_SIZE(io_ringSectionBufSize).
set_RING_BUF_SIZE1(i_ringBufSize1).
set_RING_BUF_SIZE2(i_ringBufSize2).
set_OCCURRENCE(2),
"One or more invalid input buffer sizes for SBE:\n"
" MAX_SEEPROM_IMAGE_SIZE=0x%016llx\n"
" io_imageSize=0x%016llx\n"
" io_ringSectionBufSize=0x%016llx\n",
(uintptr_t)MAX_SEEPROM_IMAGE_SIZE,
(uintptr_t)io_imageSize,
(uintptr_t)io_ringSectionBufSize );
l_maxImageSize = MAX_SEEPROM_IMAGE_SIZE;
// Copy, save and delete the .rings section, wherever it is (even if
// not the last section), and re-arrange other sections located above
// the .rings section.
// Keep a copy of the original input image, io_image, in io_ringSectionBuf.
l_rc = p9_xip_delete_section(io_image, io_ringSectionBuf, l_initialImageSize, P9_XIP_SECTION_SBE_RINGS);
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_XIP_API_MISC_ERROR().
set_CHIP_TARGET(i_proc_target).
set_XIP_RC(l_rc).
set_OCCURRENCE(2),
"p9_xip_delete_section() failed removing .rings w/rc=0x%08X",
(uint32_t)l_rc );
// Make a note of the image size without .rings
l_rc = p9_xip_image_size(io_image, &l_imageSizeWithoutRings);
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_XIP_API_MISC_ERROR().
set_CHIP_TARGET(i_proc_target).
set_XIP_RC(l_rc).
set_OCCURRENCE(3),
"p9_xip_image_size() failed (3) w/rc=0x%08X",
(uint32_t)l_rc );
FAPI_DBG("Size of image before VPD update (excl .rings): %d", l_imageSizeWithoutRings);
// Get the size of our .rings section.
l_rc = p9_xip_get_section(io_ringSectionBuf, P9_XIP_SECTION_SBE_RINGS, &l_xipRingsSection);
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_XIP_API_MISC_ERROR().
set_CHIP_TARGET(i_proc_target).
set_XIP_RC(l_rc).
set_OCCURRENCE(4),
"p9_xip_get_section() failed (4) getting .rings section w/rc=0x%08X",
(uint32_t)l_rc );
io_ringSectionBufSize = l_xipRingsSection.iv_size;
FAPI_ASSERT( io_ringSectionBufSize > 0,
fapi2::XIPC_EMPTY_RING_SECTION().
set_CHIP_TARGET(i_proc_target),
"Ring section size in SBE image is zero. No TOR. Can't append rings.");
FAPI_DBG("Size of .rings section before VPD update: %d", io_ringSectionBufSize);
l_maxRingSectionSize = l_maxImageSize - l_imageSizeWithoutRings;
FAPI_DBG("Max allowable size of .rings section: %d", l_maxRingSectionSize);
// Move .rings to the top of ringSectionBuf (which currently holds a copy of the
// io_image but which can now be destroyed.)
memcpy( io_ringSectionBuf,
(void*)(((uint8_t*)io_ringSectionBuf) + l_xipRingsSection.iv_offset),
io_ringSectionBufSize );
//----------------------------------------
// Append VPD Rings to the .rings section
//----------------------------------------
l_fapiRc = fetch_and_insert_vpd_rings( i_proc_target,
io_ringSectionBuf,
io_ringSectionBufSize, // Running section size
l_maxRingSectionSize, // Max section size
i_sysPhase,
io_ringBuf1,
i_ringBufSize1,
io_ringBuf2,
i_ringBufSize2,
io_bootCoreMask );
FAPI_DBG("bootCoreMask: Requested=0x%08X Final=0x%08X",
l_requestedBootCoreMask, io_bootCoreMask);
if (l_fapiRc)
{
if (l_fapiRc.isRC(RC_XIPC_IMAGE_WOULD_OVERFLOW))
{
FAPI_INF("p9_xip_customize(): Image is full. Ran out of space appending VPD rings"
" to the .rings section");
// Check the bootCoreMask to determine if enough cores have been configured.
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
uint8_t attrMinReqdEcs = 0;
uint8_t l_actualEcCount = 0;
l_fapiRc2 = FAPI_ATTR_GET(fapi2::ATTR_SBE_IMAGE_MINIMUM_VALID_ECS, FAPI_SYSTEM, attrMinReqdEcs);
FAPI_ASSERT( l_fapiRc2.isRC(fapi2::FAPI2_RC_SUCCESS),
fapi2::XIPC_IMAGE_WOULD_OVERFLOW_ADDL_INFO().
set_CHIP_TARGET(i_proc_target).
set_REQUESTED_BOOT_CORE_MASK(l_requestedBootCoreMask).
set_CURRENT_BOOT_CORE_MASK(io_bootCoreMask),
"FAPI_ATTR_GET(ATTR_SBE_IMAGE_MINIMUM_VALID_ECS) failed."
" Unable to determine ATTR_SBE_IMAGE_MINIMUM_VALID_ECS,"
" so don't know if the minimum core set was met." );
FAPI_DBG("attrMinReqdEcs = 0x%x", attrMinReqdEcs);
// Count number of ECs set in bootCoreMask
l_actualEcCount = 0;
for (uint8_t iCore = 0; iCore < NUM_OF_CORES; iCore++)
{
if (io_bootCoreMask & ((0x00000001 << (NUM_OF_CORES - 1)) >> iCore))
{
l_actualEcCount++;
}
}
FAPI_ASSERT( l_actualEcCount >= attrMinReqdEcs,
fapi2::XIPC_IMAGE_WOULD_OVERFLOW_BEFORE_REACHING_MIN_ECS().
set_CHIP_TARGET(i_proc_target).
set_REQUESTED_BOOT_CORE_MASK(l_requestedBootCoreMask).
set_CURRENT_BOOT_CORE_MASK(io_bootCoreMask).
set_MIN_REQD_ECS(attrMinReqdEcs).
set_ACTUAL_EC_COUNT(l_actualEcCount),
"Image buffer would overflow before reaching the minimum required"
" number of EC boot cores" );
FAPI_INF( "Image is full and with sufficient boot cores:\n"
" Final bootCoreMask: 0x%08X\n"
" Number of boot cores: %d\n"
" Min req'd boot cores: %d",
io_bootCoreMask, l_actualEcCount, attrMinReqdEcs );
l_fapiRc = fapi2::FAPI2_RC_SUCCESS;
}
fapi2::current_err = l_fapiRc;
goto fapi_try_exit;
}
// More size code sanity checks of section and image sizes.
FAPI_ASSERT( io_ringSectionBufSize <= l_maxRingSectionSize,
fapi2::XIPC_SECTION_SIZING().
set_CHIP_TARGET(i_proc_target).
set_RING_SECTION_SIZE(io_ringSectionBufSize).
set_MAX_RING_SECTION_SIZE(l_maxRingSectionSize),
"Code bug: ringSectionBufSize>maxRingSectionSize" );
FAPI_ASSERT( (l_imageSizeWithoutRings + io_ringSectionBufSize) <= l_maxImageSize,
fapi2::XIPC_IMAGE_SIZING().
set_CHIP_TARGET(i_proc_target).
set_IMAGE_SIZE_WITHOUT_RINGS(l_imageSizeWithoutRings).
set_RING_SECTION_SIZE(io_ringSectionBufSize).
set_MAX_IMAGE_SIZE(l_maxImageSize),
"Code bug: imageSize would exceed maxImageSize" );
FAPI_DBG( "Image details: io_ringSectionBufSize=%d l_imageSizeWithoutRings=%d l_maxImageSize=%d",
io_ringSectionBufSize, l_imageSizeWithoutRings, l_maxImageSize );
//--------------------------------------------------------
// Append the updated .rings section to the Seeprom image
//--------------------------------------------------------
l_rc = p9_xip_append( io_image,
P9_XIP_SECTION_SBE_RINGS,
io_ringSectionBuf,
(const uint32_t)io_ringSectionBufSize,
(const uint32_t)l_maxImageSize,
&l_sectionOffset );
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_XIP_API_MISC_ERROR().
set_CHIP_TARGET(i_proc_target).
set_XIP_RC(l_rc).
set_OCCURRENCE(5),
"p9_xip_append() failed w/rc=0x%08x",
(uint32_t)l_rc );
FAPI_DBG("sectionOffset=0x%08X", l_sectionOffset);
l_rc = p9_xip_image_size(io_image, &l_imageSize);
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_XIP_API_MISC_ERROR().
set_CHIP_TARGET(i_proc_target).
set_XIP_RC(l_rc).
set_OCCURRENCE(6),
"p9_xip_image_size() failed (6) w/rc=0x%08X",
(uint32_t)l_rc );
FAPI_DBG( "Seeprom image size after VPD updates: %d", l_imageSize );
FAPI_ASSERT( l_imageSize <= l_maxImageSize,
fapi2::XIPC_IMAGE_TOO_LARGE().
set_CHIP_TARGET(i_proc_target).
set_IMAGE_SIZE(l_imageSize).
set_MAX_IMAGE_SIZE(l_maxImageSize).
set_OCCURRENCE(1),
"Seeprom image size after VPD updates (=%d) exceeds max image size (=%d)",
l_imageSize, l_maxImageSize );
break;
case SYSPHASE_RT_CME:
case SYSPHASE_RT_SGPE:
FAPI_ASSERT( io_imageSize == l_initialImageSize &&
io_ringSectionBufSize == MAX_SEEPROM_IMAGE_SIZE,
fapi2::XIPC_INVALID_INPUT_BUFFER_SIZE_PARM().
set_CHIP_TARGET(i_proc_target).
set_INPUT_IMAGE_SIZE(l_initialImageSize).
set_IMAGE_BUF_SIZE(io_imageSize).
set_RING_SECTION_BUF_SIZE(io_ringSectionBufSize).
set_RING_BUF_SIZE1(i_ringBufSize1).
set_RING_BUF_SIZE2(i_ringBufSize2).
set_OCCURRENCE(3),
"One or more invalid input buffer sizes for CME or SGPE:\n"
" l_initialImageSize=0x%016llx\n"
" io_imageSize=0x%016llx\n"
" io_ringSectionBufSize=0x%016llx\n",
(uintptr_t)l_initialImageSize,
(uintptr_t)io_imageSize,
(uintptr_t)io_ringSectionBufSize );
l_maxRingSectionSize = io_ringSectionBufSize;
// Calculate pointer to HW image's .rings section
l_rc = p9_xip_get_section(io_image, P9_XIP_SECTION_HW_RINGS, &l_xipRingsSection);
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_XIP_API_MISC_ERROR().
set_CHIP_TARGET(i_proc_target).
set_XIP_RC(l_rc).
set_OCCURRENCE(7),
"p9_xip_get_section() failed (7) getting .rings section w/rc=0x%08X",
(uint32_t)l_rc );
FAPI_ASSERT( l_xipRingsSection.iv_size > 0,
fapi2::XIPC_EMPTY_RING_SECTION().
set_CHIP_TARGET(i_proc_target),
"CME or SGPE ring section size is zero (sysPhase=%d). No TOR. Can't append rings.",
i_sysPhase );
l_hwRingsSection = (void*)((uintptr_t)io_image + l_xipRingsSection.iv_offset);
// Extract the DD level to enable retrieval of correct CME/SGPE ring blocks
l_fapiRc = FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, i_proc_target, attrDdLevel);
FAPI_ASSERT( l_fapiRc.isRC(fapi2::FAPI2_RC_SUCCESS),
fapi2::XIPC_FAPI_ATTR_SVC_FAIL().
set_CHIP_TARGET(i_proc_target).
set_OCCURRENCE(1),
"FAPI_ATTR_GET(ATTR_EC) failed." );
FAPI_DBG("attrDdLevel = 0x%x", attrDdLevel);
//------------------------------------------------------------
// Get the CME or SGPE block of rings from .rings in HW image
//------------------------------------------------------------
if ( i_sysPhase == SYSPHASE_RT_CME )
{
FAPI_DBG("Getting the CME block of rings from HW image");
l_rc = tor_get_block_of_rings( l_hwRingsSection,
attrDdLevel,
P9_TOR::CME,
P9_TOR::ALLRING,
BASE,
0,
&io_ringSectionBuf,
io_ringSectionBufSize );
}
else
{
FAPI_DBG("Getting the SGPE block of rings from HW image");
l_rc = tor_get_block_of_rings( l_hwRingsSection,
attrDdLevel,
P9_TOR::SGPE,
P9_TOR::ALLRING,
BASE,
0,
&io_ringSectionBuf,
io_ringSectionBufSize );
}
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_TOR_GET_BLOCK_OF_RINGS_FAILED().
set_CHIP_TARGET(i_proc_target).
set_TOR_RC(l_rc).
set_SYSPHASE(i_sysPhase),
"tor_get_block_of_rings() failed w/rc=0x%08X",
(uint32_t)l_rc );
FAPI_DBG("Size of .rings section before VPD update: %d", io_ringSectionBufSize);
//----------------------------------------
// Append VPD Rings to the .rings section
//----------------------------------------
l_fapiRc = fetch_and_insert_vpd_rings( i_proc_target,
io_ringSectionBuf,
io_ringSectionBufSize, // Running section size
l_maxRingSectionSize, // Max section size
i_sysPhase,
io_ringBuf1,
i_ringBufSize1,
io_ringBuf2,
i_ringBufSize2,
io_bootCoreMask );
FAPI_DBG("Size of .rings section after VPD update: %d", io_ringSectionBufSize );
FAPI_DBG("bootCoreMask: Requested=0x%08X Final=0x%08X",
l_requestedBootCoreMask, io_bootCoreMask);
if (l_fapiRc)
{
FAPI_ASSERT( !l_fapiRc.isRC(RC_XIPC_IMAGE_WOULD_OVERFLOW),
fapi2::XIPC_IMAGE_WOULD_OVERFLOW_BEFORE_REACHING_MIN_ECS().
set_CHIP_TARGET(i_proc_target).
set_REQUESTED_BOOT_CORE_MASK(l_requestedBootCoreMask).
set_CURRENT_BOOT_CORE_MASK(io_bootCoreMask),
"Ran out of space appending VPD rings to the .rings section" );
fapi2::current_err = l_fapiRc;
goto fapi_try_exit;
}
// More size code sanity checks of section and image sizes.
FAPI_ASSERT( io_ringSectionBufSize <= l_maxRingSectionSize,
fapi2::XIPC_SECTION_SIZING().
set_CHIP_TARGET(i_proc_target).
set_RING_SECTION_SIZE(io_ringSectionBufSize).
set_MAX_RING_SECTION_SIZE(l_maxRingSectionSize),
"Code bug: ringSectionBufSize>maxRingSectionSize" );
break;
default:
FAPI_ASSERT( false,
fapi2::XIPC_INVALID_SYSPHASE_PARM().
set_CHIP_TARGET(i_proc_target).
set_SYSPHASE(i_sysPhase).
set_OCCURRENCE(1),
"Caller bug: Caller supplied unsupported value of sysPhase (=%d)",
i_sysPhase );
break;
}
///////////////////////////////////////////////////////////////////////////
// CUSTOMIZE item: Removal of .toc, .fixed_toc and .strings
// System phase: HB_SBE
///////////////////////////////////////////////////////////////////////////
if (i_sysPhase == SYSPHASE_HB_SBE)
{
// Remove .toc:
// This will remove external visibility to image's attributes and other global variables.
l_rc = p9_xip_delete_section(io_image, io_ringSectionBuf, l_imageSize, P9_XIP_SECTION_TOC);
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_SECTION_REMOVAL_ERROR().
set_CHIP_TARGET(i_proc_target).
set_XIP_SECTION(P9_XIP_SECTION_TOC),
"p9_xip_delete_section() failed to remove .toc section w/rc=0x%08X",
(uint32_t)l_rc );
// Remove .fixedtoc:
l_rc = p9_xip_delete_section(io_image, io_ringSectionBuf, l_imageSize, P9_XIP_SECTION_FIXED_TOC);
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_SECTION_REMOVAL_ERROR().
set_CHIP_TARGET(i_proc_target).
set_XIP_SECTION(P9_XIP_SECTION_FIXED_TOC),
"p9_xip_delete_section() failed to remove .fixedtoc section w/rc=0x%08X",
(uint32_t)l_rc );
// Remove .strings:
// The .strings section must be removed after .toc and .fixed_toc. Otherwise
// we get an P9_XIP_TOC_ERROR, probably because either of those two sections
// will "complain" on the next XIP API access that info they need in .strings
// is missing, i.e. as part of p9_xip_validate_image().
l_rc = p9_xip_delete_section(io_image, io_ringSectionBuf, l_imageSize, P9_XIP_SECTION_STRINGS);
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_SECTION_REMOVAL_ERROR().
set_CHIP_TARGET(i_proc_target).
set_XIP_SECTION(P9_XIP_SECTION_STRINGS),
"p9_xip_delete_section() failed to remove .fixedtoc section w/rc=0x%08X",
(uint32_t)l_rc );
// Check the image size.
l_rc = p9_xip_image_size(io_image, &l_imageSize);
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_XIP_API_MISC_ERROR().
set_CHIP_TARGET(i_proc_target).
set_XIP_RC(l_rc).
set_OCCURRENCE(8),
"p9_xip_image_size() failed (7) w/rc=0x%08X",
(uint32_t)l_rc );
FAPI_DBG("Image size after section removals: %d", l_imageSize);
FAPI_ASSERT( l_imageSize <= l_maxImageSize,
fapi2::XIPC_IMAGE_TOO_LARGE().
set_CHIP_TARGET(i_proc_target).
set_IMAGE_SIZE(l_imageSize).
set_MAX_IMAGE_SIZE(l_maxImageSize).
set_OCCURRENCE(2),
"Final Seeprom image size (=%d) exceeds max image size (=%d)",
l_imageSize, l_maxImageSize );
}
///////////////////////////////////////////////////////////////////////////
// Other customizations
///////////////////////////////////////////////////////////////////////////
// TBD
///////////////////////////////////////////////////////////////////////////
// Done
///////////////////////////////////////////////////////////////////////////
if (i_sysPhase == SYSPHASE_HB_SBE)
{
io_imageSize = l_imageSize;
FAPI_DBG("Final customized Seeprom image size: %d", io_imageSize);
}
FAPI_DBG("Final customized .rings section size: %d", io_ringSectionBufSize);
fapi_try_exit:
FAPI_DBG("Exiting p9_xip_customize");
return fapi2::current_err;
}
xip_customize: Updating SBE image's PIBMEM repair attributes.
Change-Id: Ied6ef432be1a27d6cc6bca00fb983949dcd69a68
Original-Change-Id: Ib6d2ce6b8fe18c007a86dafb7c9bbec8eb8b22fa
Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/32403
Tested-by: Jenkins Server <8e3f934e4c44875bc48d33da3ea13d93ba9a233f@us.ibm.com>
Tested-by: Hostboot CI <52521565bd8ea18a2b112942dce4f4220a97c2c8@us.ibm.com>
Reviewed-by: Joseph J. McGill <4a85c6614f9f065f63d8fd57cde15e48af07ea2a@us.ibm.com>
Reviewed-by: SRINIVAS V. POLISETTY <56f0c2e4236ce2352f11655a765c7ff32aee4dbb@in.ibm.com>
Reviewed-by: Martin Gloff <df0a4963746ae04ab678d064fccc7ee68adfd751@us.ibm.com>
Reviewed-by: Jennifer A. Stofer <ab93eca12e43608f33daa16a67357cd7b7e867ab@us.ibm.com>
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/customize/p9_xip_customize.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
#include <p9_xip_customize.H>
#include <p9_xip_image.h>
#include <p9_ring_identification.H>
#include <p9_get_mvpd_ring.H>
#include <p9_tor.H>
#include <p9_scan_compression.H>
#include <p9_infrastruct_help.H>
#include <p9_ringId.H>
using namespace fapi2;
#define MBOX_ATTR_WRITE(ID,TARGET,IMAGE) \
{ \
fapi2::ID##_Type ID##_attrVal; \
FAPI_TRY(FAPI_ATTR_GET(fapi2::ID,TARGET,ID##_attrVal),\
"MBOX_ATTR_WRITE: Error getting %s", #ID); \
FAPI_TRY(p9_xip_set_scalar(IMAGE,#ID,ID##_attrVal),\
"MBOX_ATTR_WRITE: Error writing attr %s to seeprom image",\
#ID); \
}
fapi2::ReturnCode writeMboxRegs (
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_proc_target,
void* i_image)
{
FAPI_DBG ("writeMboxRegs Entering...");
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
MBOX_ATTR_WRITE (ATTR_I2C_BUS_DIV_REF, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_EQ_GARD, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_EC_GARD, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_NEST_PLL_BUCKET, FAPI_SYSTEM, i_image);
MBOX_ATTR_WRITE (ATTR_BOOT_FREQ_MULT, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_CLOCK_PLL_MUX, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_DPLL_BYPASS, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_SS_FILTER_BYPASS, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_CP_FILTER_BYPASS, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_IO_FILTER_BYPASS, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_NEST_MEM_X_O_PCI_BYPASS, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_SYSTEM_IPL_PHASE, FAPI_SYSTEM, i_image);
MBOX_ATTR_WRITE (ATTR_SYS_FORCE_ALL_CORES, FAPI_SYSTEM, i_image);
MBOX_ATTR_WRITE (ATTR_RISK_LEVEL, FAPI_SYSTEM, i_image);
MBOX_ATTR_WRITE (ATTR_DISABLE_HBBL_VECTORS, FAPI_SYSTEM, i_image);
MBOX_ATTR_WRITE (ATTR_MC_SYNC_MODE, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_PROC_SBE_MASTER_CHIP, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_PROC_FABRIC_GROUP_ID, i_proc_target, i_image);
MBOX_ATTR_WRITE (ATTR_PROC_FABRIC_CHIP_ID, i_proc_target, i_image);
fapi_try_exit:
FAPI_DBG("writeMboxRegs Exiting...");
return fapi2::current_err;
}
fapi2::ReturnCode writePG(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_proc_target,
void* i_image)
{
const uint8_t IMG_PG_ENTRIES = 64;
const uint16_t DEFAULT_PG_VAL = 0xffff;
FAPI_DBG ("writePG Entering...");
// Make all chiplets "not good".
for (auto l_pg_idx = 0; l_pg_idx < IMG_PG_ENTRIES; l_pg_idx++)
{
FAPI_TRY( p9_xip_set_element(i_image, "ATTR_PG", l_pg_idx, DEFAULT_PG_VAL),
"Error (1) from p9_xip_set_element (idx %d)", l_pg_idx );
}
for (auto l_perv_tgt : i_proc_target.getChildren<fapi2::TARGET_TYPE_PERV>())
{
uint8_t l_unit_id = 0;
uint16_t l_pg_data = 0;
uint8_t l_pg_idx = 0;
FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_perv_tgt, l_unit_id),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)" );
FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_PG, l_perv_tgt, l_pg_data),
"Error from FAPI_ATTR_GET (ATTR_PG)" );
l_pg_idx = l_unit_id;
FAPI_ASSERT( l_pg_idx < IMG_PG_ENTRIES,
fapi2::XIPC_BAD_PG_XLATE().
set_CHIP_TARGET(i_proc_target).
set_CHIP_UNIT_POS(l_unit_id).
set_PG_INDEX(l_pg_idx),
"Code bug: Invalid translation from PERV chip unit position to image PG index" );
// Update the image
FAPI_TRY( p9_xip_set_element(i_image, "ATTR_PG", l_pg_idx, l_pg_data),
"Error (2) from p9_xip_set_element (idx %d)", l_pg_idx );
FAPI_DBG("Write value of pg_data[%d] = %08X", l_pg_idx, l_pg_data);
}
for (auto l_pg_idx = 0; l_pg_idx < IMG_PG_ENTRIES; l_pg_idx++)
{
uint64_t l_val;
FAPI_TRY( p9_xip_get_element(i_image, "ATTR_PG", l_pg_idx, &l_val),
"Error from p9_xip_get_element (idx %d)", l_pg_idx );
FAPI_DBG("Read value of pg_data[%d] = %08X", l_pg_idx, l_val);
}
fapi_try_exit:
FAPI_DBG ("writePG Exiting...");
return fapi2::current_err;
}
// Function: _fetch_and_insert_vpd_rings()
//
// Parameter list:
// const fapi::Target &i_target: Processor chip target.
// void* i_ringSection: Ptr to ring section.
// uint32_t& io_ringSectionSize: Running ring section size
// uint32_t i_maxRingSectionSize: Max ring section size
// uint8_t i_sysPhase: ={HB_SBE, RT_CME, RT_SGPE}
// void* i_vpdRing: VPD ring buffer.
// uint32_t i_vpdRingSize: Size of VPD ring buffer.
// void* i_ringBuf2: Ring work buffer.
// uint32_t i_ringBufSize2: Size of ring work buffer.
// const RingIdList i_ring: The ring ID list (#G or #R list)
// uint32_t& io_bootCoreMask: Desired (in) and actual (out) boot cores.
//
fapi2::ReturnCode _fetch_and_insert_vpd_rings(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_proc_target,
void* i_ringSection,
uint32_t& io_ringSectionSize,
uint32_t i_maxRingSectionSize,
uint8_t i_sysPhase,
void* i_vpdRing,
uint32_t i_vpdRingSize,
void* i_ringBuf2,
uint32_t i_ringBufSize2,
const RingIdList i_ring,
uint32_t& io_bootCoreMask )
{
ReturnCode l_fapiRc = fapi2::FAPI2_RC_SUCCESS;
int l_rc = 0;
uint8_t l_chipletId;
uint8_t l_ringsPerChipletId = 0;
uint8_t l_instanceIdMax;
uint8_t l_evenOdd;
uint64_t l_evenOddMaskStart;
uint64_t l_evenOddMask; // 0:even, 1:odd
uint8_t bSkipRing = 0;
FAPI_DBG("Entering _fetch_and_insert_vpd_rings");
// Filter out GPTR requests. Not supported in DD1. Coming in through initfiles instead.
if (i_ring.vpdRingClass == VPD_RING_CLASS_GPTR)
{
FAPI_INF("Skipping extraction of GPTR ring...");
fapi2::current_err = l_fapiRc;
goto fapi_try_exit;
}
// For EX rings, there's two rings listed in the Mvpd per [EQ] chipletId
// listed in ring_identification.C: One for each of the two EX, even and odd.
// Each of these two rings have the same [EQ] chipletId encoded in their
// iv_chipletId (current RS4 header) or iv_scanAddress (next gen RS4 header).
// They are distinguished by their even-odd bits in iv_scanSelect as follows:
if (i_ring.vpdRingClass == VPD_RING_CLASS_EX_INS)
{
l_ringsPerChipletId = 2;
switch (i_ring.ringId)
{
case ex_l3_refr_time:
case ex_l3_refr_repr:
l_evenOddMaskStart = ((uint64_t)0x00080000) << 32;
break;
case ex_l2_repr:
l_evenOddMaskStart = ((uint64_t)0x00800000) << 32;
break;
case ex_l3_repr:
l_evenOddMaskStart = ((uint64_t)0x02000000) << 32;
break;
default:
FAPI_ASSERT( false,
fapi2::XIPC_MVPD_RING_ID_MESS().
set_CHIP_TARGET(i_proc_target).
set_RING_ID(i_ring.ringId),
"Code bug: Wrong assumption about supported ringIds in this context. "
"ringId=%d(=0x%x)(=ringId.ringName) is not allowed here. ",
i_ring.ringId, i_ring.ringId, i_ring.ringName );
break;
}
}
else
{
l_ringsPerChipletId = 1;
l_evenOddMaskStart = 0;
}
// We use ring.instanceIdMax column to govern max value of instanceIdMax (i.e., the
// max chipletId). But unlike in P8, in P9 we will not search for chipletId=0xff in P9
// MVPD. It is no longer used in the MVPD. We merely keep the multicast Id, 0xff, in
// the ring list for now, just in case it is needed later on.
if (i_ring.instanceIdMax == 0xff)
{
l_instanceIdMax = i_ring.instanceIdMin;
}
else
{
l_instanceIdMax = i_ring.instanceIdMax;
}
for (l_chipletId = i_ring.instanceIdMin; l_chipletId <= l_instanceIdMax; l_chipletId++)
{
for (l_evenOdd = 0; l_evenOdd < l_ringsPerChipletId; l_evenOdd++)
{
l_evenOddMask = l_evenOddMaskStart >> l_evenOdd;
FAPI_INF("_fetch_and_insert_vpd_rings: (ringId,chipletId) = (0x%02X,0x%02x)",
i_ring.ringId, l_chipletId);
auto l_vpdRingSize = i_vpdRingSize;
MvpdKeyword l_mvpdKeyword;
switch (i_ring.vpdKeyword)
{
case VPD_KEYWORD_PDG: // #G Time rings
l_mvpdKeyword = fapi2::MVPD_KEYWORD_PDG;
break;
case VPD_KEYWORD_PDR: // #R Repair rings
l_mvpdKeyword = fapi2::MVPD_KEYWORD_PDR;
break;
default:
FAPI_ASSERT( false,
fapi2::XIPC_INVALID_VPD_KEYWORD().
set_CHIP_TARGET(i_proc_target).
set_VPD_KEYWORD(i_ring.vpdKeyword),
"Code bug: Unsupported value of vpdKeyword (=%d)",
i_ring.vpdKeyword );
break;
}
/////////////////////////////////////////////////////////////////////
// Fetch rings from the MVPD:
/////////////////////////////////////////////////////////////////////
// If an EC ring is an instance ring, then check if EC chipletId is represented in bootCoreMask,
// and only fetch if it is.
// If an EX/EQ ring is an instance ring, then check if the associated EC chipletId range in
// in bootCoreMask is represented by at least one EC chipletId, and fetch it if it is.
// Otherwise the ring is a common ring which we always must fetch.
bSkipRing = 0;
if ( i_ring.vpdRingClass == VPD_RING_CLASS_EQ_INS &&
(i_sysPhase == SYSPHASE_HB_SBE || i_sysPhase == SYSPHASE_RT_SGPE) )
{
// Fetch EQ instance ring
// - Fetch for SBE and SGPE only.
if ( ((0x0000000F << ((NUM_OF_QUADS - 1)*CORES_PER_QUAD)) >> ((l_chipletId - i_ring.instanceIdMin)*CORES_PER_QUAD)) &
io_bootCoreMask )
{
l_fapiRc = getMvpdRing( MVPD_RECORD_CP00,
l_mvpdKeyword,
i_proc_target,
l_chipletId,
l_evenOddMask,
i_ring.ringId,
(uint8_t*)i_vpdRing,
l_vpdRingSize );
}
else
{
bSkipRing = 1;
}
}
else if ( i_ring.vpdRingClass == VPD_RING_CLASS_EX_INS &&
(i_sysPhase == SYSPHASE_HB_SBE || i_sysPhase == SYSPHASE_RT_SGPE) )
{
// Fetch EX instance ring
// - Fetch for SBE and SGPE only.
if ( ((0x0000000F << ((NUM_OF_QUADS - 1)*CORES_PER_QUAD)) >> ((l_chipletId - i_ring.instanceIdMin)*CORES_PER_QUAD)) &
io_bootCoreMask )
{
l_fapiRc = getMvpdRing( MVPD_RECORD_CP00,
l_mvpdKeyword,
i_proc_target,
l_chipletId,
l_evenOddMask,
i_ring.ringId,
(uint8_t*)i_vpdRing,
l_vpdRingSize );
}
else
{
bSkipRing = 1;
}
}
else if ( i_ring.vpdRingClass == VPD_RING_CLASS_EC_INS &&
(i_sysPhase == SYSPHASE_HB_SBE || i_sysPhase == SYSPHASE_RT_CME) )
{
// Fetch EC instance ring
// - Fetch for SBE and CME only.
if ( ((0x00000001 << (NUM_OF_CORES - 1)) >> (l_chipletId - i_ring.instanceIdMin)) & io_bootCoreMask )
{
l_fapiRc = getMvpdRing( MVPD_RECORD_CP00,
l_mvpdKeyword,
i_proc_target,
l_chipletId,
l_evenOddMask,
i_ring.ringId,
(uint8_t*)i_vpdRing,
l_vpdRingSize );
}
else
{
bSkipRing = 1;
}
}
else if ( i_sysPhase == SYSPHASE_HB_SBE ||
(i_sysPhase == SYSPHASE_RT_CME && i_ring.vpdRingClass == VPD_RING_CLASS_EC) ||
(i_sysPhase == SYSPHASE_RT_SGPE && (i_ring.vpdRingClass == VPD_RING_CLASS_EX ||
i_ring.vpdRingClass == VPD_RING_CLASS_EQ)) )
{
// Fetch common ring
// - Fetch all VPD rings for SBE.
// - Fetch only EC VPD rings for CME.
// - Fetch only EX+EQ VPD rings for SGPE.
l_fapiRc = getMvpdRing( MVPD_RECORD_CP00,
l_mvpdKeyword,
i_proc_target,
l_chipletId,
l_evenOddMask,
i_ring.ringId,
(uint8_t*)i_vpdRing,
l_vpdRingSize );
}
else
{
bSkipRing = 1;
}
///////////////////////////////////////////////////////////////////////
//Append VPD ring to the ring section
///////////////////////////////////////////////////////////////////////
if (bSkipRing)
{
continue;
}
else if (l_fapiRc == fapi2::FAPI2_RC_SUCCESS)
{
auto l_vpdChipletId = ((CompressedScanData*)i_vpdRing)->iv_chipletId;
// Even though success, checking that chipletId didn't somehow get
// messed up (code bug).
//@TODO: Modify this when chipletId becomes part of iv_scanAddress
// as part of RS4 shrinkage (RTC158101).
FAPI_ASSERT( l_vpdChipletId == l_chipletId,
fapi2::XIPC_MVPD_CHIPLET_ID_MESS().
set_CHIP_TARGET(i_proc_target).
set_CHIPLET_ID(l_chipletId).
set_MVPD_CHIPLET_ID(l_vpdChipletId).
set_RING_ID(i_ring.ringId),
"_fetch_and_insert_vpd_rings: Code bug: VPD ring's chipletId"
" in scan container (=0x%X) doesn't match the requested"
" chipletId (=0x%X)",
l_vpdChipletId, l_chipletId );
// Even though success, checking for accidental buffer overflow (code bug).
FAPI_ASSERT( l_vpdRingSize <= i_vpdRingSize,
fapi2::XIPC_MVPD_RING_SIZE_MESS().
set_CHIP_TARGET(i_proc_target).
set_RING_ID(i_ring.ringId).
set_CHIPLET_ID(l_chipletId).
set_RING_BUFFER_SIZE(i_vpdRingSize).
set_MVPD_RING_SIZE(l_vpdRingSize),
"_fetch_and_insert_vpd_rings: Code bug: VPD ring size (=0x%X) exceeds"
" allowed ring buffer size (=0x%X)",
l_vpdRingSize, i_vpdRingSize );
//@TODO: Remove following line asap. Temporary fix until Sgro starts using
// latest p9_scan_compression.H.
// Also fix p9_mvpd_ring_funcs.C to look for entire RS4_MAGIC string.
// Actually, do all the above in connection with RS4 header
// shrinkage (RTC158101 and RTC159801).
((CompressedScanData*)i_vpdRing)->iv_magic = htobe32(RS4_MAGIC);
// Check if ring is a flush ring, i.e. if it is redundant, meaning that it will
// result in no change.
int redundant = 0;
l_rc = rs4_redundant((CompressedScanData*)i_vpdRing, &redundant);
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_RS4_REDUNDANT_ERROR().
set_CHIP_TARGET(i_proc_target).
set_RING_ID(i_ring.ringId).
set_CHIPLET_ID(l_chipletId),
"rs4_redundant: Failed w/rc=%i for "
"ringId=0x%02X, chipletId=0x%02X ",
l_rc, i_ring.ringId, l_chipletId );
if (redundant)
{
FAPI_DBG("Skipping redundant VPD ring: ringId=0x%02X, chipletId=0x%02X ", i_ring.ringId, l_chipletId);
fapi2::current_err = fapi2::FAPI2_RC_SUCCESS;
// Note that we do not want to exit here. There could be content in the next
// instance. We're just not appending the current redundant one.
}
else
{
//@TODO: Temporary fix to convert VPD RS4 container format to
// to RingLayout format. Remove/replace in connection
// with RS4 header shrinkage (RTC158101)
uint32_t i;
for (i = 0; i < l_vpdRingSize; i++)
{
*(((uint8_t*)i_vpdRing) + l_vpdRingSize - 1 + sizeof(P9_TOR::RingLayout_t) - i) =
*(((uint8_t*)i_vpdRing) + l_vpdRingSize - 1 - i);
}
uint32_t l_sizeOfThisRing = l_vpdRingSize + sizeof(P9_TOR::RingLayout_t);
((P9_TOR::RingLayout_t*)i_vpdRing)->sizeOfThis = htobe32(l_sizeOfThisRing);
((P9_TOR::RingLayout_t*)i_vpdRing)->sizeOfCmsk = 0;
((P9_TOR::RingLayout_t*)i_vpdRing)->sizeOfMeta = 0;
// Checking for potential image overflow BEFORE appending the ring.
if ( (io_ringSectionSize + l_sizeOfThisRing) > i_maxRingSectionSize )
{
//@TODO: We can't update bootCoreMask until RTC158106. So for now
// we're simply returning the requested bootCoreMask. Thus,
// should there be an overflow condition before RTC158106
// gets implemented (i.e., inserting VPD rings in EC order),
// we would manually have to scale back on the requested
// cores in the initialled supplied io_bootCoreMask arg to
// xip_customize.
FAPI_ASSERT( false,
fapi2::XIPC_IMAGE_WOULD_OVERFLOW().
set_CHIP_TARGET(i_proc_target).
set_CURRENT_RING_SECTION_SIZE(io_ringSectionSize).
set_SIZE_OF_THIS_RING(l_sizeOfThisRing).
set_MAX_RING_SECTION_SIZE(i_maxRingSectionSize).
set_RING_ID(i_ring.ringId).
set_CHIPLET_ID(l_chipletId).
set_CURRENT_BOOT_CORE_MASK(io_bootCoreMask),
"Ran out of image buffer space trying to append a ring"
" to the .rings section" );
}
//------------------------------------------
// Now, append the ring to the ring section
//------------------------------------------
// Calculate the chiplet TOR index
uint8_t l_chipletTorId = l_chipletId +
(l_chipletId - i_ring.instanceIdMin ) * (l_ringsPerChipletId - 1) +
l_evenOdd;
switch (i_sysPhase)
{
case SYSPHASE_HB_SBE:
l_rc = tor_append_ring(
i_ringSection,
io_ringSectionSize, // In: Exact size. Out: Updated size.
i_ringBuf2,
i_ringBufSize2, // Max size.
(RingID)i_ring.ringId,
P9_TOR::SBE, // We're working on the SBE image
P9_TOR::ALLRING, // No-care
BASE, // All VPD rings are Base ringVariant
l_chipletTorId, // Chiplet instance TOR Index
i_vpdRing ); // The VPD RS4 ring container
if (l_rc == TOR_APPEND_RING_DONE)
{
FAPI_INF("Successfully added VPD ring: (ringId,evenOdd,chipletId)=(0x%02X,0x%X,0x%02X)",
i_ring.ringId, l_evenOdd, l_chipletId);
}
else
{
FAPI_ASSERT( false,
fapi2::XIPC_TOR_APPEND_RING_FAILED().
set_CHIP_TARGET(i_proc_target).
set_TOR_RC(l_rc),
"tor_append_ring() failed w/l_rc=%d",
l_rc );
}
break;
case SYSPHASE_RT_CME:
l_rc = tor_append_ring(
i_ringSection,
io_ringSectionSize, // In: Exact size. Out: Updated size.
i_ringBuf2,
i_ringBufSize2, // Max size.
(RingID)i_ring.ringId,
P9_TOR::CME, // We're working on the SBE image
P9_TOR::ALLRING, // No-care
BASE, // All VPD rings are Base ringVariant
l_chipletTorId, // Chiplet instance ID
i_vpdRing ); // The VPD RS4 ring container
if (l_rc == TOR_APPEND_RING_DONE)
{
FAPI_INF("Successfully added VPD ring: (ringId,evenOdd,chipletId)=(0x%02X,0x%X,0x%02X)",
i_ring.ringId, l_evenOdd, l_chipletId);
}
else
{
FAPI_ASSERT( false,
fapi2::XIPC_TOR_APPEND_RING_FAILED().
set_CHIP_TARGET(i_proc_target).
set_TOR_RC(l_rc),
"tor_append_ring() failed w/l_rc=%d",
l_rc );
}
FAPI_DBG("(After tor_append) io_ringSectionSize = %d", io_ringSectionSize);
break;
case SYSPHASE_RT_SGPE:
l_rc = tor_append_ring(
i_ringSection,
io_ringSectionSize, // In: Exact size. Out: Updated size.
i_ringBuf2,
i_ringBufSize2, // Max size.
(RingID)i_ring.ringId,
P9_TOR::SGPE, // We're working on the SGPE image
P9_TOR::ALLRING, // No-care
BASE, // All VPD rings are Base ringVariant
l_chipletTorId, // Chiplet instance ID
i_vpdRing ); // The VPD RS4 ring container
if (l_rc == TOR_APPEND_RING_DONE)
{
FAPI_INF("Successfully added VPD ring: (ringId,evenOdd,chipletId)=(0x%02X,0x%X,0x%02X)",
i_ring.ringId, l_evenOdd, l_chipletId);
}
else
{
FAPI_ASSERT( false,
fapi2::XIPC_TOR_APPEND_RING_FAILED().
set_CHIP_TARGET(i_proc_target).
set_TOR_RC(l_rc),
"tor_append_ring() failed w/l_rc=%d",
l_rc );
}
FAPI_DBG("(After tor_append) io_ringSectionSize = %d", io_ringSectionSize);
break;
default:
FAPI_ASSERT( false,
fapi2::XIPC_INVALID_SYSPHASE_PARM().
set_CHIP_TARGET(i_proc_target).
set_SYSPHASE(i_sysPhase).
set_OCCURRENCE(2),
"Code bug: Unsupported value of sysPhase (=%d)",
i_sysPhase );
break;
} // End switch(sysPhase)
} // End if(redundant)
}
else if (l_fapiRc.isRC(RC_MVPD_RING_NOT_FOUND))
{
// No match, do nothing. Next chipletId.
//@TODO: Uncomment the following after PowerOn. Also, need to come
// to agreement whether this should be fatal error or not.
// For now, for PO, it's considered benigh and noise and is
// being commented out.
//FAPI_INF("_fetch_and_insert_vpd_rings():"
// "(ringId,chipletId)=(0x%X,0x%X) not found.",
// i_ring.ringId, l_chipletId);
fapi2::current_err = fapi2::FAPI2_RC_SUCCESS;
}
else
{
//--------------------------
// Handle other error cases
//--------------------------
// getMvpdRing failed due to insufficient ring buffer space.
// Assumption here is that getMvpdRing returns required buffer size
// in l_vpdRingSize (and which it does!).
FAPI_ASSERT( !l_fapiRc.isRC(RC_MVPD_RING_BUFFER_TOO_SMALL),
fapi2::XIPC_MVPD_RING_SIZE_TOO_BIG().
set_CHIP_TARGET(i_proc_target).
set_RING_ID(i_ring.ringId).
set_CHIPLET_ID(l_chipletId).
set_RING_BUFFER_SIZE(i_vpdRingSize).
set_MVPD_RING_SIZE(l_vpdRingSize),
"_fetch_and_insert_vpd_rings(): VPD ring size (=0x%X) exceeds"
" allowed ring buffer size (=0x%X)",
l_vpdRingSize, i_vpdRingSize );
// getMvpdRing failed due to invalid record data magic word.
FAPI_ASSERT( !l_fapiRc.isRC(RC_MVPD_INVALID_RS4_HEADER),
fapi2::XIPC_MVPD_INVALID_RECORD_DATA().
set_CHIP_TARGET(i_proc_target).
set_RING_ID(i_ring.ringId).
set_CHIPLET_ID(l_chipletId),
"_fetch_and_insert_vpd_rings(): MVPD has invalid record data" );
// getMvpdRing failed for some other reason aside from above handled cases.
if (l_fapiRc != fapi2::FAPI2_RC_SUCCESS)
{
FAPI_ERR("_fetch_and_insert_vpd_rings(): getMvpdRing failed "
" w/rc=0x%08X", (uint64_t)l_fapiRc);
fapi2::current_err = l_fapiRc;
goto fapi_try_exit;
}
} // End if(bSkipRing)
} // Loop on evenOdd
} //Loop on chipletId
fapi_try_exit:
FAPI_DBG("Exiting _fetch_and_insert_vpd_rings");
return fapi2::current_err;
}
// Function: fetch_and_insert_vpd_rings()
//
// Parameter list:
// const fapi::Target &i_target: Processor chip target.
// void* i_ringSection: Ptr to ring section.
// uint32_t& io_ringSectionSize: Running size
// uint32_t i_maxRingSectionSize: Max size
// uint8_t i_sysPhase: ={IPL, RT_CME, RT_SGPE}
// void* i_vpdRing: VPD ring buffer.
// uint32_t i_vpdRingSize: Size of VPD ring buffer.
// void* i_ringBuf2: Ring work buffer.
// uint32_t i_ringBufSize2: Size of ring work buffer.
// uint32_t& io_bootCoreMask: Desired (in) and actual (out) boot cores.
//
fapi2::ReturnCode fetch_and_insert_vpd_rings(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_proc_target,
void* i_ringSection,
uint32_t& io_ringSectionSize, // Running size
uint32_t i_maxRingSectionSize, // Max size
uint8_t i_sysPhase,
void* i_vpdRing,
uint32_t i_vpdRingSize,
void* i_ringBuf2,
uint32_t i_ringBufSize2,
uint32_t& io_bootCoreMask )
{
FAPI_DBG("Entering fetch_and_insert_vpd_rings");
// Walk through all Vpd rings and add any that's there to the image.
// Do this in two steps:
// 1- Add all NEST rings
// 2- Add QUAD rings in EC order
// 1- Add all common rings
for (auto vpdType = 0; vpdType < NUM_OF_VPD_TYPES; vpdType++)
{
const RingIdList* l_ring_id_list = ALL_VPD_RINGS[vpdType].ringIdList;
auto l_ring_id_list_size = ALL_VPD_RINGS[vpdType].ringIdListSize;
for (size_t iRing = 0; iRing < l_ring_id_list_size; iRing++)
{
if (l_ring_id_list[iRing].vpdRingClass != VPD_RING_CLASS_EQ_INS &&
l_ring_id_list[iRing].vpdRingClass != VPD_RING_CLASS_EX_INS &&
l_ring_id_list[iRing].vpdRingClass != VPD_RING_CLASS_EC_INS)
{
FAPI_TRY( _fetch_and_insert_vpd_rings( i_proc_target,
i_ringSection,
io_ringSectionSize,
i_maxRingSectionSize,
i_sysPhase,
i_vpdRing,
i_vpdRingSize,
i_ringBuf2,
i_ringBufSize2,
l_ring_id_list[iRing],
io_bootCoreMask ),
"fetch_and_insert_vpd_rings(): Failed to execute "
"_fetch_and_insert_vpd_rings() w/rc:0x%.8x",
(uint64_t)fapi2::current_err );
FAPI_DBG("(CMN) io_ringSectionSize = %d", io_ringSectionSize);
}
} //Loop on ringId
} //Loop on VPD types
// 2- Add all instance [QUAD-level] rings in EC order - TBD
//@TODO: For now, just add everything though honoring bootCoreMask with
// which we can control any potential overfilling of the image
// by manually ditching cores in bootCoreMask until it fits. For
// the actual VPD ring insertion order effort in RTC158106, we need
// a dual fetch_and_insert_{common,instance}_vpd_rings where the
// common part pretty much is already completed in the above step
// #1. The step #2 instance part needs updating to ditch looping
// over vpdType and instead loop over chipletId to fill up one
// core chipletId "column" at a time (RTC158106).
for (auto vpdType = 0; vpdType < NUM_OF_VPD_TYPES; vpdType++)
{
const RingIdList* l_ring_id_list = ALL_VPD_RINGS[vpdType].ringIdList;
auto l_ring_id_list_size = ALL_VPD_RINGS[vpdType].ringIdListSize;
for (size_t iRing = 0; iRing < l_ring_id_list_size; iRing++)
{
if (l_ring_id_list[iRing].vpdRingClass == VPD_RING_CLASS_EQ_INS ||
l_ring_id_list[iRing].vpdRingClass == VPD_RING_CLASS_EX_INS ||
l_ring_id_list[iRing].vpdRingClass == VPD_RING_CLASS_EC_INS)
{
FAPI_TRY( _fetch_and_insert_vpd_rings( i_proc_target,
i_ringSection,
io_ringSectionSize,
i_maxRingSectionSize,
i_sysPhase,
i_vpdRing,
i_vpdRingSize,
i_ringBuf2,
i_ringBufSize2,
l_ring_id_list[iRing],
io_bootCoreMask ),
"fetch_and_insert_vpd_rings(): Failed to execute "
"_fetch_and_insert_vpd_rings() w/rc:0x%.8x",
(uint64_t)fapi2::current_err );
FAPI_DBG("(INS) io_ringSectionSize = %d", io_ringSectionSize);
} // if (Quad instance ring)
} // Loop on ringId
} //Loop on VPD types
fapi_try_exit:
FAPI_DBG("Exiting fetch_and_insert_vpd_rings");
return fapi2::current_err;
}
fapi2::ReturnCode p9_xip_customize (
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_proc_target,
void* io_image,
uint32_t& io_imageSize, // In: Max, Out: Actual
void* io_ringSectionBuf,
uint32_t& io_ringSectionBufSize, // In: Max, Out: Actual
uint8_t i_sysPhase,
uint8_t i_modeBuild,
void* io_ringBuf1,
uint32_t i_ringBufSize1,
void* io_ringBuf2,
uint32_t i_ringBufSize2,
uint32_t& io_bootCoreMask ) // Bits(8:31) = EC00:EC23
{
fapi2::ReturnCode l_fapiRc = fapi2::FAPI2_RC_SUCCESS;
fapi2::ReturnCode l_fapiRc2 = fapi2::FAPI2_RC_SUCCESS;
int l_rc = 0; // Non-fapi RC
P9XipSection l_xipRingsSection;
uint32_t l_initialImageSize;
uint32_t l_imageSizeWithoutRings;
uint32_t l_maxImageSize, l_imageSize;
uint32_t l_maxRingSectionSize;
uint32_t l_sectionOffset = 1;
uint8_t attrDdLevel = 0;
uint32_t l_requestedBootCoreMask = (i_sysPhase == SYSPHASE_HB_SBE) ? io_bootCoreMask : 0x00FFFFFF;
void* l_hwRingsSection;
FAPI_DBG ("Entering p9_xip_customize w/sysPhase=%d...", i_sysPhase);
io_bootCoreMask = l_requestedBootCoreMask;
//-------------------------------------------
// Check some input buffer parameters:
// - sysPhase, modeBuild are checked later
// - log the initial image size
// - more buffer size checks in big switch()
//-------------------------------------------
FAPI_ASSERT( io_image != NULL &&
io_ringSectionBuf != NULL &&
io_ringBuf1 != NULL &&
io_ringBuf2 != NULL,
fapi2::XIPC_INVALID_INPUT_BUFFER_PARM().
set_CHIP_TARGET(i_proc_target).
set_IMAGE_BUF(io_image).
set_RING_SECTION_BUF(io_ringSectionBuf).
set_RING_BUF1(io_ringBuf1).
set_RING_BUF2(io_ringBuf2),
"One or more invalid input buffer pointers:\n"
" io_image=0x%016llx\n"
" io_ringSectionBuf=0x%016llx\n"
" io_ringBuf1=0x%016llx\n"
" io_ringBuf2=0x%016llx\n",
(uintptr_t)io_image,
(uintptr_t)io_ringSectionBuf,
(uintptr_t)io_ringBuf1,
(uintptr_t)io_ringBuf2 );
l_rc = p9_xip_image_size(io_image, &l_initialImageSize);
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_XIP_API_MISC_ERROR().
set_CHIP_TARGET(i_proc_target).
set_XIP_RC(l_rc).
set_OCCURRENCE(1),
"p9_xip_image_size() failed (1) w/rc=0x%08X",
(uint32_t)l_rc );
FAPI_ASSERT( io_imageSize >= l_initialImageSize &&
io_ringSectionBufSize == MAX_SEEPROM_IMAGE_SIZE &&
i_ringBufSize1 == MAX_RING_BUF_SIZE &&
i_ringBufSize2 == MAX_RING_BUF_SIZE,
fapi2::XIPC_INVALID_INPUT_BUFFER_SIZE_PARM().
set_CHIP_TARGET(i_proc_target).
set_INPUT_IMAGE_SIZE(l_initialImageSize).
set_IMAGE_BUF_SIZE(io_imageSize).
set_RING_SECTION_BUF_SIZE(io_ringSectionBufSize).
set_RING_BUF_SIZE1(i_ringBufSize1).
set_RING_BUF_SIZE2(i_ringBufSize2).
set_OCCURRENCE(1),
"One or more invalid input buffer sizes:\n"
" l_initialImageSize=0x%016llx\n"
" io_imageSize=0x%016llx\n"
" io_ringSectionBufSize=0x%016llx\n"
" i_ringBufSize1=0x%016llx\n"
" i_ringBufSize2=0x%016llx\n",
(uintptr_t)l_initialImageSize,
(uintptr_t)io_imageSize,
(uintptr_t)io_ringSectionBufSize,
(uintptr_t)i_ringBufSize1,
(uintptr_t)i_ringBufSize2 );
FAPI_DBG("Input image size: %d", l_initialImageSize);
///////////////////////////////////////////////////////////////////////////
// CUSTOMIZE item: Write mailbox attributes
// System phase: HB_SBE
///////////////////////////////////////////////////////////////////////////
if (i_sysPhase == SYSPHASE_HB_SBE)
{
FAPI_TRY(writeMboxRegs(i_proc_target, io_image),
"p9_xip_customize: error writing mbox regs in SBE image rc=0x%.8x",
(uint64_t)fapi2::current_err);
FAPI_TRY(writePG(i_proc_target, io_image),
"p9_xip_customize: error writing PG data in SBE image rc=0x%.8x",
(uint64_t)fapi2::current_err);
}
///////////////////////////////////////////////////////////////////////////
// CUSTOMIZE item: Update PIBMEM repair attributes in Seeprom image
// System phase: HB_SBE
///////////////////////////////////////////////////////////////////////////
if (i_sysPhase == SYSPHASE_HB_SBE)
{
uint8_t l_pibmemRepVersion = 0;
uint64_t l_pibmemRepData[4] = {0};
uint32_t l_sizeMvpdFieldExpected = sizeof(l_pibmemRepVersion) + sizeof(l_pibmemRepData);
uint32_t l_sizeMvpdField = 0;
uint8_t* l_bufMvpdField = (uint8_t*)io_ringBuf1;
FAPI_TRY( getMvpdField(MVPD_RECORD_CP00,
MVPD_KEYWORD_PB,
i_proc_target,
NULL,
l_sizeMvpdField),
"getMvpdField(NULL buffer) failed w/rc=0x%08x",
(uint64_t)fapi2::current_err );
FAPI_ASSERT( l_sizeMvpdField == l_sizeMvpdFieldExpected,
fapi2::XIPC_MVPD_FIELD_SIZE_MESS().
set_CHIP_TARGET(i_proc_target).
set_MVPD_FIELD_SIZE(l_sizeMvpdField).
set_EXPECTED_SIZE(l_sizeMvpdFieldExpected),
"MVPD field size bug:\n"
" Returned MVPD field size of PB keyword = %d\n"
" Anticipated MVPD field size = %d",
l_sizeMvpdField,
l_sizeMvpdFieldExpected );
FAPI_TRY( getMvpdField(MVPD_RECORD_CP00,
MVPD_KEYWORD_PB,
i_proc_target,
l_bufMvpdField,
l_sizeMvpdField),
"getMvpdField(valid buffer) failed w/rc=0x%08x",
(uint64_t)fapi2::current_err );
// Copy over the data into suitable 8Byte containers
l_pibmemRepVersion = (uint8_t)(*l_bufMvpdField);
l_pibmemRepData[0] = htobe64( *((uint64_t*)(l_bufMvpdField + 1)) );
l_pibmemRepData[1] = htobe64( *((uint64_t*)(l_bufMvpdField + 1 + 8)) );
l_pibmemRepData[2] = htobe64( *((uint64_t*)(l_bufMvpdField + 1 + 16)) );
l_pibmemRepData[3] = htobe64( *((uint64_t*)(l_bufMvpdField + 1 + 24)) );
FAPI_DBG("Retrieved Mvpd PB keyword field:\n");
FAPI_DBG(" l_pibmemRepVersion = 0x%02x\n"
" l_pibmemRepData[1] = 0x%016llx\n"
" l_pibmemRepData[1] = 0x%016llx\n"
" l_pibmemRepData[2] = 0x%016llx\n"
" l_pibmemRepData[3] = 0x%016llx\n",
l_pibmemRepVersion,
l_pibmemRepData[0],
l_pibmemRepData[1],
l_pibmemRepData[2],
l_pibmemRepData[3]);
FAPI_TRY( p9_xip_set_scalar(io_image, "ATTR_PIBMEM_REPAIR0", l_pibmemRepData[0]),
"p9_xip_set_scalar(ATTR_PIBMEM_REPAIR0) failed w/rc=0x%08x",
(uint64_t)fapi2::current_err );
FAPI_TRY( p9_xip_set_scalar(io_image, "ATTR_PIBMEM_REPAIR1", l_pibmemRepData[1]),
"p9_xip_set_scalar(ATTR_PIBMEM_REPAIR1) failed w/rc=0x%08x",
(uint64_t)fapi2::current_err );
FAPI_TRY( p9_xip_set_scalar(io_image, "ATTR_PIBMEM_REPAIR2", l_pibmemRepData[2]),
"p9_xip_set_scalar(ATTR_PIBMEM_REPAIR2) failed w/rc=0x%08x",
(uint64_t)fapi2::current_err );
}
//////////////////////////////////////////////////////////////////////////
// CUSTOMIZE item: Append VPD rings to ring section
// System phase: All phases
//------------------------------------------------------------------------
// Notes:
// Do some sysPhase specific initial operations:
// - Set max image size
// - Copy image's sysPhase specific [sub-]section into separate ring
// section buffer
// - Delete (IPL sysPhase only) .rings, since we need to append later
//////////////////////////////////////////////////////////////////////////
switch (i_sysPhase)
{
case SYSPHASE_HB_SBE:
FAPI_DBG("Image size before any updates: %d", l_initialImageSize);
FAPI_ASSERT( io_imageSize >= MAX_SEEPROM_IMAGE_SIZE &&
io_ringSectionBufSize == MAX_SEEPROM_IMAGE_SIZE,
fapi2::XIPC_INVALID_INPUT_BUFFER_SIZE_PARM().
set_CHIP_TARGET(i_proc_target).
set_INPUT_IMAGE_SIZE(l_initialImageSize).
set_IMAGE_BUF_SIZE(io_imageSize).
set_RING_SECTION_BUF_SIZE(io_ringSectionBufSize).
set_RING_BUF_SIZE1(i_ringBufSize1).
set_RING_BUF_SIZE2(i_ringBufSize2).
set_OCCURRENCE(2),
"One or more invalid input buffer sizes for SBE:\n"
" MAX_SEEPROM_IMAGE_SIZE=0x%016llx\n"
" io_imageSize=0x%016llx\n"
" io_ringSectionBufSize=0x%016llx\n",
(uintptr_t)MAX_SEEPROM_IMAGE_SIZE,
(uintptr_t)io_imageSize,
(uintptr_t)io_ringSectionBufSize );
l_maxImageSize = MAX_SEEPROM_IMAGE_SIZE;
// Copy, save and delete the .rings section, wherever it is (even if
// not the last section), and re-arrange other sections located above
// the .rings section.
// Keep a copy of the original input image, io_image, in io_ringSectionBuf.
l_rc = p9_xip_delete_section(io_image, io_ringSectionBuf, l_initialImageSize, P9_XIP_SECTION_SBE_RINGS);
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_XIP_API_MISC_ERROR().
set_CHIP_TARGET(i_proc_target).
set_XIP_RC(l_rc).
set_OCCURRENCE(2),
"p9_xip_delete_section() failed removing .rings w/rc=0x%08X",
(uint32_t)l_rc );
// Make a note of the image size without .rings
l_rc = p9_xip_image_size(io_image, &l_imageSizeWithoutRings);
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_XIP_API_MISC_ERROR().
set_CHIP_TARGET(i_proc_target).
set_XIP_RC(l_rc).
set_OCCURRENCE(3),
"p9_xip_image_size() failed (3) w/rc=0x%08X",
(uint32_t)l_rc );
FAPI_DBG("Size of image before VPD update (excl .rings): %d", l_imageSizeWithoutRings);
// Get the size of our .rings section.
l_rc = p9_xip_get_section(io_ringSectionBuf, P9_XIP_SECTION_SBE_RINGS, &l_xipRingsSection);
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_XIP_API_MISC_ERROR().
set_CHIP_TARGET(i_proc_target).
set_XIP_RC(l_rc).
set_OCCURRENCE(4),
"p9_xip_get_section() failed (4) getting .rings section w/rc=0x%08X",
(uint32_t)l_rc );
io_ringSectionBufSize = l_xipRingsSection.iv_size;
FAPI_ASSERT( io_ringSectionBufSize > 0,
fapi2::XIPC_EMPTY_RING_SECTION().
set_CHIP_TARGET(i_proc_target),
"Ring section size in SBE image is zero. No TOR. Can't append rings.");
FAPI_DBG("Size of .rings section before VPD update: %d", io_ringSectionBufSize);
l_maxRingSectionSize = l_maxImageSize - l_imageSizeWithoutRings;
FAPI_DBG("Max allowable size of .rings section: %d", l_maxRingSectionSize);
// Move .rings to the top of ringSectionBuf (which currently holds a copy of the
// io_image but which can now be destroyed.)
memcpy( io_ringSectionBuf,
(void*)(((uint8_t*)io_ringSectionBuf) + l_xipRingsSection.iv_offset),
io_ringSectionBufSize );
//----------------------------------------
// Append VPD Rings to the .rings section
//----------------------------------------
l_fapiRc = fetch_and_insert_vpd_rings( i_proc_target,
io_ringSectionBuf,
io_ringSectionBufSize, // Running section size
l_maxRingSectionSize, // Max section size
i_sysPhase,
io_ringBuf1,
i_ringBufSize1,
io_ringBuf2,
i_ringBufSize2,
io_bootCoreMask );
FAPI_DBG("bootCoreMask: Requested=0x%08X Final=0x%08X",
l_requestedBootCoreMask, io_bootCoreMask);
if (l_fapiRc)
{
if (l_fapiRc.isRC(RC_XIPC_IMAGE_WOULD_OVERFLOW))
{
FAPI_INF("p9_xip_customize(): Image is full. Ran out of space appending VPD rings"
" to the .rings section");
// Check the bootCoreMask to determine if enough cores have been configured.
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
uint8_t attrMinReqdEcs = 0;
uint8_t l_actualEcCount = 0;
l_fapiRc2 = FAPI_ATTR_GET(fapi2::ATTR_SBE_IMAGE_MINIMUM_VALID_ECS, FAPI_SYSTEM, attrMinReqdEcs);
FAPI_ASSERT( l_fapiRc2.isRC(fapi2::FAPI2_RC_SUCCESS),
fapi2::XIPC_IMAGE_WOULD_OVERFLOW_ADDL_INFO().
set_CHIP_TARGET(i_proc_target).
set_REQUESTED_BOOT_CORE_MASK(l_requestedBootCoreMask).
set_CURRENT_BOOT_CORE_MASK(io_bootCoreMask),
"FAPI_ATTR_GET(ATTR_SBE_IMAGE_MINIMUM_VALID_ECS) failed."
" Unable to determine ATTR_SBE_IMAGE_MINIMUM_VALID_ECS,"
" so don't know if the minimum core set was met." );
FAPI_DBG("attrMinReqdEcs = 0x%x", attrMinReqdEcs);
// Count number of ECs set in bootCoreMask
l_actualEcCount = 0;
for (uint8_t iCore = 0; iCore < NUM_OF_CORES; iCore++)
{
if (io_bootCoreMask & ((0x00000001 << (NUM_OF_CORES - 1)) >> iCore))
{
l_actualEcCount++;
}
}
FAPI_ASSERT( l_actualEcCount >= attrMinReqdEcs,
fapi2::XIPC_IMAGE_WOULD_OVERFLOW_BEFORE_REACHING_MIN_ECS().
set_CHIP_TARGET(i_proc_target).
set_REQUESTED_BOOT_CORE_MASK(l_requestedBootCoreMask).
set_CURRENT_BOOT_CORE_MASK(io_bootCoreMask).
set_MIN_REQD_ECS(attrMinReqdEcs).
set_ACTUAL_EC_COUNT(l_actualEcCount),
"Image buffer would overflow before reaching the minimum required"
" number of EC boot cores" );
FAPI_INF( "Image is full and with sufficient boot cores:\n"
" Final bootCoreMask: 0x%08X\n"
" Number of boot cores: %d\n"
" Min req'd boot cores: %d",
io_bootCoreMask, l_actualEcCount, attrMinReqdEcs );
l_fapiRc = fapi2::FAPI2_RC_SUCCESS;
}
fapi2::current_err = l_fapiRc;
goto fapi_try_exit;
}
// More size code sanity checks of section and image sizes.
FAPI_ASSERT( io_ringSectionBufSize <= l_maxRingSectionSize,
fapi2::XIPC_SECTION_SIZING().
set_CHIP_TARGET(i_proc_target).
set_RING_SECTION_SIZE(io_ringSectionBufSize).
set_MAX_RING_SECTION_SIZE(l_maxRingSectionSize),
"Code bug: ringSectionBufSize>maxRingSectionSize" );
FAPI_ASSERT( (l_imageSizeWithoutRings + io_ringSectionBufSize) <= l_maxImageSize,
fapi2::XIPC_IMAGE_SIZING().
set_CHIP_TARGET(i_proc_target).
set_IMAGE_SIZE_WITHOUT_RINGS(l_imageSizeWithoutRings).
set_RING_SECTION_SIZE(io_ringSectionBufSize).
set_MAX_IMAGE_SIZE(l_maxImageSize),
"Code bug: imageSize would exceed maxImageSize" );
FAPI_DBG( "Image details: io_ringSectionBufSize=%d l_imageSizeWithoutRings=%d l_maxImageSize=%d",
io_ringSectionBufSize, l_imageSizeWithoutRings, l_maxImageSize );
//--------------------------------------------------------
// Append the updated .rings section to the Seeprom image
//--------------------------------------------------------
l_rc = p9_xip_append( io_image,
P9_XIP_SECTION_SBE_RINGS,
io_ringSectionBuf,
(const uint32_t)io_ringSectionBufSize,
(const uint32_t)l_maxImageSize,
&l_sectionOffset );
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_XIP_API_MISC_ERROR().
set_CHIP_TARGET(i_proc_target).
set_XIP_RC(l_rc).
set_OCCURRENCE(5),
"p9_xip_append() failed w/rc=0x%08x",
(uint32_t)l_rc );
FAPI_DBG("sectionOffset=0x%08X", l_sectionOffset);
l_rc = p9_xip_image_size(io_image, &l_imageSize);
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_XIP_API_MISC_ERROR().
set_CHIP_TARGET(i_proc_target).
set_XIP_RC(l_rc).
set_OCCURRENCE(6),
"p9_xip_image_size() failed (6) w/rc=0x%08X",
(uint32_t)l_rc );
FAPI_DBG( "Seeprom image size after VPD updates: %d", l_imageSize );
FAPI_ASSERT( l_imageSize <= l_maxImageSize,
fapi2::XIPC_IMAGE_TOO_LARGE().
set_CHIP_TARGET(i_proc_target).
set_IMAGE_SIZE(l_imageSize).
set_MAX_IMAGE_SIZE(l_maxImageSize).
set_OCCURRENCE(1),
"Seeprom image size after VPD updates (=%d) exceeds max image size (=%d)",
l_imageSize, l_maxImageSize );
break;
case SYSPHASE_RT_CME:
case SYSPHASE_RT_SGPE:
FAPI_ASSERT( io_imageSize == l_initialImageSize &&
io_ringSectionBufSize == MAX_SEEPROM_IMAGE_SIZE,
fapi2::XIPC_INVALID_INPUT_BUFFER_SIZE_PARM().
set_CHIP_TARGET(i_proc_target).
set_INPUT_IMAGE_SIZE(l_initialImageSize).
set_IMAGE_BUF_SIZE(io_imageSize).
set_RING_SECTION_BUF_SIZE(io_ringSectionBufSize).
set_RING_BUF_SIZE1(i_ringBufSize1).
set_RING_BUF_SIZE2(i_ringBufSize2).
set_OCCURRENCE(3),
"One or more invalid input buffer sizes for CME or SGPE:\n"
" l_initialImageSize=0x%016llx\n"
" io_imageSize=0x%016llx\n"
" io_ringSectionBufSize=0x%016llx\n",
(uintptr_t)l_initialImageSize,
(uintptr_t)io_imageSize,
(uintptr_t)io_ringSectionBufSize );
l_maxRingSectionSize = io_ringSectionBufSize;
// Calculate pointer to HW image's .rings section
l_rc = p9_xip_get_section(io_image, P9_XIP_SECTION_HW_RINGS, &l_xipRingsSection);
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_XIP_API_MISC_ERROR().
set_CHIP_TARGET(i_proc_target).
set_XIP_RC(l_rc).
set_OCCURRENCE(7),
"p9_xip_get_section() failed (7) getting .rings section w/rc=0x%08X",
(uint32_t)l_rc );
FAPI_ASSERT( l_xipRingsSection.iv_size > 0,
fapi2::XIPC_EMPTY_RING_SECTION().
set_CHIP_TARGET(i_proc_target),
"CME or SGPE ring section size is zero (sysPhase=%d). No TOR. Can't append rings.",
i_sysPhase );
l_hwRingsSection = (void*)((uintptr_t)io_image + l_xipRingsSection.iv_offset);
// Extract the DD level to enable retrieval of correct CME/SGPE ring blocks
l_fapiRc = FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, i_proc_target, attrDdLevel);
FAPI_ASSERT( l_fapiRc.isRC(fapi2::FAPI2_RC_SUCCESS),
fapi2::XIPC_FAPI_ATTR_SVC_FAIL().
set_CHIP_TARGET(i_proc_target).
set_OCCURRENCE(1),
"FAPI_ATTR_GET(ATTR_EC) failed." );
FAPI_DBG("attrDdLevel = 0x%x", attrDdLevel);
//------------------------------------------------------------
// Get the CME or SGPE block of rings from .rings in HW image
//------------------------------------------------------------
if ( i_sysPhase == SYSPHASE_RT_CME )
{
FAPI_DBG("Getting the CME block of rings from HW image");
l_rc = tor_get_block_of_rings( l_hwRingsSection,
attrDdLevel,
P9_TOR::CME,
P9_TOR::ALLRING,
BASE,
0,
&io_ringSectionBuf,
io_ringSectionBufSize );
}
else
{
FAPI_DBG("Getting the SGPE block of rings from HW image");
l_rc = tor_get_block_of_rings( l_hwRingsSection,
attrDdLevel,
P9_TOR::SGPE,
P9_TOR::ALLRING,
BASE,
0,
&io_ringSectionBuf,
io_ringSectionBufSize );
}
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_TOR_GET_BLOCK_OF_RINGS_FAILED().
set_CHIP_TARGET(i_proc_target).
set_TOR_RC(l_rc).
set_SYSPHASE(i_sysPhase),
"tor_get_block_of_rings() failed w/rc=0x%08X",
(uint32_t)l_rc );
FAPI_DBG("Size of .rings section before VPD update: %d", io_ringSectionBufSize);
//----------------------------------------
// Append VPD Rings to the .rings section
//----------------------------------------
l_fapiRc = fetch_and_insert_vpd_rings( i_proc_target,
io_ringSectionBuf,
io_ringSectionBufSize, // Running section size
l_maxRingSectionSize, // Max section size
i_sysPhase,
io_ringBuf1,
i_ringBufSize1,
io_ringBuf2,
i_ringBufSize2,
io_bootCoreMask );
FAPI_DBG("Size of .rings section after VPD update: %d", io_ringSectionBufSize );
FAPI_DBG("bootCoreMask: Requested=0x%08X Final=0x%08X",
l_requestedBootCoreMask, io_bootCoreMask);
if (l_fapiRc)
{
FAPI_ASSERT( !l_fapiRc.isRC(RC_XIPC_IMAGE_WOULD_OVERFLOW),
fapi2::XIPC_IMAGE_WOULD_OVERFLOW_BEFORE_REACHING_MIN_ECS().
set_CHIP_TARGET(i_proc_target).
set_REQUESTED_BOOT_CORE_MASK(l_requestedBootCoreMask).
set_CURRENT_BOOT_CORE_MASK(io_bootCoreMask),
"Ran out of space appending VPD rings to the .rings section" );
fapi2::current_err = l_fapiRc;
goto fapi_try_exit;
}
// More size code sanity checks of section and image sizes.
FAPI_ASSERT( io_ringSectionBufSize <= l_maxRingSectionSize,
fapi2::XIPC_SECTION_SIZING().
set_CHIP_TARGET(i_proc_target).
set_RING_SECTION_SIZE(io_ringSectionBufSize).
set_MAX_RING_SECTION_SIZE(l_maxRingSectionSize),
"Code bug: ringSectionBufSize>maxRingSectionSize" );
break;
default:
FAPI_ASSERT( false,
fapi2::XIPC_INVALID_SYSPHASE_PARM().
set_CHIP_TARGET(i_proc_target).
set_SYSPHASE(i_sysPhase).
set_OCCURRENCE(1),
"Caller bug: Caller supplied unsupported value of sysPhase (=%d)",
i_sysPhase );
break;
}
///////////////////////////////////////////////////////////////////////////
// CUSTOMIZE item: Removal of .toc, .fixed_toc and .strings
// System phase: HB_SBE
///////////////////////////////////////////////////////////////////////////
if (i_sysPhase == SYSPHASE_HB_SBE)
{
// Remove .toc:
// This will remove external visibility to image's attributes and other global variables.
l_rc = p9_xip_delete_section(io_image, io_ringSectionBuf, l_imageSize, P9_XIP_SECTION_TOC);
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_SECTION_REMOVAL_ERROR().
set_CHIP_TARGET(i_proc_target).
set_XIP_SECTION(P9_XIP_SECTION_TOC),
"p9_xip_delete_section() failed to remove .toc section w/rc=0x%08X",
(uint32_t)l_rc );
// Remove .fixedtoc:
l_rc = p9_xip_delete_section(io_image, io_ringSectionBuf, l_imageSize, P9_XIP_SECTION_FIXED_TOC);
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_SECTION_REMOVAL_ERROR().
set_CHIP_TARGET(i_proc_target).
set_XIP_SECTION(P9_XIP_SECTION_FIXED_TOC),
"p9_xip_delete_section() failed to remove .fixedtoc section w/rc=0x%08X",
(uint32_t)l_rc );
// Remove .strings:
// The .strings section must be removed after .toc and .fixed_toc. Otherwise
// we get an P9_XIP_TOC_ERROR, probably because either of those two sections
// will "complain" on the next XIP API access that info they need in .strings
// is missing, i.e. as part of p9_xip_validate_image().
l_rc = p9_xip_delete_section(io_image, io_ringSectionBuf, l_imageSize, P9_XIP_SECTION_STRINGS);
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_SECTION_REMOVAL_ERROR().
set_CHIP_TARGET(i_proc_target).
set_XIP_SECTION(P9_XIP_SECTION_STRINGS),
"p9_xip_delete_section() failed to remove .fixedtoc section w/rc=0x%08X",
(uint32_t)l_rc );
// Check the image size.
l_rc = p9_xip_image_size(io_image, &l_imageSize);
FAPI_ASSERT( l_rc == 0,
fapi2::XIPC_XIP_API_MISC_ERROR().
set_CHIP_TARGET(i_proc_target).
set_XIP_RC(l_rc).
set_OCCURRENCE(8),
"p9_xip_image_size() failed (7) w/rc=0x%08X",
(uint32_t)l_rc );
FAPI_DBG("Image size after section removals: %d", l_imageSize);
FAPI_ASSERT( l_imageSize <= l_maxImageSize,
fapi2::XIPC_IMAGE_TOO_LARGE().
set_CHIP_TARGET(i_proc_target).
set_IMAGE_SIZE(l_imageSize).
set_MAX_IMAGE_SIZE(l_maxImageSize).
set_OCCURRENCE(2),
"Final Seeprom image size (=%d) exceeds max image size (=%d)",
l_imageSize, l_maxImageSize );
}
///////////////////////////////////////////////////////////////////////////
// Other customizations
///////////////////////////////////////////////////////////////////////////
// TBD
///////////////////////////////////////////////////////////////////////////
// Done
///////////////////////////////////////////////////////////////////////////
if (i_sysPhase == SYSPHASE_HB_SBE)
{
io_imageSize = l_imageSize;
FAPI_DBG("Final customized Seeprom image size: %d", io_imageSize);
}
FAPI_DBG("Final customized .rings section size: %d", io_ringSectionBufSize);
fapi_try_exit:
FAPI_DBG("Exiting p9_xip_customize");
return fapi2::current_err;
}
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/lib/p9_hcode_image_defines.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef __HW_IMG_DEFINE
#define __HW_IMG_DEFINE
///
/// @file p9_hcode_image_defines.H
/// @brief defines constants associated with hcode image build.
///
// *HWP HWP Owner: Greg Still <stillgs@us.ibm.com>
// *HWP FW Owner: Prem S Jha <premjha2@in.ibm.com>
// *HWP Team: PM
// *HWP Level: 2
// *HWP Consumed by: Hostboot: Phyp
//--------------------------------------------------------------------------
// local structs and constants
// -------------------------------------------------------------------------
#ifndef __ASSEMBLER__
#ifndef __PPE_PLAT
namespace p9_hcodeImageBuild
{
#endif //__PPE_PLAT
/**
* @brief summarizes constants associated with hcode image build.
*/
enum
{
ONE_KB = 1024,
ONE_MB = 1024 * 1024,
HARDWARE_IMG_SIZE = ONE_MB,
OCC_HOST_AREA_SIZE = ONE_MB,
MAX_CORES_PER_CHIP = 24,
PAD_OPCODE = 0x00000200, //ATTN Opcode
PPE_RESERVE_AREA = 0x200,
QPMR_HEADER_SIZE = 0x00000200,
SGPE_LVL_1_BOOT_LOAD_SIZE = ONE_KB,
SGPE_LVL_2_BOOT_LOAD_SIZE = ONE_KB,
SGPE_INT_VECT = 384,
SGPE_IMG_HEADER = 64,
SGPE_DBG_PTR_AREA_SIZE = 64,
CME_HCODE_REL_OFFSET = (SGPE_INT_VECT +
SGPE_IMG_HEADER +
SGPE_DBG_PTR_AREA_SIZE),
SGPE_HCODE_SIZE = 30 * ONE_KB,
SGPE_COMMON_RING = 2 * ONE_KB,
CACHE_SCOM_RESTORE_SIZE = 6 * ONE_KB,
CACHE_INST_SPECIFIC_SIZE = 4 * ONE_KB,
MAX_CACHE_CHIPLET = 6,
SGPE_MAX_AREA_SIZE = 64 * ONE_KB,
CPMR_HEADER_SIZE = 256,
THREAD_LAUNCHER_SIZE = 256,
CORE_INT_AREA = 8 * ONE_KB,
SELF_REST_SIZE = CORE_INT_AREA + THREAD_LAUNCHER_SIZE,
CORE_RESTORE_SIZE = 192 * ONE_KB,
CORE_SCOM_RES_SIZE = 6 * ONE_KB,
CME_INT_VECTOR = 384,
CME_IMG_HEADER = 64,
CME_DBG_PTR_AREA_SIZE = 64,
CME_HCODE_SIZE = 20 * ONE_KB,
CORE_COMMON_RING_SIZE = 6 * ONE_KB,
QUAD_PSTATE_SIZE = 2 * ONE_KB,
CORE_SPECIFIC_RING = 2 * ONE_KB,
CORE_SCOM_START = 256 * ONE_KB,
CORE_RESERVE_SIZE =
CORE_SCOM_START - ( CORE_RESTORE_SIZE + CORE_INT_AREA +
CME_HCODE_SIZE + CORE_COMMON_RING_SIZE +
QUAD_PSTATE_SIZE + CME_IMG_HEADER ),
CME_REGION_START = CORE_SCOM_START + CORE_SCOM_RES_SIZE,
CME_INST_SPEC_RING_START = (300 * ONE_KB ) , // offset from CPMR
RESERVE_CME_RING_AREA = ( CME_INST_SPEC_RING_START - ( CME_REGION_START +
PPE_RESERVE_AREA +
CME_HCODE_SIZE +
CORE_COMMON_RING_SIZE +
QUAD_PSTATE_SIZE)),
PGPE_LVL_1_BOOT_LOAD_SIZE = ONE_KB,
PGPE_LVL_2_BOOT_LOAD_SIZE = ONE_KB,
PGPE_IMG_HEADER = 64, // need to get confirmation on this
PGPE_HCODE_INT_VECT = 384,
PGPE_HCODE_SIZE = 16 * ONE_KB,
PGPE_PARAM_BLOCK_SIZE = 8 * ONE_KB,
PSTATE_OUTPUT_TABLE = 8 * ONE_KB,
FUSE_STATE = 0xAA,
UNFUSE_STATE = 0xBB,
CME_BLOCK_READ_LEN = 32,
CACHE_SCOM_START = 128 * ONE_KB,
CPMR_MAGIC_WORD = 0x484F4D4552312E30ll,
CME_BLK_SIZE_SHIFT = 0x05,
};
/**
* @brief enumerates all return codes associated with hcode image build.
*/
enum ImgBldRetCode_t
{
IMG_BUILD_SUCCESS = 0,
BUILD_FAIL_SGPE_IMAGE = 1,
BUILD_FAIL_SELF_REST_IMAGE = 2,
BUILD_FAIL_CME_IMAGE = 3,
BUILD_FAIL_PGPE_IMAGE = 4,
BUILD_FAIL_SGPE_QPMR = 5,
BUILD_FAIL_SGPE_BL1 = 6,
BUILD_FAIL_SGPE_BL2 = 7,
BUILD_FAIL_SGPE_INT_VECT = 8,
BUILD_FAIL_SGPE_HDR = 9,
BUILD_FAIL_SGPE_HCODE = 10,
BUILD_FAIL_SGPE_CMN_RINGS = 11,
BUILD_FAIL_SGPE_SPEC_RINGS = 12,
BUILD_FAIL_P9_CPMR_HDR = 13,
BUILD_FAIL_P9_SRESET_HNDLR = 14,
BUILD_FAIL_P9_THRD_LAUNCHER = 15,
BUILD_FAIL_P9_SPR_RESTORE = 16,
BUILD_FAIL_P9_SCOM_RESTORE = 17,
BUILD_FAIL_CME_IMG_HDR = 18,
BUILD_FAIL_CME_HCODE = 19,
BUILD_FAIL_CME_CMN_RINGS = 20,
BUILD_FAIL_CME_QUAD_PSTATE = 21,
BUILD_FAIL_CME_SPEC_RINGS = 22,
BUILD_FAIL_CME_INT_VECT = 23,
};
/**
* @brief models image section of SGPE in HOMER.
*/
typedef struct
{
uint8_t qpmrHeader[QPMR_HEADER_SIZE];
uint8_t l1BootLoader[SGPE_LVL_1_BOOT_LOAD_SIZE];
uint8_t l2BootLoader[SGPE_LVL_2_BOOT_LOAD_SIZE];
uint8_t hcodeIntVect[SGPE_INT_VECT];
uint8_t imgHeader[SGPE_IMG_HEADER];
uint8_t debugPtrArea[SGPE_DBG_PTR_AREA_SIZE];
uint8_t hcode[SGPE_HCODE_SIZE];
uint8_t commonRings[SGPE_COMMON_RING];
uint8_t cacheSpecificRing[MAX_CACHE_CHIPLET][CACHE_INST_SPECIFIC_SIZE];
} SgpeLayout_t;
/**
* @brief models image section associated with core self restore in HOMER.
*/
typedef struct
{
uint8_t selfRestoreArea[SELF_REST_SIZE];
uint8_t coreSelfRestore[CORE_RESTORE_SIZE];
uint8_t reserve[CORE_SCOM_START - (SELF_REST_SIZE + CORE_RESTORE_SIZE)];
uint8_t coreScom[CORE_SCOM_RES_SIZE];
} SelfRestoreLayout_t;
typedef struct
{
uint8_t cmeIntVector[CME_INT_VECTOR];
uint8_t imgHeader[CME_IMG_HEADER];
uint8_t debugPtrArea[CME_DBG_PTR_AREA_SIZE];
uint8_t hcode[CME_HCODE_SIZE];
uint8_t commonRings[CORE_COMMON_RING_SIZE];
uint8_t quadPstateArea[QUAD_PSTATE_SIZE];
uint8_t resvRingArea[RESERVE_CME_RING_AREA];
uint8_t instSpecificRing[MAX_CORES_PER_CHIP][CORE_SPECIFIC_RING]; // 300KB offset from CPMR
} CmeRegionLayout_t;
/**
* @brief models image section associated with core self restore in HOMER.
*/
typedef struct
{
uint8_t l1BootLoader[PGPE_LVL_1_BOOT_LOAD_SIZE];
uint8_t l2BootLoader[PGPE_LVL_2_BOOT_LOAD_SIZE];
uint8_t pgpeIntVector[PGPE_HCODE_INT_VECT];
uint8_t imgHeader[PGPE_IMG_HEADER];
uint8_t hcode[PGPE_HCODE_SIZE];
uint8_t paramBlock[PGPE_PARAM_BLOCK_SIZE];
uint8_t pstateOutputTable[PSTATE_OUTPUT_TABLE];
} PgpeLayout_t;
/**
* @brief models CME image header in HOMER.
*/
typedef struct
{
uint64_t magicNumber;
uint32_t buildDate;
uint32_t buildVer;
uint32_t hcodeOffset;
uint32_t hcodeLength;
uint32_t commonRingOffset;
uint32_t commonRingLength;
uint32_t pStateOffset;
uint32_t pStateLength;
uint32_t coreSpecificRingOffset;;
uint32_t coreSpecificRingLength;
uint32_t cmeMode;
uint8_t reserve[12];
} CmeImageHeader_t;
/**
* @brief models SGPE image header in HOMER.
*/
struct SgpeImageHeader_t
{
uint64_t magicNumber;
uint32_t sysResetAddr;
uint32_t reserve1;
uint32_t ivprAddress;
uint32_t reserve2;
uint32_t buildDate;
uint32_t buildVer;
uint64_t reserveFlag;
uint32_t quadCmnRingOccOffset;
uint32_t quadSpecRingOccOffset;
uint32_t quadCommonScomOccOffset;
uint8_t reserve3[12];
};
/**
* @brief models layout of HOMER.
*/
struct Homerlayout_t
{
uint8_t occHostArea[OCC_HOST_AREA_SIZE];
SgpeLayout_t sgpeRegion;
uint8_t sgpeReserve1[CACHE_SCOM_START - sizeof(SgpeLayout_t)];
uint8_t cacheScomRegion[CACHE_SCOM_RESTORE_SIZE];
uint8_t sgpeReserve2[ONE_MB - (CACHE_SCOM_START + CACHE_SCOM_RESTORE_SIZE )];
SelfRestoreLayout_t selfRestoreRegion;
CmeRegionLayout_t cmeRegion;
uint8_t cmeReserve[ONE_MB - (sizeof( CmeRegionLayout_t ) + sizeof( SelfRestoreLayout_t ))];
PgpeLayout_t pgpeRegion;
uint8_t pgpeReserve[ONE_MB - sizeof( PgpeLayout_t )];
};
/*************************** compilation issue fix starts here ***************/
//FIXME to be removed once Martin's commit is merged.
#define P9_XIP_MAGIC 0x58495020 // "XIP "
#define P9_XIP_MAGIC_BASE ULL(0x5849502042415345) // "XIP BASE"
#define P9_XIP_MAGIC_SEEPROM ULL(0x584950205345504d) // "XIP SEPM"
#define P9_XIP_MAGIC_CENTAUR ULL(0x58495020434e5452) // "XIP CNTR"
#define P9_XIP_MAGIC_HW ULL(0x5849502020204857) // "XIP HW"
#define P9_XIP_MAGIC_SGPE ULL(0x5849502053475045) // "XIP SGPE"
#define P9_XIP_MAGIC_RESTORE ULL(0x5849502052455354) // "XIP REST"
#define P9_XIP_MAGIC_CME ULL(0x5849502020434d45) // "XIP CME"
#define P9_XIP_MAGIC_PGPE ULL(0x5849502050475045) // "XIP PGPE"
#define P9_XIP_MAGIC_IOPPE ULL(0x5849502049505045) // "XIP IPPE"
#define P9_XIP_MAGIC_FPPE ULL(0x5849502046505045) // "XIP FPPE"
#define P9_XIP_SECTIONS_PLUS(sectionId) \
(sectionId + 4)
typedef enum
{
P9_XIP_SECTION_HW_SGPE = P9_XIP_SECTIONS_PLUS(0),
P9_XIP_SECTION_HW_RESTORE = P9_XIP_SECTIONS_PLUS(1),
P9_XIP_SECTION_HW_CME = P9_XIP_SECTIONS_PLUS(2),
P9_XIP_SECTION_HW_PGPE = P9_XIP_SECTIONS_PLUS(3),
P9_XIP_SECTION_HW_IOPPE = P9_XIP_SECTIONS_PLUS(4),
P9_XIP_SECTION_HW_FPPE = P9_XIP_SECTIONS_PLUS(5),
P9_XIP_SECTION_HW_OVERRIDES = P9_XIP_SECTIONS_PLUS(6),
P9_XIP_SECTION_HW_RINGS = P9_XIP_SECTIONS_PLUS(7),
P9_XIP_SECTIONS_HW = P9_XIP_SECTIONS_PLUS(8) // # sections
} p9_xip_section_hw_t;
typedef enum
{
P9_XIP_SECTION_SGPE_QPMR = P9_XIP_SECTIONS_PLUS(0),
P9_XIP_SECTION_SGPE_LVL1_BL = P9_XIP_SECTIONS_PLUS(1),
P9_XIP_SECTION_SGPE_LVL2_BL = P9_XIP_SECTIONS_PLUS(2),
P9_XIP_SECTION_SGPE_INT_VECT = P9_XIP_SECTIONS_PLUS(3),
P9_XIP_SECTION_SGPE_IMG_HDR = P9_XIP_SECTIONS_PLUS(4),
P9_XIP_SECTION_SGPE_HCODE = P9_XIP_SECTIONS_PLUS(5),
P9_XIP_SECTIONS_SGPE = P9_XIP_SECTIONS_PLUS(6) // # sections
} p9_xip_section_sgpe_t;
typedef enum
{
P9_XIP_SECTION_RESTORE_CPMR = P9_XIP_SECTIONS_PLUS(0),
P9_XIP_SECTION_RESTORE_SELF = P9_XIP_SECTIONS_PLUS(1),
P9_XIP_SECTION_RESTORE_SPR = P9_XIP_SECTIONS_PLUS(2),
P9_XIP_SECTION_RESTORE_SCOM = P9_XIP_SECTIONS_PLUS(3),
P9_XIP_SECTIONS_RESTORE = P9_XIP_SECTIONS_PLUS(4) // # sections
} p9_xip_section_restore_t;
typedef enum
{
P9_XIP_SECTION_CME_INT_VECT = P9_XIP_SECTIONS_PLUS(0),
P9_XIP_SECTION_CME_IMG_HDR = P9_XIP_SECTIONS_PLUS(1),
P9_XIP_SECTION_CME_HCODE = P9_XIP_SECTIONS_PLUS(2),
P9_XIP_SECTION_CME_CMN_RING = P9_XIP_SECTIONS_PLUS(3),
P9_XIP_SECTION_CME_SPEC_RING = P9_XIP_SECTIONS_PLUS(4),
P9_XIP_SECTIONS_CME = P9_XIP_SECTIONS_PLUS(5) // # sections
} p9_xip_section_cme_t;
typedef enum
{
P9_XIP_SECTION_PGPE_LVL1_BL = P9_XIP_SECTIONS_PLUS(0),
P9_XIP_SECTION_PGPE_LVL2_BL = P9_XIP_SECTIONS_PLUS(1),
P9_XIP_SECTION_PGPE_INT_VECT = P9_XIP_SECTIONS_PLUS(2),
P9_XIP_SECTION_PGPE_IMG_HDR = P9_XIP_SECTIONS_PLUS(3),
P9_XIP_SECTION_PGPE_HCODE = P9_XIP_SECTIONS_PLUS(4),
P9_XIP_SECTIONS_PGPE = P9_XIP_SECTIONS_PLUS(5) // # sections
} p9_xip_section_pgpe_t;
/*************************** compilation issue fix ends here ***************/
#ifndef __PPE_PLAT
}// namespace p9_hcodeImageBuild ends
#endif //__PPE_PLAT
#endif //__ASSEMBLER__
/**
* @brief models QPMR header in HOMER
*/
#ifdef __ASSEMBLER__
#define DEF_MEM_QPMR_UINT64( member )\
member: \
.quad 0
#else
#define DEF_MEM_QPMR_UINT64( member ) uint64_t member;
#endif
#ifdef __ASSEMBLER__
#define DEF_MEM_QPMR_UINT32( member )\
member: \
.long 0
#else
#define DEF_MEM_QPMR_UINT32( member ) uint32_t member;
#endif
#ifdef __ASSEMBLER__
.section ".qpmr" , "aw"
.balign 8
#else
#ifndef __PPE_PLAT
namespace p9_hcodeImageBuild
{
#endif //__PPE_PLAT
struct QpmrHeaderLayout_t
{
#endif
DEF_MEM_QPMR_UINT64( magicNumber )
DEF_MEM_QPMR_UINT32( bootCopierOffset ) // level 1 boot loader
DEF_MEM_QPMR_UINT32( reserve1 )
DEF_MEM_QPMR_UINT32( bootLoaderOffset ) // level 2 boot loader
DEF_MEM_QPMR_UINT32( bootLoaderLength )
DEF_MEM_QPMR_UINT32( buildDate )
DEF_MEM_QPMR_UINT32( buildVersion )
DEF_MEM_QPMR_UINT64( reservedFlags )
DEF_MEM_QPMR_UINT32( sgpeImgOffset )
DEF_MEM_QPMR_UINT32( sgpeImgLength )
DEF_MEM_QPMR_UINT32( quadCmnRingOffset )
DEF_MEM_QPMR_UINT32( quadCmnRingLength )
DEF_MEM_QPMR_UINT32( quadSpecRingOffset )
DEF_MEM_QPMR_UINT32( quadSpecRingLength )
DEF_MEM_QPMR_UINT32( quadSpecScomOffset )
DEF_MEM_QPMR_UINT32( quadSpecScomLength )
DEF_MEM_QPMR_UINT32( quadCmnRingOccOffset )
DEF_MEM_QPMR_UINT32( quadSpecRingOccOffset )
DEF_MEM_QPMR_UINT32( quadCmnScomOccOffset )
#ifndef __ASSEMBLER__
};
#ifndef __PPE_PLAT
} // p9_hcodeImageBuild ends
#endif //__PPE_PLAT
#endif
#endif
P9-XIP: enhanced section table layout and HW Image
This enhances the section table layout in order to allow
nesting of images, as needed for the Hardware Image.
Change-Id: I19fe69487a6ef788072af9dc1a88d8baf0d6744b
Original-Change-Id: I259aabe1b292d0de92a61635583e2cc3b535df8d
Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/10598
Tested-by: PPE CI
Tested-by: Jenkins Server
Tested-by: Hostboot CI
Reviewed-by: Martin Peschke <4c516a35580133f593dfe866810ac6bfbd5b0dba@de.ibm.com>
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/lib/p9_hcode_image_defines.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef __HW_IMG_DEFINE
#define __HW_IMG_DEFINE
///
/// @file p9_hcode_image_defines.H
/// @brief defines constants associated with hcode image build.
///
// *HWP HWP Owner: Greg Still <stillgs@us.ibm.com>
// *HWP FW Owner: Prem S Jha <premjha2@in.ibm.com>
// *HWP Team: PM
// *HWP Level: 2
// *HWP Consumed by: Hostboot: Phyp
//--------------------------------------------------------------------------
// local structs and constants
// -------------------------------------------------------------------------
#ifndef __ASSEMBLER__
#ifndef __PPE_PLAT
namespace p9_hcodeImageBuild
{
#endif //__PPE_PLAT
/**
* @brief summarizes constants associated with hcode image build.
*/
enum
{
ONE_KB = 1024,
ONE_MB = 1024 * 1024,
HARDWARE_IMG_SIZE = ONE_MB,
OCC_HOST_AREA_SIZE = ONE_MB,
MAX_CORES_PER_CHIP = 24,
PAD_OPCODE = 0x00000200, //ATTN Opcode
PPE_RESERVE_AREA = 0x200,
QPMR_HEADER_SIZE = 0x00000200,
SGPE_LVL_1_BOOT_LOAD_SIZE = ONE_KB,
SGPE_LVL_2_BOOT_LOAD_SIZE = ONE_KB,
SGPE_INT_VECT = 384,
SGPE_IMG_HEADER = 64,
SGPE_DBG_PTR_AREA_SIZE = 64,
CME_HCODE_REL_OFFSET = (SGPE_INT_VECT +
SGPE_IMG_HEADER +
SGPE_DBG_PTR_AREA_SIZE),
SGPE_HCODE_SIZE = 30 * ONE_KB,
SGPE_COMMON_RING = 2 * ONE_KB,
CACHE_SCOM_RESTORE_SIZE = 6 * ONE_KB,
CACHE_INST_SPECIFIC_SIZE = 4 * ONE_KB,
MAX_CACHE_CHIPLET = 6,
SGPE_MAX_AREA_SIZE = 64 * ONE_KB,
CPMR_HEADER_SIZE = 256,
THREAD_LAUNCHER_SIZE = 256,
CORE_INT_AREA = 8 * ONE_KB,
SELF_REST_SIZE = CORE_INT_AREA + THREAD_LAUNCHER_SIZE,
CORE_RESTORE_SIZE = 192 * ONE_KB,
CORE_SCOM_RES_SIZE = 6 * ONE_KB,
CME_INT_VECTOR = 384,
CME_IMG_HEADER = 64,
CME_DBG_PTR_AREA_SIZE = 64,
CME_HCODE_SIZE = 20 * ONE_KB,
CORE_COMMON_RING_SIZE = 6 * ONE_KB,
QUAD_PSTATE_SIZE = 2 * ONE_KB,
CORE_SPECIFIC_RING = 2 * ONE_KB,
CORE_SCOM_START = 256 * ONE_KB,
CORE_RESERVE_SIZE =
CORE_SCOM_START - ( CORE_RESTORE_SIZE + CORE_INT_AREA +
CME_HCODE_SIZE + CORE_COMMON_RING_SIZE +
QUAD_PSTATE_SIZE + CME_IMG_HEADER ),
CME_REGION_START = CORE_SCOM_START + CORE_SCOM_RES_SIZE,
CME_INST_SPEC_RING_START = (300 * ONE_KB ) , // offset from CPMR
RESERVE_CME_RING_AREA = ( CME_INST_SPEC_RING_START - ( CME_REGION_START +
PPE_RESERVE_AREA +
CME_HCODE_SIZE +
CORE_COMMON_RING_SIZE +
QUAD_PSTATE_SIZE)),
PGPE_LVL_1_BOOT_LOAD_SIZE = ONE_KB,
PGPE_LVL_2_BOOT_LOAD_SIZE = ONE_KB,
PGPE_IMG_HEADER = 64, // need to get confirmation on this
PGPE_HCODE_INT_VECT = 384,
PGPE_HCODE_SIZE = 16 * ONE_KB,
PGPE_PARAM_BLOCK_SIZE = 8 * ONE_KB,
PSTATE_OUTPUT_TABLE = 8 * ONE_KB,
FUSE_STATE = 0xAA,
UNFUSE_STATE = 0xBB,
CME_BLOCK_READ_LEN = 32,
CACHE_SCOM_START = 128 * ONE_KB,
CPMR_MAGIC_WORD = 0x484F4D4552312E30ll,
CME_BLK_SIZE_SHIFT = 0x05,
};
/**
* @brief enumerates all return codes associated with hcode image build.
*/
enum ImgBldRetCode_t
{
IMG_BUILD_SUCCESS = 0,
BUILD_FAIL_SGPE_IMAGE = 1,
BUILD_FAIL_SELF_REST_IMAGE = 2,
BUILD_FAIL_CME_IMAGE = 3,
BUILD_FAIL_PGPE_IMAGE = 4,
BUILD_FAIL_SGPE_QPMR = 5,
BUILD_FAIL_SGPE_BL1 = 6,
BUILD_FAIL_SGPE_BL2 = 7,
BUILD_FAIL_SGPE_INT_VECT = 8,
BUILD_FAIL_SGPE_HDR = 9,
BUILD_FAIL_SGPE_HCODE = 10,
BUILD_FAIL_SGPE_CMN_RINGS = 11,
BUILD_FAIL_SGPE_SPEC_RINGS = 12,
BUILD_FAIL_P9_CPMR_HDR = 13,
BUILD_FAIL_P9_SRESET_HNDLR = 14,
BUILD_FAIL_P9_THRD_LAUNCHER = 15,
BUILD_FAIL_P9_SPR_RESTORE = 16,
BUILD_FAIL_P9_SCOM_RESTORE = 17,
BUILD_FAIL_CME_IMG_HDR = 18,
BUILD_FAIL_CME_HCODE = 19,
BUILD_FAIL_CME_CMN_RINGS = 20,
BUILD_FAIL_CME_QUAD_PSTATE = 21,
BUILD_FAIL_CME_SPEC_RINGS = 22,
BUILD_FAIL_CME_INT_VECT = 23,
};
/**
* @brief models image section of SGPE in HOMER.
*/
typedef struct
{
uint8_t qpmrHeader[QPMR_HEADER_SIZE];
uint8_t l1BootLoader[SGPE_LVL_1_BOOT_LOAD_SIZE];
uint8_t l2BootLoader[SGPE_LVL_2_BOOT_LOAD_SIZE];
uint8_t hcodeIntVect[SGPE_INT_VECT];
uint8_t imgHeader[SGPE_IMG_HEADER];
uint8_t debugPtrArea[SGPE_DBG_PTR_AREA_SIZE];
uint8_t hcode[SGPE_HCODE_SIZE];
uint8_t commonRings[SGPE_COMMON_RING];
uint8_t cacheSpecificRing[MAX_CACHE_CHIPLET][CACHE_INST_SPECIFIC_SIZE];
} SgpeLayout_t;
/**
* @brief models image section associated with core self restore in HOMER.
*/
typedef struct
{
uint8_t selfRestoreArea[SELF_REST_SIZE];
uint8_t coreSelfRestore[CORE_RESTORE_SIZE];
uint8_t reserve[CORE_SCOM_START - (SELF_REST_SIZE + CORE_RESTORE_SIZE)];
uint8_t coreScom[CORE_SCOM_RES_SIZE];
} SelfRestoreLayout_t;
typedef struct
{
uint8_t cmeIntVector[CME_INT_VECTOR];
uint8_t imgHeader[CME_IMG_HEADER];
uint8_t debugPtrArea[CME_DBG_PTR_AREA_SIZE];
uint8_t hcode[CME_HCODE_SIZE];
uint8_t commonRings[CORE_COMMON_RING_SIZE];
uint8_t quadPstateArea[QUAD_PSTATE_SIZE];
uint8_t resvRingArea[RESERVE_CME_RING_AREA];
uint8_t instSpecificRing[MAX_CORES_PER_CHIP][CORE_SPECIFIC_RING]; // 300KB offset from CPMR
} CmeRegionLayout_t;
/**
* @brief models image section associated with core self restore in HOMER.
*/
typedef struct
{
uint8_t l1BootLoader[PGPE_LVL_1_BOOT_LOAD_SIZE];
uint8_t l2BootLoader[PGPE_LVL_2_BOOT_LOAD_SIZE];
uint8_t pgpeIntVector[PGPE_HCODE_INT_VECT];
uint8_t imgHeader[PGPE_IMG_HEADER];
uint8_t hcode[PGPE_HCODE_SIZE];
uint8_t paramBlock[PGPE_PARAM_BLOCK_SIZE];
uint8_t pstateOutputTable[PSTATE_OUTPUT_TABLE];
} PgpeLayout_t;
/**
* @brief models CME image header in HOMER.
*/
typedef struct
{
uint64_t magicNumber;
uint32_t buildDate;
uint32_t buildVer;
uint32_t hcodeOffset;
uint32_t hcodeLength;
uint32_t commonRingOffset;
uint32_t commonRingLength;
uint32_t pStateOffset;
uint32_t pStateLength;
uint32_t coreSpecificRingOffset;;
uint32_t coreSpecificRingLength;
uint32_t cmeMode;
uint8_t reserve[12];
} CmeImageHeader_t;
/**
* @brief models SGPE image header in HOMER.
*/
struct SgpeImageHeader_t
{
uint64_t magicNumber;
uint32_t sysResetAddr;
uint32_t reserve1;
uint32_t ivprAddress;
uint32_t reserve2;
uint32_t buildDate;
uint32_t buildVer;
uint64_t reserveFlag;
uint32_t quadCmnRingOccOffset;
uint32_t quadSpecRingOccOffset;
uint32_t quadCommonScomOccOffset;
uint8_t reserve3[12];
};
/**
* @brief models layout of HOMER.
*/
struct Homerlayout_t
{
uint8_t occHostArea[OCC_HOST_AREA_SIZE];
SgpeLayout_t sgpeRegion;
uint8_t sgpeReserve1[CACHE_SCOM_START - sizeof(SgpeLayout_t)];
uint8_t cacheScomRegion[CACHE_SCOM_RESTORE_SIZE];
uint8_t sgpeReserve2[ONE_MB - (CACHE_SCOM_START + CACHE_SCOM_RESTORE_SIZE )];
SelfRestoreLayout_t selfRestoreRegion;
CmeRegionLayout_t cmeRegion;
uint8_t cmeReserve[ONE_MB - (sizeof( CmeRegionLayout_t ) + sizeof( SelfRestoreLayout_t ))];
PgpeLayout_t pgpeRegion;
uint8_t pgpeReserve[ONE_MB - sizeof( PgpeLayout_t )];
};
#ifndef __PPE_PLAT
}// namespace p9_hcodeImageBuild ends
#endif //__PPE_PLAT
#endif //__ASSEMBLER__
/**
* @brief models QPMR header in HOMER
*/
#ifdef __ASSEMBLER__
#define DEF_MEM_QPMR_UINT64( member )\
member: \
.quad 0
#else
#define DEF_MEM_QPMR_UINT64( member ) uint64_t member;
#endif
#ifdef __ASSEMBLER__
#define DEF_MEM_QPMR_UINT32( member )\
member: \
.long 0
#else
#define DEF_MEM_QPMR_UINT32( member ) uint32_t member;
#endif
#ifdef __ASSEMBLER__
.section ".qpmr" , "aw"
.balign 8
#else
#ifndef __PPE_PLAT
namespace p9_hcodeImageBuild
{
#endif //__PPE_PLAT
struct QpmrHeaderLayout_t
{
#endif
DEF_MEM_QPMR_UINT64( magicNumber )
DEF_MEM_QPMR_UINT32( bootCopierOffset ) // level 1 boot loader
DEF_MEM_QPMR_UINT32( reserve1 )
DEF_MEM_QPMR_UINT32( bootLoaderOffset ) // level 2 boot loader
DEF_MEM_QPMR_UINT32( bootLoaderLength )
DEF_MEM_QPMR_UINT32( buildDate )
DEF_MEM_QPMR_UINT32( buildVersion )
DEF_MEM_QPMR_UINT64( reservedFlags )
DEF_MEM_QPMR_UINT32( sgpeImgOffset )
DEF_MEM_QPMR_UINT32( sgpeImgLength )
DEF_MEM_QPMR_UINT32( quadCmnRingOffset )
DEF_MEM_QPMR_UINT32( quadCmnRingLength )
DEF_MEM_QPMR_UINT32( quadSpecRingOffset )
DEF_MEM_QPMR_UINT32( quadSpecRingLength )
DEF_MEM_QPMR_UINT32( quadSpecScomOffset )
DEF_MEM_QPMR_UINT32( quadSpecScomLength )
DEF_MEM_QPMR_UINT32( quadCmnRingOccOffset )
DEF_MEM_QPMR_UINT32( quadSpecRingOccOffset )
DEF_MEM_QPMR_UINT32( quadCmnScomOccOffset )
#ifndef __ASSEMBLER__
};
#ifndef __PPE_PLAT
} // p9_hcodeImageBuild ends
#endif //__PPE_PLAT
#endif
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.